Fix the spacing and clean it up.

This commit is contained in:
graywolf336 2014-07-27 14:46:25 -05:00
parent f89de50d75
commit 71a60e6ee3
92 changed files with 9955 additions and 9940 deletions

View File

@ -26,72 +26,72 @@ import org.bukkit.Location;
* @version 1.0.2 * @version 1.0.2
*/ */
public class HandCuffManager { public class HandCuffManager {
private HashMap<UUID, Long> handcuffed; private HashMap<UUID, Long> handcuffed;
private HashMap<UUID, Location> locs; private HashMap<UUID, Location> locs;
/** Constructs a new HandCuff Manager, for handling all the handcuffing. */ /** Constructs a new HandCuff Manager, for handling all the handcuffing. */
public HandCuffManager() { public HandCuffManager() {
this.handcuffed = new HashMap<UUID, Long>(); this.handcuffed = new HashMap<UUID, Long>();
this.locs = new HashMap<UUID, Location>(); this.locs = new HashMap<UUID, Location>();
} }
/** /**
* Adds handcuffs to a player. * 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 * @param location where the player was handcuffed, so they can't move
*/ */
public void addHandCuffs(UUID uuid, Location location) { public void addHandCuffs(UUID uuid, Location location) {
this.handcuffed.put(uuid, System.currentTimeMillis()); this.handcuffed.put(uuid, System.currentTimeMillis());
this.locs.put(uuid, location); this.locs.put(uuid, location);
} }
/** /**
* Removes the handcuffs from the given player. * Removes the handcuffs from the given player.
* *
* @param uuid of the person to remove the handcuffs from * @param uuid of the person to remove the handcuffs from
*/ */
public void removeHandCuffs(UUID uuid) { public void removeHandCuffs(UUID uuid) {
this.handcuffed.remove(uuid); this.handcuffed.remove(uuid);
this.locs.remove(uuid); this.locs.remove(uuid);
} }
/** /**
* Gets if the player is handcuffed or not. * Gets if the player is handcuffed or not.
* *
* @param uuid of the player to check * @param uuid of the player to check
* @return true if they are handcuffed, false if not * @return true if they are handcuffed, false if not
*/ */
public boolean isHandCuffed(UUID uuid) { public boolean isHandCuffed(UUID uuid) {
return this.handcuffed.containsKey(uuid); return this.handcuffed.containsKey(uuid);
} }
/** /**
* Gets the next Long time we should send a message to the player. * 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 * @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 * @return long value of the system time in milliseconds
*/ */
public Long getNextMessageTime(UUID uuid) { public Long getNextMessageTime(UUID uuid) {
return this.handcuffed.get(uuid); return this.handcuffed.get(uuid);
} }
/** /**
* Updates the time to the next 10 seconds from now to when we should send them a message. * 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 * @param uuid of the player we're setting the message time to
*/ */
public void updateNextTime(UUID uuid) { public void updateNextTime(UUID uuid) {
this.handcuffed.put(uuid, System.currentTimeMillis() + 10000); this.handcuffed.put(uuid, System.currentTimeMillis() + 10000);
} }
/** /**
* Gets the location where the given player was handcuffed at. * Gets the location where the given player was handcuffed at.
* *
* @param uuid of the player get the location for * @param uuid of the player get the location for
* @return the location where the player was handcuffed at * @return the location where the player was handcuffed at
*/ */
public Location getLocation(UUID uuid) { public Location getLocation(UUID uuid) {
return this.locs.get(uuid); return this.locs.get(uuid);
} }
} }

File diff suppressed because it is too large Load Diff

View File

@ -31,286 +31,286 @@ import com.graywolf336.jail.listeners.WorldListener;
* @version 3.0.0 * @version 3.0.0
*/ */
public class JailMain extends JavaPlugin { public class JailMain extends JavaPlugin {
private CommandHandler cmdHand; private CommandHandler cmdHand;
private HandCuffManager hcm; private HandCuffManager hcm;
private JailHandler jh; private JailHandler jh;
private JailIO io; private JailIO io;
private JailManager jm; private JailManager jm;
private JailPayManager jpm; private JailPayManager jpm;
private JailStickManager jsm; private JailStickManager jsm;
private JailTimer jt; private JailTimer jt;
private PrisonerManager pm; private PrisonerManager pm;
private ScoreBoardManager sbm; private ScoreBoardManager sbm;
private MoveProtectionListener mpl; private MoveProtectionListener mpl;
private Update update; private Update update;
private boolean debug = false; private boolean debug = false;
private int updateCheckTask = -1; private int updateCheckTask = -1;
public void onEnable() { public void onEnable() {
long st = System.currentTimeMillis(); long st = System.currentTimeMillis();
loadConfig(); loadConfig();
debug = getConfig().getBoolean(Settings.DEBUG.getPath()); debug = getConfig().getBoolean(Settings.DEBUG.getPath());
if(debug) getLogger().info("Debugging enabled."); if(debug) getLogger().info("Debugging enabled.");
hcm = new HandCuffManager(); hcm = new HandCuffManager();
jm = new JailManager(this); jm = new JailManager(this);
//Try to load the old stuff before we load anything, esp the storage stuff //Try to load the old stuff before we load anything, esp the storage stuff
LegacyManager lm = new LegacyManager(this); LegacyManager lm = new LegacyManager(this);
if(lm.doWeNeedToConvert()) { if(lm.doWeNeedToConvert()) {
lm.convertOldData(); lm.convertOldData();
if(!lm.wasAnythingConverted()) getLogger().severe("We was unable to convert some, or all, of the old data."); if(!lm.wasAnythingConverted()) getLogger().severe("We was unable to convert some, or all, of the old data.");
} }
io = new JailIO(this); io = new JailIO(this);
io.loadLanguage(); io.loadLanguage();
//If the prepareStorage returns false, we need to disable the plugin //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.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); this.getServer().getPluginManager().disablePlugin(this);
return; return;
} }
io.loadJails(); io.loadJails();
//If we converted something, let's save EVERYTHING including the cells //If we converted something, let's save EVERYTHING including the cells
if(lm.wasAnythingConverted()) { if(lm.wasAnythingConverted()) {
io.saveEverything(); io.saveEverything();
} }
cmdHand = new CommandHandler(this); cmdHand = new CommandHandler(this);
jh = new JailHandler(this); jh = new JailHandler(this);
pm = new PrisonerManager(this); pm = new PrisonerManager(this);
PluginManager plm = this.getServer().getPluginManager(); PluginManager plm = this.getServer().getPluginManager();
plm.registerEvents(new BlockListener(this), this); plm.registerEvents(new BlockListener(this), this);
plm.registerEvents(new CacheListener(this), this); plm.registerEvents(new CacheListener(this), this);
plm.registerEvents(new EntityListener(this), this); plm.registerEvents(new EntityListener(this), this);
plm.registerEvents(new HandCuffListener(this), this); plm.registerEvents(new HandCuffListener(this), this);
plm.registerEvents(new JailingListener(this), this); plm.registerEvents(new JailingListener(this), this);
plm.registerEvents(new PlayerListener(this), this); plm.registerEvents(new PlayerListener(this), this);
plm.registerEvents(new ProtectionListener(this), this); plm.registerEvents(new ProtectionListener(this), this);
plm.registerEvents(new WorldListener(this), this); plm.registerEvents(new WorldListener(this), this);
//Only register the move protection listener if this is enabled in the //Only register the move protection listener if this is enabled in the
//config when we first start the plugin. The reason for this change is //config when we first start the plugin. The reason for this change is
//that the move event is called a ton of times per single move and so //that the move event is called a ton of times per single move and so
//not registering this event listener will hopefully safe some performance. //not registering this event listener will hopefully safe some performance.
//But doing this also forces people to restart their server if they to //But doing this also forces people to restart their server if they to
//enable it after disabling it. //enable it after disabling it.
if(getConfig().getBoolean(Settings.MOVEPROTECTION.getPath())) { if(getConfig().getBoolean(Settings.MOVEPROTECTION.getPath())) {
this.mpl = new MoveProtectionListener(this); this.mpl = new MoveProtectionListener(this);
plm.registerEvents(this.mpl, this); plm.registerEvents(this.mpl, this);
} }
jt = new JailTimer(this); jt = new JailTimer(this);
sbm = new ScoreBoardManager(this); sbm = new ScoreBoardManager(this);
reloadJailPayManager(); reloadJailPayManager();
reloadJailSticks(); reloadJailSticks();
reloadUpdateCheck(); reloadUpdateCheck();
new JailsAPI(this); new JailsAPI(this);
debug("Took " + (System.currentTimeMillis() - st) + " to enable the plugin."); debug("Took " + (System.currentTimeMillis() - st) + " to enable the plugin.");
getLogger().info("Completed enablement."); getLogger().info("Completed enablement.");
} }
public void onDisable() { public void onDisable() {
if(jm != null) if(jm != null)
for(Jail j : jm.getJails()) for(Jail j : jm.getJails())
io.saveJail(j); io.saveJail(j);
if(jt != null) if(jt != null)
if(jt.getTimer() != null) if(jt.getTimer() != null)
jt.getTimer().stop(); jt.getTimer().stop();
if(io != null) if(io != null)
io.closeConnection(); io.closeConnection();
getServer().getScheduler().cancelTasks(this); getServer().getScheduler().cancelTasks(this);
update = null; update = null;
jt = null; jt = null;
sbm = null; sbm = null;
jpm = null; jpm = null;
cmdHand = null; cmdHand = null;
pm = null; pm = null;
jm = null; jm = null;
jsm = null; jsm = null;
io = null; io = null;
hcm = null; hcm = null;
} }
private void loadConfig() { private void loadConfig() {
//Only create the default config if it doesn't exist //Only create the default config if it doesn't exist
saveDefaultConfig(); saveDefaultConfig();
//Append new key-value pairs to the config //Append new key-value pairs to the config
getConfig().options().copyDefaults(true); getConfig().options().copyDefaults(true);
// Set the header and save // Set the header and save
getConfig().options().header(getHeader()); getConfig().options().header(getHeader());
saveConfig(); saveConfig();
} }
private String getHeader() { private String getHeader() {
String sep = System.getProperty("line.separator"); String sep = System.getProperty("line.separator");
return "###################" + sep return "###################" + sep
+ "Jail v" + this.getDescription().getVersion() + " config file" + sep + "Jail v" + this.getDescription().getVersion() + " config file" + sep
+ "Note: You -must- use spaces instead of tabs!" + sep + + "Note: You -must- use spaces instead of tabs!" + sep +
"###################"; "###################";
} }
/* Majority of the new command system was heavily influenced by the MobArena. /* Majority of the new command system was heavily influenced by the MobArena.
* Thank you garbagemule for the great system you have in place there. * Thank you garbagemule for the great system you have in place there.
* *
* Send the command off to the CommandHandler class, that way this main class doesn't get clogged up. * 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) { public boolean onCommand(CommandSender sender, Command command, String commandLabel, String[] args) {
if(commandLabel.equalsIgnoreCase("jail") || commandLabel.equalsIgnoreCase("j")) { if(commandLabel.equalsIgnoreCase("jail") || commandLabel.equalsIgnoreCase("j")) {
jh.parseCommand(jm, sender, args); jh.parseCommand(jm, sender, args);
}else { }else {
cmdHand.handleCommand(jm, sender, command.getName().toLowerCase(), args); 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. return true;//Always return true here, that way we can handle the help and command usage ourself.
} }
/** Reloads the scoreboard manager class, useful when something is changed int he config about it. */ /** Reloads the scoreboard manager class, useful when something is changed int he config about it. */
public void reloadScoreBoardManager() { public void reloadScoreBoardManager() {
this.sbm.removeAllScoreboards(); this.sbm.removeAllScoreboards();
this.sbm = null; this.sbm = null;
this.sbm = new ScoreBoardManager(this); this.sbm = new ScoreBoardManager(this);
if(getConfig().getBoolean(Settings.SCOREBOARDENABLED.getPath())) { if(getConfig().getBoolean(Settings.SCOREBOARDENABLED.getPath())) {
for(Jail j : jm.getJails()) { for(Jail j : jm.getJails()) {
for(Prisoner p : j.getAllPrisoners().values()) { for(Prisoner p : j.getAllPrisoners().values()) {
if(getServer().getPlayer(p.getUUID()) != null) { if(getServer().getPlayer(p.getUUID()) != null) {
this.sbm.addScoreBoard(getServer().getPlayer(p.getUUID()), p); this.sbm.addScoreBoard(getServer().getPlayer(p.getUUID()), p);
} }
} }
} }
} }
} }
/** 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. */
public void reloadJailSticks() { public void reloadJailSticks() {
if(getConfig().getBoolean(Settings.JAILSTICKENABLED.getPath())) { if(getConfig().getBoolean(Settings.JAILSTICKENABLED.getPath())) {
if(this.jsm != null) { if(this.jsm != null) {
this.jsm.removeAllStickUsers(); this.jsm.removeAllStickUsers();
this.jsm = null; this.jsm = null;
} }
this.jsm = new JailStickManager(this); this.jsm = new JailStickManager(this);
} }
} }
/** /**
* Reloads the {@link JailPayManager}. * Reloads the {@link JailPayManager}.
* *
* @throws Exception If we couldn't successfully create a new Jail Pay Manager instance. * @throws Exception If we couldn't successfully create a new Jail Pay Manager instance.
*/ */
public void reloadJailPayManager() { public void reloadJailPayManager() {
this.jpm = null; this.jpm = null;
if(getConfig().getBoolean(Settings.JAILPAYENABLED.getPath())) { if(getConfig().getBoolean(Settings.JAILPAYENABLED.getPath())) {
if(getServer().getPluginManager().isPluginEnabled("Vault")) { if(getServer().getPluginManager().isPluginEnabled("Vault")) {
this.jpm = new JailPayManager(this); this.jpm = new JailPayManager(this);
}else { }else {
getConfig().set(Settings.JAILPAYENABLED.getPath(), false); getConfig().set(Settings.JAILPAYENABLED.getPath(), false);
getLogger().severe("Jail Pay couldn't find an economy, disabling Jail Pay."); getLogger().severe("Jail Pay couldn't find an economy, disabling Jail Pay.");
} }
} }
} }
/** Reloads the update checker, in case they changed a setting about it. */ /** Reloads the update checker, in case they changed a setting about it. */
public void reloadUpdateCheck() { public void reloadUpdateCheck() {
getServer().getScheduler().cancelTask(updateCheckTask); getServer().getScheduler().cancelTask(updateCheckTask);
update = new Update(this); update = new Update(this);
if(getConfig().getBoolean(Settings.UPDATENOTIFICATIONS.getPath())) { if(getConfig().getBoolean(Settings.UPDATENOTIFICATIONS.getPath())) {
try { try {
updateCheckTask = getServer().getScheduler().runTaskTimerAsynchronously(this, new Runnable() { updateCheckTask = getServer().getScheduler().runTaskTimerAsynchronously(this, new Runnable() {
public void run() { public void run() {
update.query(); update.query();
} }
}, 80L, Util.getTime(getConfig().getString(Settings.UPDATETIME.getPath()), TimeUnit.SECONDS) * 20).getTaskId(); }, 80L, Util.getTime(getConfig().getString(Settings.UPDATETIME.getPath()), TimeUnit.SECONDS) * 20).getTaskId();
} catch (Exception e) { } catch (Exception e) {
e.printStackTrace(); e.printStackTrace();
getLogger().severe("Was unable to schedule the update checking, please check your time format is correct."); getLogger().severe("Was unable to schedule the update checking, please check your time format is correct.");
} }
} }
} }
/** Gets the {@link HandCuffManager} instance. */ /** Gets the {@link HandCuffManager} instance. */
public HandCuffManager getHandCuffManager() { public HandCuffManager getHandCuffManager() {
return this.hcm; return this.hcm;
} }
/** Gets the {@link JailIO} instance. */ /** Gets the {@link JailIO} instance. */
public JailIO getJailIO() { public JailIO getJailIO() {
return this.io; return this.io;
} }
/** Gets the {@link JailManager} instance. */ /** Gets the {@link JailManager} instance. */
public JailManager getJailManager() { public JailManager getJailManager() {
return this.jm; return this.jm;
} }
/** Gets the {@link JailPayManager} instance. */ /** Gets the {@link JailPayManager} instance. */
public JailPayManager getJailPayManager() { public JailPayManager getJailPayManager() {
return this.jpm; return this.jpm;
} }
/** Gets the {@link PrisonerManager} instance. */ /** Gets the {@link PrisonerManager} instance. */
public PrisonerManager getPrisonerManager() { public PrisonerManager getPrisonerManager() {
return this.pm; return this.pm;
} }
/** Gets the {@link JailStickManager} instance. */ /** Gets the {@link JailStickManager} instance. */
public JailStickManager getJailStickManager() { public JailStickManager getJailStickManager() {
return this.jsm; return this.jsm;
} }
/** Gets the {@link ScoreBoardManager} instance. */ /** Gets the {@link ScoreBoardManager} instance. */
public ScoreBoardManager getScoreBoardManager() { public ScoreBoardManager getScoreBoardManager() {
return this.sbm; return this.sbm;
} }
/** Gets the {@link Update} instance. */ /** Gets the {@link Update} instance. */
public Update getUpdate() { public Update getUpdate() {
return this.update; return this.update;
} }
/** Sets whether the plugin is in debugging or not. */ /** Sets whether the plugin is in debugging or not. */
public boolean setDebugging(boolean debug) { public boolean setDebugging(boolean debug) {
this.debug = debug; this.debug = debug;
//Save whether we are debugging when we disable the plugin //Save whether we are debugging when we disable the plugin
getConfig().set(Settings.DEBUG.getPath(), this.debug); getConfig().set(Settings.DEBUG.getPath(), this.debug);
saveConfig(); saveConfig();
return this.debug; return this.debug;
} }
/** Returns if the plugin is in debug state or not. */ /** Returns if the plugin is in debug state or not. */
public boolean inDebug() { public boolean inDebug() {
return this.debug; return this.debug;
} }
/** Logs a debugging message to the console if debugging is enabled. */ /** Logs a debugging message to the console if debugging is enabled. */
public void debug(String message) { 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. * This method is only for testing, there is no need to use this.
* *
* @return the move protection listener * @return the move protection listener
* @deprecated * @deprecated
*/ */
public MoveProtectionListener getPlayerMoveListener() { public MoveProtectionListener getPlayerMoveListener() {
return this.mpl; return this.mpl;
} }
} }

File diff suppressed because it is too large Load Diff

View File

@ -11,156 +11,156 @@ import com.graywolf336.jail.beans.Prisoner;
import com.graywolf336.jail.enums.Settings; import com.graywolf336.jail.enums.Settings;
public class JailPayManager { public class JailPayManager {
private Economy economy = null; private Economy economy = null;
private double minteCost, infiniteCost; private double minteCost, infiniteCost;
private Material item; private Material item;
private boolean infinite, timed; private boolean infinite, timed;
public JailPayManager(JailMain plugin) { public JailPayManager(JailMain plugin) {
this.item = Material.getMaterial(plugin.getConfig().getString(Settings.JAILPAYITEM.getPath().toUpperCase())); this.item = Material.getMaterial(plugin.getConfig().getString(Settings.JAILPAYITEM.getPath().toUpperCase()));
if(this.item == null) this.item = Material.AIR; if(this.item == null) this.item = Material.AIR;
this.minteCost = plugin.getConfig().getDouble(Settings.JAILPAYPRICEPERMINUTE.getPath()); this.minteCost = plugin.getConfig().getDouble(Settings.JAILPAYPRICEPERMINUTE.getPath());
if(!this.usingItemsForPayment()) { if(!this.usingItemsForPayment()) {
if(!this.setupEconomy(plugin)) { if(!this.setupEconomy(plugin)) {
plugin.getConfig().set(Settings.JAILPAYENABLED.getPath(), false); plugin.getConfig().set(Settings.JAILPAYENABLED.getPath(), false);
} }
} }
this.timed = plugin.getConfig().getDouble(Settings.JAILPAYPRICEPERMINUTE.getPath()) != 0; this.timed = plugin.getConfig().getDouble(Settings.JAILPAYPRICEPERMINUTE.getPath()) != 0;
this.infinite = plugin.getConfig().getDouble(Settings.JAILPAYPRICEINFINITE.getPath()) != 0; this.infinite = plugin.getConfig().getDouble(Settings.JAILPAYPRICEINFINITE.getPath()) != 0;
} }
/** Checks if paying for infinite is enabled. */ /** Checks if paying for infinite is enabled. */
public boolean isInfiniteEnabled() { public boolean isInfiniteEnabled() {
return this.infinite; return this.infinite;
} }
/** Checks if paying for timed is enabled. */ /** Checks if paying for timed is enabled. */
public boolean isTimedEnabled() { public boolean isTimedEnabled() {
return this.timed; return this.timed;
} }
/** Gets how much it cost per minute in string format. */ /** Gets how much it cost per minute in string format. */
public String getCostPerMinute() { public String getCostPerMinute() {
return String.valueOf(this.minteCost); return String.valueOf(this.minteCost);
} }
/** /**
* Calculates how much players have to pay to get completely free. * Calculates how much players have to pay to get completely free.
* *
* @param prisoner data of who we're calculating * @param prisoner data of who we're calculating
* @return The economy cost the prisoner will need to pay to get completely free. * @return The economy cost the prisoner will need to pay to get completely free.
*/ */
public double calculateBill(Prisoner prisoner) { public double calculateBill(Prisoner prisoner) {
return prisoner.getRemainingTime() > 0 ? prisoner.getRemainingTimeInMinutes() * this.minteCost : infiniteCost; return prisoner.getRemainingTime() > 0 ? prisoner.getRemainingTimeInMinutes() * this.minteCost : infiniteCost;
} }
/** Gets how many minutes someone is paying for (rounds to the lowest number). */ /** Gets how many minutes someone is paying for (rounds to the lowest number). */
public long getMinutesPayingFor(double amount) { public long getMinutesPayingFor(double amount) {
return (long) Math.floor(amount / this.minteCost); return (long) Math.floor(amount / this.minteCost);
} }
/** Returns if we are using items for payment instead of economy. */ /** Returns if we are using items for payment instead of economy. */
public boolean usingItemsForPayment() { public boolean usingItemsForPayment() {
return this.item != Material.AIR; return this.item != Material.AIR;
} }
/** /**
* Gets the {@link Material} it costs for jail pay, will be air if using economy. * Gets the {@link Material} it costs for jail pay, will be air if using economy.
* *
* @return The item type it costs, air if using virtual economy. * @return The item type it costs, air if using virtual economy.
*/ */
public Material getItemItCost() { public Material getItemItCost() {
return this.item; return this.item;
} }
/** /**
* Checks if the player has enough money/items to pay what they have said they want to. * Checks if the player has enough money/items to pay what they have said they want to.
* *
* @param p The player who is doing the paying. * @param p The player who is doing the paying.
* @param amt The amount to check they if they have. * @param amt The amount to check they if they have.
* @return true if they have enough, false if not. * @return true if they have enough, false if not.
*/ */
public boolean hasEnoughToPay(Player p, double amt) { public boolean hasEnoughToPay(Player p, double amt) {
if(this.usingItemsForPayment()) { if(this.usingItemsForPayment()) {
return p.getInventory().contains(this.item, (int) Math.ceil(amt)); return p.getInventory().contains(this.item, (int) Math.ceil(amt));
}else { }else {
return this.economy.has(p.getName(), amt); return this.economy.has(p.getName(), amt);
} }
} }
/** /**
* Pays the required fees from the given player, removing items or money from economy. * Pays the required fees from the given player, removing items or money from economy.
* *
* @param p The player who is paying. * @param p The player who is paying.
* @param amt The amount of items or money to withdraw from the player. * @param amt The amount of items or money to withdraw from the player.
*/ */
public void pay(Player p, double amt) { public void pay(Player p, double amt) {
if(this.usingItemsForPayment()) { if(this.usingItemsForPayment()) {
int amtNeeded = (int) Math.ceil(amt); int amtNeeded = (int) Math.ceil(amt);
for (int i = 0; i < p.getInventory().getSize(); i++) { for (int i = 0; i < p.getInventory().getSize(); i++) {
ItemStack it = p.getInventory().getItem(i); ItemStack it = p.getInventory().getItem(i);
//The item is either air or we doesn't match out needs //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 //If the itemstack has more than or equal to the amount
//that we need, remove it and subject from the amt needed //that we need, remove it and subject from the amt needed
if (amtNeeded >= it.getAmount()) { if (amtNeeded >= it.getAmount()) {
amtNeeded -= it.getAmount(); amtNeeded -= it.getAmount();
p.getInventory().clear(i); p.getInventory().clear(i);
} else { } else {
//Otherwise, subject from the itemstack just the amount we need //Otherwise, subject from the itemstack just the amount we need
it.setAmount(it.getAmount() - amtNeeded); it.setAmount(it.getAmount() - amtNeeded);
p.getInventory().setItem(i, it); p.getInventory().setItem(i, it);
amtNeeded = 0; amtNeeded = 0;
} }
if (amtNeeded == 0) break; if (amtNeeded == 0) break;
} }
}else { }else {
this.economy.withdrawPlayer(p.getName(), amt); this.economy.withdrawPlayer(p.getName(), amt);
} }
} }
/** Gets the name of the item in nice capitals. */ /** Gets the name of the item in nice capitals. */
public String getCurrencyName(){ public String getCurrencyName(){
if(this.usingItemsForPayment()) { if(this.usingItemsForPayment()) {
String name = item.toString().replaceAll("_", " "); String name = item.toString().replaceAll("_", " ");
if(name.contains(" ")){ if(name.contains(" ")){
String[] split = name.split(" "); String[] split = name.split(" ");
for(int i=0; i < split.length; i++){ for(int i=0; i < split.length; i++){
split[i] = split[i].substring(0, 1).toUpperCase() + split[i].substring(1).toLowerCase(); split[i] = split[i].substring(0, 1).toUpperCase() + split[i].substring(1).toLowerCase();
} }
name = ""; name = "";
for(String s : split){ for(String s : split){
name += " " + s; name += " " + s;
} }
name = name.substring(1); name = name.substring(1);
} else { } else {
name = name.substring(0, 1).toUpperCase() + name.substring(1).toLowerCase(); name = name.substring(0, 1).toUpperCase() + name.substring(1).toLowerCase();
} }
return name; return name;
}else { }else {
return this.economy.currencyNamePlural(); return this.economy.currencyNamePlural();
} }
} }
/** Returns the economy provider to do transaction with. */ /** Returns the economy provider to do transaction with. */
public Economy getEconomy() { public Economy getEconomy() {
return this.economy; return this.economy;
} }
private boolean setupEconomy(JailMain plugin) { private boolean setupEconomy(JailMain plugin) {
if (economy != null) return true; if (economy != null) return true;
RegisteredServiceProvider<Economy> economyProvider = plugin.getServer().getServicesManager().getRegistration(net.milkbowl.vault.economy.Economy.class); RegisteredServiceProvider<Economy> economyProvider = plugin.getServer().getServicesManager().getRegistration(net.milkbowl.vault.economy.Economy.class);
if (economyProvider != null) { if (economyProvider != null) {

View File

@ -18,134 +18,134 @@ import com.graywolf336.jail.enums.Settings;
* *
*/ */
public class JailStickManager { public class JailStickManager {
private ArrayList<UUID> stickers; private ArrayList<UUID> stickers;
private HashMap<Material, Stick> sticks; private HashMap<Material, Stick> sticks;
public JailStickManager(JailMain plugin) { public JailStickManager(JailMain plugin) {
this.stickers = new ArrayList<UUID>(); this.stickers = new ArrayList<UUID>();
this.sticks = new HashMap<Material, Stick>(); this.sticks = new HashMap<Material, Stick>();
this.loadJailSticks(plugin); this.loadJailSticks(plugin);
} }
private void loadJailSticks(JailMain pl) { private void loadJailSticks(JailMain pl) {
//item name,time,jail name,reason //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."); pl.getLogger().warning("Can't have jail sticks without any jails.");
}else { }else {
for(String s : pl.getConfig().getStringList(Settings.JAILSTICKSTICKS.getPath())) { for(String s : pl.getConfig().getStringList(Settings.JAILSTICKSTICKS.getPath())) {
pl.debug(s); pl.debug(s);
String[] a = s.split(","); String[] a = s.split(",");
String jail = a[2]; String jail = a[2];
//Check if the jail given, if any, exists //Check if the jail given, if any, exists
if(jail.isEmpty()) { if(jail.isEmpty()) {
jail = pl.getJailManager().getJail("").getName(); jail = pl.getJailManager().getJail("").getName();
}else { }else {
if(!pl.getJailManager().isValidJail(jail)) { if(!pl.getJailManager().isValidJail(jail)) {
pl.getLogger().severe(s); pl.getLogger().severe(s);
pl.getLogger().severe("The above jail stick configuration is invalid and references a jail that doesn't exist."); pl.getLogger().severe("The above jail stick configuration is invalid and references a jail that doesn't exist.");
continue; continue;
} }
} }
Material m = Material.getMaterial(a[0].toUpperCase()); Material m = Material.getMaterial(a[0].toUpperCase());
if(this.sticks.containsKey(m)) { if(this.sticks.containsKey(m)) {
pl.getLogger().severe(s); 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]); 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; continue;
} }
long time = 5; long time = 5;
try { try {
time = Util.getTime(a[1]); time = Util.getTime(a[1]);
} catch (Exception e) { } catch (Exception e) {
pl.getLogger().severe(s); pl.getLogger().severe(s);
pl.getLogger().severe("The time format on the above jail stick configuration is incorrect."); pl.getLogger().severe("The time format on the above jail stick configuration is incorrect.");
continue; continue;
} }
double health = -1; double health = -1;
if(a.length > 5) health = Double.valueOf(a[4]); if(a.length > 5) health = Double.valueOf(a[4]);
try { try {
this.sticks.put(m, new Stick(jail, a[3], time, health)); this.sticks.put(m, new Stick(jail, a[3], time, health));
}catch (Exception e) { }catch (Exception e) {
e.printStackTrace(); e.printStackTrace();
pl.getLogger().severe(s); pl.getLogger().severe(s);
pl.getLogger().severe("Unable to create a new stick for " + a[0] + ", see the exception above for details."); pl.getLogger().severe("Unable to create a new stick for " + a[0] + ", see the exception above for details.");
continue; continue;
} }
} }
} }
int c = sticks.size(); int c = sticks.size();
pl.getLogger().info("Loaded " + c + " jail stick" + (c == 1 ? "" : "s") + "."); pl.getLogger().info("Loaded " + c + " jail stick" + (c == 1 ? "" : "s") + ".");
} }
/** /**
* Gets the {@link Stick jail stick} by the provided {@link Material}, can be null. * Gets the {@link Stick jail stick} by the provided {@link Material}, can be null.
* *
* @param mat of the stick to get * @param mat of the stick to get
* @return The {@link Stick jail stick} * @return The {@link Stick jail stick}
*/ */
public Stick getStick(Material mat) { public Stick getStick(Material mat) {
return this.sticks.get(mat); return this.sticks.get(mat);
} }
/** Checks if the provided Material is a valid {@link Stick jail stick}. */ /** Checks if the provided Material is a valid {@link Stick jail stick}. */
public boolean isValidStick(Material mat) { public boolean isValidStick(Material mat) {
return this.sticks.containsKey(mat); return this.sticks.containsKey(mat);
} }
/** /**
* Adds a player to be using a jail stick, with the uuid of the player. * Adds a player to be using a jail stick, with the uuid of the player.
* *
* @param id of the player to add * @param id of the player to add
*/ */
public void addUsingStick(UUID id) { public void addUsingStick(UUID id) {
this.stickers.add(id); this.stickers.add(id);
} }
/** /**
* Removes a player from using a jail stick, with the uuid of the player. * Removes a player from using a jail stick, with the uuid of the player.
* *
* @param id of the player to remove using a jail stick * @param id of the player to remove using a jail stick
*/ */
public void removeUsingStick(UUID id) { public void removeUsingStick(UUID id) {
this.stickers.remove(id); this.stickers.remove(id);
} }
/** /**
* Returns whether or not the player is using a jail stick. * Returns whether or not the player is using a jail stick.
* *
* @param id of the player to check if using one * @param id of the player to check if using one
* @return true if the player is using a jail stick, false if not * @return true if the player is using a jail stick, false if not
*/ */
public boolean isUsingJailStick(UUID id) { public boolean isUsingJailStick(UUID id) {
return this.stickers.contains(id); return this.stickers.contains(id);
} }
/** /**
* Toggles whether the player is using a jail stick, returning the true if enabled false if disabled. * Toggles whether the player is using a jail stick, returning the true if enabled false if disabled.
* *
* @param id of the player to toggle using a stick * @param id of the player to toggle using a stick
* @return true if we enabled it, false if we disabled it. * @return true if we enabled it, false if we disabled it.
*/ */
public boolean toggleUsingStick(UUID id) { public boolean toggleUsingStick(UUID id) {
if(this.stickers.contains(id)) { if(this.stickers.contains(id)) {
this.stickers.remove(id); this.stickers.remove(id);
return false; return false;
}else { }else {
this.stickers.add(id); this.stickers.add(id);
return true; return true;
} }
} }
/** Removes all the users currently using the sticks. */ /** Removes all the users currently using the sticks. */
public void removeAllStickUsers() { public void removeAllStickUsers() {
for(UUID id : stickers) { for(UUID id : stickers) {
this.removeUsingStick(id); this.removeUsingStick(id);
} }
} }
} }

View File

@ -21,87 +21,87 @@ import com.graywolf336.jail.enums.Settings;
* *
*/ */
public class JailTimer { public class JailTimer {
private JailMain pl; private JailMain pl;
private Timer timer; private Timer timer;
private Long lastTime; private Long lastTime;
private Long afkTime = 0L; private Long afkTime = 0L;
public JailTimer(JailMain plugin) { public JailTimer(JailMain plugin) {
this.pl = plugin; this.pl = plugin;
try { try {
afkTime = Util.getTime(pl.getConfig().getString(Settings.MAXAFKTIME.getPath())); afkTime = Util.getTime(pl.getConfig().getString(Settings.MAXAFKTIME.getPath()));
} catch (Exception e) { } catch (Exception e) {
pl.getLogger().severe("Error while processing the max afk time: " + e.getMessage()); pl.getLogger().severe("Error while processing the max afk time: " + e.getMessage());
} }
this.lastTime = System.currentTimeMillis(); 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.getLogger().info("Using the Bukkit Scheduler.");
pl.getServer().getScheduler().runTaskTimerAsynchronously(pl, new TimeEvent(), 200, 200); pl.getServer().getScheduler().runTaskTimerAsynchronously(pl, new TimeEvent(), 200, 200);
}else { }else {
pl.getLogger().info("Using the Java Timer."); pl.getLogger().info("Using the Java Timer.");
timer = new Timer(10000, new ActionListener () { timer = new Timer(10000, new ActionListener () {
public void actionPerformed (ActionEvent event) { public void actionPerformed (ActionEvent event) {
pl.getServer().getScheduler().scheduleSyncDelayedTask(pl, new TimeEvent()); pl.getServer().getScheduler().scheduleSyncDelayedTask(pl, new TimeEvent());
}; };
}); });
timer.start(); timer.start();
} }
//Save all the jail information every minute, not every 10 seconds //Save all the jail information every minute, not every 10 seconds
pl.getServer().getScheduler().runTaskTimerAsynchronously(pl, new Runnable() { pl.getServer().getScheduler().runTaskTimerAsynchronously(pl, new Runnable() {
public void run() { public void run() {
for(Jail j : pl.getJailManager().getJails()) { for(Jail j : pl.getJailManager().getJails()) {
pl.getJailIO().saveJail(j); pl.getJailIO().saveJail(j);
} }
} }
}, 1200L, 1200L); }, 1200L, 1200L);
} }
/** Returns the instance of this timer. */ /** Returns the instance of this timer. */
public Timer getTimer() { public Timer getTimer() {
return this.timer; return this.timer;
} }
class TimeEvent implements Runnable { class TimeEvent implements Runnable {
public void run() { public void run() {
long timePassed = System.currentTimeMillis() - lastTime; long timePassed = System.currentTimeMillis() - lastTime;
lastTime = System.currentTimeMillis(); lastTime = System.currentTimeMillis();
for(Jail j : pl.getJailManager().getJails()) { for(Jail j : pl.getJailManager().getJails()) {
for(Prisoner p : j.getAllPrisoners().values()) { for(Prisoner p : j.getAllPrisoners().values()) {
//only execute this code if the prisoner's time is more than 0 milliseconds //only execute this code if the prisoner's time is more than 0 milliseconds
//and they don't have any offline pending things //and they don't have any offline pending things
if(p.getRemainingTime() > 0 && !p.isOfflinePending()) { if(p.getRemainingTime() > 0 && !p.isOfflinePending()) {
Player player = pl.getServer().getPlayer(p.getUUID()); Player player = pl.getServer().getPlayer(p.getUUID());
//Check if the player is offline //Check if the player is offline
if(player == null) { if(player == null) {
//if they are offline AND the config has counting down the time //if they are offline AND the config has counting down the time
//while the prisoner is offline, then let's do it //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 //Set their remaining time but if it is less than zero, set it to zero
p.setRemainingTime(Math.max(0, p.getRemainingTime() - timePassed)); p.setRemainingTime(Math.max(0, p.getRemainingTime() - timePassed));
if(p.getRemainingTime() == 0) pl.getPrisonerManager().schedulePrisonerRelease(p); if(p.getRemainingTime() == 0) pl.getPrisonerManager().schedulePrisonerRelease(p);
} }
}else { }else {
if(afkTime > 0) { if(afkTime > 0) {
p.setAFKTime(p.getAFKTime() + timePassed); p.setAFKTime(p.getAFKTime() + timePassed);
if(p.getAFKTime() > afkTime) { if(p.getAFKTime() > afkTime) {
p.setAFKTime(0); p.setAFKTime(0);
player.kickPlayer(Lang.AFKKICKMESSAGE.get()); player.kickPlayer(Lang.AFKKICKMESSAGE.get());
} }
} }
//The prisoner isn't offline, so let's count down //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 //Set their remaining time but if it is less than zero, set it to zero
p.setRemainingTime(Math.max(0, p.getRemainingTime() - timePassed)); p.setRemainingTime(Math.max(0, p.getRemainingTime() - timePassed));
if(p.getRemainingTime() == 0) pl.getPrisonerManager().schedulePrisonerRelease(p); if(p.getRemainingTime() == 0) pl.getPrisonerManager().schedulePrisonerRelease(p);
} }
} }
} }
} }
} }
} }
} }

View File

@ -13,39 +13,39 @@ package com.graywolf336.jail;
* @since 3.0.0 * @since 3.0.0
*/ */
public class JailsAPI { public class JailsAPI {
private static JailMain pl; private static JailMain pl;
public JailsAPI(JailMain plugin) { public JailsAPI(JailMain plugin) {
pl = plugin; pl = plugin;
} }
/** /**
* The instance of the {@link JailManager} which contains all the jails and in return prisoners. * The instance of the {@link JailManager} which contains all the jails and in return prisoners.
* *
* @return instance of the {@link JailManager} * @return instance of the {@link JailManager}
* @see JailManager * @see JailManager
*/ */
public static JailManager getJailManager() { public static JailManager getJailManager() {
return pl.getJailManager(); return pl.getJailManager();
} }
/** /**
* The instance of the {@link PrisonerManager} which handles all the jailing of players. * The instance of the {@link PrisonerManager} which handles all the jailing of players.
* *
* @return instance of the {@link PrisonerManager} * @return instance of the {@link PrisonerManager}
* @see PrisonerManager * @see PrisonerManager
*/ */
public static PrisonerManager getPrisonerManager() { public static PrisonerManager getPrisonerManager() {
return pl.getPrisonerManager(); return pl.getPrisonerManager();
} }
/** /**
* The instance of the {@link HandCuffManager} which handles all the handcuffing of players. * The instance of the {@link HandCuffManager} which handles all the handcuffing of players.
* *
* @return instance of the {@link HandCuffManager} * @return instance of the {@link HandCuffManager}
* @see HandCuffManager * @see HandCuffManager
*/ */
public static HandCuffManager getHandCuffManager() { public static HandCuffManager getHandCuffManager() {
return pl.getHandCuffManager(); return pl.getHandCuffManager();
} }
} }

File diff suppressed because it is too large Load Diff

View File

@ -15,90 +15,90 @@ import com.graywolf336.jail.beans.Prisoner;
import com.graywolf336.jail.enums.Settings; import com.graywolf336.jail.enums.Settings;
public class ScoreBoardManager { public class ScoreBoardManager {
private JailMain pl; private JailMain pl;
private ScoreboardManager man; private ScoreboardManager man;
private HashMap<UUID, Scoreboard> boards; private HashMap<UUID, Scoreboard> boards;
private OfflinePlayer time; private OfflinePlayer time;
public ScoreBoardManager(JailMain plugin) { public ScoreBoardManager(JailMain plugin) {
this.pl = plugin; this.pl = plugin;
this.man = plugin.getServer().getScoreboardManager(); this.man = plugin.getServer().getScoreboardManager();
this.boards = new HashMap<UUID, Scoreboard>(); this.boards = new HashMap<UUID, Scoreboard>();
this.time = plugin.getServer().getOfflinePlayer(Util.getColorfulMessage(pl.getConfig().getString(Settings.SCOREBOARDTIME.getPath()))); this.time = plugin.getServer().getOfflinePlayer(Util.getColorfulMessage(pl.getConfig().getString(Settings.SCOREBOARDTIME.getPath())));
//Start the task if it is enabled //Start the task if it is enabled
if(plugin.getConfig().getBoolean(Settings.SCOREBOARDENABLED.getPath())) { if(plugin.getConfig().getBoolean(Settings.SCOREBOARDENABLED.getPath())) {
plugin.getServer().getScheduler().scheduleSyncRepeatingTask(plugin, new Runnable() { plugin.getServer().getScheduler().scheduleSyncRepeatingTask(plugin, new Runnable() {
public void run() { public void run() {
updatePrisonersTime(); updatePrisonersTime();
} }
}, 200L, 100L); }, 200L, 100L);
} }
} }
/** /**
* Adds the jailing score board to the player if they don't have one, otherwise it just updates it. * 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 player of whom to add the scoreboard to.
* @param pris data for the provided prisoner * @param pris data for the provided prisoner
*/ */
public void addScoreBoard(Player player, Prisoner pris) { public void addScoreBoard(Player player, Prisoner pris) {
if(!boards.containsKey(player.getUniqueId())) { if(!boards.containsKey(player.getUniqueId())) {
boards.put(player.getUniqueId(), man.getNewScoreboard()); boards.put(player.getUniqueId(), man.getNewScoreboard());
Objective o = boards.get(player.getUniqueId()).registerNewObjective("test", "dummy"); Objective o = boards.get(player.getUniqueId()).registerNewObjective("test", "dummy");
o.setDisplaySlot(DisplaySlot.SIDEBAR); o.setDisplaySlot(DisplaySlot.SIDEBAR);
o.setDisplayName(Util.getColorfulMessage(pl.getConfig().getString(Settings.SCOREBOARDTITLE.getPath()))); o.setDisplayName(Util.getColorfulMessage(pl.getConfig().getString(Settings.SCOREBOARDTITLE.getPath())));
o.getScore(time).setScore(pris.getRemainingTimeInMinutesInt()); o.getScore(time).setScore(pris.getRemainingTimeInMinutesInt());
player.setScoreboard(boards.get(player.getUniqueId())); player.setScoreboard(boards.get(player.getUniqueId()));
}else { }else {
updatePrisonersBoard(player, pris); updatePrisonersBoard(player, pris);
} }
} }
/** /**
* Removes a player's jail scoreboard for their jail time and sets it to the main one. * 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. * @param player of whom to remove the scoreboard for.
*/ */
public void removeScoreBoard(Player player) { public void removeScoreBoard(Player player) {
boards.remove(player.getUniqueId()); boards.remove(player.getUniqueId());
//TODO: See if this works or if we need to set it to a new one //TODO: See if this works or if we need to set it to a new one
player.setScoreboard(man.getMainScoreboard()); player.setScoreboard(man.getMainScoreboard());
} }
/** Removes all of the scoreboards from the prisoners. */ /** Removes all of the scoreboards from the prisoners. */
public void removeAllScoreboards() { public void removeAllScoreboards() {
HashMap<UUID, Scoreboard> temp = new HashMap<UUID, Scoreboard>(boards); HashMap<UUID, Scoreboard> temp = new HashMap<UUID, Scoreboard>(boards);
for(UUID id : temp.keySet()) { for(UUID id : temp.keySet()) {
Player p = pl.getServer().getPlayer(id); Player p = pl.getServer().getPlayer(id);
if(p != null) { if(p != null) {
p.setScoreboard(man.getMainScoreboard()); p.setScoreboard(man.getMainScoreboard());
} }
boards.remove(id); boards.remove(id);
} }
} }
/** Updates the prisoners time on their scoreboard. */ /** Updates the prisoners time on their scoreboard. */
private void updatePrisonersTime() { private void updatePrisonersTime() {
for(Jail j : pl.getJailManager().getJails()) { for(Jail j : pl.getJailManager().getJails()) {
for(Prisoner p : j.getAllPrisoners().values()) { for(Prisoner p : j.getAllPrisoners().values()) {
if(pl.getServer().getPlayer(p.getUUID()) != null) { if(pl.getServer().getPlayer(p.getUUID()) != null) {
addScoreBoard(pl.getServer().getPlayer(p.getUUID()), p); addScoreBoard(pl.getServer().getPlayer(p.getUUID()), p);
} }
} }
} }
} }
/** /**
* Updates a player's time in the scoreboard. * Updates a player's time in the scoreboard.
* *
* @param player of whom to update the scoreboard for. * @param player of whom to update the scoreboard for.
* @param pris data for the player * @param pris data for the player
*/ */
private void updatePrisonersBoard(Player player, Prisoner pris) { private void updatePrisonersBoard(Player player, Prisoner pris) {
boards.get(player.getUniqueId()).getObjective("test").getScore(time).setScore(pris.getRemainingTimeInMinutesInt()); boards.get(player.getUniqueId()).getObjective("test").getScore(time).setScore(pris.getRemainingTimeInMinutesInt());
} }
} }

View File

@ -14,9 +14,9 @@ import org.json.simple.JSONValue;
import com.graywolf336.jail.enums.Settings; import com.graywolf336.jail.enums.Settings;
public class Update { public class Update {
private JailMain plugin; private JailMain plugin;
// The project's unique ID // The project's unique ID
private static final int projectID = 31139; private static final int projectID = 31139;
// Static information for querying the API // Static information for querying the API
@ -29,23 +29,23 @@ public class Update {
private String fileUrl = "", version = ""; private String fileUrl = "", version = "";
public Update(JailMain plugin) { public Update(JailMain plugin) {
this.plugin = plugin; this.plugin = plugin;
} }
public void query() { public void query() {
String channel = plugin.getConfig().getString(Settings.UPDATECHANNEL.getPath(), "bukkit"); String channel = plugin.getConfig().getString(Settings.UPDATECHANNEL.getPath(), "bukkit");
URL url = null; URL url = null;
try { try {
if(channel.equalsIgnoreCase("stable-dev")) { if(channel.equalsIgnoreCase("stable-dev")) {
url = new URL(CI_STABLEDEV_API_QUERY); url = new URL(CI_STABLEDEV_API_QUERY);
}else if(channel.equalsIgnoreCase("dev")) { }else if(channel.equalsIgnoreCase("dev")) {
url = new URL(CI_DEV_API_QUERY); url = new URL(CI_DEV_API_QUERY);
}else { }else {
url = new URL(BUKKIT_API_QUERY); url = new URL(BUKKIT_API_QUERY);
} }
} catch (MalformedURLException e) { } catch (MalformedURLException e) {
plugin.getLogger().warning("The url for checking for an update was malformed, please open a ticket about this."); plugin.getLogger().warning("The url for checking for an update was malformed, please open a ticket about this.");
return; return;
} }
@ -62,30 +62,30 @@ public class Update {
String response = reader.readLine(); 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 // Parse the object from the response from the CI server
JSONObject obj = (JSONObject) JSONValue.parse(response); JSONObject obj = (JSONObject) JSONValue.parse(response);
// Get the latest build number // Get the latest build number
long number = Long.parseLong(obj.get("number").toString()); long number = Long.parseLong(obj.get("number").toString());
// Get the current running version // Get the current running version
String[] ver = plugin.getDescription().getVersion().split("-b"); String[] ver = plugin.getDescription().getVersion().split("-b");
// Let them know they're on a custom version when on build #0. // 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."); plugin.getLogger().info("You are using a custom version, you can disable update checking.");
} }
// Parse the current build number to a number // Parse the current build number to a number
long curr = Long.parseLong(ver[ver.length - 1]); long curr = Long.parseLong(ver[ver.length - 1]);
plugin.debug(number + " verus " + curr); plugin.debug(number + " verus " + curr);
// Check if the build on the CI server is higher than the one we're running // Check if the build on the CI server is higher than the one we're running
needed = number > curr; needed = number > curr;
// Alert the console that an update is needed, if it is needed // Alert the console that an update is needed, if it is needed
if(needed) { if(needed) {
this.version = obj.get("fullDisplayName").toString(); this.version = obj.get("fullDisplayName").toString();
this.fileUrl = obj.get("url").toString(); this.fileUrl = obj.get("url").toString();
plugin.getLogger().info("New development version of Jail is available: " + this.version); plugin.getLogger().info("New development version of Jail is available: " + this.version);
plugin.getLogger().info(this.fileUrl); plugin.getLogger().info(this.fileUrl);
} }
}else { }else {
// Parse the array of files from the query's response // Parse the array of files from the query's response
JSONArray array = (JSONArray) JSONValue.parse(response); JSONArray array = (JSONArray) JSONValue.parse(response);
@ -105,10 +105,10 @@ public class Update {
this.needed = this.versionCompare(remoteVer, currentVer) > 0; this.needed = this.versionCompare(remoteVer, currentVer) > 0;
if(needed) { if(needed) {
this.version = latest.get("name").toString(); this.version = latest.get("name").toString();
this.fileUrl = latest.get("fileUrl").toString(); this.fileUrl = latest.get("fileUrl").toString();
plugin.getLogger().info("New stable version of Jail is available: " + this.version); plugin.getLogger().info("New stable version of Jail is available: " + this.version);
plugin.getLogger().info(this.fileUrl); plugin.getLogger().info(this.fileUrl);
} }
} }
} }
@ -140,7 +140,7 @@ public class Update {
int i = 0; int i = 0;
// set index to first non-equal ordinal or length of shortest version string // set index to first non-equal ordinal or length of shortest version string
while (i < vals1.length && i < vals2.length && vals1[i].equals(vals2[i])) { while (i < vals1.length && i < vals2.length && vals1[i].equals(vals2[i])) {
i++; i++;
} }
// compare first non-equal ordinal number // compare first non-equal ordinal number
@ -157,16 +157,16 @@ public class Update {
/** Returns true if there is an update needed, false if not. */ /** Returns true if there is an update needed, false if not. */
public boolean isAvailable() { public boolean isAvailable() {
return this.needed; return this.needed;
} }
/** Returns the new version. */ /** Returns the new version. */
public String getNewVersion() { public String getNewVersion() {
return this.version; return this.version;
} }
/** Returns the new file url. */ /** Returns the new file url. */
public String getFileUrl() { public String getFileUrl() {
return this.fileUrl; return this.fileUrl;
} }
} }

View File

@ -32,25 +32,25 @@ import com.graywolf336.jail.beans.Prisoner;
* @version 3.0.0 * @version 3.0.0
*/ */
public class Util { 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 final static Pattern DURATION_PATTERN = Pattern.compile("^(\\d+)\\s*(m(?:inute)?s?|h(?:ours?)?|d(?:ays?)?|s(?:econd)?s?)?$", Pattern.CASE_INSENSITIVE);
/** /**
* Checks if the first {@link Vector} is inside this region. * Checks if the first {@link Vector} is inside this region.
* *
* @param point The point to check * @param point The point to check
* @param first point of the region * @param first point of the region
* @param second second 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. * @return True if all the coords of the first vector are in the entire region.
*/ */
public static boolean isInsideAB(Vector point, Vector first, Vector second) { public static boolean isInsideAB(Vector point, Vector first, Vector second) {
boolean x = isInside(point.getBlockX(), first.getBlockX(), second.getBlockX()); boolean x = isInside(point.getBlockX(), first.getBlockX(), second.getBlockX());
boolean y = isInside(point.getBlockY(), first.getBlockY(), second.getBlockY()); boolean y = isInside(point.getBlockY(), first.getBlockY(), second.getBlockY());
boolean z = isInside(point.getBlockZ(), first.getBlockZ(), second.getBlockZ()); boolean z = isInside(point.getBlockZ(), first.getBlockZ(), second.getBlockZ());
return x && y && z; return x && y && z;
} }
/** /**
* Checks if two numbers are inside a point, or something. * Checks if two numbers are inside a point, or something.
* *
* <p /> * <p />
@ -84,30 +84,30 @@ public class Util {
* @return true if the list contains the provided value, false if it doesn't * @return true if the list contains the provided value, false if it doesn't
*/ */
public static boolean isStringInsideList(List<String> list, String value) { public static boolean isStringInsideList(List<String> list, String value) {
for(String s : list) for(String s : list)
if(s.equalsIgnoreCase(value)) if(s.equalsIgnoreCase(value))
return true; return true;
return false; return false;
} }
/** Returns a colorful message from the color codes. */ /** Returns a colorful message from the color codes. */
public static String getColorfulMessage(String message) { public static String getColorfulMessage(String message) {
return message.replaceAll("(?i)&([0-9abcdefklmnor])", "\u00A7$1"); return message.replaceAll("(?i)&([0-9abcdefklmnor])", "\u00A7$1");
} }
/** Returns the wand used throughout the different creation steps. */ /** Returns the wand used throughout the different creation steps. */
public static ItemStack getWand() { public static ItemStack getWand() {
ItemStack wand = new ItemStack(Material.WOOD_SWORD); ItemStack wand = new ItemStack(Material.WOOD_SWORD);
ItemMeta meta = wand.getItemMeta(); ItemMeta meta = wand.getItemMeta();
meta.setDisplayName(ChatColor.AQUA + "Jail Wand"); meta.setDisplayName(ChatColor.AQUA + "Jail Wand");
LinkedList<String> lore = new LinkedList<String>(); LinkedList<String> lore = new LinkedList<String>();
lore.add(ChatColor.BLUE + "The wand for creating"); lore.add(ChatColor.BLUE + "The wand for creating");
lore.add(ChatColor.BLUE + "a jail or cell."); lore.add(ChatColor.BLUE + "a jail or cell.");
meta.setLore(lore); meta.setLore(lore);
wand.setItemMeta(meta); wand.setItemMeta(meta);
return wand; return wand;
} }
/** /**
@ -120,7 +120,7 @@ public class Util {
* @throws Exception if there are no matches * @throws Exception if there are no matches
*/ */
public static Long getTime(String time, TimeUnit unit) throws Exception { public static Long getTime(String time, TimeUnit unit) throws Exception {
return unit.convert(getTime(time), TimeUnit.MILLISECONDS); return unit.convert(getTime(time), TimeUnit.MILLISECONDS);
} }
/** /**
@ -131,33 +131,33 @@ public class Util {
* @throws Exception if there are no matches * @throws Exception if there are no matches
*/ */
public static Long getTime(String time) throws Exception { 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 = 10L;
Matcher match = DURATION_PATTERN.matcher(time); Matcher match = DURATION_PATTERN.matcher(time);
if (match.matches()) { if (match.matches()) {
String units = match.group(2); String units = match.group(2);
if ("seconds".equals(units) || "second".equals(units) || "s".equals(units)) 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.valueOf(match.group(1)), TimeUnit.SECONDS);
else if ("minutes".equals(units) || "minute".equals(units) || "mins".equals(units) || "min".equals(units) || "m".equals(units)) 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.valueOf(match.group(1)), TimeUnit.MINUTES);
else if ("hours".equals(units) || "hour".equals(units) || "h".equals(units)) else if ("hours".equals(units) || "hour".equals(units) || "h".equals(units))
t = TimeUnit.MILLISECONDS.convert(Long.valueOf(match.group(1)), TimeUnit.HOURS); t = TimeUnit.MILLISECONDS.convert(Long.valueOf(match.group(1)), TimeUnit.HOURS);
else if ("days".equals(units) || "day".equals(units) || "d".equals(units)) else if ("days".equals(units) || "day".equals(units) || "d".equals(units))
t = TimeUnit.MILLISECONDS.convert(Long.valueOf(match.group(1)), TimeUnit.DAYS); t = TimeUnit.MILLISECONDS.convert(Long.valueOf(match.group(1)), TimeUnit.DAYS);
else { else {
try { try {
t = TimeUnit.MILLISECONDS.convert(Long.parseLong(time), TimeUnit.MINUTES); t = TimeUnit.MILLISECONDS.convert(Long.parseLong(time), TimeUnit.MINUTES);
}catch(NumberFormatException e) { }catch(NumberFormatException e) {
throw new Exception("Invalid format."); throw new Exception("Invalid format.");
} }
} }
}else { }else {
throw new Exception("Invalid format."); throw new Exception("Invalid format.");
} }
return t; return t;
} }
/** /**
@ -168,11 +168,11 @@ public class Util {
* @throws IllegalStateException * @throws IllegalStateException
*/ */
public static String[] playerInventoryToBase64(PlayerInventory playerInventory) throws IllegalStateException { public static String[] playerInventoryToBase64(PlayerInventory playerInventory) throws IllegalStateException {
//get the main content part, this doesn't return the armor //get the main content part, this doesn't return the armor
String content = toBase64(playerInventory); String content = toBase64(playerInventory);
String armor = itemStackArrayToBase64(playerInventory.getArmorContents()); String armor = itemStackArrayToBase64(playerInventory.getArmorContents());
return new String[] { content, armor }; return new String[] { content, armor };
} }
/** /**
@ -188,7 +188,7 @@ public class Util {
* @throws IllegalStateException * @throws IllegalStateException
*/ */
public static String itemStackArrayToBase64(ItemStack[] items) throws IllegalStateException { public static String itemStackArrayToBase64(ItemStack[] items) throws IllegalStateException {
try { try {
ByteArrayOutputStream outputStream = new ByteArrayOutputStream(); ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
BukkitObjectOutputStream dataOutput = new BukkitObjectOutputStream(outputStream); BukkitObjectOutputStream dataOutput = new BukkitObjectOutputStream(outputStream);
@ -259,7 +259,7 @@ public class Util {
* @throws IOException * @throws IOException
*/ */
public static Inventory fromBase64(String data) throws IOException { public static Inventory fromBase64(String data) throws IOException {
if(data.isEmpty()) return Bukkit.getServer().createInventory(null, 0); if(data.isEmpty()) return Bukkit.getServer().createInventory(null, 0);
try { try {
ByteArrayInputStream inputStream = new ByteArrayInputStream(Base64Coder.decodeLines(data)); ByteArrayInputStream inputStream = new ByteArrayInputStream(Base64Coder.decodeLines(data));
@ -290,16 +290,16 @@ public class Util {
* @throws IOException * @throws IOException
*/ */
public static ItemStack[] itemStackArrayFromBase64(String data) throws IOException { public static ItemStack[] itemStackArrayFromBase64(String data) throws IOException {
if(data.isEmpty()) return new ItemStack[] {}; if(data.isEmpty()) return new ItemStack[] {};
try { try {
ByteArrayInputStream inputStream = new ByteArrayInputStream(Base64Coder.decodeLines(data)); ByteArrayInputStream inputStream = new ByteArrayInputStream(Base64Coder.decodeLines(data));
BukkitObjectInputStream dataInput = new BukkitObjectInputStream(inputStream); BukkitObjectInputStream dataInput = new BukkitObjectInputStream(inputStream);
ItemStack[] items = new ItemStack[dataInput.readInt()]; ItemStack[] items = new ItemStack[dataInput.readInt()];
// Read the serialized inventory // Read the serialized inventory
for (int i = 0; i < items.length; i++) { for (int i = 0; i < items.length; i++) {
items[i] = (ItemStack) dataInput.readObject(); items[i] = (ItemStack) dataInput.readObject();
} }
dataInput.close(); dataInput.close();
@ -309,38 +309,38 @@ public class Util {
} }
} }
public static void restoreInventory(Player player, Prisoner prisoner) { public static void restoreInventory(Player player, Prisoner prisoner) {
try { try {
Inventory content = Util.fromBase64(prisoner.getInventory()); Inventory content = Util.fromBase64(prisoner.getInventory());
ItemStack[] armor = Util.itemStackArrayFromBase64(prisoner.getArmor()); ItemStack[] armor = Util.itemStackArrayFromBase64(prisoner.getArmor());
for(ItemStack item : armor) { for(ItemStack item : armor) {
if(item == null) if(item == null)
continue; continue;
else if(item.getType().toString().toLowerCase().contains("helmet")) else if(item.getType().toString().toLowerCase().contains("helmet"))
player.getInventory().setHelmet(item); player.getInventory().setHelmet(item);
else if(item.getType().toString().toLowerCase().contains("chestplate")) else if(item.getType().toString().toLowerCase().contains("chestplate"))
player.getInventory().setChestplate(item); player.getInventory().setChestplate(item);
else if(item.getType().toString().toLowerCase().contains("leg")) else if(item.getType().toString().toLowerCase().contains("leg"))
player.getInventory().setLeggings(item); player.getInventory().setLeggings(item);
else if(item.getType().toString().toLowerCase().contains("boots")) else if(item.getType().toString().toLowerCase().contains("boots"))
player.getInventory().setBoots(item); player.getInventory().setBoots(item);
else if (player.getInventory().firstEmpty() == -1) else if (player.getInventory().firstEmpty() == -1)
player.getWorld().dropItem(player.getLocation(), item); player.getWorld().dropItem(player.getLocation(), item);
else else
player.getInventory().addItem(item); player.getInventory().addItem(item);
} }
for(ItemStack item : content.getContents()) { for(ItemStack item : content.getContents()) {
if(item == null) continue; if(item == null) continue;
else if(player.getInventory().firstEmpty() == -1) else if(player.getInventory().firstEmpty() == -1)
player.getWorld().dropItem(player.getLocation(), item); player.getWorld().dropItem(player.getLocation(), item);
else else
player.getInventory().addItem(item); player.getInventory().addItem(item);
} }
} catch (IOException e) { } catch (IOException e) {
e.printStackTrace(); e.printStackTrace();
Bukkit.getLogger().severe("Unable to restore " + player.getName() + "'s inventory."); Bukkit.getLogger().severe("Unable to restore " + player.getName() + "'s inventory.");
} }
} }
} }

View File

@ -8,21 +8,21 @@ package com.graywolf336.jail.beans;
* @version 1.0.0 * @version 1.0.0
*/ */
public class CachePrisoner { public class CachePrisoner {
private Jail jail; private Jail jail;
private Prisoner p; private Prisoner p;
public CachePrisoner(Jail jail, Prisoner prisoner) { public CachePrisoner(Jail jail, Prisoner prisoner) {
this.jail = jail; this.jail = jail;
this.p = prisoner; this.p = prisoner;
} }
/** Gets the Jail this cache is in. */ /** Gets the Jail this cache is in. */
public Jail getJail() { public Jail getJail() {
return this.jail; return this.jail;
} }
/** Gets the Prisoner in this cache. */ /** Gets the Prisoner in this cache. */
public Prisoner getPrisoner() { public Prisoner getPrisoner() {
return this.p; return this.p;
} }
} }

View File

@ -14,131 +14,131 @@ import org.bukkit.block.Chest;
* @version 1.1.2 * @version 1.1.2
*/ */
public class Cell { public class Cell {
private String name; private String name;
private Prisoner p; private Prisoner p;
private HashSet<SimpleLocation> signs; private HashSet<SimpleLocation> signs;
private SimpleLocation teleport, chest; private SimpleLocation teleport, chest;
/** Creates a new Cell with the given name /** Creates a new Cell with the given name
* *
* @param name The name of the cell. * @param name The name of the cell.
*/ */
public Cell(String name) { public Cell(String name) {
this.name = name; this.name = name;
this.signs = new HashSet<SimpleLocation>(); this.signs = new HashSet<SimpleLocation>();
} }
/** Gets the name of the cell. */ /** Gets the name of the cell. */
public String getName() { public String getName() {
return this.name; return this.name;
} }
/** Updates the signs of the cell, with the player name and time and such. TODO */ /** Updates the signs of the cell, with the player name and time and such. TODO */
public void update() { public void update() {
//TODO: Update the signs //TODO: Update the signs
} }
/** Sets the prisoner in this cell. */ /** Sets the prisoner in this cell. */
public void setPrisoner(Prisoner prisoner) { public void setPrisoner(Prisoner prisoner) {
this.p = prisoner; this.p = prisoner;
} }
/** Gets the prisoner being held in this cell. */ /** Gets the prisoner being held in this cell. */
public Prisoner getPrisoner() { public Prisoner getPrisoner() {
return this.p; return this.p;
} }
/** Nullifies the prisoner data. */ /** Nullifies the prisoner data. */
public void removePrisoner() { public void removePrisoner() {
this.p = null; this.p = null;
} }
/** Returns true if there is currently a prisoner in this cell. */ /** Returns true if there is currently a prisoner in this cell. */
public boolean hasPrisoner() { public boolean hasPrisoner() {
return this.p != null; //Return true if prison is not null, as when it isn't null we have a prisoner in this cell return this.p != null; //Return true if prison is not null, as when it isn't null we have a prisoner in this cell
} }
/** Adds all the given signs to the cell. */ /** Adds all the given signs to the cell. */
public void addAllSigns(HashSet<SimpleLocation> signs) { public void addAllSigns(HashSet<SimpleLocation> signs) {
this.signs.addAll(signs); this.signs.addAll(signs);
} }
/** Adds a sign to the cell. */ /** Adds a sign to the cell. */
public void addSign(SimpleLocation sign) { public void addSign(SimpleLocation sign) {
this.signs.add(sign); this.signs.add(sign);
} }
/** Returns all the signs for this cell. */ /** Returns all the signs for this cell. */
public HashSet<SimpleLocation> getSigns() { public HashSet<SimpleLocation> getSigns() {
return this.signs; return this.signs;
} }
/** Returns the entire list of signs in a string. */ /** Returns the entire list of signs in a string. */
public String getSignString() { public String getSignString() {
String r = ""; String r = "";
for(SimpleLocation s : signs) { for(SimpleLocation s : signs) {
if(r.isEmpty()) { if(r.isEmpty()) {
r = s.toString(); r = s.toString();
}else { }else {
r += ";" + s.toString(); r += ";" + s.toString();
} }
} }
return r; return r;
} }
/** Sets the location of where the prisoner will be teleported at when jailed here. */ /** Sets the location of where the prisoner will be teleported at when jailed here. */
public void setTeleport(SimpleLocation location) { public void setTeleport(SimpleLocation location) {
this.teleport = location; this.teleport = location;
} }
/** Gets the teleport location where the prisoner will be teleported at when jailed here. */ /** Gets the teleport location where the prisoner will be teleported at when jailed here. */
public Location getTeleport() { public Location getTeleport() {
return this.teleport.getLocation(); return this.teleport.getLocation();
} }
/** Sets the location of the chest. */ /** Sets the location of the chest. */
public void setChestLocation(Location location) { public void setChestLocation(Location location) {
this.chest = new SimpleLocation(location); this.chest = new SimpleLocation(location);
} }
/** /**
* Gets the location of the chest, returns null if no chest is stored at this cell. * Gets the location of the chest, returns null if no chest is stored at this cell.
* *
* @return The location of the chest, null if none. * @return The location of the chest, null if none.
*/ */
public Location getChestLocation() { public Location getChestLocation() {
return this.chest.getLocation(); return this.chest.getLocation();
} }
/** /**
* Gets the chest for this cell, returns null if there is no chest or the location we have is not a chest. * Gets the chest for this cell, returns null if there is no chest or the location we have is not a chest.
* *
* @return The chest and its state. * @return The chest and its state.
*/ */
public Chest getChest() { public Chest getChest() {
if(this.chest == null) return null; if(this.chest == null) return null;
if((this.chest.getLocation().getBlock() == null) || (this.chest.getLocation().getBlock().getType() != Material.CHEST)) return null; if((this.chest.getLocation().getBlock() == null) || (this.chest.getLocation().getBlock().getType() != Material.CHEST)) return null;
return (Chest) this.chest.getLocation().getBlock().getState(); return (Chest) this.chest.getLocation().getBlock().getState();
} }
/** /**
* Checks if the chest location doesn't equal null and if it is a double chest. * Checks if the chest location doesn't equal null and if it is a double chest.
* *
* @return true if there is a chest, false if there isn't. * @return true if there is a chest, false if there isn't.
*/ */
public boolean hasChest() { public boolean hasChest() {
Chest c = getChest(); Chest c = getChest();
if(c != null) { if(c != null) {
if(c.getInventory().getSize() >= 40) if(c.getInventory().getSize() >= 40)
return true; return true;
else { else {
Bukkit.getLogger().severe("The cell " + this.name + " has chest that isn't a double chest, please fix."); Bukkit.getLogger().severe("The cell " + this.name + " has chest that isn't a double chest, please fix.");
return false; return false;
} }
}else }else
return false; return false;
} }
} }

View File

@ -10,35 +10,35 @@ import com.graywolf336.jail.enums.Confirmation;
* @since 3.0.0 * @since 3.0.0
*/ */
public class ConfirmPlayer { public class ConfirmPlayer {
private String name; private String name;
private String[] args; private String[] args;
private Confirmation confirm; private Confirmation confirm;
private Long expires; private Long expires;
public ConfirmPlayer(String name, String[] args, Confirmation confirm) { public ConfirmPlayer(String name, String[] args, Confirmation confirm) {
this.name = name; this.name = name;
this.args = args; this.args = args;
this.confirm = confirm; this.confirm = confirm;
this.expires = System.currentTimeMillis() + 5000L; this.expires = System.currentTimeMillis() + 5000L;
} }
/** Returns the name of the thing needing to confirm. */ /** Returns the name of the thing needing to confirm. */
public String getName() { public String getName() {
return this.name; return this.name;
} }
/** Returns the initial arguments they sent with their command. */ /** Returns the initial arguments they sent with their command. */
public String[] getArguments() { public String[] getArguments() {
return this.args; return this.args;
} }
/** Returns what they are {@link Confirmation confirming}. */ /** Returns what they are {@link Confirmation confirming}. */
public Confirmation getConfirming() { public Confirmation getConfirming() {
return this.confirm; return this.confirm;
} }
/** Returns the time in milliseconds their confirmation time frame expires. */ /** Returns the time in milliseconds their confirmation time frame expires. */
public Long getExpiryTime() { public Long getExpiryTime() {
return this.expires; return this.expires;
} }
} }

View File

@ -14,214 +14,214 @@ import org.bukkit.Location;
* *
*/ */
public class CreationPlayer { public class CreationPlayer {
private String jailName, cellName; private String jailName, cellName;
private int step; private int step;
private int x1, y1, z1, x2, y2, z2; private int x1, y1, z1, x2, y2, z2;
private String inWorld, freeWorld; private String inWorld, freeWorld;
private double inX, inY, inZ, freeX, freeY, freeZ; private double inX, inY, inZ, freeX, freeY, freeZ;
private float inPitch, inYaw, freePitch, freeYaw; private float inPitch, inYaw, freePitch, freeYaw;
private HashSet<SimpleLocation> signs; private HashSet<SimpleLocation> signs;
private Location chest; private Location chest;
/** /**
* Create a new instance of a CreationPlayer, given the name of the jail. * Create a new instance of a CreationPlayer, given the name of the jail.
* *
* @param jailName The name of the jail. * @param jailName The name of the jail.
*/ */
public CreationPlayer(String jailName) { public CreationPlayer(String jailName) {
this.jailName = jailName; this.jailName = jailName;
this.step = 1; //Set the default to 1 when creating this. this.step = 1; //Set the default to 1 when creating this.
} }
/** /**
* Creates a new instance of a CreationPlayer, give the name of the jail and cell. * Creates a new instance of a CreationPlayer, give the name of the jail and cell.
* *
* @param jailName The name of the jail. * @param jailName The name of the jail.
* @param cellName The name of the cell. * @param cellName The name of the cell.
*/ */
public CreationPlayer(String jailName, String cellName) { public CreationPlayer(String jailName, String cellName) {
this.jailName = jailName; this.jailName = jailName;
this.cellName = cellName; this.cellName = cellName;
this.signs = new HashSet<SimpleLocation>(); this.signs = new HashSet<SimpleLocation>();
this.step = 1; this.step = 1;
} }
/** Gets the name of the jail. */ /** Gets the name of the jail. */
public String getJailName() { public String getJailName() {
return this.jailName; return this.jailName;
} }
/** Gets the name of the cell. */ /** Gets the name of the cell. */
public String getCellName() { public String getCellName() {
return this.cellName; return this.cellName;
} }
/** /**
* Returns the step the creation is in. * Returns the step the creation is in.
* *
* <p> * <p>
* *
* If it is a <strong>Jail</strong>, then when these numbers are returned it means the following: * If it is a <strong>Jail</strong>, then when these numbers are returned it means the following:
* <ol> * <ol>
* <li>Creating the first block of the Jail region.</li> * <li>Creating the first block of the Jail region.</li>
* <li>Creating the second block of the Jail region.</li> * <li>Creating the second block of the Jail region.</li>
* <li>Creating the teleport in location.</li> * <li>Creating the teleport in location.</li>
* <li>Creating the teleport out location.</li> * <li>Creating the teleport out location.</li>
* </ol> * </ol>
* *
* If it is a <strong>Cell</strong>, then when these numbers are returned it means the following: * If it is a <strong>Cell</strong>, then when these numbers are returned it means the following:
* <ol> * <ol>
* <li>Setting the teleport in location.</li> * <li>Setting the teleport in location.</li>
* <li>Setting all the signs.</li> * <li>Setting all the signs.</li>
* <li>Setting the double chest.</li> * <li>Setting the double chest.</li>
* </ol> * </ol>
* *
* @return The step of the Jail/Cell Creation, as an integer. * @return The step of the Jail/Cell Creation, as an integer.
*/ */
public int getStep() { public int getStep() {
return this.step; return this.step;
} }
/** /**
* Sets the step of the creation. * Sets the step of the creation.
* *
* @param step The state of the creation, see {@link #getStep() getStep} for more information. * @param step The state of the creation, see {@link #getStep() getStep} for more information.
*/ */
public void setStep(int step) { public void setStep(int step) {
this.step = step; this.step = step;
} }
/** /**
* Increments the current step up one. * Increments the current step up one.
* *
* <p> * <p>
* *
* <em>Notice:</em> Using this method can cause the step to go above four (three for cell), * <em>Notice:</em> 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 * 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). * be used again or you know for a fact that the next step is not above four (three for cell).
* *
*/ */
public void nextStep() { public void nextStep() {
this.step++; this.step++;
} }
/** Sets the first corner with the given location. */ /** Sets the first corner with the given location. */
public void setCornerOne(Location loc) { public void setCornerOne(Location loc) {
this.x1 = loc.getBlockX(); this.x1 = loc.getBlockX();
this.y1 = loc.getBlockY(); this.y1 = loc.getBlockY();
this.z1 = loc.getBlockZ(); this.z1 = loc.getBlockZ();
} }
/** Sets the first corner with the given x, y, and z. */ /** Sets the first corner with the given x, y, and z. */
public void setCornerOne(int x, int y, int z) { public void setCornerOne(int x, int y, int z) {
this.x1 = x; this.x1 = x;
this.y1 = y; this.y1 = y;
this.z1 = z; this.z1 = z;
} }
/** Returns the <strong>first corner</strong> coords an array of int. <strong>0 = x</strong>, <strong>1 = y</strong>, <strong>2 = z</strong> */ /** Returns the <strong>first corner</strong> coords an array of int. <strong>0 = x</strong>, <strong>1 = y</strong>, <strong>2 = z</strong> */
public int[] getCornerOne() { public int[] getCornerOne() {
int[] t = {x1, y1, z1}; int[] t = {x1, y1, z1};
return t; return t;
} }
/** Sets the second corner with the given location. */ /** Sets the second corner with the given location. */
public void setCornerTwo(Location loc) { public void setCornerTwo(Location loc) {
this.x2 = loc.getBlockX(); this.x2 = loc.getBlockX();
this.y2 = loc.getBlockY(); this.y2 = loc.getBlockY();
this.z2 = loc.getBlockZ(); 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. */
public void setCornerTwo(int x, int y, int z) { public void setCornerTwo(int x, int y, int z) {
this.x2 = x; this.x2 = x;
this.y2 = y; this.y2 = y;
this.z2 = z; this.z2 = z;
} }
/** Returns the <strong>second corner</strong> coords an array of int. <strong>0 = x</strong>, <strong>1 = y</strong>, <strong>2 = z</strong> */ /** Returns the <strong>second corner</strong> coords an array of int. <strong>0 = x</strong>, <strong>1 = y</strong>, <strong>2 = z</strong> */
public int[] getCornerTwo() { public int[] getCornerTwo() {
int[] t = {x2, y2, z2}; int[] t = {x2, y2, z2};
return t; return t;
} }
/** Sets the teleport in coords from the given location. */ /** Sets the teleport in coords from the given location. */
public void setTeleportIn(Location location) { public void setTeleportIn(Location location) {
this.inWorld = location.getWorld().getName(); this.inWorld = location.getWorld().getName();
this.inX = location.getX(); this.inX = location.getX();
this.inY = location.getY(); this.inY = location.getY();
this.inZ = location.getZ(); this.inZ = location.getZ();
this.inYaw = location.getYaw(); this.inYaw = location.getYaw();
this.inPitch = location.getPitch(); this.inPitch = location.getPitch();
} }
/** Sets the teleport in coords from the given params. */ /** Sets the teleport in coords from the given params. */
public void setTeleportIn(String world, double x, double y, double z, float yaw, float pitch) { public void setTeleportIn(String world, double x, double y, double z, float yaw, float pitch) {
this.inWorld = world; this.inWorld = world;
this.inX = x; this.inX = x;
this.inY = y; this.inY = y;
this.inZ = z; this.inZ = z;
this.inYaw = yaw; this.inYaw = yaw;
this.inPitch = pitch; this.inPitch = pitch;
} }
/** Gets the teleport in location in a {@link Location}. */ /** Gets the teleport in location in a {@link Location}. */
public Location getTeleportIn() { public Location getTeleportIn() {
return new Location(Bukkit.getWorld(inWorld), inX, inY, inZ, inYaw, inPitch); return new Location(Bukkit.getWorld(inWorld), inX, inY, inZ, inYaw, inPitch);
} }
/** Gets the teleport in location in a {@link SimpleLocation}. */ /** Gets the teleport in location in a {@link SimpleLocation}. */
public SimpleLocation getTeleportInSL() { public SimpleLocation getTeleportInSL() {
return new SimpleLocation(inWorld, inX, inY, inZ, inYaw, inPitch); return new SimpleLocation(inWorld, inX, inY, inZ, inYaw, inPitch);
} }
/** Sets the teleport free coords from the given location. */ /** Sets the teleport free coords from the given location. */
public void setTeleportFree(Location location) { public void setTeleportFree(Location location) {
this.freeWorld = location.getWorld().getName(); this.freeWorld = location.getWorld().getName();
this.freeX = location.getX(); this.freeX = location.getX();
this.freeY = location.getY(); this.freeY = location.getY();
this.freeZ = location.getZ(); this.freeZ = location.getZ();
this.freeYaw = location.getYaw(); this.freeYaw = location.getYaw();
this.freePitch = location.getPitch(); this.freePitch = location.getPitch();
} }
/** Sets the teleport in coords from the given params. */ /** Sets the teleport in coords from the given params. */
public void setTeleportFree(String world, double x, double y, double z, float yaw, float pitch) { public void setTeleportFree(String world, double x, double y, double z, float yaw, float pitch) {
this.freeWorld = world; this.freeWorld = world;
this.freeX = x; this.freeX = x;
this.freeY = y; this.freeY = y;
this.freeZ = z; this.freeZ = z;
this.freeYaw = yaw; this.freeYaw = yaw;
this.freePitch = pitch; this.freePitch = pitch;
} }
/** Gets the teleport free location in a {@link Location}. */ /** Gets the teleport free location in a {@link Location}. */
public Location getTeleportFree() { public Location getTeleportFree() {
return new Location(Bukkit.getWorld(freeWorld), freeX, freeY, freeZ, freeYaw, freePitch); return new Location(Bukkit.getWorld(freeWorld), freeX, freeY, freeZ, freeYaw, freePitch);
} }
/** Gets the teleport free location in a {@link SimpleLocation}. */ /** Gets the teleport free location in a {@link SimpleLocation}. */
public SimpleLocation getTeleportFreeSL() { public SimpleLocation getTeleportFreeSL() {
return new SimpleLocation(freeWorld, freeX, freeY, freeZ, freeYaw, freePitch); return new SimpleLocation(freeWorld, freeX, freeY, freeZ, freeYaw, freePitch);
} }
/** Adds a sign to this cell. */ /** Adds a sign to this cell. */
public void addSign(SimpleLocation sign) { public void addSign(SimpleLocation sign) {
this.signs.add(sign); this.signs.add(sign);
} }
/** Returns all the signs, null if none (usually null when a jail is being created). */ /** Returns all the signs, null if none (usually null when a jail is being created). */
public HashSet<SimpleLocation> getSigns() { public HashSet<SimpleLocation> getSigns() {
return this.signs == null ? null : new HashSet<SimpleLocation>(this.signs); return this.signs == null ? null : new HashSet<SimpleLocation>(this.signs);
} }
/** Sets the chest's location, used mainly for cells. */ /** Sets the chest's location, used mainly for cells. */
public void setChestLocation(Location loc) { public void setChestLocation(Location loc) {
this.chest = loc; this.chest = loc;
} }
/** Gets the chest's location. */ /** Gets the chest's location. */
public Location getChestLocation() { public Location getChestLocation() {
return this.chest; return this.chest;
} }
} }

View File

@ -20,375 +20,375 @@ import com.graywolf336.jail.Util;
* @version 1.0.3 * @version 1.0.3
*/ */
public class Jail { public class Jail {
private JailMain plugin; private JailMain plugin;
private boolean enabled; private boolean enabled;
private HashMap<String, Cell> cells; private HashMap<String, Cell> cells;
private HashMap<UUID, Prisoner> nocellPrisoners;//prisoners who aren't in a cell private HashMap<UUID, Prisoner> 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 int minX, minY, minZ, maxX, maxY, maxZ;
private Location in, free; private Location in, free;
public Jail(JailMain plugin, String name) { public Jail(JailMain plugin, String name) {
this.plugin = plugin; this.plugin = plugin;
this.enabled = true; this.enabled = true;
this.name = name; this.name = name;
cells = new HashMap<String, Cell>(); cells = new HashMap<String, Cell>();
nocellPrisoners = new HashMap<UUID, Prisoner>(); nocellPrisoners = new HashMap<UUID, Prisoner>();
} }
/** Gets the instance of the plugin's main class. */ /** Gets the instance of the plugin's main class. */
public JailMain getPlugin() { public JailMain getPlugin() {
return this.plugin; return this.plugin;
} }
/** Sets whether this jail can be used or not. */ /** Sets whether this jail can be used or not. */
public void setEnabled(boolean enabled) { public void setEnabled(boolean enabled) {
this.enabled = enabled; this.enabled = enabled;
} }
/** Gets whether this jail is enabled or not. */ /** Gets whether this jail is enabled or not. */
public boolean isEnabled() { public boolean isEnabled() {
return this.enabled; return this.enabled;
} }
/** Sets the name of the jail. */ /** Sets the name of the jail. */
public void setName(String name) { public void setName(String name) {
this.name = name; this.name = name;
} }
/** Gets the name of the jail. */ /** Gets the name of the jail. */
public String getName() { public String getName() {
return this.name; return this.name;
} }
/** Sets the location of the <b>minimum</b> point to the given location's coordinates. */ /** Sets the location of the <b>minimum</b> point to the given location's coordinates. */
public void setMinPoint(Location location) { 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.minX = location.getBlockX();
this.minY = location.getBlockY(); this.minY = location.getBlockY();
this.minZ = location.getBlockZ(); this.minZ = location.getBlockZ();
} }
/** Accepts an array of ints as the coord, where <strong>0 = x</strong>, <strong>1 = y</strong>, <strong>2 = z</strong>. */ /** Accepts an array of ints as the coord, where <strong>0 = x</strong>, <strong>1 = y</strong>, <strong>2 = z</strong>. */
public void setMinPoint(int[] coords) { public void setMinPoint(int[] coords) {
if(coords.length != 3) return; if(coords.length != 3) return;
this.minX = coords[0]; this.minX = coords[0];
this.minY = coords[1]; this.minY = coords[1];
this.minZ = coords[2]; this.minZ = coords[2];
} }
/** Gets the minimum point as a Bukkit Location class. */ /** Gets the minimum point as a Bukkit Location class. */
public Location getMinPoint() { public Location getMinPoint() {
return new Location(plugin.getServer().getWorld(world), minX, minY, minZ); return new Location(plugin.getServer().getWorld(world), minX, minY, minZ);
} }
/** Sets the location of the <b>maximum</b> point to the given location's coordinates. */ /** Sets the location of the <b>maximum</b> point to the given location's coordinates. */
public void setMaxPoint(Location location) { 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.maxX = location.getBlockX();
this.maxY = location.getBlockY(); this.maxY = location.getBlockY();
this.maxZ = location.getBlockZ(); this.maxZ = location.getBlockZ();
} }
/** Gets the minimum point as a Bukkit Location class. */ /** Gets the minimum point as a Bukkit Location class. */
public Location getMaxPoint() { public Location getMaxPoint() {
return new Location(plugin.getServer().getWorld(world), maxX, maxY, maxZ); return new Location(plugin.getServer().getWorld(world), maxX, maxY, maxZ);
} }
/** Accepts an array of ints as the coord, where <strong>0 = x</strong>, <strong>1 = y</strong>, <strong>2 = z</strong>. */ /** Accepts an array of ints as the coord, where <strong>0 = x</strong>, <strong>1 = y</strong>, <strong>2 = z</strong>. */
public void setMaxPoint(int[] coords) { public void setMaxPoint(int[] coords) {
if(coords.length != 3) return; if(coords.length != 3) return;
this.maxX = coords[0]; this.maxX = coords[0];
this.maxY = coords[1]; this.maxY = coords[1];
this.maxZ = coords[2]; 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) { public void setWorld(String name) {
this.world = 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() { public String getWorldName() {
return this.world; 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() { public World getWorld() {
return plugin.getServer().getWorld(world); return plugin.getServer().getWorld(world);
} }
/** Sets the {@link Location location} of the teleport <strong>in</strong>. */ /** Sets the {@link Location location} of the teleport <strong>in</strong>. */
public void setTeleportIn(Location location) { 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; this.in = location;
} }
/** Gets the {@link Location location} of the teleport in. */ /** Gets the {@link Location location} of the teleport in. */
public Location getTeleportIn() { public Location getTeleportIn() {
return this.in; return this.in;
} }
/** Sets the {@link Location location} of the teleport for the <strong>free</strong> spot. */ /** Sets the {@link Location location} of the teleport for the <strong>free</strong> spot. */
public void setTeleportFree(Location location) { public void setTeleportFree(Location location) {
this.free = 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() { public Location getTeleportFree() {
return this.free; return this.free;
} }
/** Add a prisoner to this jail. */ /** Add a prisoner to this jail. */
public void addPrisoner(Prisoner p) { public void addPrisoner(Prisoner p) {
this.nocellPrisoners.put(p.getUUID(), 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) { public void removePrisoner(Prisoner p) {
this.nocellPrisoners.remove(p.getUUID()); this.nocellPrisoners.remove(p.getUUID());
} }
/** Adds a cell to the Jail. */ /** Adds a cell to the Jail. */
public void addCell(Cell cell, boolean save) { public void addCell(Cell cell, boolean save) {
if(save) plugin.getJailIO().saveCell(this, cell); if(save) plugin.getJailIO().saveCell(this, cell);
this.cells.put(cell.getName(), cell); this.cells.put(cell.getName(), cell);
} }
/** Gets the cell with the given name. */ /** Gets the cell with the given name. */
public Cell getCell(String name) { public Cell getCell(String name) {
return this.cells.get(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) { public boolean isValidCell(String name) {
return this.cells.get(name) != null; return this.cells.get(name) != null;
} }
/** Removes the cell from the jail. */ /** Removes the cell from the jail. */
public void removeCell(String name) { public void removeCell(String name) {
Cell c = this.cells.get(name); Cell c = this.cells.get(name);
//If we have a chest, clear the inventory //If we have a chest, clear the inventory
if(c.hasChest()) { if(c.hasChest()) {
c.getChest().getInventory().clear(); c.getChest().getInventory().clear();
} }
//For each sign, clear the lines on the sign //For each sign, clear the lines on the sign
for(SimpleLocation s : c.getSigns()) { for(SimpleLocation s : c.getSigns()) {
if(s.getLocation().getBlock() instanceof Sign) { if(s.getLocation().getBlock() instanceof Sign) {
Sign sign = (Sign) s.getLocation().getBlock(); Sign sign = (Sign) s.getLocation().getBlock();
for(int i = 0; i < 4; i++) { for(int i = 0; i < 4; i++) {
sign.setLine(i, ""); sign.setLine(i, "");
} }
} }
} }
//remove the information from the storage first as it requires an instance //remove the information from the storage first as it requires an instance
plugin.getJailIO().removeCell(this, c); plugin.getJailIO().removeCell(this, c);
//now remove it from the local storage //now remove it from the local storage
this.cells.remove(name); 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) { public Cell getCellPrisonerIsIn(UUID uuid) {
for(Cell c : cells.values()) for(Cell c : cells.values())
if(c.hasPrisoner()) if(c.hasPrisoner())
if(c.getPrisoner().getUUID().equals(uuid)) if(c.getPrisoner().getUUID().equals(uuid))
return c; return c;
return null; 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() { public Cell getFirstEmptyCell() {
for(Cell c : getCells()) for(Cell c : getCells())
if(c.hasPrisoner()) if(c.hasPrisoner())
continue; continue;
else else
return c; return c;
return null; return null;
} }
/** Gets the amount of cells the jail. */ /** Gets the amount of cells the jail. */
public int getCellCount() { public int getCellCount() {
return this.cells.size(); return this.cells.size();
} }
/** Gets all the cells in the jail. */ /** Gets all the cells in the jail. */
public HashSet<Cell> getCells() { public HashSet<Cell> getCells() {
return new HashSet<Cell>(this.cells.values()); return new HashSet<Cell>(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) { public Cell getNearestCell(Location loc) {
Cell cell = null; Cell cell = null;
double distance = -1; 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 //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 //They are in the same world
double dist = c.getTeleport().distance(loc); double dist = c.getTeleport().distance(loc);
if (dist < distance || distance < 0) { if (dist < distance || distance < 0) {
cell = c; cell = c;
distance = dist; distance = dist;
} }
}else { }else {
//If they aren't, return the first cell found. //If they aren't, return the first cell found.
return c; return c;
} }
} }
return cell; return cell;
} }
/** Clears all the prisoners from this Jail. */ /** Clears all the prisoners from this Jail. */
public void clearPrisoners() { public void clearPrisoners() {
//Remove the prisoners from all the cells //Remove the prisoners from all the cells
for(Cell c : getCells()) { for(Cell c : getCells()) {
c.removePrisoner(); c.removePrisoner();
} }
//Replace all the current no cell prisoners with //Replace all the current no cell prisoners with
//a new hashset of prisoners. //a new hashset of prisoners.
this.nocellPrisoners = new HashMap<UUID, Prisoner>(); this.nocellPrisoners = new HashMap<UUID, Prisoner>();
} }
/** Gets a HashMap of <b>all</b> the prisoners, the ones in cells and ones who aren't. */ /** Gets a HashMap of <b>all</b> the prisoners, the ones in cells and ones who aren't. */
public HashMap<UUID, Prisoner> getAllPrisoners() { public HashMap<UUID, Prisoner> getAllPrisoners() {
HashMap<UUID, Prisoner> all = new HashMap<UUID, Prisoner>(nocellPrisoners); //initalize the temp one to return with the prisoners not in any cells HashMap<UUID, Prisoner> all = new HashMap<UUID, Prisoner>(nocellPrisoners); //initalize the temp one to return with the prisoners not in any cells
for(Cell c : cells.values()) for(Cell c : cells.values())
if(c.hasPrisoner()) if(c.hasPrisoner())
all.put(c.getPrisoner().getUUID(), c.getPrisoner()); all.put(c.getPrisoner().getUUID(), c.getPrisoner());
return all; return all;
} }
/** Gets a HashSet of the prisoners <b>in cells</b>. */ /** Gets a HashSet of the prisoners <b>in cells</b>. */
public HashSet<Prisoner> getPrisonersInCells() { public HashSet<Prisoner> getPrisonersInCells() {
HashSet<Prisoner> all = new HashSet<Prisoner>(); HashSet<Prisoner> all = new HashSet<Prisoner>();
for(Cell c : getCells()) for(Cell c : getCells())
if(c.hasPrisoner()) if(c.hasPrisoner())
all.add(c.getPrisoner()); all.add(c.getPrisoner());
return all; return all;
} }
/** Gets a HashSet of the prisoners <b>not</b> in cells.*/ /** Gets a HashSet of the prisoners <b>not</b> in cells.*/
public HashMap<UUID, Prisoner> getPrisonersNotInCells() { public HashMap<UUID, Prisoner> getPrisonersNotInCells() {
return this.nocellPrisoners; return this.nocellPrisoners;
} }
/** /**
* Returns whether the player is a prisoner in the system, whether in a cell or no cell. * 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. * @param player The {@link Player player instance} of the person we're checking.
* @return true if is jailed, false if not. * @return true if is jailed, false if not.
*/ */
public boolean isPlayerJailed(Player player) { public boolean isPlayerJailed(Player player) {
return this.isPlayerAPrisoner(player.getUniqueId()); return this.isPlayerAPrisoner(player.getUniqueId());
} }
/** /**
* Returns whether the uuid of a player is a prisoner in the system, whether in a cell or no cell. * 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. * @param uuid The uuid of the person we're checking.
* @return true if is jailed, false if not. * @return true if is jailed, false if not.
*/ */
public boolean isPlayerJailed(UUID uuid) { public boolean isPlayerJailed(UUID uuid) {
return this.isPlayerAPrisoner(uuid); return this.isPlayerAPrisoner(uuid);
} }
/** /**
* Returns whether the uuid of a player is a prisoner in this jail, no matter if they're in a cell or not. * 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. * @param uuid The name of the person we're checking.
* @return true if is a prisoner, false if not. * @return true if is a prisoner, false if not.
*/ */
private boolean isPlayerAPrisoner(UUID uuid) { private boolean isPlayerAPrisoner(UUID uuid) {
return this.getAllPrisoners().containsKey(uuid); return this.getAllPrisoners().containsKey(uuid);
} }
/** /**
* Checks if the given uuid of a player is a prisoner in a cell. * Checks if the given uuid of a player is a prisoner in a cell.
* *
* @param uuid of the prisoner to check. * @param uuid of the prisoner to check.
* @return true if is jailed in a cell, false if not. * @return true if is jailed in a cell, false if not.
*/ */
public boolean isJailedInACell(UUID uuid) { public boolean isJailedInACell(UUID uuid) {
if(this.nocellPrisoners.containsKey(uuid)) return false; if(this.nocellPrisoners.containsKey(uuid)) return false;
for(Cell c : cells.values()) for(Cell c : cells.values())
if(c.getPrisoner() != null) if(c.getPrisoner() != null)
if(c.getPrisoner().getUUID().equals(uuid)) if(c.getPrisoner().getUUID().equals(uuid))
return true; return true;
return false; return false;
} }
/** /**
* Gets the {@link Prisoner prisoner} instance for the given name. * Gets the {@link Prisoner prisoner} instance for the given name.
* *
* @param name The name of the prisoner to get. * @param name The name of the prisoner to get.
* @return the prisoner instance, can be null * @return the prisoner instance, can be null
*/ */
public Prisoner getPrisonerByLastKnownName(String name) { public Prisoner getPrisonerByLastKnownName(String name) {
for(Prisoner p : this.getAllPrisoners().values()) for(Prisoner p : this.getAllPrisoners().values())
if(p.getLastKnownName().equalsIgnoreCase(name)) if(p.getLastKnownName().equalsIgnoreCase(name))
return p; return p;
return null; return null;
} }
/** /**
* Gets the {@link Prisoner prisoner} instance for the given uuid. * Gets the {@link Prisoner prisoner} instance for the given uuid.
* *
* @param uuid The uuid of the prisoner to get. * @param uuid The uuid of the prisoner to get.
* @return the prisoner instance, can be null * @return the prisoner instance, can be null
*/ */
public Prisoner getPrisoner(UUID uuid) { 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()) for(Cell c : cells.values())
if(c.hasPrisoner()) if(c.hasPrisoner())
if(c.getPrisoner().getUUID().equals(uuid)) if(c.getPrisoner().getUUID().equals(uuid))
return c.getPrisoner(); return c.getPrisoner();
return null; return null;
} }
/** /**
* Returns the squared distance between teleport location of this jail * Returns the squared distance between teleport location of this jail
* and specified location in blocks. If locations are not in same world, * and specified location in blocks. If locations are not in same world,
* distance cannot be calculated and it will return Integer.MAX_VALUE. * distance cannot be calculated and it will return Integer.MAX_VALUE.
* *
* @param loc The location to check * @param loc The location to check
* @return Distance between the location provided and the teleport in location. * @return Distance between the location provided and the teleport in location.
*/ */
public double getDistance(Location loc) { public double getDistance(Location loc) {
if (!loc.getWorld().getName().equalsIgnoreCase(getTeleportIn().getWorld().getName())) return (double) Integer.MAX_VALUE; if (!loc.getWorld().getName().equalsIgnoreCase(getTeleportIn().getWorld().getName())) return Integer.MAX_VALUE;
else return loc.distance(getTeleportIn()); else return loc.distance(getTeleportIn());
} }
/** /**
* Returns whether the given location is inside this Jail. * Returns whether the given location is inside this Jail.
* *
* @param loc to check whether 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 * @return True if the location is in the jail, false if it isn't
*/ */
public boolean isInside(Location loc) { 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)); return Util.isInsideAB(loc.toVector(), new Vector(minX, minY, minZ), new Vector(maxX, maxY, maxZ));
}else { }else {
return false; return false;
} }
} }
} }

View File

@ -15,273 +15,273 @@ import org.bukkit.Location;
* @version 3.0.2 * @version 3.0.2
*/ */
public class Prisoner { public class Prisoner {
private String uuid, name, jailer, reason, inventory, armor; private String uuid, name, jailer, reason, inventory, armor;
private boolean muted, offlinePending, teleporting, toBeTransferred, changed; private boolean muted, offlinePending, teleporting, toBeTransferred, changed;
private long time, afk; private long time, afk;
private Location previousPosition; private Location previousPosition;
private GameMode previousGameMode; private GameMode previousGameMode;
/** /**
* Creates a new prisoner with a name and whether they are muted or not. * Creates a new prisoner with a name and whether they are muted or not.
* *
* @param uuid The uuid of the prisoner * @param uuid The uuid of the prisoner
* @param name The name of the prisoner * @param name The name of the prisoner
* @param muted Whether the prisoner is muted or not * @param muted Whether the prisoner is muted or not
* @param time The amount of remaining time the prisoner has * @param time The amount of remaining time the prisoner has
* @param jailer The name of the person who jailed this prisoner * @param jailer The name of the person who jailed this prisoner
* @param reason The reason why this prisoner is in jail * @param reason The reason why this prisoner is in jail
*/ */
public Prisoner(String uuid, String name, boolean muted, long time, String jailer, String reason) { public Prisoner(String uuid, String name, boolean muted, long time, String jailer, String reason) {
this.uuid = uuid; this.uuid = uuid;
this.name = name; this.name = name;
this.muted = muted; this.muted = muted;
this.time = time; this.time = time;
this.jailer = jailer; this.jailer = jailer;
this.reason = reason; this.reason = reason;
this.offlinePending = false; this.offlinePending = false;
this.teleporting = false; this.teleporting = false;
this.toBeTransferred = false; this.toBeTransferred = false;
this.previousPosition = null; this.previousPosition = null;
this.previousGameMode = GameMode.SURVIVAL; this.previousGameMode = GameMode.SURVIVAL;
this.inventory = ""; this.inventory = "";
this.armor = ""; this.armor = "";
this.afk = 0; this.afk = 0;
this.changed = false; this.changed = false;
} }
/** Returns the UUID of the prisoner. */ /** Returns the UUID of the prisoner. */
public UUID getUUID() { public UUID getUUID() {
return UUID.fromString(this.uuid); return UUID.fromString(this.uuid);
} }
/** Gets the name of this prisoner. */ /** Gets the name of this prisoner. */
public String getLastKnownName() { public String getLastKnownName() {
return this.name; return this.name;
} }
/** Sets the name of this prisoner. */ /** Sets the name of this prisoner. */
public String setLastKnownName(String username) { public String setLastKnownName(String username) {
this.name = username; this.name = username;
this.changed = true; this.changed = true;
return this.name; return this.name;
} }
/** Gets the reason this player was jailed for. */ /** Gets the reason this player was jailed for. */
public String getReason() { public String getReason() {
return this.reason; return this.reason;
} }
/** /**
* Sets the reason this player was jailed for. * Sets the reason this player was jailed for.
* *
* @param reason the player was jailed. * @param reason the player was jailed.
* @return the reason the player was jailed, what we have stored about them. * @return the reason the player was jailed, what we have stored about them.
*/ */
public String setReason(String reason) { public String setReason(String reason) {
this.reason = reason; this.reason = reason;
this.changed = true; this.changed = true;
return this.reason; return this.reason;
} }
/** Gets the person who jailed this prisoner. */ /** Gets the person who jailed this prisoner. */
public String getJailer() { public String getJailer() {
return this.jailer; return this.jailer;
} }
/** Sets the person who jailed this prisoner. */ /** Sets the person who jailed this prisoner. */
public void setJailer(String jailer) { public void setJailer(String jailer) {
this.jailer = jailer; this.jailer = jailer;
this.changed = true; this.changed = true;
} }
/** Gets whether the prisoner is muted or not. */ /** Gets whether the prisoner is muted or not. */
public boolean isMuted() { public boolean isMuted() {
return this.muted; return this.muted;
} }
/** Sets whether the prisoner is muted or not. */ /** Sets whether the prisoner is muted or not. */
public void setMuted(boolean muted) { public void setMuted(boolean muted) {
this.muted = muted; this.muted = muted;
this.changed = true; this.changed = true;
} }
/** Gets the remaining time the prisoner has. */ /** Gets the remaining time the prisoner has. */
public long getRemainingTime() { public long getRemainingTime() {
return this.time; return this.time;
} }
/** Gets the remaining time the prisoner has in minutes. */ /** Gets the remaining time the prisoner has in minutes. */
public long getRemainingTimeInMinutes() { public long getRemainingTimeInMinutes() {
return TimeUnit.MINUTES.convert(time, TimeUnit.MILLISECONDS); 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() { public int getRemainingTimeInMinutesInt() {
return (int) this.getRemainingTimeInMinutes(); return (int) this.getRemainingTimeInMinutes();
} }
/** /**
* Sets the remaining time the prisoner has left. * Sets the remaining time the prisoner has left.
* *
* @param time The amount of time left, in milliseconds. * @param time The amount of time left, in milliseconds.
*/ */
public void setRemainingTime(long time) { public void setRemainingTime(long time) {
this.time = time; this.time = time;
this.changed = true; this.changed = true;
} }
/** /**
* Adds the given time to the remaining time the prisoner has left. * Adds the given time to the remaining time the prisoner has left.
* *
* @param time to add to the prisoner's remaining time. * @param time to add to the prisoner's remaining time.
* @return the new remaining time the prisoner has * @return the new remaining time the prisoner has
*/ */
public long addTime(long time) { public long addTime(long time) {
this.time += time; this.time += time;
this.changed = true; this.changed = true;
return this.time; return this.time;
} }
/** /**
* Subtracts the given time from the remaining time the prisoner has left. * Subtracts the given time from the remaining time the prisoner has left.
* *
* @param time to subtract from the prisoner's remaining time. * @param time to subtract from the prisoner's remaining time.
* @return the new remaining time the prisoner has * @return the new remaining time the prisoner has
*/ */
public long subtractTime(long time) { public long subtractTime(long time) {
this.time -= time; this.time -= time;
this.changed = true; this.changed = true;
return this.time; return this.time;
} }
/** Gets whether the player is offline or not. */ /** Gets whether the player is offline or not. */
public boolean isOfflinePending() { public boolean isOfflinePending() {
return this.offlinePending; return this.offlinePending;
} }
/** Sets whether the player is offline or not. */ /** Sets whether the player is offline or not. */
public void setOfflinePending(boolean offline) { public void setOfflinePending(boolean offline) {
this.offlinePending = offline; this.offlinePending = offline;
this.changed = true; this.changed = true;
} }
/** Gets whether the player is being teleported or not. */ /** Gets whether the player is being teleported or not. */
public boolean isTeleporting() { public boolean isTeleporting() {
return this.teleporting; 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) { public void setTeleporting(boolean teleport) {
this.teleporting = 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() { public boolean isToBeTransferred() {
return this.toBeTransferred; 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) { public void setToBeTransferred(boolean transferred) {
this.toBeTransferred = transferred; this.toBeTransferred = transferred;
this.changed = true; 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() { public Location getPreviousLocation() {
return this.previousPosition; 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() { public String getPreviousLocationString() {
if(previousPosition == null) return ""; if(previousPosition == null) return "";
else if(previousPosition.getWorld() == null) return ""; else if(previousPosition.getWorld() == null) return "";
else return previousPosition.getWorld().getName() + "," + else return previousPosition.getWorld().getName() + "," +
previousPosition.getX() + "," + previousPosition.getX() + "," +
previousPosition.getY() + "," + previousPosition.getY() + "," +
previousPosition.getZ() + "," + previousPosition.getZ() + "," +
previousPosition.getYaw() + "," + previousPosition.getYaw() + "," +
previousPosition.getPitch(); previousPosition.getPitch();
} }
/** Sets the previous location of this player. */ /** Sets the previous location of this player. */
public void setPreviousPosition(Location location) { public void setPreviousPosition(Location location) {
this.previousPosition = 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) { public void setPreviousPosition(String location) {
if(location == null) return; if(location == null) return;
if(location.isEmpty()) return; if(location.isEmpty()) return;
this.changed = true; this.changed = true;
String[] s = location.split(","); String[] s = location.split(",");
this.previousPosition = new Location(Bukkit.getWorld(s[0]), this.previousPosition = new Location(Bukkit.getWorld(s[0]),
Double.valueOf(s[1]), Double.valueOf(s[1]),
Double.valueOf(s[2]), Double.valueOf(s[2]),
Double.valueOf(s[3]), Double.valueOf(s[3]),
Float.valueOf(s[4]), Float.valueOf(s[4]),
Float.valueOf(s[5])); Float.valueOf(s[5]));
} }
/** Gets the previous gamemode of this player. */ /** Gets the previous gamemode of this player. */
public GameMode getPreviousGameMode() { public GameMode getPreviousGameMode() {
return this.previousGameMode; return this.previousGameMode;
} }
/** Sets the previous gamemode of this player. */ /** Sets the previous gamemode of this player. */
public void setPreviousGameMode(GameMode previous) { public void setPreviousGameMode(GameMode previous) {
this.previousGameMode = previous; this.previousGameMode = previous;
this.changed = true; 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) { public void setPreviousGameMode(String previous) {
if(previous == null) return; if(previous == null) return;
else if(previous.isEmpty()) return; else if(previous.isEmpty()) return;
else this.previousGameMode = GameMode.valueOf(previous); else this.previousGameMode = GameMode.valueOf(previous);
this.changed = true; 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() { public String getInventory() {
return this.inventory; return this.inventory;
} }
/** Sets the inventory Base64 string. */ /** Sets the inventory Base64 string. */
public void setInventory(String inventory) { public void setInventory(String inventory) {
this.inventory = inventory; this.inventory = inventory;
this.changed = true; this.changed = true;
} }
/** Gets the armor content, encoded in Base64 string. */ /** Gets the armor content, encoded in Base64 string. */
public String getArmor() { public String getArmor() {
return this.armor; return this.armor;
} }
/** Sets the armor inventory Base64 string. */ /** Sets the armor inventory Base64 string. */
public void setArmor(String armor) { public void setArmor(String armor) {
this.armor = armor; this.armor = armor;
this.changed = true; 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() { public long getAFKTime() {
return this.afk; 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) { public void setAFKTime(long time) {
this.afk = time; this.afk = time;
} }
/** Checks if the prisoner was changed or not. */ /** Checks if the prisoner was changed or not. */
public boolean wasChanged() { public boolean wasChanged() {
return this.changed; return this.changed;
} }
/** Sets whether the prisoner was changed or not. */ /** Sets whether the prisoner was changed or not. */
public boolean setChanged(boolean change) { public boolean setChanged(boolean change) {
this.changed = change; this.changed = change;
return this.changed; return this.changed;
} }
} }

View File

@ -12,92 +12,92 @@ import org.bukkit.World;
* @version 1.1.1 * @version 1.1.1
*/ */
public class SimpleLocation { public class SimpleLocation {
private String world; private String world;
private double x, y, z; private double x, y, z;
private float yaw, pitch; private float yaw, pitch;
/** /**
* Creates a new SimpleLocation with each detail provided separately. * Creates a new SimpleLocation with each detail provided separately.
* *
* @param world as a string * @param world as a string
* @param x coordinate as a double * @param x coordinate as a double
* @param y coordinate as a double * @param y coordinate as a double
* @param z coordinate as a double * @param z coordinate as a double
* @param yaw as a float * @param yaw as a float
* @param pitch as a float * @param pitch as a float
*/ */
public SimpleLocation(String world, double x, double y, double z, float yaw, float pitch) { public SimpleLocation(String world, double x, double y, double z, float yaw, float pitch) {
this.world = world; this.world = world;
this.x = x; this.x = x;
this.y = y; this.y = y;
this.z = z; this.z = z;
this.yaw = yaw; this.yaw = yaw;
this.pitch = pitch; this.pitch = pitch;
} }
/** /**
* Creates a new SimpleLocation with all the detail provided from {@link Location}. * Creates a new SimpleLocation with all the detail provided from {@link Location}.
* *
* @param location to convert to a SimpleLocation * @param location to convert to a SimpleLocation
*/ */
public SimpleLocation(Location location) { public SimpleLocation(Location location) {
this.world = location.getWorld().getName(); this.world = location.getWorld().getName();
this.x = location.getX(); this.x = location.getX();
this.y = location.getY(); this.y = location.getY();
this.z = location.getZ(); this.z = location.getZ();
this.yaw = location.getYaw(); this.yaw = location.getYaw();
this.pitch = location.getPitch(); this.pitch = location.getPitch();
} }
/** /**
* Creates a new Simple Location with all the inputs being in string. * Creates a new Simple Location with all the inputs being in string.
* *
* @param world the name of the world * @param world the name of the world
* @param x coordinate as a string * @param x coordinate as a string
* @param y coordinate as a string * @param y coordinate as a string
* @param z coordinate as a string * @param z coordinate as a string
*/ */
public SimpleLocation(String world, String x, String y, String z) { public SimpleLocation(String world, String x, String y, String z) {
this.world = world; this.world = world;
this.x = Double.valueOf(x); this.x = Double.valueOf(x);
this.y = Double.valueOf(y); this.y = Double.valueOf(y);
this.z = Double.valueOf(z); this.z = Double.valueOf(z);
this.yaw = 0; this.yaw = 0;
this.pitch = 0; this.pitch = 0;
} }
/** /**
* Creates a new SimpleLocation with each detail provided separately. * Creates a new SimpleLocation with each detail provided separately.
* *
* @param world as a string * @param world as a string
* @param x coordinate as a double * @param x coordinate as a double
* @param y coordinate as a double * @param y coordinate as a double
* @param z coordinate as a double * @param z coordinate as a double
*/ */
public SimpleLocation(String world, double x, double y, double z) { public SimpleLocation(String world, double x, double y, double z) {
this.world = world; this.world = world;
this.x = x; this.x = x;
this.y = y; this.y = y;
this.z = z; 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() { public World getWorld() {
return Bukkit.getWorld(world); 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() { public String getWorldName() {
return this.world; return this.world;
} }
/** Returns a new {@link Location} from this SimpleLocation. */ /** Returns a new {@link Location} from this SimpleLocation. */
public Location getLocation() { public Location getLocation() {
return new Location(Bukkit.getWorld(world), x, y, z, yaw, pitch); return new Location(Bukkit.getWorld(world), x, y, z, yaw, pitch);
} }
@Override @Override
public String toString() { public String toString() {
return world + "," + x + "," + y + "," + z + "," + yaw + "," + pitch; return world + "," + x + "," + y + "," + z + "," + yaw + "," + pitch;
} }
} }

View File

@ -9,52 +9,52 @@ package com.graywolf336.jail.beans;
* *
*/ */
public class Stick { public class Stick {
private String jail, reason; private String jail, reason;
private long time; private long time;
private double health; private double health;
/** /**
* Creates a new Jail Stick instance. * 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 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 * @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) { public Stick(String jail, String reason, long time, double health) {
this.jail = jail; this.jail = jail;
this.reason = reason; this.reason = reason;
this.time = time; this.time = time;
this.health = health; this.health = health;
} }
/** Gets the name of the jail a player will be sent when jailed via this jail stick. */ /** Gets the name of the jail a player will be sent when jailed via this jail stick. */
public String getJail() { public String getJail() {
return this.jail; return this.jail;
} }
/** Gets the reason a player will be jailed for when jailed via this stick. */ /** Gets the reason a player will be jailed for when jailed via this stick. */
public String getReason() { public String getReason() {
return this.reason; return this.reason;
} }
/** Gets the amount of time a player has to serve when they are jailed via this stick. */ /** Gets the amount of time a player has to serve when they are jailed via this stick. */
public long getTime() { public long getTime() {
return this.time; 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.
* *
* <p /> * <p />
* *
* See here for reference: http://dev.bukkit.org/bukkit-plugins/jail/tickets/415/ * See here for reference: http://dev.bukkit.org/bukkit-plugins/jail/tickets/415/
*/ */
public double getHealth() { public double getHealth() {
return this.health; return this.health;
} }
@Override @Override
public String toString() { public String toString() {
return time + "," + jail + "," + reason + "," + health; return time + "," + jail + "," + reason + "," + health;
} }
} }

View File

@ -12,20 +12,20 @@ import com.graywolf336.jail.JailManager;
* @version 1.0.0 * @version 1.0.0
*/ */
public interface Command { public interface Command {
/** /**
* Execute the command given the arguments, returning whether the command handled it or not. * Execute the command given the arguments, returning whether the command handled it or not.
* *
* <p> * <p>
* *
* When the method returns false, the usage message is printed to the sender. If the method * 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 * 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 * something, then it should return true so that the sender of the command doesn't get the
* usage message. * 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 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. * @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 boolean execute(JailManager jm, CommandSender sender, String... args) throws Exception;
} }

View File

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

View File

@ -31,45 +31,45 @@ import java.lang.annotation.RetentionPolicy;
*/ */
@Retention (RetentionPolicy.RUNTIME) @Retention (RetentionPolicy.RUNTIME)
public @interface CommandInfo { public @interface CommandInfo {
/** /**
* Gets the maximum amount of arguments required, -1 if no maximum (ex: Jailing someone with a reason or editing a reason). * 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. * @return The maximum number of arguments required, -1 if no maximum.
*/ */
public int maxArgs(); public int maxArgs();
/** /**
* Gets the minimum amount of arguments required. * Gets the minimum amount of arguments required.
* *
* @return The minimum number of arguments required. * @return The minimum number of arguments required.
*/ */
public int minimumArgs(); public int minimumArgs();
/** /**
* Whether the command needs a player context or not. * Whether the command needs a player context or not.
* *
* @return True if requires a player, false if not. * @return True if requires a player, false if not.
*/ */
public boolean needsPlayer(); public boolean needsPlayer();
/** /**
* A regex pattern that allows for alternatives to the command (ex: /jail or /j, /jailstatus or /js). * A regex pattern that allows for alternatives to the command (ex: /jail or /j, /jailstatus or /js).
* *
* @return The regex pattern to match. * @return The regex pattern to match.
*/ */
public String pattern(); public String pattern();
/** /**
* Gets the permission required to execute this command. * Gets the permission required to execute this command.
* *
* @return The permission required. * @return The permission required.
*/ */
public String permission(); public String permission();
/** /**
* Gets the usage message for this command. * Gets the usage message for this command.
* *
* @return The usage message. * @return The usage message.
*/ */
public String usage(); public String usage();
} }

View File

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

View File

@ -9,33 +9,33 @@ import com.graywolf336.jail.command.CommandInfo;
import com.graywolf336.jail.enums.Lang; import com.graywolf336.jail.enums.Lang;
@CommandInfo( @CommandInfo(
maxArgs = 1, maxArgs = 1,
minimumArgs = 1, minimumArgs = 1,
needsPlayer = false, needsPlayer = false,
pattern = "handcuff|hc", pattern = "handcuff|hc",
permission = "jail.command.handcuff", permission = "jail.command.handcuff",
usage = "/handcuff [player]" usage = "/handcuff [player]"
) )
public class HandCuffCommand implements Command { public class HandCuffCommand implements Command {
public boolean execute(JailManager jm, CommandSender sender, String... args) { public boolean execute(JailManager jm, CommandSender sender, String... args) {
Player player = jm.getPlugin().getServer().getPlayer(args[0]); Player player = jm.getPlugin().getServer().getPlayer(args[0]);
if(player == null) { if(player == null) {
sender.sendMessage(Lang.PLAYERNOTONLINE.get()); sender.sendMessage(Lang.PLAYERNOTONLINE.get());
}else if(player.hasPermission("jail.cantbehandcuffed")) { }else if(player.hasPermission("jail.cantbehandcuffed")) {
sender.sendMessage(Lang.CANTBEHANDCUFFED.get(player.getName())); 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())); 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())); sender.sendMessage(Lang.HANDCUFFSRELEASED.get(player.getName()));
jm.getPlugin().getHandCuffManager().removeHandCuffs(player.getUniqueId()); jm.getPlugin().getHandCuffManager().removeHandCuffs(player.getUniqueId());
player.sendMessage(Lang.UNHANDCUFFED.get()); player.sendMessage(Lang.UNHANDCUFFED.get());
}else { }else {
jm.getPlugin().getHandCuffManager().addHandCuffs(player.getUniqueId(), player.getLocation()); jm.getPlugin().getHandCuffManager().addHandCuffs(player.getUniqueId(), player.getLocation());
sender.sendMessage(Lang.HANDCUFFSON.get(player.getName())); sender.sendMessage(Lang.HANDCUFFSON.get(player.getName()));
player.sendMessage(Lang.HANDCUFFED.get()); player.sendMessage(Lang.HANDCUFFED.get());
} }
return true; return true;
} }
} }

View File

@ -8,17 +8,17 @@ import com.graywolf336.jail.command.Command;
import com.graywolf336.jail.command.CommandInfo; import com.graywolf336.jail.command.CommandInfo;
@CommandInfo( @CommandInfo(
maxArgs = 0, maxArgs = 0,
minimumArgs = 0, minimumArgs = 0,
needsPlayer = false, needsPlayer = false,
pattern = "togglejaildebug|tjd", pattern = "togglejaildebug|tjd",
permission = "jail.command.toggledebug", permission = "jail.command.toggledebug",
usage = "/togglejaildebug" usage = "/togglejaildebug"
) )
public class ToggleJailDebugCommand implements Command { public class ToggleJailDebugCommand implements Command {
public boolean execute(JailManager jm, CommandSender sender, String... args) { public boolean execute(JailManager jm, CommandSender sender, String... args) {
boolean debug = jm.getPlugin().setDebugging(!jm.getPlugin().inDebug()); boolean debug = jm.getPlugin().setDebugging(!jm.getPlugin().inDebug());
sender.sendMessage("Jail debugging is now: " + (debug ? ChatColor.GREEN + "enabled" : ChatColor.RED + "disabled")); sender.sendMessage("Jail debugging is now: " + (debug ? ChatColor.GREEN + "enabled" : ChatColor.RED + "disabled"));
return true; return true;
} }
} }

View File

@ -9,27 +9,27 @@ import com.graywolf336.jail.command.CommandInfo;
import com.graywolf336.jail.enums.Lang; import com.graywolf336.jail.enums.Lang;
@CommandInfo( @CommandInfo(
maxArgs = 1, maxArgs = 1,
minimumArgs = 1, minimumArgs = 1,
needsPlayer = false, needsPlayer = false,
pattern = "unhandcuff|uhc", pattern = "unhandcuff|uhc",
permission = "jail.command.handcuff", permission = "jail.command.handcuff",
usage = "/unhandcuff [player]" usage = "/unhandcuff [player]"
) )
public class UnHandCuffCommand implements Command { public class UnHandCuffCommand implements Command {
public boolean execute(JailManager jm, CommandSender sender, String... args) { public boolean execute(JailManager jm, CommandSender sender, String... args) {
Player player = jm.getPlugin().getServer().getPlayerExact(args[0]); Player player = jm.getPlugin().getServer().getPlayerExact(args[0]);
if(player == null) { if(player == null) {
sender.sendMessage(Lang.PLAYERNOTONLINE.get()); 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())); sender.sendMessage(Lang.HANDCUFFSRELEASED.get(player.getName()));
jm.getPlugin().getHandCuffManager().removeHandCuffs(player.getUniqueId()); jm.getPlugin().getHandCuffManager().removeHandCuffs(player.getUniqueId());
player.sendMessage(Lang.UNHANDCUFFED.get()); player.sendMessage(Lang.UNHANDCUFFED.get());
}else { }else {
sender.sendMessage(Lang.NOTHANDCUFFED.get(player.getName())); sender.sendMessage(Lang.NOTHANDCUFFED.get(player.getName()));
} }
return true; return true;
} }
} }

View File

@ -13,51 +13,51 @@ import com.graywolf336.jail.enums.Lang;
import com.graywolf336.jail.enums.Settings; import com.graywolf336.jail.enums.Settings;
@CommandInfo( @CommandInfo(
maxArgs = 1, maxArgs = 1,
minimumArgs = 1, minimumArgs = 1,
needsPlayer = false, needsPlayer = false,
pattern = "unjail|uj", pattern = "unjail|uj",
permission = "jail.command.unjail", permission = "jail.command.unjail",
usage = "/unjail [player]" usage = "/unjail [player]"
) )
public class UnJailCommand implements Command { public class UnJailCommand implements Command {
public boolean execute(JailManager jm, CommandSender sender, String... args) { public boolean execute(JailManager jm, CommandSender sender, String... args) {
//Check if the player is jailed //Check if the player is jailed
if(jm.isPlayerJailedByLastKnownUsername(args[0])) { if(jm.isPlayerJailedByLastKnownUsername(args[0])) {
Jail j = jm.getJailPlayerIsInByLastKnownName(args[0]); Jail j = jm.getJailPlayerIsInByLastKnownName(args[0]);
Prisoner pris = j.getPrisonerByLastKnownName(args[0]); Prisoner pris = j.getPrisonerByLastKnownName(args[0]);
Player p = jm.getPlugin().getServer().getPlayer(pris.getUUID()); Player p = jm.getPlugin().getServer().getPlayer(pris.getUUID());
//Check if the player is on the server or not //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 //Check if the player has offline pending and their remaining time is above 0, if so then
//forceably unjail them //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); 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 //The player is not, so we'll set the remaining time to zero and do it when they login next
pris.setRemainingTime(0L); pris.setRemainingTime(0L);
pris.setOfflinePending(true); pris.setOfflinePending(true);
sender.sendMessage(Lang.WILLBEUNJAILED.get(args[0])); sender.sendMessage(Lang.WILLBEUNJAILED.get(args[0]));
} }
}else { }else {
//Player is online, so let's try unjailing them //Player is online, so let's try unjailing them
try { try {
jm.getPlugin().getPrisonerManager().unJail(j, j.getCellPrisonerIsIn(pris.getUUID()), p, pris, sender); jm.getPlugin().getPrisonerManager().unJail(j, j.getCellPrisonerIsIn(pris.getUUID()), p, pris, sender);
} catch (Exception e) { } catch (Exception e) {
sender.sendMessage(ChatColor.RED + e.getMessage()); sender.sendMessage(ChatColor.RED + e.getMessage());
} }
} }
if(jm.getPlugin().getConfig().getBoolean(Settings.LOGJAILINGTOCONSOLE.getPath())) { if(jm.getPlugin().getConfig().getBoolean(Settings.LOGJAILINGTOCONSOLE.getPath())) {
jm.getPlugin().getLogger().info(ChatColor.stripColor(Lang.BROADCASTUNJAILING.get(new String[] { args[0], sender.getName() }))); jm.getPlugin().getLogger().info(ChatColor.stripColor(Lang.BROADCASTUNJAILING.get(new String[] { args[0], sender.getName() })));
} }
}else { }else {
//The player is not currently jailed //The player is not currently jailed
sender.sendMessage(Lang.NOTJAILED.get(args[0])); sender.sendMessage(Lang.NOTJAILED.get(args[0]));
} }
return true; return true;
} }
} }

View File

@ -10,28 +10,28 @@ import com.graywolf336.jail.enums.Lang;
import com.graywolf336.jail.enums.Settings; import com.graywolf336.jail.enums.Settings;
@CommandInfo( @CommandInfo(
maxArgs = 1, maxArgs = 1,
minimumArgs = 1, minimumArgs = 1,
needsPlayer = false, needsPlayer = false,
pattern = "unjailforce|ujf", pattern = "unjailforce|ujf",
permission = "jail.command.unjailforce", permission = "jail.command.unjailforce",
usage = "/unjailforce [player]" usage = "/unjailforce [player]"
) )
public class UnJailForceCommand implements Command { public class UnJailForceCommand implements Command {
public boolean execute(JailManager jm, CommandSender sender, String... args) { public boolean execute(JailManager jm, CommandSender sender, String... args) {
//Check if the player is jailed //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); jm.getPlugin().getPrisonerManager().forceRelease(jm.getPrisonerByLastKnownName(args[0]), sender);
if(jm.getPlugin().getConfig().getBoolean(Settings.LOGJAILINGTOCONSOLE.getPath())) { if(jm.getPlugin().getConfig().getBoolean(Settings.LOGJAILINGTOCONSOLE.getPath())) {
jm.getPlugin().getLogger().info(ChatColor.stripColor(Lang.BROADCASTUNJAILING.get(new String[] { args[0], sender.getName() }))); jm.getPlugin().getLogger().info(ChatColor.stripColor(Lang.BROADCASTUNJAILING.get(new String[] { args[0], sender.getName() })));
} }
}else { }else {
//The player is not currently jailed //The player is not currently jailed
sender.sendMessage(Lang.NOTJAILED.get(args[0])); sender.sendMessage(Lang.NOTJAILED.get(args[0]));
} }
return true; return true;
} }
} }

View File

@ -6,31 +6,31 @@ import com.lexicalscope.jewel.cli.Option;
public interface Jailing { public interface Jailing {
@Option(longName={"player", "pl"}, shortName="p", description = "the player's name") @Option(longName={"player", "pl"}, shortName="p", description = "the player's name")
public String getPlayer(); public String getPlayer();
@Option(longName={"time", "length"}, shortName="t", description = "the amount of time") @Option(longName={"time", "length"}, shortName="t", description = "the amount of time")
public String getTime(); public String getTime();
@Option(longName={"jail", "prison"}, shortName="j", description = "the jail") @Option(longName={"jail", "prison"}, shortName="j", description = "the jail")
public String getJail(); public String getJail();
@Option(longName={"cell"}, shortName="c", description = "the cell") @Option(longName={"cell"}, shortName="c", description = "the cell")
public String getCell(); public String getCell();
@Option(longName={"anycell"}, shortName="a", description = "decides whether the plugin will pick any open cell") @Option(longName={"anycell"}, shortName="a", description = "decides whether the plugin will pick any open cell")
public boolean getAnyCell(); public boolean getAnyCell();
@Option(longName={"muted", "canttalk"}, shortName="m", description = "whether the prisoner is muted or not") @Option(longName={"muted", "canttalk"}, shortName="m", description = "whether the prisoner is muted or not")
public boolean getMuted(); public boolean getMuted();
@Option(longName={"reason"}, shortName="r", description = "the reason this player is being jailed") @Option(longName={"reason"}, shortName="r", description = "the reason this player is being jailed")
public List<String> getReason(); public List<String> getReason();
public boolean isTime(); public boolean isTime();
public boolean isJail(); public boolean isJail();
public boolean isCell(); public boolean isCell();
public boolean isAnyCell(); public boolean isAnyCell();
public boolean isMuted(); public boolean isMuted();
public boolean isReason(); public boolean isReason();
} }

View File

@ -4,16 +4,16 @@ import com.lexicalscope.jewel.cli.Option;
public interface Transfer { public interface Transfer {
@Option(longName={"player", "pl"}, shortName="p", description = "the player's name") @Option(longName={"player", "pl"}, shortName="p", description = "the player's name")
public String getPlayer(); public String getPlayer();
@Option(longName={"jail", "prison"}, shortName="j", description = "the jail") @Option(longName={"jail", "prison"}, shortName="j", description = "the jail")
public String getJail(); public String getJail();
@Option(longName={"cell"}, shortName="c", description = "the cell") @Option(longName={"cell"}, shortName="c", description = "the cell")
public String getCell(); public String getCell();
public boolean isPlayer(); public boolean isPlayer();
public boolean isJail(); public boolean isJail();
public boolean isCell(); public boolean isCell();
} }

View File

@ -10,29 +10,29 @@ import com.graywolf336.jail.command.CommandInfo;
import com.graywolf336.jail.enums.Lang; import com.graywolf336.jail.enums.Lang;
@CommandInfo( @CommandInfo(
maxArgs = 1, maxArgs = 1,
minimumArgs = 1, minimumArgs = 1,
needsPlayer = false, needsPlayer = false,
pattern = "check", pattern = "check",
permission = "jail.command.jailcheck", permission = "jail.command.jailcheck",
usage = "/jail check [name]" usage = "/jail check [name]"
) )
public class JailCheckCommand implements Command{ public class JailCheckCommand implements Command{
// Checks the status of the specified prisoner // Checks the status of the specified prisoner
public boolean execute(JailManager jm, CommandSender sender, String... args) { public boolean execute(JailManager jm, CommandSender sender, String... args) {
//Otherwise let's check the first argument //Otherwise let's check the first argument
if(jm.isPlayerJailedByLastKnownUsername(args[1])) { if(jm.isPlayerJailedByLastKnownUsername(args[1])) {
Prisoner p = jm.getPrisonerByLastKnownName(args[1]); Prisoner p = jm.getPrisonerByLastKnownName(args[1]);
//graywolf663: Being gray's evil twin; CONSOLE (10) //graywolf663: Being gray's evil twin; CONSOLE (10)
//prisoner: reason; jailer (time in minutes) //prisoner: reason; jailer (time in minutes)
sender.sendMessage(ChatColor.BLUE + " " + p.getLastKnownName() + ": " + p.getReason() + "; " + p.getJailer() + " (" + p.getRemainingTimeInMinutes() + " mins)"); sender.sendMessage(ChatColor.BLUE + " " + p.getLastKnownName() + ": " + p.getReason() + "; " + p.getJailer() + " (" + p.getRemainingTimeInMinutes() + " mins)");
}else { }else {
sender.sendMessage(Lang.NOTJAILED.get(args[1])); sender.sendMessage(Lang.NOTJAILED.get(args[1]));
} }
return true; return true;
} }
} }

View File

@ -10,32 +10,32 @@ import com.graywolf336.jail.enums.Confirmation;
import com.graywolf336.jail.enums.Lang; import com.graywolf336.jail.enums.Lang;
@CommandInfo( @CommandInfo(
maxArgs = 2, maxArgs = 2,
minimumArgs = 0, minimumArgs = 0,
needsPlayer = false, needsPlayer = false,
pattern = "clear|clearforce", pattern = "clear|clearforce",
permission = "jail.command.jailclear", permission = "jail.command.jailclear",
usage = "/jail clear (-f) (jail)" usage = "/jail clear (-f) (jail)"
) )
public class JailClearCommand implements Command { public class JailClearCommand implements Command {
public boolean execute(JailManager jm, CommandSender sender, String... args) { public boolean execute(JailManager jm, CommandSender sender, String... args) {
boolean force = false; boolean force = false;
//Check if we need to forcefully clear something //Check if we need to forcefully clear something
for(String s : args) for(String s : args)
if(s.equalsIgnoreCase("-f") || s.equalsIgnoreCase("-force")) if(s.equalsIgnoreCase("-f") || s.equalsIgnoreCase("-force"))
force = true; force = true;
if(jm.isConfirming(sender.getName())) { if(jm.isConfirming(sender.getName())) {
sender.sendMessage(Lang.ALREADY.get()); 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)); jm.addConfirming(sender.getName(), new ConfirmPlayer(sender.getName(), args, Confirmation.CLEARFORCE));
sender.sendMessage(Lang.START.get()); sender.sendMessage(Lang.START.get());
}else { }else {
jm.addConfirming(sender.getName(), new ConfirmPlayer(sender.getName(), args, Confirmation.CLEAR)); jm.addConfirming(sender.getName(), new ConfirmPlayer(sender.getName(), args, Confirmation.CLEAR));
sender.sendMessage(Lang.START.get()); sender.sendMessage(Lang.START.get());
} }
return true; return true;
} }
} }

View File

@ -23,213 +23,213 @@ import com.lexicalscope.jewel.cli.ArgumentValidationException;
import com.lexicalscope.jewel.cli.CliFactory; import com.lexicalscope.jewel.cli.CliFactory;
@CommandInfo( @CommandInfo(
maxArgs = -1, maxArgs = -1,
minimumArgs = 0, minimumArgs = 0,
needsPlayer = false, needsPlayer = false,
pattern = "jail|j", pattern = "jail|j",
permission = "jail.command.jail", permission = "jail.command.jail",
usage = "/jail [name] (-t time) (-j JailName) (-c CellName) (-a AnyCell) (-m Muted) (-r A reason for jailing)" usage = "/jail [name] (-t time) (-j JailName) (-c CellName) (-a AnyCell) (-m Muted) (-r A reason for jailing)"
) )
public class JailCommand implements Command { public class JailCommand implements Command {
/* /*
* Executes the command. Checks the following: * Executes the command. Checks the following:
* *
* - If there are any jails. * - If there are any jails.
* - If the command can be parsed correctly. * - If the command can be parsed correctly.
* - If the player is already jailed. * - If the player is already jailed.
* - If the given time can be parsed correctly, defaults to what is defined in the config * - If the given time can be parsed correctly, defaults to what is defined in the config
* - If the jail is reasonable or not, else sets the one from the config * - If the jail is reasonable or not, else sets the one from the config
* - If the cell is not empty then checks to be sure that cell exists * - If the cell is not empty then checks to be sure that cell exists
* - If the prisoner is online or not. * - If the prisoner is online or not.
*/ */
public boolean execute(JailManager jm, CommandSender sender, String... args) { public boolean execute(JailManager jm, CommandSender sender, String... args) {
if(jm.getJails().isEmpty()) { if(jm.getJails().isEmpty()) {
sender.sendMessage(Lang.NOJAILS.get()); sender.sendMessage(Lang.NOJAILS.get());
return true; return true;
} }
//This is just to add the -p param so CliFactory doesn't blow up //This is just to add the -p param so CliFactory doesn't blow up
List<String> arguments = new LinkedList<String>(Arrays.asList(args)); List<String> arguments = new LinkedList<String>(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 //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 //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 = null;
try { try {
params = CliFactory.parseArguments(Jailing.class, arguments.toArray(new String[arguments.size()])); params = CliFactory.parseArguments(Jailing.class, arguments.toArray(new String[arguments.size()]));
}catch(ArgumentValidationException e) { }catch(ArgumentValidationException e) {
sender.sendMessage(ChatColor.RED + e.getMessage()); sender.sendMessage(ChatColor.RED + e.getMessage());
return true; return true;
} }
//Check if they've actually given us a player to jail //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)); sender.sendMessage(Lang.PROVIDEAPLAYER.get(Lang.JAILING));
return true; return true;
}else { }else {
jm.getPlugin().debug("We are getting ready to handle jailing: " + params.getPlayer()); jm.getPlugin().debug("We are getting ready to handle jailing: " + params.getPlayer());
} }
//Check if the given player is already jailed or not //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())); sender.sendMessage(Lang.ALREADYJAILED.get(params.getPlayer()));
return true; return true;
} }
//Try to parse the time, if they give us nothing in the time parameter then we get the default time //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. //from the config and if that isn't there then we default to thirty minutes.
Long time = 10L; Long time = 10L;
try { try {
if(!params.isTime()) { if(!params.isTime()) {
time = Util.getTime(jm.getPlugin().getConfig().getString(Settings.DEFAULTTIME.getPath(), "30m")); time = Util.getTime(jm.getPlugin().getConfig().getString(Settings.DEFAULTTIME.getPath(), "30m"));
}else if(params.getTime() == String.valueOf(-1)) { }else if(params.getTime() == String.valueOf(-1)) {
time = -1L; time = -1L;
}else { }else {
time = Util.getTime(params.getTime()); time = Util.getTime(params.getTime());
} }
}catch(Exception e) { }catch(Exception e) {
sender.sendMessage(Lang.NUMBERFORMATINCORRECT.get()); sender.sendMessage(Lang.NUMBERFORMATINCORRECT.get());
return true; return true;
} }
//Check the jail params. If it is empty, let's get the default jail //Check the jail params. If it is empty, let's get the default jail
//from the config. If that is nearest, let's make a call to getting the nearest jail to //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 //the sender but otherwise if it isn't nearest then let's set it to the default jail
//which is defined in the config. //which is defined in the config.
String jailName = ""; String jailName = "";
if(!params.isJail()) { if(!params.isJail()) {
String dJail = jm.getPlugin().getConfig().getString(Settings.DEFAULTJAIL.getPath()); String dJail = jm.getPlugin().getConfig().getString(Settings.DEFAULTJAIL.getPath());
if(dJail.equalsIgnoreCase("nearest")) { if(dJail.equalsIgnoreCase("nearest")) {
jailName = jm.getNearestJail(sender).getName(); jailName = jm.getNearestJail(sender).getName();
}else { }else {
jailName = dJail; jailName = dJail;
} }
}else if(!jm.isValidJail(params.getJail())) { }else if(!jm.isValidJail(params.getJail())) {
sender.sendMessage(Lang.NOJAIL.get(params.getJail())); sender.sendMessage(Lang.NOJAIL.get(params.getJail()));
return true; return true;
}else { }else {
jailName = params.getJail(); jailName = params.getJail();
} }
//Get the jail instance from the name of jail in the params. //Get the jail instance from the name of jail in the params.
Jail j = jm.getJail(jailName); Jail j = jm.getJail(jailName);
if(!j.isEnabled()) { if(!j.isEnabled()) {
sender.sendMessage(Lang.WORLDUNLOADED.get(j.getName())); sender.sendMessage(Lang.WORLDUNLOADED.get(j.getName()));
return true; return true;
} }
Cell c = null; Cell c = null;
//Check if the cell is defined //Check if the cell is defined
if(params.isCell()) { if(params.isCell()) {
//Check if it is a valid cell //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 //There is no cell by that name
sender.sendMessage(Lang.NOCELL.get(new String[] { params.getCell(), jailName })); sender.sendMessage(Lang.NOCELL.get(new String[] { params.getCell(), jailName }));
return true; 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 //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())); sender.sendMessage(Lang.CELLNOTEMPTY.get(params.getCell()));
Cell suggestedCell = jm.getJail(jailName).getFirstEmptyCell(); Cell suggestedCell = jm.getJail(jailName).getFirstEmptyCell();
if(suggestedCell != null) { if(suggestedCell != null) {
sender.sendMessage(Lang.SUGGESTEDCELL.get(new String[] { jailName, suggestedCell.getName() })); sender.sendMessage(Lang.SUGGESTEDCELL.get(new String[] { jailName, suggestedCell.getName() }));
}else { }else {
sender.sendMessage(Lang.NOEMPTYCELLS.get(jailName)); sender.sendMessage(Lang.NOEMPTYCELLS.get(jailName));
} }
return true; return true;
}else { }else {
c = jm.getJail(jailName).getCell(params.getCell()); c = jm.getJail(jailName).getCell(params.getCell());
} }
} }
//If they want just any open cell, then let's find the first empty one //If they want just any open cell, then let's find the first empty one
if(params.isAnyCell()) { if(params.isAnyCell()) {
c = jm.getJail(jailName).getFirstEmptyCell(); c = jm.getJail(jailName).getFirstEmptyCell();
if(c == null) { if(c == null) {
//If there wasn't an empty cell, then tell them so. //If there wasn't an empty cell, then tell them so.
sender.sendMessage(Lang.NOEMPTYCELLS.get(jailName)); sender.sendMessage(Lang.NOEMPTYCELLS.get(jailName));
return true; return true;
} }
} }
//If the jailer gave no reason, then let's get the default reason //If the jailer gave no reason, then let's get the default reason
String reason = ""; String reason = "";
if(!params.isReason()) { if(!params.isReason()) {
reason = Lang.DEFAULTJAILEDREASON.get(); reason = Lang.DEFAULTJAILEDREASON.get();
}else { }else {
StringBuilder sb = new StringBuilder(); StringBuilder sb = new StringBuilder();
for(String s : params.getReason()) { for(String s : params.getReason()) {
sb.append(s).append(' '); sb.append(s).append(' ');
} }
sb.deleteCharAt(sb.length() - 1); sb.deleteCharAt(sb.length() - 1);
reason = sb.toString(); reason = sb.toString();
} }
//If the config has automatic muting, then let's set them as muted //If the config has automatic muting, then let's set them as muted
boolean muted = params.getMuted(); boolean muted = params.getMuted();
if(jm.getPlugin().getConfig().getBoolean(Settings.AUTOMATICMUTE.getPath())) { if(jm.getPlugin().getConfig().getBoolean(Settings.AUTOMATICMUTE.getPath())) {
muted = true; muted = true;
} }
Player p = jm.getPlugin().getServer().getPlayer(params.getPlayer()); Player p = jm.getPlugin().getServer().getPlayer(params.getPlayer());
//If the player instance is not null and the player has the permission //If the player instance is not null and the player has the permission
//'jail.cantbejailed' then don't allow this to happen //'jail.cantbejailed' then don't allow this to happen
if(p != null && p.hasPermission("jail.cantbejailed")) { if(p != null && p.hasPermission("jail.cantbejailed")) {
sender.sendMessage(Lang.CANTBEJAILED.get()); sender.sendMessage(Lang.CANTBEJAILED.get());
return true; return true;
} }
String uuid = ""; String uuid = "";
if(p == null) { if(p == null) {
//TODO: Make this whole jail command non-blocking //TODO: Make this whole jail command non-blocking
uuid = jm.getPlugin().getServer().getOfflinePlayer(params.getPlayer()).getUniqueId().toString(); uuid = jm.getPlugin().getServer().getOfflinePlayer(params.getPlayer()).getUniqueId().toString();
}else { }else {
uuid = p.getUniqueId().toString(); uuid = p.getUniqueId().toString();
} }
Prisoner pris = new Prisoner(uuid, params.getPlayer(), muted, time, sender.getName(), reason); Prisoner pris = new Prisoner(uuid, params.getPlayer(), muted, time, sender.getName(), reason);
//call the event //call the event
PrePrisonerJailedEvent event = new PrePrisonerJailedEvent(j, c, pris, p, p == null, pris.getJailer()); PrePrisonerJailedEvent event = new PrePrisonerJailedEvent(j, c, pris, p, p == null, pris.getJailer());
jm.getPlugin().getServer().getPluginManager().callEvent(event); jm.getPlugin().getServer().getPluginManager().callEvent(event);
//check if the event is cancelled //check if the event is cancelled
if(event.isCancelled()) { if(event.isCancelled()) {
if(event.getCancelledMessage().isEmpty()) if(event.getCancelledMessage().isEmpty())
sender.sendMessage(Lang.CANCELLEDBYANOTHERPLUGIN.get(params.getPlayer())); sender.sendMessage(Lang.CANCELLEDBYANOTHERPLUGIN.get(params.getPlayer()));
else else
sender.sendMessage(event.getCancelledMessage()); sender.sendMessage(event.getCancelledMessage());
return true; return true;
} }
//recall data from the event //recall data from the event
j = event.getJail(); j = event.getJail();
c = event.getCell(); c = event.getCell();
pris = event.getPrisoner(); pris = event.getPrisoner();
p = event.getPlayer(); p = event.getPlayer();
//Player is not online //Player is not online
if(p == null) { if(p == null) {
sender.sendMessage(Lang.OFFLINEJAIL.get(new String[] { pris.getLastKnownName(), String.valueOf(pris.getRemainingTimeInMinutes()) })); sender.sendMessage(Lang.OFFLINEJAIL.get(new String[] { pris.getLastKnownName(), String.valueOf(pris.getRemainingTimeInMinutes()) }));
}else { }else {
//Player *is* online //Player *is* online
sender.sendMessage(Lang.ONLINEJAIL.get(new String[] { pris.getLastKnownName(), String.valueOf(pris.getRemainingTimeInMinutes()) })); sender.sendMessage(Lang.ONLINEJAIL.get(new String[] { pris.getLastKnownName(), String.valueOf(pris.getRemainingTimeInMinutes()) }));
} }
try { try {
jm.getPlugin().getPrisonerManager().prepareJail(j, c, p, pris); jm.getPlugin().getPrisonerManager().prepareJail(j, c, p, pris);
} catch (Exception e) { } catch (Exception e) {
sender.sendMessage(ChatColor.RED + e.getMessage()); sender.sendMessage(ChatColor.RED + e.getMessage());
return true; return true;
} }
return true; return true;
} }
} }

View File

@ -8,84 +8,84 @@ import com.graywolf336.jail.command.CommandInfo;
import com.graywolf336.jail.enums.Lang; import com.graywolf336.jail.enums.Lang;
@CommandInfo( @CommandInfo(
maxArgs = 0, maxArgs = 0,
minimumArgs = 0, minimumArgs = 0,
needsPlayer = false, needsPlayer = false,
pattern = "confirm|con", pattern = "confirm|con",
permission = "", permission = "",
usage = "/jail confirm" usage = "/jail confirm"
) )
public class JailConfirmCommand implements Command{ public class JailConfirmCommand implements Command{
public boolean execute(JailManager jm, CommandSender sender, String... args) { public boolean execute(JailManager jm, CommandSender sender, String... args) {
//Check if the sender is actually confirming something. //Check if the sender is actually confirming something.
if(jm.isConfirming(sender.getName())) { if(jm.isConfirming(sender.getName())) {
if(jm.confirmingHasExpired(sender.getName())) { if(jm.confirmingHasExpired(sender.getName())) {
//Their confirmation time frame has closed //Their confirmation time frame has closed
sender.sendMessage(Lang.EXPIRED.get()); sender.sendMessage(Lang.EXPIRED.get());
}else { }else {
switch(jm.getWhatIsConfirming(sender.getName())) { switch(jm.getWhatIsConfirming(sender.getName())) {
case CLEAR: case CLEAR:
//Copy the original arguments for easy access //Copy the original arguments for easy access
String[] cArgs = jm.getOriginalArgs(sender.getName()); String[] cArgs = jm.getOriginalArgs(sender.getName());
//Clear a jail if the args length is two, else send null //Clear a jail if the args length is two, else send null
String msg = jm.clearJailOfPrisoners(cArgs.length == 2 ? cArgs[1] : null); String msg = jm.clearJailOfPrisoners(cArgs.length == 2 ? cArgs[1] : null);
//Send the message we got back //Send the message we got back
sender.sendMessage(msg); sender.sendMessage(msg);
//Remove them from confirming so they can't do it again //Remove them from confirming so they can't do it again
jm.removeConfirming(sender.getName()); jm.removeConfirming(sender.getName());
break; break;
case CLEARFORCE: case CLEARFORCE:
//Copy the original arguments for easy access //Copy the original arguments for easy access
String[] cArgs2 = jm.getOriginalArgs(sender.getName()); String[] cArgs2 = jm.getOriginalArgs(sender.getName());
//Forcefully clear a jail if the args length is two, else send null to clear all //Forcefully clear a jail if the args length is two, else send null to clear all
String msg2 = jm.forcefullyClearJailOrJails(cArgs2.length == 2 ? cArgs2[1] : null); String msg2 = jm.forcefullyClearJailOrJails(cArgs2.length == 2 ? cArgs2[1] : null);
//Send the message we got back //Send the message we got back
sender.sendMessage(msg2); sender.sendMessage(msg2);
jm.removeConfirming(sender.getName()); jm.removeConfirming(sender.getName());
break; break;
case DELETECELL: case DELETECELL:
//Copy the original arguments for easy access //Copy the original arguments for easy access
String[] cArgs3 = jm.getOriginalArgs(sender.getName()); String[] cArgs3 = jm.getOriginalArgs(sender.getName());
//delete a cell from a jail with the given arguments //delete a cell from a jail with the given arguments
String msg3 = jm.deleteJailCell(cArgs3[1], cArgs3[2]); String msg3 = jm.deleteJailCell(cArgs3[1], cArgs3[2]);
//Send the message we got back //Send the message we got back
sender.sendMessage(msg3); sender.sendMessage(msg3);
jm.removeConfirming(sender.getName()); jm.removeConfirming(sender.getName());
break; break;
case DELETECELLS: case DELETECELLS:
//Copy the original arguments for easy access //Copy the original arguments for easy access
String[] cArgs4 = jm.getOriginalArgs(sender.getName()); String[] cArgs4 = jm.getOriginalArgs(sender.getName());
//delete a cell from a jail with the given arguments //delete a cell from a jail with the given arguments
String[] msgs4 = jm.deleteAllJailCells(cArgs4[1]); String[] msgs4 = jm.deleteAllJailCells(cArgs4[1]);
//Send the messages we got back //Send the messages we got back
for(String s : msgs4) { for(String s : msgs4) {
sender.sendMessage(s); sender.sendMessage(s);
} }
jm.removeConfirming(sender.getName()); jm.removeConfirming(sender.getName());
break; break;
case DELETE: case DELETE:
//Copy the original arguments for easy access //Copy the original arguments for easy access
String[] cArgs5 = jm.getOriginalArgs(sender.getName()); String[] cArgs5 = jm.getOriginalArgs(sender.getName());
//delete a cell from a jail with the given arguments //delete a cell from a jail with the given arguments
String msg5 = jm.deleteJail(cArgs5[1]); String msg5 = jm.deleteJail(cArgs5[1]);
//Send the message we got back //Send the message we got back
sender.sendMessage(msg5); sender.sendMessage(msg5);
jm.removeConfirming(sender.getName()); jm.removeConfirming(sender.getName());
break; break;
default: default:
sender.sendMessage(Lang.NOTHING.get()); sender.sendMessage(Lang.NOTHING.get());
jm.removeConfirming(sender.getName()); jm.removeConfirming(sender.getName());
break; break;
} }
} }
}else { }else {
//They aren't confirming anything right now. //They aren't confirming anything right now.
sender.sendMessage(Lang.NOTHING.get()); sender.sendMessage(Lang.NOTHING.get());
} }
return true; return true;
} }
} }

View File

@ -10,57 +10,57 @@ import com.graywolf336.jail.command.Command;
import com.graywolf336.jail.command.CommandInfo; import com.graywolf336.jail.command.CommandInfo;
@CommandInfo( @CommandInfo(
maxArgs = 2, maxArgs = 2,
minimumArgs = 1, minimumArgs = 1,
needsPlayer = true, needsPlayer = true,
pattern = "createcell|createcells|cellcreate|cellscreate|cc", pattern = "createcell|createcells|cellcreate|cellscreate|cc",
permission = "jail.command.jailcreatecells", permission = "jail.command.jailcreatecells",
usage = "/jail createcell [jail] (cellname)" usage = "/jail createcell [jail] (cellname)"
) )
public class JailCreateCellCommand implements Command { public class JailCreateCellCommand implements Command {
public boolean execute(JailManager jm, CommandSender sender, String... args) { public boolean execute(JailManager jm, CommandSender sender, String... args) {
Player player = (Player) sender; Player player = (Player) sender;
String name = player.getName(); String name = player.getName();
String jail = args[1].toLowerCase(); String jail = args[1].toLowerCase();
String cell = ""; String cell = "";
//Only get the cell name they provide if they provide it //Only get the cell name they provide if they provide it
if(args.length >= 3) { if(args.length >= 3) {
cell = args[2]; cell = args[2];
} }
//Check if the player is currently creating something else //Check if the player is currently creating something else
if(jm.isCreatingSomething(name)) { if(jm.isCreatingSomething(name)) {
String message = jm.getStepMessage(name); String message = jm.getStepMessage(name);
if(!message.isEmpty()) { if(!message.isEmpty()) {
player.sendMessage(ChatColor.RED + message); player.sendMessage(ChatColor.RED + message);
}else { }else {
player.sendMessage(ChatColor.RED + "You're already creating something else, please finish it or cancel."); 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. //Not creating anything, so let them create some cells.
if(jm.isValidJail(jail)) { if(jm.isValidJail(jail)) {
Jail j = jm.getJail(jail); Jail j = jm.getJail(jail);
//If they didn't provide a cell name, let's provide one ourself. //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(j.getCell(cell) == null) {
if(jm.addCreatingCell(name, jail, cell)) { if(jm.addCreatingCell(name, jail, cell)) {
jm.getCellCreationSteps().startStepping(player); jm.getCellCreationSteps().startStepping(player);
}else { }else {
player.sendMessage(ChatColor.RED + "Appears you're creating a cell or something went wrong on our side."); 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."); 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 + "'."); player.sendMessage(ChatColor.RED + "No such jail found by the name of '" + jail + "'.");
} }
} }
return true; return true;
} }
} }

View File

@ -9,40 +9,40 @@ import com.graywolf336.jail.command.Command;
import com.graywolf336.jail.command.CommandInfo; import com.graywolf336.jail.command.CommandInfo;
@CommandInfo( @CommandInfo(
maxArgs = 1, maxArgs = 1,
minimumArgs = 1, minimumArgs = 1,
needsPlayer = true, needsPlayer = true,
pattern = "create", pattern = "create",
permission = "jail.command.jailcreate", permission = "jail.command.jailcreate",
usage = "/jail create [name]" usage = "/jail create [name]"
) )
public class JailCreateCommand implements Command { public class JailCreateCommand implements Command {
public boolean execute(JailManager jm, CommandSender sender, String... args) { public boolean execute(JailManager jm, CommandSender sender, String... args) {
Player player = (Player) sender; Player player = (Player) sender;
String name = player.getName(); String name = player.getName();
String jail = args[1]; String jail = args[1];
//Check if the player is currently creating something else //Check if the player is currently creating something else
if(jm.isCreatingSomething(name)) { if(jm.isCreatingSomething(name)) {
String message = jm.getStepMessage(name); String message = jm.getStepMessage(name);
if(!message.isEmpty()) { if(!message.isEmpty()) {
player.sendMessage(ChatColor.RED + message); player.sendMessage(ChatColor.RED + message);
}else { }else {
player.sendMessage(ChatColor.RED + "You're already creating something else, please finish it or cancel."); player.sendMessage(ChatColor.RED + "You're already creating something else, please finish it or cancel.");
} }
}else { }else {
if(jm.isValidJail(jail)) { if(jm.isValidJail(jail)) {
player.sendMessage(ChatColor.RED + "Jail by the name of '" + jail + "' already exist!"); player.sendMessage(ChatColor.RED + "Jail by the name of '" + jail + "' already exist!");
}else { }else {
if(jm.addCreatingJail(name, jail)) { if(jm.addCreatingJail(name, jail)) {
jm.getJailCreationSteps().startStepping(player); 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."); player.sendMessage(ChatColor.RED + "Seems like you're already creating a Jail or something went wrong on our side.");
} }
} }
} }
return true; return true;
} }
} }

View File

@ -10,22 +10,22 @@ import com.graywolf336.jail.enums.Confirmation;
import com.graywolf336.jail.enums.Lang; import com.graywolf336.jail.enums.Lang;
@CommandInfo( @CommandInfo(
maxArgs = 2, maxArgs = 2,
minimumArgs = 2, minimumArgs = 2,
needsPlayer = false, needsPlayer = false,
pattern = "deletecell|dc", pattern = "deletecell|dc",
permission = "jail.command.jaildeletecell", permission = "jail.command.jaildeletecell",
usage = "/jail deletecell [jail] [cell]" usage = "/jail deletecell [jail] [cell]"
) )
public class JailDeleteCellCommand implements Command { public class JailDeleteCellCommand implements Command {
public boolean execute(JailManager jm, CommandSender sender, String... args) throws Exception { public boolean execute(JailManager jm, CommandSender sender, String... args) throws Exception {
if(jm.isConfirming(sender.getName())) { if(jm.isConfirming(sender.getName())) {
sender.sendMessage(Lang.ALREADY.get()); sender.sendMessage(Lang.ALREADY.get());
}else { }else {
jm.addConfirming(sender.getName(), new ConfirmPlayer(sender.getName(), args, Confirmation.DELETECELL)); jm.addConfirming(sender.getName(), new ConfirmPlayer(sender.getName(), args, Confirmation.DELETECELL));
sender.sendMessage(Lang.START.get()); sender.sendMessage(Lang.START.get());
} }
return true; return true;
} }
} }

View File

@ -10,22 +10,22 @@ import com.graywolf336.jail.enums.Confirmation;
import com.graywolf336.jail.enums.Lang; import com.graywolf336.jail.enums.Lang;
@CommandInfo( @CommandInfo(
maxArgs = 1, maxArgs = 1,
minimumArgs = 1, minimumArgs = 1,
needsPlayer = false, needsPlayer = false,
pattern = "deletecells|dcs", pattern = "deletecells|dcs",
permission = "jail.command.jaildeletecell", permission = "jail.command.jaildeletecell",
usage = "/jail deletecells [jail]" usage = "/jail deletecells [jail]"
) )
public class JailDeleteCellsCommand implements Command { public class JailDeleteCellsCommand implements Command {
public boolean execute(JailManager jm, CommandSender sender, String... args) throws Exception { public boolean execute(JailManager jm, CommandSender sender, String... args) throws Exception {
if(jm.isConfirming(sender.getName())) { if(jm.isConfirming(sender.getName())) {
sender.sendMessage(Lang.ALREADY.get()); sender.sendMessage(Lang.ALREADY.get());
}else { }else {
jm.addConfirming(sender.getName(), new ConfirmPlayer(sender.getName(), args, Confirmation.DELETECELLS)); jm.addConfirming(sender.getName(), new ConfirmPlayer(sender.getName(), args, Confirmation.DELETECELLS));
sender.sendMessage(Lang.START.get()); sender.sendMessage(Lang.START.get());
} }
return true; return true;
} }
} }

View File

@ -10,22 +10,22 @@ import com.graywolf336.jail.enums.Confirmation;
import com.graywolf336.jail.enums.Lang; import com.graywolf336.jail.enums.Lang;
@CommandInfo( @CommandInfo(
maxArgs = 1, maxArgs = 1,
minimumArgs = 1, minimumArgs = 1,
needsPlayer = false, needsPlayer = false,
pattern = "delete|d", pattern = "delete|d",
permission = "jail.command.jaildelete", permission = "jail.command.jaildelete",
usage = "/jail delete [jail]" usage = "/jail delete [jail]"
) )
public class JailDeleteCommand implements Command { public class JailDeleteCommand implements Command {
public boolean execute(JailManager jm, CommandSender sender, String... args) throws Exception { public boolean execute(JailManager jm, CommandSender sender, String... args) throws Exception {
if(jm.isConfirming(sender.getName())) { if(jm.isConfirming(sender.getName())) {
sender.sendMessage(Lang.ALREADY.get()); sender.sendMessage(Lang.ALREADY.get());
}else { }else {
jm.addConfirming(sender.getName(), new ConfirmPlayer(sender.getName(), args, Confirmation.DELETE)); jm.addConfirming(sender.getName(), new ConfirmPlayer(sender.getName(), args, Confirmation.DELETE));
sender.sendMessage(Lang.START.get()); sender.sendMessage(Lang.START.get());
} }
return true; return true;
} }
} }

View File

@ -11,44 +11,44 @@ import com.graywolf336.jail.command.CommandInfo;
import com.graywolf336.jail.enums.Lang; import com.graywolf336.jail.enums.Lang;
@CommandInfo( @CommandInfo(
maxArgs = 1, maxArgs = 1,
minimumArgs = 1, minimumArgs = 1,
needsPlayer = false, needsPlayer = false,
pattern = "listcells|lc", pattern = "listcells|lc",
permission = "jail.command.jaillistcell", permission = "jail.command.jaillistcell",
usage = "/jail listcells [jail]" usage = "/jail listcells [jail]"
) )
public class JailListCellsCommand implements Command { public class JailListCellsCommand implements Command {
@Override @Override
public boolean execute(JailManager jm, CommandSender sender, String... args) { public boolean execute(JailManager jm, CommandSender sender, String... args) {
sender.sendMessage(ChatColor.AQUA + "----------Cells----------"); sender.sendMessage(ChatColor.AQUA + "----------Cells----------");
if(!jm.getJails().isEmpty()) { if(!jm.getJails().isEmpty()) {
if(jm.getJail(args[1]) != null) { if(jm.getJail(args[1]) != null) {
Jail j = jm.getJail(args[1]); Jail j = jm.getJail(args[1]);
String message = ""; String message = "";
for(Cell c : j.getCells()) { for(Cell c : j.getCells()) {
if(message.isEmpty()) { if(message.isEmpty()) {
message = c.getName() + (c.getPrisoner() == null ? "" : " (" + c.getPrisoner().getLastKnownName() + ")"); message = c.getName() + (c.getPrisoner() == null ? "" : " (" + c.getPrisoner().getLastKnownName() + ")");
}else { }else {
message += ", " + c.getName() + (c.getPrisoner() == null ? "" : " (" + c.getPrisoner().getLastKnownName() + ")"); message += ", " + c.getName() + (c.getPrisoner() == null ? "" : " (" + c.getPrisoner().getLastKnownName() + ")");
} }
} }
if(message.isEmpty()) { if(message.isEmpty()) {
sender.sendMessage(Lang.NOCELLS.get(j.getName())); sender.sendMessage(Lang.NOCELLS.get(j.getName()));
}else { }else {
sender.sendMessage(ChatColor.GREEN + message); sender.sendMessage(ChatColor.GREEN + message);
} }
}else { }else {
sender.sendMessage(Lang.NOJAIL.get(args[1])); sender.sendMessage(Lang.NOJAIL.get(args[1]));
} }
}else { }else {
sender.sendMessage(Lang.NOJAILS.get()); sender.sendMessage(Lang.NOJAILS.get());
} }
sender.sendMessage(ChatColor.AQUA + "-------------------------"); sender.sendMessage(ChatColor.AQUA + "-------------------------");
return true; return true;
} }
} }

View File

@ -13,52 +13,52 @@ import com.graywolf336.jail.command.CommandInfo;
import com.graywolf336.jail.enums.Lang; import com.graywolf336.jail.enums.Lang;
@CommandInfo( @CommandInfo(
maxArgs = 1, maxArgs = 1,
minimumArgs = 0, minimumArgs = 0,
needsPlayer = false, needsPlayer = false,
pattern = "list|l", pattern = "list|l",
permission = "jail.command.jaillist", permission = "jail.command.jaillist",
usage = "/jail list (jail)" usage = "/jail list (jail)"
) )
public class JailListCommand implements Command { public class JailListCommand implements Command {
public boolean execute(JailManager jm, CommandSender sender, String... args) { public boolean execute(JailManager jm, CommandSender sender, String... args) {
sender.sendMessage(ChatColor.AQUA + "----------" + (args.length == 1 ? "Jails" : "Prisoners") + "----------"); sender.sendMessage(ChatColor.AQUA + "----------" + (args.length == 1 ? "Jails" : "Prisoners") + "----------");
//Check if there are any jails //Check if there are any jails
if(jm.getJails().isEmpty()) { if(jm.getJails().isEmpty()) {
sender.sendMessage(" " + Lang.NOJAILS.get()); sender.sendMessage(" " + Lang.NOJAILS.get());
}else { }else {
//Check if they have provided a jail to list or not //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 //No jail provided, so give them a list of the jails
for(Jail j : jm.getJails()) { for(Jail j : jm.getJails()) {
if(j.isEnabled()) sender.sendMessage(ChatColor.BLUE + " " + j.getName() + " (" + j.getAllPrisoners().size() + ")"); 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 sender.sendMessage(ChatColor.RED + " " + j.getName() + " (" + j.getAllPrisoners().size() + ") - WORLD UNLOADED");
} }
}else { }else {
Jail j = jm.getJail(args[1]); Jail j = jm.getJail(args[1]);
if(j == null) { if(j == null) {
//No jail was found //No jail was found
sender.sendMessage(" " + Lang.NOJAIL.get(args[1])); sender.sendMessage(" " + Lang.NOJAIL.get(args[1]));
}else { }else {
Collection<Prisoner> pris = j.getAllPrisoners().values(); Collection<Prisoner> pris = j.getAllPrisoners().values();
if(pris.isEmpty()) { if(pris.isEmpty()) {
//If there are no prisoners, then send that message //If there are no prisoners, then send that message
sender.sendMessage(" " + Lang.NOPRISONERS.get(j.getName())); sender.sendMessage(" " + Lang.NOPRISONERS.get(j.getName()));
}else { }else {
for(Prisoner p : pris) { for(Prisoner p : pris) {
//graywolf663: Being gray's evil twin; CONSOLE (10) //graywolf663: Being gray's evil twin; CONSOLE (10)
//prisoner: reason; jailer (time in minutes) //prisoner: reason; jailer (time in minutes)
sender.sendMessage(ChatColor.BLUE + " " + p.getLastKnownName() + ": " + p.getReason() + "; " + p.getJailer() + " (" + p.getRemainingTimeInMinutes() + " mins)"); sender.sendMessage(ChatColor.BLUE + " " + p.getLastKnownName() + ": " + p.getReason() + "; " + p.getJailer() + " (" + p.getRemainingTimeInMinutes() + " mins)");
} }
} }
} }
} }
} }
sender.sendMessage(ChatColor.AQUA + "-------------------------"); sender.sendMessage(ChatColor.AQUA + "-------------------------");
return true; return true;
} }
} }

View File

@ -8,31 +8,31 @@ import com.graywolf336.jail.command.CommandInfo;
import com.graywolf336.jail.enums.Lang; import com.graywolf336.jail.enums.Lang;
@CommandInfo( @CommandInfo(
maxArgs = 1, maxArgs = 1,
minimumArgs = 1, minimumArgs = 1,
needsPlayer = false, needsPlayer = false,
pattern = "mute|m", pattern = "mute|m",
permission = "jail.command.jailmute", permission = "jail.command.jailmute",
usage = "/jail mute [name]" usage = "/jail mute [name]"
) )
public class JailMuteCommand implements Command { 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) throws Exception {
//Let's check if the player they're sending us is jailed //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 //They are, so let's toggle whether they are muted or not
boolean muted = !jm.getPrisonerByLastKnownName(args[1]).isMuted(); boolean muted = !jm.getPrisonerByLastKnownName(args[1]).isMuted();
jm.getPrisonerByLastKnownName(args[1]).setMuted(muted); jm.getPrisonerByLastKnownName(args[1]).setMuted(muted);
//Send the message to the sender based upon whether they are muted or unmuted //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])); sender.sendMessage(Lang.NOWMUTED.get(args[1]));
else else
sender.sendMessage(Lang.NOWUNMUTED.get(args[1])); sender.sendMessage(Lang.NOWUNMUTED.get(args[1]));
}else { }else {
//The player provided is not jailed, so let's tell the sender that //The player provided is not jailed, so let's tell the sender that
sender.sendMessage(Lang.NOTJAILED.get(args[1])); sender.sendMessage(Lang.NOTJAILED.get(args[1]));
} }
return true; return true;
} }
} }

View File

@ -15,195 +15,195 @@ import com.graywolf336.jail.enums.Lang;
import com.graywolf336.jail.enums.Settings; import com.graywolf336.jail.enums.Settings;
@CommandInfo( @CommandInfo(
maxArgs = 2, maxArgs = 2,
minimumArgs = 0, minimumArgs = 0,
needsPlayer = true, needsPlayer = true,
pattern = "pay", pattern = "pay",
permission = "jail.usercmd.jailpay", permission = "jail.usercmd.jailpay",
usage = "/jail pay (amount) (name)" usage = "/jail pay (amount) (name)"
) )
public class JailPayCommand implements Command { public class JailPayCommand implements Command {
public boolean execute(JailManager jm, CommandSender sender, String... args) throws Exception { public boolean execute(JailManager jm, CommandSender sender, String... args) throws Exception {
if(jm.getPlugin().getConfig().getBoolean(Settings.JAILPAYENABLED.getPath())) { if(jm.getPlugin().getConfig().getBoolean(Settings.JAILPAYENABLED.getPath())) {
JailPayManager pm = jm.getPlugin().getJailPayManager(); JailPayManager pm = jm.getPlugin().getJailPayManager();
switch(args.length) { switch(args.length) {
case 1: case 1:
// `/jail pay` // `/jail pay`
//send how much it costs to get out //send how much it costs to get out
if(jm.isPlayerJailedByLastKnownUsername(sender.getName())) { if(jm.isPlayerJailedByLastKnownUsername(sender.getName())) {
Prisoner p = jm.getPrisonerByLastKnownName(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))); amt = String.valueOf((int) Math.ceil(pm.calculateBill(p)));
}else { }else {
amt = String.valueOf(pm.calculateBill(p)); amt = String.valueOf(pm.calculateBill(p));
} }
if(p.getRemainingTime() > 0) { if(p.getRemainingTime() > 0) {
if(pm.isTimedEnabled()) { if(pm.isTimedEnabled()) {
sender.sendMessage(Lang.PAYCOST.get(new String[] { pm.getCostPerMinute(), pm.getCurrencyName(), amt })); sender.sendMessage(Lang.PAYCOST.get(new String[] { pm.getCostPerMinute(), pm.getCurrencyName(), amt }));
}else { }else {
sender.sendMessage(Lang.PAYNOTENABLED.get()); sender.sendMessage(Lang.PAYNOTENABLED.get());
jm.getPlugin().debug("Jail pay 'timed' paying is not enabled (config has 0 as the cost)."); jm.getPlugin().debug("Jail pay 'timed' paying is not enabled (config has 0 as the cost).");
} }
}else { }else {
if(pm.isInfiniteEnabled()) { if(pm.isInfiniteEnabled()) {
sender.sendMessage(Lang.PAYCOST.get(new String[] { amt, pm.getCurrencyName() })); sender.sendMessage(Lang.PAYCOST.get(new String[] { amt, pm.getCurrencyName() }));
}else { }else {
sender.sendMessage(Lang.PAYNOTENABLED.get()); sender.sendMessage(Lang.PAYNOTENABLED.get());
jm.getPlugin().debug("Jail pay 'infinite' paying is not enabled (config has 0 as the cost)."); jm.getPlugin().debug("Jail pay 'infinite' paying is not enabled (config has 0 as the cost).");
} }
} }
}else { }else {
sender.sendMessage(Lang.YOUARENOTJAILED.get()); sender.sendMessage(Lang.YOUARENOTJAILED.get());
} }
break; break;
case 2: case 2:
// `/jail pay <amount>` // `/jail pay <amount>`
//They are trying to pay for their self //They are trying to pay for their self
if(jm.isPlayerJailedByLastKnownUsername(sender.getName())) { if(jm.isPlayerJailedByLastKnownUsername(sender.getName())) {
Prisoner p = jm.getPrisonerByLastKnownName(sender.getName()); Prisoner p = jm.getPrisonerByLastKnownName(sender.getName());
if(p.getRemainingTime() > 0) { if(p.getRemainingTime() > 0) {
if(!pm.isTimedEnabled()) { if(!pm.isTimedEnabled()) {
sender.sendMessage(Lang.PAYNOTENABLED.get()); sender.sendMessage(Lang.PAYNOTENABLED.get());
return true; return true;
} }
}else { }else {
if(!pm.isInfiniteEnabled()) { if(!pm.isInfiniteEnabled()) {
sender.sendMessage(Lang.PAYNOTENABLED.get()); sender.sendMessage(Lang.PAYNOTENABLED.get());
return true; return true;
} }
} }
if(args[1].startsWith("-")) { if(args[1].startsWith("-")) {
sender.sendMessage(Lang.PAYNONEGATIVEAMOUNTS.get()); sender.sendMessage(Lang.PAYNONEGATIVEAMOUNTS.get());
}else { }else {
double amt = 0; double amt = 0;
try { try {
amt = Double.parseDouble(args[1]); amt = Double.parseDouble(args[1]);
}catch(NumberFormatException e) { }catch(NumberFormatException e) {
sender.sendMessage(ChatColor.RED + "<amount> must be a number."); sender.sendMessage(ChatColor.RED + "<amount> must be a number.");
throw e; throw e;
} }
if(pm.hasEnoughToPay((Player) sender, amt)) { if(pm.hasEnoughToPay((Player) sender, amt)) {
double bill = pm.calculateBill(p); double bill = pm.calculateBill(p);
if(p.getRemainingTime() > 0) { if(p.getRemainingTime() > 0) {
//timed sentence //timed sentence
if(amt >= bill) { if(amt >= bill) {
pm.pay((Player) sender, bill); pm.pay((Player) sender, bill);
sender.sendMessage(Lang.PAYPAIDRELEASED.get(String.valueOf(bill))); sender.sendMessage(Lang.PAYPAIDRELEASED.get(String.valueOf(bill)));
jm.getPlugin().getPrisonerManager().schedulePrisonerRelease(p); jm.getPlugin().getPrisonerManager().schedulePrisonerRelease(p);
}else { }else {
long minutes = pm.getMinutesPayingFor(amt); long minutes = pm.getMinutesPayingFor(amt);
pm.pay((Player) sender, amt); pm.pay((Player) sender, amt);
long remain = p.subtractTime(TimeUnit.MILLISECONDS.convert(minutes, TimeUnit.MINUTES)); 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(new String[] { String.valueOf(amt), String.valueOf(TimeUnit.MINUTES.convert(remain, TimeUnit.MILLISECONDS)) }));
} }
}else { }else {
//infinite jailing //infinite jailing
if(amt >= bill) { if(amt >= bill) {
pm.pay((Player) sender, bill); pm.pay((Player) sender, bill);
sender.sendMessage(Lang.PAYPAIDRELEASED.get(String.valueOf(bill))); sender.sendMessage(Lang.PAYPAIDRELEASED.get(String.valueOf(bill)));
jm.getPlugin().getPrisonerManager().schedulePrisonerRelease(p); jm.getPlugin().getPrisonerManager().schedulePrisonerRelease(p);
}else { }else {
//You haven't provided enough money to get them out //You haven't provided enough money to get them out
sender.sendMessage(Lang.PAYNOTENOUGHMONEYPROVIDED.get()); sender.sendMessage(Lang.PAYNOTENOUGHMONEYPROVIDED.get());
} }
} }
}else { }else {
sender.sendMessage(Lang.PAYNOTENOUGHMONEY.get()); sender.sendMessage(Lang.PAYNOTENOUGHMONEY.get());
} }
} }
}else { }else {
sender.sendMessage(Lang.YOUARENOTJAILED.get()); sender.sendMessage(Lang.YOUARENOTJAILED.get());
} }
break; break;
case 3: case 3:
// `/jail pay <amount> <person> // `/jail pay <amount> <person>
//they are trying to pay for someone else //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 //When they are jailed they can not pay for someone else
sender.sendMessage(Lang.PAYCANTPAYWHILEJAILED.get()); sender.sendMessage(Lang.PAYCANTPAYWHILEJAILED.get());
}else { }else {
if(jm.isPlayerJailedByLastKnownUsername(args[2])) { if(jm.isPlayerJailedByLastKnownUsername(args[2])) {
Prisoner p = jm.getPrisonerByLastKnownName(args[2]); Prisoner p = jm.getPrisonerByLastKnownName(args[2]);
if(p.getRemainingTime() > 0) { if(p.getRemainingTime() > 0) {
if(!pm.isTimedEnabled()) { if(!pm.isTimedEnabled()) {
sender.sendMessage(Lang.PAYNOTENABLED.get()); sender.sendMessage(Lang.PAYNOTENABLED.get());
return true; return true;
} }
}else { }else {
if(!pm.isInfiniteEnabled()) { if(!pm.isInfiniteEnabled()) {
sender.sendMessage(Lang.PAYNOTENABLED.get()); sender.sendMessage(Lang.PAYNOTENABLED.get());
return true; return true;
} }
} }
if(args[1].startsWith("-")) { if(args[1].startsWith("-")) {
sender.sendMessage(Lang.PAYNONEGATIVEAMOUNTS.get()); sender.sendMessage(Lang.PAYNONEGATIVEAMOUNTS.get());
}else { }else {
double amt = 0; double amt = 0;
try { try {
amt = Double.parseDouble(args[1]); amt = Double.parseDouble(args[1]);
}catch(NumberFormatException e) { }catch(NumberFormatException e) {
sender.sendMessage(ChatColor.RED + "<amount> must be a number."); sender.sendMessage(ChatColor.RED + "<amount> must be a number.");
throw e; throw e;
} }
if(pm.hasEnoughToPay((Player) sender, amt)) { if(pm.hasEnoughToPay((Player) sender, amt)) {
double bill = pm.calculateBill(p); double bill = pm.calculateBill(p);
if(p.getRemainingTime() > 0) { if(p.getRemainingTime() > 0) {
//timed sentence //timed sentence
if(amt >= bill) { if(amt >= bill) {
pm.pay((Player) sender, bill); pm.pay((Player) sender, bill);
sender.sendMessage(Lang.PAYPAIDRELEASEDELSE.get(new String[] { String.valueOf(bill), p.getLastKnownName() })); sender.sendMessage(Lang.PAYPAIDRELEASEDELSE.get(new String[] { String.valueOf(bill), p.getLastKnownName() }));
jm.getPlugin().getPrisonerManager().schedulePrisonerRelease(p); jm.getPlugin().getPrisonerManager().schedulePrisonerRelease(p);
}else { }else {
long minutes = pm.getMinutesPayingFor(amt); long minutes = pm.getMinutesPayingFor(amt);
pm.pay((Player) sender, amt); pm.pay((Player) sender, amt);
long remain = p.subtractTime(TimeUnit.MILLISECONDS.convert(minutes, TimeUnit.MINUTES)); 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(new String[] { String.valueOf(amt), p.getLastKnownName(), String.valueOf(TimeUnit.MINUTES.convert(remain, TimeUnit.MILLISECONDS)) }));
} }
}else { }else {
//infinite jailing //infinite jailing
if(amt >= bill) { if(amt >= bill) {
pm.pay((Player) sender, bill); pm.pay((Player) sender, bill);
sender.sendMessage(Lang.PAYPAIDRELEASEDELSE.get(new String[] { String.valueOf(bill), p.getLastKnownName() })); sender.sendMessage(Lang.PAYPAIDRELEASEDELSE.get(new String[] { String.valueOf(bill), p.getLastKnownName() }));
jm.getPlugin().getPrisonerManager().schedulePrisonerRelease(p); jm.getPlugin().getPrisonerManager().schedulePrisonerRelease(p);
}else { }else {
//You haven't provided enough money to get them out //You haven't provided enough money to get them out
sender.sendMessage(Lang.PAYNOTENOUGHMONEYPROVIDED.get()); sender.sendMessage(Lang.PAYNOTENOUGHMONEYPROVIDED.get());
} }
} }
}else { }else {
sender.sendMessage(Lang.PAYNOTENOUGHMONEY.get()); sender.sendMessage(Lang.PAYNOTENOUGHMONEY.get());
} }
} }
}else { }else {
//Person they're trying to pay for is not jailed //Person they're trying to pay for is not jailed
sender.sendMessage(Lang.NOTJAILED.get(args[2])); sender.sendMessage(Lang.NOTJAILED.get(args[2]));
} }
} }
break; break;
default: default:
return false; return false;
} }
}else { }else {
jm.getPlugin().debug("Jail pay not enabled."); jm.getPlugin().debug("Jail pay not enabled.");
sender.sendMessage(Lang.PAYNOTENABLED.get()); sender.sendMessage(Lang.PAYNOTENABLED.get());
} }
return true; return true;
} }
} }

View File

@ -10,36 +10,36 @@ import com.graywolf336.jail.command.CommandInfo;
import com.graywolf336.jail.enums.Lang; import com.graywolf336.jail.enums.Lang;
@CommandInfo( @CommandInfo(
maxArgs = 2, maxArgs = 2,
minimumArgs = 1, minimumArgs = 1,
needsPlayer = false, needsPlayer = false,
pattern = "record|r", pattern = "record|r",
permission = "jail.command.jailrecord", permission = "jail.command.jailrecord",
usage = "/jail record [name] (display)" usage = "/jail record [name] (display)"
) )
public class JailRecordCommand implements Command { public class JailRecordCommand implements Command {
public boolean execute(JailManager jm, CommandSender sender, String... args) { public boolean execute(JailManager jm, CommandSender sender, String... args) {
if(args.length == 2) { if(args.length == 2) {
// /jail record <username> // /jail record <username>
List<String> entries = jm.getPlugin().getJailIO().getRecordEntries(args[1]); List<String> entries = jm.getPlugin().getJailIO().getRecordEntries(args[1]);
sender.sendMessage(Lang.RECORDTIMESJAILED.get(new String[] { args[1], String.valueOf(entries.size()) })); sender.sendMessage(Lang.RECORDTIMESJAILED.get(new String[] { args[1], String.valueOf(entries.size()) }));
}else if(args.length == 3) { }else if(args.length == 3) {
// /jail record <username> something // /jail record <username> something
List<String> entries = jm.getPlugin().getJailIO().getRecordEntries(args[1]); List<String> entries = jm.getPlugin().getJailIO().getRecordEntries(args[1]);
//Send all the record entries //Send all the record entries
for(String s : entries) { for(String s : entries) {
sender.sendMessage(s); sender.sendMessage(s);
} }
sender.sendMessage(Lang.RECORDTIMESJAILED.get(new String[] { args[1], String.valueOf(entries.size()) })); sender.sendMessage(Lang.RECORDTIMESJAILED.get(new String[] { args[1], String.valueOf(entries.size()) }));
}else { }else {
//They didn't do the command right //They didn't do the command right
//send them back to get the usage //send them back to get the usage
return false; return false;
} }
return true; return true;
} }
} }

View File

@ -9,29 +9,29 @@ import com.graywolf336.jail.command.CommandInfo;
import com.graywolf336.jail.enums.Lang; import com.graywolf336.jail.enums.Lang;
@CommandInfo( @CommandInfo(
maxArgs = 0, maxArgs = 0,
minimumArgs = 0, minimumArgs = 0,
needsPlayer = false, needsPlayer = false,
pattern = "reload", pattern = "reload",
permission = "jail.command.jailreload", permission = "jail.command.jailreload",
usage = "/jail reload" usage = "/jail reload"
) )
public class JailReloadCommand implements Command { public class JailReloadCommand implements Command {
public boolean execute(JailManager jm, CommandSender sender, String... args) { public boolean execute(JailManager jm, CommandSender sender, String... args) {
try { try {
jm.getPlugin().reloadConfig(); jm.getPlugin().reloadConfig();
jm.getPlugin().getJailIO().loadLanguage(); jm.getPlugin().getJailIO().loadLanguage();
jm.getPlugin().getJailIO().loadJails(); jm.getPlugin().getJailIO().loadJails();
jm.getPlugin().reloadScoreBoardManager(); jm.getPlugin().reloadScoreBoardManager();
jm.getPlugin().reloadJailSticks(); jm.getPlugin().reloadJailSticks();
jm.getPlugin().reloadJailPayManager(); jm.getPlugin().reloadJailPayManager();
jm.getPlugin().reloadUpdateCheck(); jm.getPlugin().reloadUpdateCheck();
sender.sendMessage(Lang.PLUGINRELOADED.get()); sender.sendMessage(Lang.PLUGINRELOADED.get());
}catch (Exception e) { }catch (Exception e) {
sender.sendMessage(ChatColor.RED + "Failed to reload due to: " + e.getMessage()); sender.sendMessage(ChatColor.RED + "Failed to reload due to: " + e.getMessage());
} }
return true; return true;
} }
} }

View File

@ -10,28 +10,28 @@ import com.graywolf336.jail.command.CommandInfo;
import com.graywolf336.jail.enums.Lang; import com.graywolf336.jail.enums.Lang;
@CommandInfo( @CommandInfo(
maxArgs = 0, maxArgs = 0,
minimumArgs = 0, minimumArgs = 0,
needsPlayer = true, needsPlayer = true,
pattern = "status|s", pattern = "status|s",
permission = "jail.usercmd.jailstatus", permission = "jail.usercmd.jailstatus",
usage = "/jail status" usage = "/jail status"
) )
public class JailStatusCommand implements Command{ public class JailStatusCommand implements Command{
public boolean execute(JailManager jm, CommandSender sender, String... args) { public boolean execute(JailManager jm, CommandSender sender, String... args) {
Player pl = (Player) sender; Player pl = (Player) sender;
if(jm.isPlayerJailed(pl.getUniqueId())) { if(jm.isPlayerJailed(pl.getUniqueId())) {
Prisoner p = jm.getPrisoner(pl.getUniqueId()); Prisoner p = jm.getPrisoner(pl.getUniqueId());
//They are jailed, so let's tell them some information //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()) })); sender.sendMessage(Lang.STATUS.get(new String[] { p.getReason(), p.getJailer(), String.valueOf(p.getRemainingTimeInMinutes()) }));
}else { }else {
//the sender of the command is not jailed, tell them that //the sender of the command is not jailed, tell them that
sender.sendMessage(Lang.YOUARENOTJAILED.get()); sender.sendMessage(Lang.YOUARENOTJAILED.get());
} }
return true; return true;
} }
} }

View File

@ -10,27 +10,27 @@ import com.graywolf336.jail.enums.Lang;
import com.graywolf336.jail.enums.Settings; import com.graywolf336.jail.enums.Settings;
@CommandInfo( @CommandInfo(
maxArgs = 0, maxArgs = 0,
minimumArgs = 0, minimumArgs = 0,
needsPlayer = true, needsPlayer = true,
pattern = "stick", pattern = "stick",
permission = "jail.usercmd.jailstick", permission = "jail.usercmd.jailstick",
usage = "/jail stick" usage = "/jail stick"
) )
public class JailStickCommand implements Command { public class JailStickCommand implements Command {
public boolean execute(JailManager jm, CommandSender sender, String... args) throws Exception { public boolean execute(JailManager jm, CommandSender sender, String... args) throws Exception {
if(jm.getPlugin().getConfig().getBoolean(Settings.JAILSTICKENABLED.getPath())) { if(jm.getPlugin().getConfig().getBoolean(Settings.JAILSTICKENABLED.getPath())) {
boolean using = jm.getPlugin().getJailStickManager().toggleUsingStick(((Player) sender).getUniqueId()); boolean using = jm.getPlugin().getJailStickManager().toggleUsingStick(((Player) sender).getUniqueId());
if(using) { if(using) {
sender.sendMessage(Lang.JAILSTICKENABLED.get()); sender.sendMessage(Lang.JAILSTICKENABLED.get());
}else { }else {
sender.sendMessage(Lang.JAILSTICKDISABLED.get()); sender.sendMessage(Lang.JAILSTICKDISABLED.get());
} }
}else { }else {
sender.sendMessage(Lang.JAILSTICKUSAGEDISABLED.get()); sender.sendMessage(Lang.JAILSTICKUSAGEDISABLED.get());
} }
return true; return true;
} }
} }

View File

@ -8,33 +8,33 @@ import com.graywolf336.jail.command.Command;
import com.graywolf336.jail.command.CommandInfo; import com.graywolf336.jail.command.CommandInfo;
@CommandInfo( @CommandInfo(
maxArgs = 0, maxArgs = 0,
minimumArgs = 0, minimumArgs = 0,
needsPlayer = true, needsPlayer = true,
pattern = "stop", pattern = "stop",
permission = "jail.command.jailstop", permission = "jail.command.jailstop",
usage = "/jail stop" usage = "/jail stop"
) )
public class JailStopCommand implements Command { public class JailStopCommand implements Command {
public boolean execute(JailManager jm, CommandSender sender, String... args) { public boolean execute(JailManager jm, CommandSender sender, String... args) {
boolean nothing = true; boolean nothing = true;
if(jm.isCreatingACell(sender.getName())) { if(jm.isCreatingACell(sender.getName())) {
jm.removeCellCreationPlayer(sender.getName()); jm.removeCellCreationPlayer(sender.getName());
sender.sendMessage(ChatColor.RED + "You have stopped creating cells."); sender.sendMessage(ChatColor.RED + "You have stopped creating cells.");
nothing = false; nothing = false;
} }
if(jm.isCreatingAJail(sender.getName())) { if(jm.isCreatingAJail(sender.getName())) {
jm.removeJailCreationPlayer(sender.getName()); jm.removeJailCreationPlayer(sender.getName());
sender.sendMessage(ChatColor.RED + "You have stopped creating a jail."); sender.sendMessage(ChatColor.RED + "You have stopped creating a jail.");
nothing = false; nothing = false;
} }
if(nothing) { if(nothing) {
sender.sendMessage(ChatColor.RED + "You've stopped creating....nothing."); sender.sendMessage(ChatColor.RED + "You've stopped creating....nothing.");
} }
return true; return true;
} }
} }

View File

@ -10,45 +10,45 @@ import com.graywolf336.jail.command.CommandInfo;
import com.graywolf336.jail.enums.Lang; import com.graywolf336.jail.enums.Lang;
@CommandInfo( @CommandInfo(
maxArgs = 2, maxArgs = 2,
minimumArgs = 1, minimumArgs = 1,
needsPlayer = false, needsPlayer = false,
pattern = "telein|teleportin", pattern = "telein|teleportin",
permission = "jail.command.jailtelein", permission = "jail.command.jailtelein",
usage = "/jail telein [jail] (name)" usage = "/jail telein [jail] (name)"
) )
public class JailTeleInCommand implements Command { public class JailTeleInCommand implements Command {
public boolean execute(JailManager jm, CommandSender sender, String... args) throws Exception { public boolean execute(JailManager jm, CommandSender sender, String... args) throws Exception {
Jail j = jm.getJail(args[1]); Jail j = jm.getJail(args[1]);
//The jail doesn't exist //The jail doesn't exist
if(j == null) { if(j == null) {
sender.sendMessage(Lang.NOJAIL.get(args[1])); sender.sendMessage(Lang.NOJAIL.get(args[1]));
}else { }else {
//The jail does exist //The jail does exist
//now let's check the size of the command //now let's check the size of the command
//if it has two args then someone is sending someone else in //if it has two args then someone is sending someone else in
//otherwise it is just the sender going 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]); Player p = jm.getPlugin().getServer().getPlayer(args[2]);
//If the player they're trying to send is offline, don't do anything //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])); sender.sendMessage(Lang.PLAYERNOTONLINE.get(args[2]));
}else { }else {
p.teleport(j.getTeleportIn()); p.teleport(j.getTeleportIn());
sender.sendMessage(Lang.TELEIN.get(new String[] { args[2], args[1] })); sender.sendMessage(Lang.TELEIN.get(new String[] { args[2], args[1] }));
} }
}else { }else {
if(sender instanceof Player) { if(sender instanceof Player) {
((Player) sender).teleport(j.getTeleportIn()); ((Player) sender).teleport(j.getTeleportIn());
sender.sendMessage(Lang.TELEIN.get(new String[] { sender.getName(), args[1] })); sender.sendMessage(Lang.TELEIN.get(new String[] { sender.getName(), args[1] }));
}else { }else {
sender.sendMessage(Lang.PLAYERCONTEXTREQUIRED.get()); sender.sendMessage(Lang.PLAYERCONTEXTREQUIRED.get());
} }
} }
} }
return true; return true;
} }
} }

View File

@ -10,45 +10,45 @@ import com.graywolf336.jail.command.CommandInfo;
import com.graywolf336.jail.enums.Lang; import com.graywolf336.jail.enums.Lang;
@CommandInfo( @CommandInfo(
maxArgs = 2, maxArgs = 2,
minimumArgs = 1, minimumArgs = 1,
needsPlayer = false, needsPlayer = false,
pattern = "teleout|teleportout", pattern = "teleout|teleportout",
permission = "jail.command.jailteleout", permission = "jail.command.jailteleout",
usage = "/jail teleout [jail] (name)" usage = "/jail teleout [jail] (name)"
) )
public class JailTeleOutCommand implements Command { public class JailTeleOutCommand implements Command {
public boolean execute(JailManager jm, CommandSender sender, String... args) throws Exception { public boolean execute(JailManager jm, CommandSender sender, String... args) throws Exception {
Jail j = jm.getJail(args[1]); Jail j = jm.getJail(args[1]);
//The jail doesn't exist //The jail doesn't exist
if(j == null) { if(j == null) {
sender.sendMessage(Lang.NOJAIL.get(args[1])); sender.sendMessage(Lang.NOJAIL.get(args[1]));
}else { }else {
//The jail does exist //The jail does exist
//now let's check the size of the command //now let's check the size of the command
//if it has two args then someone is sending someone else in //if it has two args then someone is sending someone else in
//otherwise it is just the sender going 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]); Player p = jm.getPlugin().getServer().getPlayer(args[2]);
//If the player they're trying to send is offline, don't do anything //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])); sender.sendMessage(Lang.PLAYERNOTONLINE.get(args[2]));
}else { }else {
p.teleport(j.getTeleportFree()); p.teleport(j.getTeleportFree());
sender.sendMessage(Lang.TELEOUT.get(new String[] { args[2], args[1] })); sender.sendMessage(Lang.TELEOUT.get(new String[] { args[2], args[1] }));
} }
}else { }else {
if(sender instanceof Player) { if(sender instanceof Player) {
((Player) sender).teleport(j.getTeleportFree()); ((Player) sender).teleport(j.getTeleportFree());
sender.sendMessage(Lang.TELEOUT.get(new String[] { sender.getName(), args[1] })); sender.sendMessage(Lang.TELEOUT.get(new String[] { sender.getName(), args[1] }));
}else { }else {
sender.sendMessage(Lang.PLAYERCONTEXTREQUIRED.get()); sender.sendMessage(Lang.PLAYERCONTEXTREQUIRED.get());
} }
} }
} }
return true; return true;
} }
} }

View File

@ -10,44 +10,44 @@ import com.graywolf336.jail.command.CommandInfo;
import com.graywolf336.jail.enums.Lang; import com.graywolf336.jail.enums.Lang;
@CommandInfo( @CommandInfo(
maxArgs = 3, maxArgs = 3,
minimumArgs = 2, minimumArgs = 2,
needsPlayer = false, needsPlayer = false,
pattern = "time|t", pattern = "time|t",
permission = "jail.command.jailtime", permission = "jail.command.jailtime",
usage = "/jail time [add|remove|show] [name] <time>" usage = "/jail time [add|remove|show] [name] <time>"
) )
public class JailTimeCommand implements Command { public class JailTimeCommand implements Command {
public boolean execute(JailManager jm, CommandSender sender, String... args) throws Exception { public boolean execute(JailManager jm, CommandSender sender, String... args) throws Exception {
if(jm.isPlayerJailedByLastKnownUsername(args[2])) { if(jm.isPlayerJailedByLastKnownUsername(args[2])) {
Prisoner p = jm.getPrisonerByLastKnownName(args[2]); Prisoner p = jm.getPrisonerByLastKnownName(args[2]);
switch(args.length) { switch(args.length) {
case 3: case 3:
if(args[1].equalsIgnoreCase("show")) { if(args[1].equalsIgnoreCase("show")) {
sender.sendMessage(Lang.PRISONERSTIME.get(new String[] { p.getLastKnownName(), String.valueOf(p.getRemainingTimeInMinutes()) })); sender.sendMessage(Lang.PRISONERSTIME.get(new String[] { p.getLastKnownName(), String.valueOf(p.getRemainingTimeInMinutes()) }));
}else { }else {
return false; return false;
} }
break; break;
case 4: case 4:
if(args[1].equalsIgnoreCase("add")) { if(args[1].equalsIgnoreCase("add")) {
p.addTime(Util.getTime(args[3])); p.addTime(Util.getTime(args[3]));
}else if(args[1].equalsIgnoreCase("remove")) { }else if(args[1].equalsIgnoreCase("remove")) {
p.subtractTime(Util.getTime(args[3])); p.subtractTime(Util.getTime(args[3]));
}else { }else {
return false; return false;
} }
sender.sendMessage(Lang.PRISONERSTIME.get(new String[] { p.getLastKnownName(), String.valueOf(p.getRemainingTimeInMinutes()) })); sender.sendMessage(Lang.PRISONERSTIME.get(new String[] { p.getLastKnownName(), String.valueOf(p.getRemainingTimeInMinutes()) }));
break; break;
default: default:
return false; return false;
} }
}else { }else {
sender.sendMessage(Lang.NOTJAILED.get(args[2])); sender.sendMessage(Lang.NOTJAILED.get(args[2]));
} }
return true; return true;
} }
} }

View File

@ -12,45 +12,45 @@ import com.graywolf336.jail.command.CommandInfo;
import com.graywolf336.jail.enums.Lang; import com.graywolf336.jail.enums.Lang;
@CommandInfo( @CommandInfo(
maxArgs = 2, maxArgs = 2,
minimumArgs = 2, minimumArgs = 2,
needsPlayer = false, needsPlayer = false,
pattern = "transferall|transall", pattern = "transferall|transall",
permission = "jail.command.jailtransferall", permission = "jail.command.jailtransferall",
usage = "/jail transferall [current] [target]" usage = "/jail transferall [current] [target]"
) )
public class JailTransferAllCommand implements Command { public class JailTransferAllCommand implements Command {
public boolean execute(JailManager jm, CommandSender sender, String... args) throws Exception { public boolean execute(JailManager jm, CommandSender sender, String... args) throws Exception {
if(jm.getJails().isEmpty()) { if(jm.getJails().isEmpty()) {
sender.sendMessage(Lang.NOJAILS.get()); sender.sendMessage(Lang.NOJAILS.get());
return true; return true;
} }
jm.getPlugin().debug("Starting to transfer everyone from '" + args[1] + "' into '" + args[2] + "'."); jm.getPlugin().debug("Starting to transfer everyone from '" + args[1] + "' into '" + args[2] + "'.");
//Check if the oldjail is not a valid jail //Check if the oldjail is not a valid jail
if(!jm.isValidJail(args[1])) { if(!jm.isValidJail(args[1])) {
sender.sendMessage(Lang.NOJAIL.get(args[1])); sender.sendMessage(Lang.NOJAIL.get(args[1]));
return true; return true;
}else if(!jm.isValidJail(args[2])) { }else if(!jm.isValidJail(args[2])) {
//Check if the targetjail is a valid jail as well //Check if the targetjail is a valid jail as well
sender.sendMessage(Lang.NOJAIL.get(args[2])); sender.sendMessage(Lang.NOJAIL.get(args[2]));
return true; return true;
} }
jm.getPlugin().debug("Sending the transferring off, jail checks all came clean."); jm.getPlugin().debug("Sending the transferring off, jail checks all came clean.");
Jail old = jm.getJail(args[1]); Jail old = jm.getJail(args[1]);
HashSet<Prisoner> oldPrisoners = new HashSet<Prisoner>(old.getAllPrisoners().values()); HashSet<Prisoner> oldPrisoners = new HashSet<Prisoner>(old.getAllPrisoners().values());
//Transfer all the prisoners //Transfer all the prisoners
for(Prisoner p : oldPrisoners) { for(Prisoner p : oldPrisoners) {
jm.getPlugin().getPrisonerManager().transferPrisoner(old, old.getCellPrisonerIsIn(p.getUUID()), jm.getJail(args[2]), null, p); jm.getPlugin().getPrisonerManager().transferPrisoner(old, old.getCellPrisonerIsIn(p.getUUID()), jm.getJail(args[2]), null, p);
} }
//Send the messages to the sender when completed //Send the messages to the sender when completed
sender.sendMessage(Lang.TRANSFERALLCOMPLETE.get(new String[] { old.getName(), args[2] })); sender.sendMessage(Lang.TRANSFERALLCOMPLETE.get(new String[] { old.getName(), args[2] }));
return true; return true;
} }
} }

View File

@ -20,120 +20,120 @@ import com.lexicalscope.jewel.cli.ArgumentValidationException;
import com.lexicalscope.jewel.cli.CliFactory; import com.lexicalscope.jewel.cli.CliFactory;
@CommandInfo( @CommandInfo(
maxArgs = 6, maxArgs = 6,
minimumArgs = 2, minimumArgs = 2,
needsPlayer = false, needsPlayer = false,
pattern = "transfer|trans", pattern = "transfer|trans",
permission = "jail.command.jailtransfer", permission = "jail.command.jailtransfer",
usage = "/jail transfer [-p player] (-j jail) (-c cell)" usage = "/jail transfer [-p player] (-j jail) (-c cell)"
) )
public class JailTransferCommand implements Command { public class JailTransferCommand implements Command {
public boolean execute(JailManager jm, CommandSender sender, String... args) throws Exception { public boolean execute(JailManager jm, CommandSender sender, String... args) throws Exception {
if(jm.getJails().isEmpty()) { if(jm.getJails().isEmpty()) {
sender.sendMessage(Lang.NOJAILS.get()); sender.sendMessage(Lang.NOJAILS.get());
return true; return true;
} }
//Convert to a List<String> so we can edit the list //Convert to a List<String> so we can edit the list
List<String> arguments = new LinkedList<String>(Arrays.asList(args)); List<String> arguments = new LinkedList<String>(Arrays.asList(args));
//remove the first argument of "transfer" //remove the first argument of "transfer"
arguments.remove(0); arguments.remove(0);
//Parse the command //Parse the command
Transfer params = null; Transfer params = null;
try { try {
params = CliFactory.parseArguments(Transfer.class, arguments.toArray(new String[arguments.size()])); params = CliFactory.parseArguments(Transfer.class, arguments.toArray(new String[arguments.size()]));
}catch(ArgumentValidationException e) { }catch(ArgumentValidationException e) {
sender.sendMessage(ChatColor.RED + e.getMessage()); sender.sendMessage(ChatColor.RED + e.getMessage());
return true; return true;
} }
//Verify they gave us a player and if so check if they're jailed //Verify they gave us a player and if so check if they're jailed
if(params.getPlayer() == null) { if(params.getPlayer() == null) {
sender.sendMessage(Lang.PROVIDEAPLAYER.get(Lang.TRANSFERRING)); sender.sendMessage(Lang.PROVIDEAPLAYER.get(Lang.TRANSFERRING));
return true; return true;
}else if(!jm.isPlayerJailedByLastKnownUsername(params.getPlayer())) { }else if(!jm.isPlayerJailedByLastKnownUsername(params.getPlayer())) {
sender.sendMessage(Lang.NOTJAILED.get(params.getPlayer())); sender.sendMessage(Lang.NOTJAILED.get(params.getPlayer()));
return true; return true;
} }
jm.getPlugin().debug("Checking everything before we transfer: " + params.getPlayer()); jm.getPlugin().debug("Checking everything before we transfer: " + params.getPlayer());
//If they didn't provide a jail, tell them we need one //If they didn't provide a jail, tell them we need one
if(params.getJail() == null) { if(params.getJail() == null) {
sender.sendMessage(Lang.PROVIDEAJAIL.get(Lang.TRANSFERRING)); sender.sendMessage(Lang.PROVIDEAJAIL.get(Lang.TRANSFERRING));
return true; return true;
}else { }else {
//Check if the jail they did provided is not a valid jail //Check if the jail they did provided is not a valid jail
if(!jm.isValidJail(params.getJail())) { if(!jm.isValidJail(params.getJail())) {
sender.sendMessage(Lang.NOJAIL.get(params.getJail())); sender.sendMessage(Lang.NOJAIL.get(params.getJail()));
return true; return true;
} }
} }
jm.getPlugin().debug("They provided a valid jail, so let's check the target cell."); jm.getPlugin().debug("They provided a valid jail, so let's check the target cell.");
Jail target = jm.getJail(params.getJail()); Jail target = jm.getJail(params.getJail());
Cell targetCell = null; Cell targetCell = null;
//Check if they provided a cell and if so does it exist //Check if they provided a cell and if so does it exist
if(params.getCell() != null) { if(params.getCell() != null) {
if(target.getCell(params.getCell()) == null) { if(target.getCell(params.getCell()) == null) {
sender.sendMessage(Lang.NOCELL.get(new String[] { params.getCell(), params.getJail() })); sender.sendMessage(Lang.NOCELL.get(new String[] { params.getCell(), params.getJail() }));
return true; return true;
}else { }else {
//Store the cell for easy of access and also check if it already is full //Store the cell for easy of access and also check if it already is full
targetCell = target.getCell(params.getCell()); targetCell = target.getCell(params.getCell());
if(targetCell.hasPrisoner()) { if(targetCell.hasPrisoner()) {
//If the cell has a prisoner, don't allow jailing them to that particular cell //If the cell has a prisoner, don't allow jailing them to that particular cell
sender.sendMessage(Lang.CELLNOTEMPTY.get(params.getCell())); sender.sendMessage(Lang.CELLNOTEMPTY.get(params.getCell()));
//But suggest the first empty cell we find //But suggest the first empty cell we find
Cell suggestedCell = jm.getJail(params.getCell()).getFirstEmptyCell(); Cell suggestedCell = jm.getJail(params.getCell()).getFirstEmptyCell();
if(suggestedCell != null) { if(suggestedCell != null) {
sender.sendMessage(Lang.SUGGESTEDCELL.get(new String[] { params.getCell(), suggestedCell.getName() })); sender.sendMessage(Lang.SUGGESTEDCELL.get(new String[] { params.getCell(), suggestedCell.getName() }));
}else { }else {
sender.sendMessage(Lang.NOEMPTYCELLS.get(params.getCell())); sender.sendMessage(Lang.NOEMPTYCELLS.get(params.getCell()));
} }
return true; return true;
} }
} }
} }
jm.getPlugin().debug("Calling the PrePrisonerTransferredEvent, jail and cell check all came out clean."); jm.getPlugin().debug("Calling the PrePrisonerTransferredEvent, jail and cell check all came out clean.");
Prisoner p = jm.getPrisonerByLastKnownName(params.getPlayer()); Prisoner p = jm.getPrisonerByLastKnownName(params.getPlayer());
//Throw the custom event before transferring them, allowing another plugin to cancel it. //Throw the custom event before transferring them, allowing another plugin to cancel it.
PrePrisonerTransferredEvent event = new PrePrisonerTransferredEvent(jm.getJailPlayerIsIn(p.getUUID()), PrePrisonerTransferredEvent event = new PrePrisonerTransferredEvent(jm.getJailPlayerIsIn(p.getUUID()),
jm.getJailPlayerIsIn(p.getUUID()).getCellPrisonerIsIn(p.getUUID()), jm.getJailPlayerIsIn(p.getUUID()).getCellPrisonerIsIn(p.getUUID()),
target, targetCell, p, jm.getPlugin().getServer().getPlayer(p.getUUID()), sender.getName()); target, targetCell, p, jm.getPlugin().getServer().getPlayer(p.getUUID()), sender.getName());
jm.getPlugin().getServer().getPluginManager().callEvent(event); jm.getPlugin().getServer().getPluginManager().callEvent(event);
if(event.isCancelled()) { if(event.isCancelled()) {
if(event.getCancelledMessage().isEmpty()) { if(event.getCancelledMessage().isEmpty()) {
//The plugin didn't provide a cancel message/reason so send the default one //The plugin didn't provide a cancel message/reason so send the default one
sender.sendMessage(Lang.TRANSFERCANCELLEDBYANOTHERPLUGIN.get(params.getPlayer())); sender.sendMessage(Lang.TRANSFERCANCELLEDBYANOTHERPLUGIN.get(params.getPlayer()));
}else { }else {
sender.sendMessage(event.getCancelledMessage()); sender.sendMessage(event.getCancelledMessage());
} }
return true; return true;
} }
//Start the transferring of the prisoner //Start the transferring of the prisoner
jm.getPlugin().getPrisonerManager().transferPrisoner(jm.getJailPlayerIsIn(p.getUUID()), jm.getPlugin().getPrisonerManager().transferPrisoner(jm.getJailPlayerIsIn(p.getUUID()),
jm.getJailPlayerIsIn(p.getUUID()).getCellPrisonerIsIn(p.getUUID()), jm.getJailPlayerIsIn(p.getUUID()).getCellPrisonerIsIn(p.getUUID()),
target, targetCell, p); target, targetCell, p);
//Send the messages to the sender, if no cell then say that but if cell send that as well //Send the messages to the sender, if no cell then say that but if cell send that as well
if(targetCell == null) { if(targetCell == null) {
sender.sendMessage(Lang.TRANSFERCOMPLETENOCELL.get(new String[] { params.getPlayer(), target.getName() })); sender.sendMessage(Lang.TRANSFERCOMPLETENOCELL.get(new String[] { params.getPlayer(), target.getName() }));
}else { }else {
sender.sendMessage(Lang.TRANSFERCOMPLETECELL.get(new String[] { params.getPlayer(), target.getName(), targetCell.getName() })); sender.sendMessage(Lang.TRANSFERCOMPLETECELL.get(new String[] { params.getPlayer(), target.getName(), targetCell.getName() }));
} }
return true; return true;
} }
} }

View File

@ -7,20 +7,20 @@ import com.graywolf336.jail.command.Command;
import com.graywolf336.jail.command.CommandInfo; import com.graywolf336.jail.command.CommandInfo;
@CommandInfo( @CommandInfo(
maxArgs = 0, maxArgs = 0,
minimumArgs = 0, minimumArgs = 0,
needsPlayer = false, needsPlayer = false,
pattern = "version|ver|v", pattern = "version|ver|v",
permission = "jail.command.jailversion", permission = "jail.command.jailversion",
usage = "/jail version" usage = "/jail version"
) )
public class JailVersionCommand implements Command{ public class JailVersionCommand implements Command{
public boolean execute(JailManager jm, CommandSender sender, String... args) { public boolean execute(JailManager jm, CommandSender sender, String... args) {
// Sends the version number to the sender // Sends the version number to the sender
sender.sendMessage("Jail Version: " + jm.getPlugin().getDescription().getVersion()); sender.sendMessage("Jail Version: " + jm.getPlugin().getDescription().getVersion());
return true; return true;
} }
} }

View File

@ -1,14 +1,14 @@
package com.graywolf336.jail.enums; package com.graywolf336.jail.enums;
public enum Confirmation { public enum Confirmation {
/** When they are clearing a jail from all their prisoner's with releasing properly. */ /** When they are clearing a jail from all their prisoner's with releasing properly. */
CLEAR, CLEAR,
/** When they are clearing a jail from all their prisoner's by force. */ /** When they are clearing a jail from all their prisoner's by force. */
CLEARFORCE, CLEARFORCE,
/** When they are deleting a cell from a jail. */ /** When they are deleting a cell from a jail. */
DELETECELL, DELETECELL,
/** When they are deleting all a jail's cells. */ /** When they are deleting all a jail's cells. */
DELETECELLS, DELETECELLS,
/** When they are deleting a jail. */ /** When they are deleting a jail. */
DELETE; DELETE;
} }

View File

@ -1,80 +1,80 @@
package com.graywolf336.jail.enums; package com.graywolf336.jail.enums;
public enum Settings { public enum Settings {
AUTOMATICMUTE("jailing.jail.automaticMute"), AUTOMATICMUTE("jailing.jail.automaticMute"),
BROADCASTJAILING("jailing.jail.broadcastJailing"), BROADCASTJAILING("jailing.jail.broadcastJailing"),
BLOCKBREAKPENALTY("jailing.during.blockBreakPenalty"), BLOCKBREAKPENALTY("jailing.during.blockBreakPenalty"),
BLOCKBREAKPROTECTION("jailing.during.blockBreakProtection"), BLOCKBREAKPROTECTION("jailing.during.blockBreakProtection"),
BLOCKBREAKWHITELIST("jailing.during.blockBreakWhiteList"), BLOCKBREAKWHITELIST("jailing.during.blockBreakWhiteList"),
BLOCKPLACEPENALTY("jailing.during.blockPlacePenalty"), BLOCKPLACEPENALTY("jailing.during.blockPlacePenalty"),
BLOCKPLACEPROTECTION("jailing.during.blockPlaceProtection"), BLOCKPLACEPROTECTION("jailing.during.blockPlaceProtection"),
BLOCKPLACEWHITELIST("jailing.during.blockPlaceWhiteList"), BLOCKPLACEWHITELIST("jailing.during.blockPlaceWhiteList"),
CLOTHINGENABLED("jailing.jail.clothing.enabled"), CLOTHINGENABLED("jailing.jail.clothing.enabled"),
CLOTHINGHELMET("jailing.jail.clothing.helmet"), CLOTHINGHELMET("jailing.jail.clothing.helmet"),
CLOTHINGCHEST("jailing.jail.clothing.chest"), CLOTHINGCHEST("jailing.jail.clothing.chest"),
CLOTHINGLEGS("jailing.jail.clothing.legs"), CLOTHINGLEGS("jailing.jail.clothing.legs"),
CLOTHINGBOOTS("jailing.jail.clothing.boots"), CLOTHINGBOOTS("jailing.jail.clothing.boots"),
COMMANDSONJAIL("jailing.jail.commands"), COMMANDSONJAIL("jailing.jail.commands"),
COMMANDSONRELEASE("jailing.release.commands"), COMMANDSONRELEASE("jailing.release.commands"),
COMMANDPENALTY("jailing.during.commandPenalty"), COMMANDPENALTY("jailing.during.commandPenalty"),
COMMANDPROTECTION("jailing.during.commandProtection"), COMMANDPROTECTION("jailing.during.commandProtection"),
COMMANDWHITELIST("jailing.during.commandWhitelist"), COMMANDWHITELIST("jailing.during.commandWhitelist"),
CONFIGVERSION("system.version"), CONFIGVERSION("system.version"),
COUNTDOWNTIMEOFFLINE("jailing.during.countDownTimeWhileOffline"), COUNTDOWNTIMEOFFLINE("jailing.during.countDownTimeWhileOffline"),
CROPTRAMPLINGPENALTY("jailing.during.cropTramplingPenalty"), CROPTRAMPLINGPENALTY("jailing.during.cropTramplingPenalty"),
CROPTRAMPLINGPROTECTION("jailing.during.cropTramplingProtection"), CROPTRAMPLINGPROTECTION("jailing.during.cropTramplingProtection"),
DEBUG("system.debug"), DEBUG("system.debug"),
DEFAULTJAIL("jailing.jail.default.jail"), DEFAULTJAIL("jailing.jail.default.jail"),
DEFAULTTIME("jailing.jail.default.time"), DEFAULTTIME("jailing.jail.default.time"),
ENDERMENPROTECTION("jails.endermenProtection"), ENDERMENPROTECTION("jails.endermenProtection"),
EXPLOSIONPROTECTION("jails.explosionProtection"), EXPLOSIONPROTECTION("jails.explosionProtection"),
FOODCONTROL("jailing.during.foodControl.enabled"), FOODCONTROL("jailing.during.foodControl.enabled"),
FOODCONTROLMAX("jailing.during.foodControl.max"), FOODCONTROLMAX("jailing.during.foodControl.max"),
FOODCONTROLMIN("jailing.during.foodControl.min"), FOODCONTROLMIN("jailing.during.foodControl.min"),
IGNORESLEEPINGSTATE("jailing.during.ignoreSleeping"), IGNORESLEEPINGSTATE("jailing.during.ignoreSleeping"),
JAILSTICKENABLED("jailstick.enabled"), JAILSTICKENABLED("jailstick.enabled"),
JAILSTICKSTICKS("jailstick.sticks"), JAILSTICKSTICKS("jailstick.sticks"),
JAILEDGAMEMODE("jailing.jail.gameMode"), JAILEDGAMEMODE("jailing.jail.gameMode"),
JAILEDINVENTORYBLACKLIST("jailing.jail.inventory.blacklist"), JAILEDINVENTORYBLACKLIST("jailing.jail.inventory.blacklist"),
JAILEDSTOREINVENTORY("jailing.jail.inventory.store"), JAILEDSTOREINVENTORY("jailing.jail.inventory.store"),
JAILPAYENABLED("jailpay.enabled"), JAILPAYENABLED("jailpay.enabled"),
JAILPAYITEM("jailpay.item"), JAILPAYITEM("jailpay.item"),
JAILPAYPRICEPERMINUTE ("jailpay.pricePerMinute"), JAILPAYPRICEPERMINUTE ("jailpay.pricePerMinute"),
JAILPAYPRICEINFINITE ("jailpay.priceInfinite"), JAILPAYPRICEINFINITE ("jailpay.priceInfinite"),
LANGUAGE("system.language"), LANGUAGE("system.language"),
LOGJAILINGTOCONSOLE("jailing.jail.log.console"), LOGJAILINGTOCONSOLE("jailing.jail.log.console"),
LOGJAILINGTOPROFILE("jailing.jail.log.profile"), LOGJAILINGTOPROFILE("jailing.jail.log.profile"),
MAXAFKTIME("jailing.during.maxAFKTime"), MAXAFKTIME("jailing.during.maxAFKTime"),
MOVEPENALTY("jailing.during.movePenalty"), MOVEPENALTY("jailing.during.movePenalty"),
MOVEPROTECTION("jailing.during.moveProtection"), MOVEPROTECTION("jailing.during.moveProtection"),
PREVENTINTERACTIONBLOCKS("jailing.during.preventInteractionBlocks"), PREVENTINTERACTIONBLOCKS("jailing.during.preventInteractionBlocks"),
PREVENTINTERACTIONBLOCKSPENALTY("jailing.during.preventInteractionBlocksPenalty"), PREVENTINTERACTIONBLOCKSPENALTY("jailing.during.preventInteractionBlocksPenalty"),
PREVENTINTERACTIONITEMS("jailing.during.preventInteractionItems"), PREVENTINTERACTIONITEMS("jailing.during.preventInteractionItems"),
PREVENTINTERACTIONITEMSPENALTY("jailing.during.preventInteractionItemsPenalty"), PREVENTINTERACTIONITEMSPENALTY("jailing.during.preventInteractionItemsPenalty"),
PRISONEROPENCHEST("jailing.during.openChest"), PRISONEROPENCHEST("jailing.during.openChest"),
RECIEVEMESSAGES("jailing.during.recieveMessages"), RECIEVEMESSAGES("jailing.during.recieveMessages"),
RELEASETOPREVIOUSPOSITION("jailing.release.backToPreviousPosition"), RELEASETOPREVIOUSPOSITION("jailing.release.backToPreviousPosition"),
RESTOREPREVIOUSGAMEMODE("jailing.release.restorePreviousGameMode"), RESTOREPREVIOUSGAMEMODE("jailing.release.restorePreviousGameMode"),
SCOREBOARDENABLED("jailing.during.scoreboard.enabled"), SCOREBOARDENABLED("jailing.during.scoreboard.enabled"),
SCOREBOARDTITLE("jailing.during.scoreboard.title"), SCOREBOARDTITLE("jailing.during.scoreboard.title"),
SCOREBOARDTIME("jailing.during.scoreboard.time"), SCOREBOARDTIME("jailing.during.scoreboard.time"),
TELEPORTONRELEASE("jailing.release.teleport"), TELEPORTONRELEASE("jailing.release.teleport"),
UPDATECHANNEL("system.updates.channel"), UPDATECHANNEL("system.updates.channel"),
UPDATENOTIFICATIONS("system.updates.notification"), UPDATENOTIFICATIONS("system.updates.notification"),
UPDATETIME("system.updates.time"), UPDATETIME("system.updates.time"),
USEBUKKITTIMER("system.useBukkitTimer"); USEBUKKITTIMER("system.useBukkitTimer");
private String path; private String path;
private Settings(String path) { private Settings(String path) {
this.path = path; this.path = path;
} }
/** /**
* Gets the path this setting is in config. * Gets the path this setting is in config.
* @return The path where this setting resides in the config. * @return The path where this setting resides in the config.
*/ */
public String getPath() { public String getPath() {
return this.path; return this.path;
} }
} }

View File

@ -22,104 +22,104 @@ import com.graywolf336.jail.beans.Stick;
* @version 1.0.0 * @version 1.0.0
*/ */
public class PrePrisonerJailedByJailStickEvent extends Event implements Cancellable { public class PrePrisonerJailedByJailStickEvent extends Event implements Cancellable {
private static final HandlerList handlers = new HandlerList(); private static final HandlerList handlers = new HandlerList();
private boolean cancelled = false; private boolean cancelled = false;
private Jail jail; private Jail jail;
private Cell cell; private Cell cell;
private Prisoner prisoner; private Prisoner prisoner;
private Player player; private Player player;
private String jailer, cancelMsg; private String jailer, cancelMsg;
private Stick stick; private Stick stick;
/** /**
* Creates a new {@link PrePrisonerJailedByJailStickEvent prisoner jailed by a jail stick event} for the given player before they get sent to jail. * Creates a new {@link PrePrisonerJailedByJailStickEvent prisoner jailed by a jail stick event} for the given player before they get sent to jail.
* *
* @param jail The jail the prisoner will be jailed at. * @param jail The jail the prisoner will be jailed at.
* @param cell The cell we're going to be sending the prisoner to, can be null. * @param cell The cell we're going to be sending the prisoner to, can be null.
* @param prisoner The prisoner data. * @param prisoner The prisoner data.
* @param player The player being jailed. * @param player The player being jailed.
* @param jailer The name of what jailed this prisoner. * @param jailer The name of what jailed this prisoner.
* @param stick The {@link Stick jail stick} used. * @param stick The {@link Stick jail stick} used.
*/ */
public PrePrisonerJailedByJailStickEvent(Jail jail, Cell cell, Prisoner prisoner, Player player, String jailer, Stick stick) { public PrePrisonerJailedByJailStickEvent(Jail jail, Cell cell, Prisoner prisoner, Player player, String jailer, Stick stick) {
this.jail = jail; this.jail = jail;
this.cell = cell; this.cell = cell;
this.prisoner = prisoner; this.prisoner = prisoner;
this.player = player; this.player = player;
this.jailer = jailer; this.jailer = jailer;
this.stick = stick; this.stick = stick;
this.cancelMsg = ""; this.cancelMsg = "";
} }
/** Gets the {@link Jail} this prisoner is being sent to. */ /** Gets the {@link Jail} this prisoner is being sent to. */
public Jail getJail() { public Jail getJail() {
return this.jail; return this.jail;
} }
/** Gets the cell we're going to be sending the prisoner to. */ /** Gets the cell we're going to be sending the prisoner to. */
public Cell getCell() { public Cell getCell() {
return this.cell; return this.cell;
} }
/** Sets the cell we're going to be sending the prisoner to. */ /** Sets the cell we're going to be sending the prisoner to. */
public void setCell(Cell cell) { public void setCell(Cell cell) {
this.cell = cell; this.cell = cell;
} }
/** Gets the {@link Prisoner} data for this prisoner. */ /** Gets the {@link Prisoner} data for this prisoner. */
public Prisoner getPrisoner() { public Prisoner getPrisoner() {
return this.prisoner; return this.prisoner;
} }
/** Gets the instance of the player being jailed. */ /** Gets the instance of the player being jailed. */
public Player getPlayer() { public Player getPlayer() {
return this.player; return this.player;
} }
/** Gets the jailer who jailed this prisoner. */ /** Gets the jailer who jailed this prisoner. */
public String getJailer() { public String getJailer() {
return this.jailer; return this.jailer;
} }
/** /**
* Sets who jailed this prisoner. * Sets who jailed this prisoner.
* *
* @param jailer The name to put who is the jailer for this prisoner. * @param jailer The name to put who is the jailer for this prisoner.
*/ */
public void setJailer(String jailer) { public void setJailer(String jailer) {
this.jailer = jailer; this.jailer = jailer;
} }
/** Gets the jail stick used. */ /** Gets the jail stick used. */
public Stick getJailStick() { public Stick getJailStick() {
return this.stick; return this.stick;
} }
/** Checks whether this event is cancelled or not. */ /** Checks whether this event is cancelled or not. */
public boolean isCancelled() { public boolean isCancelled() {
return this.cancelled; return this.cancelled;
} }
/** Sets whether this event should be cancelled. */ /** Sets whether this event should be cancelled. */
public void setCancelled(boolean cancel) { public void setCancelled(boolean cancel) {
this.cancelled = cancel; this.cancelled = cancel;
} }
/** Returns the cancelled message. */ /** Returns the cancelled message. */
public String getCancelledMessage() { public String getCancelledMessage() {
return this.cancelMsg; return this.cancelMsg;
} }
/** Sets the cancelled message. */ /** Sets the cancelled message. */
public void setCancelledMessage(String msg) { public void setCancelledMessage(String msg) {
this.cancelMsg = msg; this.cancelMsg = msg;
} }
public static HandlerList getHandlerList() { public static HandlerList getHandlerList() {
return handlers; return handlers;
} }
public HandlerList getHandlers() { public HandlerList getHandlers() {
return handlers; return handlers;
} }
} }

View File

@ -21,104 +21,104 @@ import com.graywolf336.jail.beans.Prisoner;
* @version 1.0.0 * @version 1.0.0
*/ */
public class PrePrisonerJailedEvent extends Event implements Cancellable { public class PrePrisonerJailedEvent extends Event implements Cancellable {
private static final HandlerList handlers = new HandlerList(); private static final HandlerList handlers = new HandlerList();
private boolean cancelled = false; private boolean cancelled = false;
private boolean online; private boolean online;
private Jail jail; private Jail jail;
private Cell cell; private Cell cell;
private Prisoner prisoner; private Prisoner prisoner;
private Player player; private Player player;
private String jailer, cancelMsg; private String jailer, cancelMsg;
/** /**
* Creates a new {@link PrePrisonerJailedEvent prisoner jailed event} for the given player before they get sent to jail. * Creates a new {@link PrePrisonerJailedEvent prisoner jailed event} for the given player before they get sent to jail.
* *
* @param jail The jail the prisoner will be jailed at. * @param jail The jail the prisoner will be jailed at.
* @param cell The cell we're going to be sending the prisoner to, can be null. * @param cell The cell we're going to be sending the prisoner to, can be null.
* @param prisoner The prisoner data. * @param prisoner The prisoner data.
* @param player The player being jailed. * @param player The player being jailed.
* @param online Whether the player is online or not. * @param online Whether the player is online or not.
* @param jailer The name of what jailed this prisoner. * @param jailer The name of what jailed this prisoner.
*/ */
public PrePrisonerJailedEvent(Jail jail, Cell cell, Prisoner prisoner, Player player, boolean online, String jailer) { public PrePrisonerJailedEvent(Jail jail, Cell cell, Prisoner prisoner, Player player, boolean online, String jailer) {
this.jail = jail; this.jail = jail;
this.cell = cell; this.cell = cell;
this.prisoner = prisoner; this.prisoner = prisoner;
this.player = player; this.player = player;
this.online = online; this.online = online;
this.jailer = jailer; this.jailer = jailer;
this.cancelMsg = ""; this.cancelMsg = "";
} }
/** Gets the {@link Jail} this prisoner is being sent to. */ /** Gets the {@link Jail} this prisoner is being sent to. */
public Jail getJail() { public Jail getJail() {
return this.jail; return this.jail;
} }
/** Gets the cell we're going to be sending the prisoner to. */ /** Gets the cell we're going to be sending the prisoner to. */
public Cell getCell() { public Cell getCell() {
return this.cell; return this.cell;
} }
/** Sets the cell we're going to be sending the prisoner to. */ /** Sets the cell we're going to be sending the prisoner to. */
public void setCell(Cell cell) { public void setCell(Cell cell) {
this.cell = cell; this.cell = cell;
} }
/** Gets the {@link Prisoner} data for this prisoner. */ /** Gets the {@link Prisoner} data for this prisoner. */
public Prisoner getPrisoner() { public Prisoner getPrisoner() {
return this.prisoner; return this.prisoner;
} }
/** Gets the instance of the player being jailed <strong>but will return null if {@link #isOnline()} returns false</strong>. */ /** Gets the instance of the player being jailed <strong>but will return null if {@link #isOnline()} returns false</strong>. */
public Player getPlayer() { public Player getPlayer() {
return this.player; return this.player;
} }
/** Gets whether the prisoner being jailed is online or not. */ /** Gets whether the prisoner being jailed is online or not. */
public boolean isOnline() { public boolean isOnline() {
return this.online; return this.online;
} }
/** Gets the jailer who jailed this prisoner. */ /** Gets the jailer who jailed this prisoner. */
public String getJailer() { public String getJailer() {
return this.jailer; return this.jailer;
} }
/** /**
* Sets who jailed this prisoner. * Sets who jailed this prisoner.
* *
* @param jailer The name to put who is the jailer for this prisoner. * @param jailer The name to put who is the jailer for this prisoner.
*/ */
public void setJailer(String jailer) { public void setJailer(String jailer) {
this.jailer = jailer; this.jailer = jailer;
} }
/** Checks whether this event is cancelled or not. */ /** Checks whether this event is cancelled or not. */
public boolean isCancelled() { public boolean isCancelled() {
return this.cancelled; return this.cancelled;
} }
/** Sets whether this event should be cancelled. */ /** Sets whether this event should be cancelled. */
public void setCancelled(boolean cancel) { public void setCancelled(boolean cancel) {
this.cancelled = cancel; this.cancelled = cancel;
} }
/** Returns the cancelled message. */ /** Returns the cancelled message. */
public String getCancelledMessage() { public String getCancelledMessage() {
return this.cancelMsg; return this.cancelMsg;
} }
/** Sets the cancelled message. */ /** Sets the cancelled message. */
public void setCancelledMessage(String msg) { public void setCancelledMessage(String msg) {
this.cancelMsg = msg; this.cancelMsg = msg;
} }
public static HandlerList getHandlerList() { public static HandlerList getHandlerList() {
return handlers; return handlers;
} }
public HandlerList getHandlers() { public HandlerList getHandlers() {
return handlers; return handlers;
} }
} }

View File

@ -22,52 +22,52 @@ import com.graywolf336.jail.beans.Prisoner;
* @version 1.0.0 * @version 1.0.0
*/ */
public class PrePrisonerReleasedEvent extends Event { public class PrePrisonerReleasedEvent extends Event {
private static final HandlerList handlers = new HandlerList(); private static final HandlerList handlers = new HandlerList();
private Jail jail; private Jail jail;
private Cell cell; private Cell cell;
private Prisoner prisoner; private Prisoner prisoner;
private Player player; private Player player;
/** /**
* Creates a new {@link PrePrisonerReleasedEvent pre-prisoner released event} for the given player. * Creates a new {@link PrePrisonerReleasedEvent pre-prisoner released event} for the given player.
* *
* @param jail The jail the prisoner will be jailed at. * @param jail The jail the prisoner will be jailed at.
* @param cell The cell we're going to be sending the prisoner to, can be null. * @param cell The cell we're going to be sending the prisoner to, can be null.
* @param prisoner The prisoner data. * @param prisoner The prisoner data.
* @param player The player being jailed. * @param player The player being jailed.
*/ */
public PrePrisonerReleasedEvent(Jail jail, Cell cell, Prisoner prisoner, Player player) { public PrePrisonerReleasedEvent(Jail jail, Cell cell, Prisoner prisoner, Player player) {
this.jail = jail; this.jail = jail;
this.cell = cell; this.cell = cell;
this.prisoner = prisoner; this.prisoner = prisoner;
this.player = player; this.player = player;
} }
/** Gets the {@link Jail} this prisoner is coming from. */ /** Gets the {@link Jail} this prisoner is coming from. */
public Jail getJail() { public Jail getJail() {
return this.jail; return this.jail;
} }
/** Gets the cell where the prisoner was jailed in, null if they weren't in one. */ /** Gets the cell where the prisoner was jailed in, null if they weren't in one. */
public Cell getCell() { public Cell getCell() {
return this.cell; return this.cell;
} }
/** Gets the {@link Prisoner} data for this prisoner. */ /** Gets the {@link Prisoner} data for this prisoner. */
public Prisoner getPrisoner() { public Prisoner getPrisoner() {
return this.prisoner; return this.prisoner;
} }
/** Gets the instance of the player being released. */ /** Gets the instance of the player being released. */
public Player getPlayer() { public Player getPlayer() {
return this.player; return this.player;
} }
public static HandlerList getHandlerList() { public static HandlerList getHandlerList() {
return handlers; return handlers;
} }
public HandlerList getHandlers() { public HandlerList getHandlers() {
return handlers; return handlers;
} }
} }

View File

@ -21,132 +21,132 @@ import com.graywolf336.jail.beans.Prisoner;
* @version 1.0.0 * @version 1.0.0
*/ */
public class PrePrisonerTransferredEvent extends Event implements Cancellable { public class PrePrisonerTransferredEvent extends Event implements Cancellable {
private static final HandlerList handlers = new HandlerList(); private static final HandlerList handlers = new HandlerList();
private boolean cancelled = false; private boolean cancelled = false;
private Jail originalJail, targetJail; private Jail originalJail, targetJail;
private Cell originalCell, targetCell; private Cell originalCell, targetCell;
private Prisoner prisoner; private Prisoner prisoner;
private Player player; private Player player;
private String transferor, cancelMsg; private String transferor, cancelMsg;
/** /**
* Creates a new {@link PrePrisonerTransferredEvent prisoner transferred event} for the given player before they get transferred to their jail and cell. * Creates a new {@link PrePrisonerTransferredEvent prisoner transferred event} for the given player before they get transferred to their jail and cell.
* *
* @param originalJail The jail the prisoner is coming from. * @param originalJail The jail the prisoner is coming from.
* @param originalCell The cell the prisoner is coming from, can be null. * @param originalCell The cell the prisoner is coming from, can be null.
* @param targetJail The jail the prisoner is going to. * @param targetJail The jail the prisoner is going to.
* @param targetCell The cell the prisoner is going to, can be null. * @param targetCell The cell the prisoner is going to, can be null.
* @param prisoner The prisoner data. * @param prisoner The prisoner data.
* @param player The player being jailed. * @param player The player being jailed.
* @param transferor The name of what is transferring this prisoner. * @param transferor The name of what is transferring this prisoner.
*/ */
public PrePrisonerTransferredEvent(Jail originalJail, Cell originalCell, Jail targetJail, Cell targetCell, Prisoner prisoner, Player player, String transferor) { public PrePrisonerTransferredEvent(Jail originalJail, Cell originalCell, Jail targetJail, Cell targetCell, Prisoner prisoner, Player player, String transferor) {
this.originalJail = originalJail; this.originalJail = originalJail;
this.originalCell = originalCell; this.originalCell = originalCell;
this.targetJail = targetJail; this.targetJail = targetJail;
this.targetCell = targetCell; this.targetCell = targetCell;
this.prisoner = prisoner; this.prisoner = prisoner;
this.player = player; this.player = player;
this.transferor = transferor; this.transferor = transferor;
this.cancelMsg = ""; this.cancelMsg = "";
} }
/** Gets the {@link Jail} this prisoner is coming from. */ /** Gets the {@link Jail} this prisoner is coming from. */
public Jail getOriginalJail() { public Jail getOriginalJail() {
return this.originalJail; return this.originalJail;
} }
/** Gets the {@link Cell} this prisoner is coming from, can be null. */ /** Gets the {@link Cell} this prisoner is coming from, can be null. */
public Cell getOriginalCell() { public Cell getOriginalCell() {
return this.originalCell; return this.originalCell;
} }
/** Gets the {@link Jail} this prisoner is being transferred to. */ /** Gets the {@link Jail} this prisoner is being transferred to. */
public Jail getTargetJail() { public Jail getTargetJail() {
return this.targetJail; return this.targetJail;
} }
/** /**
* Sets the target jail where this prisoner is being sent to. * Sets the target jail where this prisoner is being sent to.
* *
* @param jail The {@link Jail} this prisoner should be sent to instead of what it was. * @param jail The {@link Jail} this prisoner should be sent to instead of what it was.
*/ */
public void setTargetJail(Jail jail) { public void setTargetJail(Jail jail) {
this.targetJail = jail; this.targetJail = jail;
} }
/** Gets the {@link Cell} this prisoner is being sent to, can be null. /** Gets the {@link Cell} this prisoner is being sent to, can be null.
* *
* Will return null if the cell is not in the targetJail. * Will return null if the cell is not in the targetJail.
*/ */
public Cell getTargetCell() { public Cell getTargetCell() {
if(this.targetJail.isValidCell(this.targetCell.getName())) return this.targetCell; if(this.targetJail.isValidCell(this.targetCell.getName())) return this.targetCell;
else return null; else return null;
} }
/** /**
* Sets the target {@link Cell} this prisoner is being sent to. * Sets the target {@link Cell} this prisoner is being sent to.
* *
* @param cell The {@link Cell} this prisoner should be sent to instead of what it was. * @param cell The {@link Cell} this prisoner should be sent to instead of what it was.
*/ */
public void setTargetCell(Cell cell) { public void setTargetCell(Cell cell) {
this.targetCell = cell; this.targetCell = cell;
} }
/** Gets the {@link Prisoner} data for this prisoner. */ /** Gets the {@link Prisoner} data for this prisoner. */
public Prisoner getPrisoner() { public Prisoner getPrisoner() {
return this.prisoner; return this.prisoner;
} }
/** Gets the instance of the player being transferred <strong>but will return null if {@link #isOnline()} returns false</strong>. */ /** Gets the instance of the player being transferred <strong>but will return null if {@link #isOnline()} returns false</strong>. */
public Player getPlayer() { public Player getPlayer() {
return this.player; return this.player;
} }
/** Gets whether the prisoner being transferred is online or not. */ /** Gets whether the prisoner being transferred is online or not. */
public boolean isOnline() { public boolean isOnline() {
return player == null; return player == null;
} }
/** Gets the name of what is transferring this prisoner. */ /** Gets the name of what is transferring this prisoner. */
public String getTransferor() { public String getTransferor() {
return this.transferor; return this.transferor;
} }
/** /**
* Sets the prisoner whom the data should say jailed this prisoner. * Sets the prisoner whom the data should say jailed this prisoner.
* *
* @param transferor The name to put who is the jailer for this prisoner. * @param transferor The name to put who is the jailer for this prisoner.
*/ */
public void setTransferor(String transferor) { public void setTransferor(String transferor) {
this.transferor = transferor; this.transferor = transferor;
} }
/** Checks whether this event is cancelled or not. */ /** Checks whether this event is cancelled or not. */
public boolean isCancelled() { public boolean isCancelled() {
return this.cancelled; return this.cancelled;
} }
/** Sets whether this event should be cancelled. */ /** Sets whether this event should be cancelled. */
public void setCancelled(boolean cancel) { public void setCancelled(boolean cancel) {
this.cancelled = cancel; this.cancelled = cancel;
} }
/** Returns the cancelled message. */ /** Returns the cancelled message. */
public String getCancelledMessage() { public String getCancelledMessage() {
return this.cancelMsg; return this.cancelMsg;
} }
/** Sets the cancelled message. */ /** Sets the cancelled message. */
public void setCancelledMessage(String msg) { public void setCancelledMessage(String msg) {
this.cancelMsg = msg; this.cancelMsg = msg;
} }
public static HandlerList getHandlerList() { public static HandlerList getHandlerList() {
return handlers; return handlers;
} }
public HandlerList getHandlers() { public HandlerList getHandlers() {
return handlers; return handlers;
} }
} }

View File

@ -17,60 +17,60 @@ import com.graywolf336.jail.beans.Prisoner;
* @version 1.0.0 * @version 1.0.0
*/ */
public class PrisonerDeathEvent extends Event { public class PrisonerDeathEvent extends Event {
private static final HandlerList handlers = new HandlerList(); private static final HandlerList handlers = new HandlerList();
private PlayerDeathEvent event; private PlayerDeathEvent event;
private Jail jail; private Jail jail;
private Cell cell; private Cell cell;
private Prisoner prisoner; private Prisoner prisoner;
private Player player; private Player player;
/** /**
* Creates a new {@link PrisonerDeathEvent prisoner death event} for the given player. * Creates a new {@link PrisonerDeathEvent prisoner death event} for the given player.
* *
* @param event The {@link PlayerDeathEvent} which triggered this event. * @param event The {@link PlayerDeathEvent} which triggered this event.
* @param jail The jail the prisoner is in. * @param jail The jail the prisoner is in.
* @param cell The cell the prisoner is in, can be null. * @param cell The cell the prisoner is in, can be null.
* @param prisoner The prisoner's data. * @param prisoner The prisoner's data.
* @param player The player being jailed. * @param player The player being jailed.
*/ */
public PrisonerDeathEvent(PlayerDeathEvent event, Jail jail, Cell cell, Prisoner prisoner, Player player) { public PrisonerDeathEvent(PlayerDeathEvent event, Jail jail, Cell cell, Prisoner prisoner, Player player) {
this.event = event; this.event = event;
this.jail = jail; this.jail = jail;
this.cell = cell; this.cell = cell;
this.prisoner = prisoner; this.prisoner = prisoner;
this.player = player; this.player = player;
} }
/** Gets the {@link PlayerDeathEvent} which triggered this PrisonerDeathEvent. */ /** Gets the {@link PlayerDeathEvent} which triggered this PrisonerDeathEvent. */
public PlayerDeathEvent getPlayerDeathEvent() { public PlayerDeathEvent getPlayerDeathEvent() {
return this.event; return this.event;
} }
/** Gets the {@link Jail} this prisoner is in. */ /** Gets the {@link Jail} this prisoner is in. */
public Jail getJail() { public Jail getJail() {
return this.jail; return this.jail;
} }
/** Gets the cell the prisoner is in, can be null. */ /** Gets the cell the prisoner is in, can be null. */
public Cell getCell() { public Cell getCell() {
return this.cell; return this.cell;
} }
/** Gets the {@link Prisoner}'s data. */ /** Gets the {@link Prisoner}'s data. */
public Prisoner getPrisoner() { public Prisoner getPrisoner() {
return this.prisoner; return this.prisoner;
} }
/** Gets the instance of the player who died. */ /** Gets the instance of the player who died. */
public Player getPlayer() { public Player getPlayer() {
return this.player; return this.player;
} }
public static HandlerList getHandlerList() { public static HandlerList getHandlerList() {
return handlers; return handlers;
} }
public HandlerList getHandlers() { public HandlerList getHandlers() {
return handlers; return handlers;
} }
} }

View File

@ -22,57 +22,57 @@ import com.graywolf336.jail.beans.Prisoner;
* @version 1.0.0 * @version 1.0.0
*/ */
public class PrisonerJailedEvent extends Event { public class PrisonerJailedEvent extends Event {
private static final HandlerList handlers = new HandlerList(); private static final HandlerList handlers = new HandlerList();
private Jail jail; private Jail jail;
private Cell cell; private Cell cell;
private Prisoner prisoner; private Prisoner prisoner;
private Player player; private Player player;
/** /**
* Creates a new {@link PrisonerJailedEvent prisoner jailed event} for the given player. * Creates a new {@link PrisonerJailedEvent prisoner jailed event} for the given player.
* *
* @param jail The jail the prisoner will be jailed at. * @param jail The jail the prisoner will be jailed at.
* @param cell The cell we're going to be sending the prisoner to, can be null. * @param cell The cell we're going to be sending the prisoner to, can be null.
* @param prisoner The prisoner data. * @param prisoner The prisoner data.
* @param player The player being jailed. * @param player The player being jailed.
*/ */
public PrisonerJailedEvent(Jail jail, Cell cell, Prisoner prisoner, Player player) { public PrisonerJailedEvent(Jail jail, Cell cell, Prisoner prisoner, Player player) {
this.jail = jail; this.jail = jail;
this.cell = cell; this.cell = cell;
this.prisoner = prisoner; this.prisoner = prisoner;
this.player = player; this.player = player;
} }
/** Gets the {@link Jail} this prisoner is being sent to. */ /** Gets the {@link Jail} this prisoner is being sent to. */
public Jail getJail() { public Jail getJail() {
return this.jail; return this.jail;
} }
/** Gets the cell we're going to be sending the prisoner to, can be null. */ /** Gets the cell we're going to be sending the prisoner to, can be null. */
public Cell getCell() { public Cell getCell() {
return this.cell; return this.cell;
} }
/** Gets the {@link Prisoner} data for this prisoner. */ /** Gets the {@link Prisoner} data for this prisoner. */
public Prisoner getPrisoner() { public Prisoner getPrisoner() {
return this.prisoner; return this.prisoner;
} }
/** Gets the instance of the player being jailed. */ /** Gets the instance of the player being jailed. */
public Player getPlayer() { public Player getPlayer() {
return this.player; return this.player;
} }
/** Gets the jailer who jailed this prisoner. */ /** Gets the jailer who jailed this prisoner. */
public String getJailer() { public String getJailer() {
return this.prisoner.getJailer(); return this.prisoner.getJailer();
} }
public static HandlerList getHandlerList() { public static HandlerList getHandlerList() {
return handlers; return handlers;
} }
public HandlerList getHandlers() { public HandlerList getHandlers() {
return handlers; return handlers;
} }
} }

View File

@ -22,52 +22,52 @@ import com.graywolf336.jail.beans.Prisoner;
* @version 1.0.0 * @version 1.0.0
*/ */
public class PrisonerReleasedEvent extends Event { public class PrisonerReleasedEvent extends Event {
private static final HandlerList handlers = new HandlerList(); private static final HandlerList handlers = new HandlerList();
private Jail jail; private Jail jail;
private Cell cell; private Cell cell;
private Prisoner prisoner; private Prisoner prisoner;
private Player player; private Player player;
/** /**
* Creates a new {@link PrisonerReleasedEvent prisoner released event} for the given player. * Creates a new {@link PrisonerReleasedEvent prisoner released event} for the given player.
* *
* @param jail The jail the prisoner will be jailed at. * @param jail The jail the prisoner will be jailed at.
* @param cell The cell we're going to be sending the prisoner to, can be null. * @param cell The cell we're going to be sending the prisoner to, can be null.
* @param prisoner The prisoner data. * @param prisoner The prisoner data.
* @param player The player being jailed. * @param player The player being jailed.
*/ */
public PrisonerReleasedEvent(Jail jail, Cell cell, Prisoner prisoner, Player player) { public PrisonerReleasedEvent(Jail jail, Cell cell, Prisoner prisoner, Player player) {
this.jail = jail; this.jail = jail;
this.cell = cell; this.cell = cell;
this.prisoner = prisoner; this.prisoner = prisoner;
this.player = player; this.player = player;
} }
/** Gets the {@link Jail} this prisoner is coming from. */ /** Gets the {@link Jail} this prisoner is coming from. */
public Jail getJail() { public Jail getJail() {
return this.jail; return this.jail;
} }
/** Gets the cell where the prisoner was jailed in, null if they weren't in one. */ /** Gets the cell where the prisoner was jailed in, null if they weren't in one. */
public Cell getCell() { public Cell getCell() {
return this.cell; return this.cell;
} }
/** Gets the {@link Prisoner} data for this prisoner. */ /** Gets the {@link Prisoner} data for this prisoner. */
public Prisoner getPrisoner() { public Prisoner getPrisoner() {
return this.prisoner; return this.prisoner;
} }
/** Gets the instance of the player being released. */ /** Gets the instance of the player being released. */
public Player getPlayer() { public Player getPlayer() {
return this.player; return this.player;
} }
public static HandlerList getHandlerList() { public static HandlerList getHandlerList() {
return handlers; return handlers;
} }
public HandlerList getHandlers() { public HandlerList getHandlers() {
return handlers; return handlers;
} }
} }

View File

@ -20,75 +20,75 @@ import com.graywolf336.jail.beans.Prisoner;
* @version 1.0.0 * @version 1.0.0
*/ */
public class PrisonerTransferredEvent extends Event { public class PrisonerTransferredEvent extends Event {
private static final HandlerList handlers = new HandlerList(); private static final HandlerList handlers = new HandlerList();
private Jail originalJail, targetJail; private Jail originalJail, targetJail;
private Cell originalCell, targetCell; private Cell originalCell, targetCell;
private Prisoner prisoner; private Prisoner prisoner;
private Player player; private Player player;
/** /**
* Creates a new {@link PrisonerTransferredEvent prisoner transferred event} for the given player after they get transferred to their new jail and cell. * Creates a new {@link PrisonerTransferredEvent prisoner transferred event} for the given player after they get transferred to their new jail and cell.
* *
* @param originalJail The jail the prisoner is coming from. * @param originalJail The jail the prisoner is coming from.
* @param originalCell The cell the prisoner is coming from, can be null. * @param originalCell The cell the prisoner is coming from, can be null.
* @param targetJail The jail the prisoner went to. * @param targetJail The jail the prisoner went to.
* @param targetCell The cell the prisoner went to, can be null. * @param targetCell The cell the prisoner went to, can be null.
* @param prisoner The prisoner data. * @param prisoner The prisoner data.
* @param player The player being jailed. * @param player The player being jailed.
*/ */
public PrisonerTransferredEvent(Jail originalJail, Cell originalCell, Jail targetJail, Cell targetCell, Prisoner prisoner, Player player) { public PrisonerTransferredEvent(Jail originalJail, Cell originalCell, Jail targetJail, Cell targetCell, Prisoner prisoner, Player player) {
this.originalJail = originalJail; this.originalJail = originalJail;
this.originalCell = originalCell; this.originalCell = originalCell;
this.targetJail = targetJail; this.targetJail = targetJail;
this.targetCell = targetCell; this.targetCell = targetCell;
this.prisoner = prisoner; this.prisoner = prisoner;
this.player = player; this.player = player;
} }
/** Gets the {@link Jail} this prisoner is coming from. */ /** Gets the {@link Jail} this prisoner is coming from. */
public Jail getOriginalJail() { public Jail getOriginalJail() {
return this.originalJail; return this.originalJail;
} }
/** Gets the {@link Cell} this prisoner is coming from, can be null. */ /** Gets the {@link Cell} this prisoner is coming from, can be null. */
public Cell getOriginalCell() { public Cell getOriginalCell() {
return this.originalCell; return this.originalCell;
} }
/** Gets the {@link Jail} this prisoner is being transferred to. */ /** Gets the {@link Jail} this prisoner is being transferred to. */
public Jail getTargetJail() { public Jail getTargetJail() {
return this.targetJail; return this.targetJail;
} }
/** Gets the {@link Cell} this prisoner is being sent to, can be null. /** Gets the {@link Cell} this prisoner is being sent to, can be null.
* *
* Will return null if the cell is not in the targetJail. * Will return null if the cell is not in the targetJail.
*/ */
public Cell getTargetCell() { public Cell getTargetCell() {
if(this.targetJail.isValidCell(this.targetCell.getName())) return this.targetCell; if(this.targetJail.isValidCell(this.targetCell.getName())) return this.targetCell;
else return null; else return null;
} }
/** Gets the {@link Prisoner} data for this prisoner. */ /** Gets the {@link Prisoner} data for this prisoner. */
public Prisoner getPrisoner() { public Prisoner getPrisoner() {
return this.prisoner; return this.prisoner;
} }
/** Gets the instance of the player being transferred <strong>but will return null if {@link #isOnline()} returns false</strong>. */ /** Gets the instance of the player being transferred <strong>but will return null if {@link #isOnline()} returns false</strong>. */
public Player getPlayer() { public Player getPlayer() {
return this.player; return this.player;
} }
/** Gets whether the prisoner being transferred is online or not. */ /** Gets whether the prisoner being transferred is online or not. */
public boolean isOnline() { public boolean isOnline() {
return player == null; return player == null;
} }
public static HandlerList getHandlerList() { public static HandlerList getHandlerList() {
return handlers; return handlers;
} }
public HandlerList getHandlers() { public HandlerList getHandlers() {
return handlers; return handlers;
} }
} }

View File

@ -25,420 +25,420 @@ import com.graywolf336.jail.enums.Settings;
* @version 1.0.0 * @version 1.0.0
*/ */
public class LegacyManager { public class LegacyManager {
private JailMain pl; private JailMain pl;
private YamlConfiguration global; private YamlConfiguration global;
private boolean wasConverted; private boolean wasConverted;
public LegacyManager(JailMain plugin) { public LegacyManager(JailMain plugin) {
this.pl = plugin; this.pl = plugin;
this.wasConverted = false; this.wasConverted = false;
} }
/** Returns true/false if the old config, global.yml, exists and needs to be converted. */ /** Returns true/false if the old config, global.yml, exists and needs to be converted. */
public boolean doWeNeedToConvert() { public boolean doWeNeedToConvert() {
return new File(pl.getDataFolder(), "global.yml").exists(); return new File(pl.getDataFolder(), "global.yml").exists();
} }
/** /**
* Returns true if we converted anything and it was successful. * Returns true if we converted anything and it was successful.
* *
* @return true if everything converted successfully, was if not. * @return true if everything converted successfully, was if not.
*/ */
public boolean wasAnythingConverted() { public boolean wasAnythingConverted() {
return this.wasConverted; return this.wasConverted;
} }
public boolean convertOldData() { public boolean convertOldData() {
File f = new File(pl.getDataFolder(), "global.yml"); File f = new File(pl.getDataFolder(), "global.yml");
if(f.exists()) { if(f.exists()) {
global = new YamlConfiguration(); global = new YamlConfiguration();
try { try {
global.load(f); global.load(f);
} catch (FileNotFoundException e) { } catch (FileNotFoundException e) {
//e.printStackTrace(); //e.printStackTrace();
pl.getLogger().severe("Unable to load the old global config, file not found."); pl.getLogger().severe("Unable to load the old global config, file not found.");
} catch (IOException e) { } catch (IOException e) {
//e.printStackTrace(); //e.printStackTrace();
pl.getLogger().severe("Unable to load the old global config: " + e.getMessage()); pl.getLogger().severe("Unable to load the old global config: " + e.getMessage());
} catch (InvalidConfigurationException e) { } catch (InvalidConfigurationException e) {
//e.printStackTrace(); //e.printStackTrace();
pl.getLogger().severe("Unable to load the old global config: " + e.getMessage()); pl.getLogger().severe("Unable to load the old global config: " + e.getMessage());
} }
}else { }else {
pl.debug("The old config file, global.yml, was not found so not loading anything."); pl.debug("The old config file, global.yml, was not found so not loading anything.");
return false; return false;
} }
try { try {
pl.getLogger().info("Starting to convert Jail 2.x data to Jail 3.0, this does use a blocking call (getOfflinePlayer) so expect the server to be held up until we are finished..."); pl.getLogger().info("Starting to convert Jail 2.x data to Jail 3.0, this does use a blocking call (getOfflinePlayer) so expect the server to be held up until we are finished...");
loadOldConfig(); loadOldConfig();
loadOldData(); loadOldData();
moveOldConfigs(); moveOldConfigs();
this.wasConverted = true; this.wasConverted = true;
pl.getLogger().info("...finished converting configs and data."); pl.getLogger().info("...finished converting configs and data.");
return true; return true;
}catch (Exception e) { }catch (Exception e) {
if(pl.inDebug()) { if(pl.inDebug()) {
e.printStackTrace(); e.printStackTrace();
} }
pl.debug(e.getMessage()); pl.debug(e.getMessage());
pl.getLogger().severe("Failed to load the old configuration for some reason."); pl.getLogger().severe("Failed to load the old configuration for some reason.");
return false; return false;
} }
} }
@SuppressWarnings("deprecation") @SuppressWarnings("deprecation")
private void loadOldConfig() { private void loadOldConfig() {
FileConfiguration c = pl.getConfig(); FileConfiguration c = pl.getConfig();
int count = 0; int count = 0;
for(OldSetting s : OldSetting.values()) { for(OldSetting s : OldSetting.values()) {
switch(s) { switch(s) {
case Debug: case Debug:
if(global.contains(s.getString())) { if(global.contains(s.getString())) {
c.set(Settings.DEBUG.getPath(), OldSettings.getGlobalBoolean(global, s)); c.set(Settings.DEBUG.getPath(), OldSettings.getGlobalBoolean(global, s));
//Only set it true if the old config had true, this way we can still hold the debuggin over //Only set it true if the old config had true, this way we can still hold the debuggin over
//if the old config had it set to false but the new one has it set to true (until a restart/reload) //if the old config had it set to false but the new one has it set to true (until a restart/reload)
if(c.getBoolean(Settings.DEBUG.getPath())) pl.setDebugging(true); if(c.getBoolean(Settings.DEBUG.getPath())) pl.setDebugging(true);
pl.debug(Settings.DEBUG.getPath() + " <-- " + s.getString()); pl.debug(Settings.DEBUG.getPath() + " <-- " + s.getString());
count++; count++;
} }
break; break;
case BroadcastJailMessage: case BroadcastJailMessage:
if(global.contains(s.getString())) { if(global.contains(s.getString())) {
c.set(Settings.BROADCASTJAILING.getPath(), OldSettings.getGlobalBoolean(global, s)); c.set(Settings.BROADCASTJAILING.getPath(), OldSettings.getGlobalBoolean(global, s));
pl.debug(Settings.BROADCASTJAILING.getPath() + " <-- " + s.getString()); pl.debug(Settings.BROADCASTJAILING.getPath() + " <-- " + s.getString());
count++; count++;
} }
break; break;
case AllowUpdateNotifications: case AllowUpdateNotifications:
if(global.contains(s.getString())) { if(global.contains(s.getString())) {
c.set(Settings.UPDATENOTIFICATIONS.getPath(), OldSettings.getGlobalBoolean(global, s)); c.set(Settings.UPDATENOTIFICATIONS.getPath(), OldSettings.getGlobalBoolean(global, s));
pl.debug(Settings.UPDATENOTIFICATIONS.getPath() + " <-- " + s.getString()); pl.debug(Settings.UPDATENOTIFICATIONS.getPath() + " <-- " + s.getString());
count++; count++;
} }
break; break;
case ExecutedCommandsOnJail: case ExecutedCommandsOnJail:
if(global.contains(s.getString())) { if(global.contains(s.getString())) {
c.set(Settings.COMMANDSONJAIL.getPath(), OldSettings.getGlobalList(global, s)); c.set(Settings.COMMANDSONJAIL.getPath(), OldSettings.getGlobalList(global, s));
pl.debug(Settings.COMMANDSONJAIL.getPath() + " <-- " + s.getString()); pl.debug(Settings.COMMANDSONJAIL.getPath() + " <-- " + s.getString());
count++; count++;
} }
break; break;
case ExecutedCommandsOnRelease: case ExecutedCommandsOnRelease:
if(global.contains(s.getString())) { if(global.contains(s.getString())) {
c.set(Settings.COMMANDSONRELEASE.getPath(), OldSettings.getGlobalList(global, s)); c.set(Settings.COMMANDSONRELEASE.getPath(), OldSettings.getGlobalList(global, s));
pl.debug(Settings.COMMANDSONRELEASE.getPath() + " <-- " + s.getString()); pl.debug(Settings.COMMANDSONRELEASE.getPath() + " <-- " + s.getString());
count++; count++;
} }
break; break;
case AutomaticMute: case AutomaticMute:
if(global.contains(s.getString())) { if(global.contains(s.getString())) {
c.set(Settings.AUTOMATICMUTE.getPath(), OldSettings.getGlobalBoolean(global, s)); c.set(Settings.AUTOMATICMUTE.getPath(), OldSettings.getGlobalBoolean(global, s));
pl.debug(Settings.AUTOMATICMUTE.getPath() + " <-- " + s.getString()); pl.debug(Settings.AUTOMATICMUTE.getPath() + " <-- " + s.getString());
count++; count++;
} }
break; break;
case StoreInventory: case StoreInventory:
if(global.contains(s.getString())) { if(global.contains(s.getString())) {
c.set(Settings.JAILEDSTOREINVENTORY.getPath(), OldSettings.getGlobalBoolean(global, s)); c.set(Settings.JAILEDSTOREINVENTORY.getPath(), OldSettings.getGlobalBoolean(global, s));
pl.debug(Settings.JAILEDSTOREINVENTORY.getPath() + " <-- " + s.getString()); pl.debug(Settings.JAILEDSTOREINVENTORY.getPath() + " <-- " + s.getString());
count++; count++;
} }
break; break;
case CanPrisonerOpenHisChest: case CanPrisonerOpenHisChest:
if(global.contains(s.getString())) { if(global.contains(s.getString())) {
c.set(Settings.PRISONEROPENCHEST.getPath(), OldSettings.getGlobalBoolean(global, s)); c.set(Settings.PRISONEROPENCHEST.getPath(), OldSettings.getGlobalBoolean(global, s));
pl.debug(Settings.PRISONEROPENCHEST.getPath() + " <-- " + s.getString()); pl.debug(Settings.PRISONEROPENCHEST.getPath() + " <-- " + s.getString());
count++; count++;
} }
break; break;
case LogJailingIntoConsole: case LogJailingIntoConsole:
if(global.contains(s.getString())) { if(global.contains(s.getString())) {
c.set(Settings.LOGJAILINGTOCONSOLE.getPath(), OldSettings.getGlobalBoolean(global, s)); c.set(Settings.LOGJAILINGTOCONSOLE.getPath(), OldSettings.getGlobalBoolean(global, s));
pl.debug(Settings.LOGJAILINGTOCONSOLE.getPath() + " <-- " + s.getString()); pl.debug(Settings.LOGJAILINGTOCONSOLE.getPath() + " <-- " + s.getString());
count++; count++;
} }
break; break;
case CountdownTimeWhenOffline: case CountdownTimeWhenOffline:
if(global.contains(s.getString())) { if(global.contains(s.getString())) {
c.set(Settings.COUNTDOWNTIMEOFFLINE.getPath(), OldSettings.getGlobalBoolean(global, s)); c.set(Settings.COUNTDOWNTIMEOFFLINE.getPath(), OldSettings.getGlobalBoolean(global, s));
pl.debug(Settings.COUNTDOWNTIMEOFFLINE.getPath() + " <-- " + s.getString()); pl.debug(Settings.COUNTDOWNTIMEOFFLINE.getPath() + " <-- " + s.getString());
count++; count++;
} }
break; break;
case ReleaseBackToPreviousPosition: case ReleaseBackToPreviousPosition:
if(global.contains(s.getString())) { if(global.contains(s.getString())) {
c.set(Settings.RELEASETOPREVIOUSPOSITION.getPath(), OldSettings.getGlobalBoolean(global, s)); c.set(Settings.RELEASETOPREVIOUSPOSITION.getPath(), OldSettings.getGlobalBoolean(global, s));
pl.debug(Settings.RELEASETOPREVIOUSPOSITION.getPath() + " <-- " + s.getString()); pl.debug(Settings.RELEASETOPREVIOUSPOSITION.getPath() + " <-- " + s.getString());
count++; count++;
} }
break; break;
case IgnorePrisonersSleepingState: case IgnorePrisonersSleepingState:
if(global.contains(s.getString())) { if(global.contains(s.getString())) {
c.set(Settings.IGNORESLEEPINGSTATE.getPath(), OldSettings.getGlobalBoolean(global, s)); c.set(Settings.IGNORESLEEPINGSTATE.getPath(), OldSettings.getGlobalBoolean(global, s));
pl.debug(Settings.IGNORESLEEPINGSTATE.getPath() + " <-- " + s.getString()); pl.debug(Settings.IGNORESLEEPINGSTATE.getPath() + " <-- " + s.getString());
count++; count++;
} }
break; break;
case TeleportPrisonerOnRelease: case TeleportPrisonerOnRelease:
if(global.contains(s.getString())) { if(global.contains(s.getString())) {
c.set(Settings.TELEPORTONRELEASE.getPath(), OldSettings.getGlobalBoolean(global, s)); c.set(Settings.TELEPORTONRELEASE.getPath(), OldSettings.getGlobalBoolean(global, s));
pl.debug(Settings.TELEPORTONRELEASE.getPath() + " <-- " + s.getString()); pl.debug(Settings.TELEPORTONRELEASE.getPath() + " <-- " + s.getString());
count++; count++;
} }
break; break;
case DefaultJailTime: case DefaultJailTime:
if(global.contains(s.getString())) { if(global.contains(s.getString())) {
c.set(Settings.DEFAULTTIME.getPath(), OldSettings.getGlobalInt(global, s)); c.set(Settings.DEFAULTTIME.getPath(), OldSettings.getGlobalInt(global, s));
pl.debug(Settings.DEFAULTTIME.getPath() + " <-- " + s.getString()); pl.debug(Settings.DEFAULTTIME.getPath() + " <-- " + s.getString());
count++; count++;
} }
break; break;
case UseBukkitSchedulerTimer: case UseBukkitSchedulerTimer:
if(global.contains(s.getString())) { if(global.contains(s.getString())) {
c.set(Settings.USEBUKKITTIMER.getPath(), OldSettings.getGlobalBoolean(global, s)); c.set(Settings.USEBUKKITTIMER.getPath(), OldSettings.getGlobalBoolean(global, s));
pl.debug(Settings.USEBUKKITTIMER.getPath() + " <-- " + s.getString()); pl.debug(Settings.USEBUKKITTIMER.getPath() + " <-- " + s.getString());
count++; count++;
} }
break; break;
case EnableJailStick: case EnableJailStick:
if(global.contains(s.getString())) { if(global.contains(s.getString())) {
c.set(Settings.JAILSTICKENABLED.getPath(), OldSettings.getGlobalBoolean(global, s)); c.set(Settings.JAILSTICKENABLED.getPath(), OldSettings.getGlobalBoolean(global, s));
pl.debug(Settings.JAILSTICKENABLED.getPath() + " <-- " + s.getString()); pl.debug(Settings.JAILSTICKENABLED.getPath() + " <-- " + s.getString());
count++; count++;
} }
break; break;
case JailStickParameters: case JailStickParameters:
if(global.contains(s.getString())) { if(global.contains(s.getString())) {
LinkedList<String> sticks = new LinkedList<String>(); LinkedList<String> sticks = new LinkedList<String>();
for (String i : OldSettings.getGlobalString(global, s).split(";")) { for (String i : OldSettings.getGlobalString(global, s).split(";")) {
String[] info = i.split(","); String[] info = i.split(",");
//item id,range,time,jail name,reason //item id,range,time,jail name,reason
Material m = Material.getMaterial(Integer.valueOf(info[0]).intValue()); Material m = Material.getMaterial(Integer.valueOf(info[0]).intValue());
//item name,time,jail name,reason //item name,time,jail name,reason
sticks.push(m.toString().toLowerCase() + "," + info[2] + "," + info[3] + "," + info[4]); sticks.push(m.toString().toLowerCase() + "," + info[2] + "," + info[3] + "," + info[4]);
} }
c.set(Settings.JAILSTICKSTICKS.getPath(), sticks); c.set(Settings.JAILSTICKSTICKS.getPath(), sticks);
pl.debug(Settings.JAILSTICKSTICKS.getPath() + " <-- " + s.getString()); pl.debug(Settings.JAILSTICKSTICKS.getPath() + " <-- " + s.getString());
count++; count++;
} }
break; break;
case EnableBlockDestroyProtection: case EnableBlockDestroyProtection:
if(global.contains(s.getString())) { if(global.contains(s.getString())) {
c.set(Settings.BLOCKBREAKPROTECTION.getPath(), OldSettings.getGlobalBoolean(global, s)); c.set(Settings.BLOCKBREAKPROTECTION.getPath(), OldSettings.getGlobalBoolean(global, s));
pl.debug(Settings.BLOCKBREAKPROTECTION.getPath() + " <-- " + s.getString()); pl.debug(Settings.BLOCKBREAKPROTECTION.getPath() + " <-- " + s.getString());
count++; count++;
} }
break; break;
case BlockDestroyPenalty: case BlockDestroyPenalty:
if(global.contains(s.getString())) { if(global.contains(s.getString())) {
c.set(Settings.BLOCKBREAKPENALTY.getPath(), OldSettings.getGlobalInt(global, s)); c.set(Settings.BLOCKBREAKPENALTY.getPath(), OldSettings.getGlobalInt(global, s));
pl.debug(Settings.BLOCKBREAKPENALTY.getPath() + " <-- " + s.getString()); pl.debug(Settings.BLOCKBREAKPENALTY.getPath() + " <-- " + s.getString());
count++; count++;
} }
break; break;
case BlockDestroyProtectionExceptions: case BlockDestroyProtectionExceptions:
if(global.contains(s.getString())) { if(global.contains(s.getString())) {
@SuppressWarnings("unchecked") @SuppressWarnings("unchecked")
List<String> exceptions = (List<String>) OldSettings.getGlobalList(global, s); List<String> exceptions = (List<String>) OldSettings.getGlobalList(global, s);
LinkedList<String> whitelist = new LinkedList<String>(); LinkedList<String> whitelist = new LinkedList<String>();
for(String e : exceptions) { for(String e : exceptions) {
whitelist.add(Material.getMaterial(Integer.valueOf(e).intValue()).toString().toLowerCase()); whitelist.add(Material.getMaterial(Integer.valueOf(e).intValue()).toString().toLowerCase());
} }
c.set(Settings.BLOCKBREAKWHITELIST.getPath(), whitelist); c.set(Settings.BLOCKBREAKWHITELIST.getPath(), whitelist);
pl.debug(Settings.BLOCKBREAKWHITELIST.getPath() + " <-- " + s.getString()); pl.debug(Settings.BLOCKBREAKWHITELIST.getPath() + " <-- " + s.getString());
count++; count++;
} }
break; break;
case EnableBlockPlaceProtection: case EnableBlockPlaceProtection:
if(global.contains(s.getString())) { if(global.contains(s.getString())) {
c.set(Settings.BLOCKPLACEPROTECTION.getPath(), OldSettings.getGlobalBoolean(global, s)); c.set(Settings.BLOCKPLACEPROTECTION.getPath(), OldSettings.getGlobalBoolean(global, s));
pl.debug(Settings.BLOCKPLACEPROTECTION.getPath() + " <-- " + s.getString()); pl.debug(Settings.BLOCKPLACEPROTECTION.getPath() + " <-- " + s.getString());
count++; count++;
} }
break; break;
case BlockPlacePenalty: case BlockPlacePenalty:
if(global.contains(s.getString())) { if(global.contains(s.getString())) {
c.set(Settings.BLOCKPLACEPENALTY.getPath(), OldSettings.getGlobalInt(global, s)); c.set(Settings.BLOCKPLACEPENALTY.getPath(), OldSettings.getGlobalInt(global, s));
pl.debug(Settings.BLOCKPLACEPENALTY.getPath() + " <-- " + s.getString()); pl.debug(Settings.BLOCKPLACEPENALTY.getPath() + " <-- " + s.getString());
count++; count++;
} }
break; break;
case BlockPlaceProtectionExceptions: case BlockPlaceProtectionExceptions:
if(global.contains(s.getString())) { if(global.contains(s.getString())) {
@SuppressWarnings("unchecked") @SuppressWarnings("unchecked")
List<String> exceptions = (List<String>) OldSettings.getGlobalList(global, s); List<String> exceptions = (List<String>) OldSettings.getGlobalList(global, s);
LinkedList<String> whitelist = new LinkedList<String>(); LinkedList<String> whitelist = new LinkedList<String>();
for(String e : exceptions) { for(String e : exceptions) {
whitelist.add(Material.getMaterial(Integer.valueOf(e).intValue()).toString().toLowerCase()); whitelist.add(Material.getMaterial(Integer.valueOf(e).intValue()).toString().toLowerCase());
} }
c.set(Settings.BLOCKPLACEWHITELIST.getPath(), whitelist); c.set(Settings.BLOCKPLACEWHITELIST.getPath(), whitelist);
pl.debug(Settings.BLOCKPLACEWHITELIST.getPath() + " <-- " + s.getString()); pl.debug(Settings.BLOCKPLACEWHITELIST.getPath() + " <-- " + s.getString());
count++; count++;
} }
break; break;
case EnablePlayerMoveProtection: case EnablePlayerMoveProtection:
if(global.contains(s.getString())) { if(global.contains(s.getString())) {
c.set(Settings.MOVEPROTECTION.getPath(), OldSettings.getGlobalBoolean(global, s)); c.set(Settings.MOVEPROTECTION.getPath(), OldSettings.getGlobalBoolean(global, s));
pl.debug(Settings.MOVEPROTECTION.getPath() + " <-- " + s.getString()); pl.debug(Settings.MOVEPROTECTION.getPath() + " <-- " + s.getString());
count++; count++;
} }
break; break;
case PlayerMoveProtectionPenalty: case PlayerMoveProtectionPenalty:
if(global.contains(s.getString())) { if(global.contains(s.getString())) {
c.set(Settings.MOVEPENALTY.getPath(), OldSettings.getGlobalInt(global, s)); c.set(Settings.MOVEPENALTY.getPath(), OldSettings.getGlobalInt(global, s));
pl.debug(Settings.MOVEPENALTY.getPath() + " <-- " + s.getString()); pl.debug(Settings.MOVEPENALTY.getPath() + " <-- " + s.getString());
count++; count++;
} }
break; break;
case WhitelistedCommands: case WhitelistedCommands:
if(global.contains(s.getString())) { if(global.contains(s.getString())) {
c.set(Settings.COMMANDWHITELIST.getPath(), OldSettings.getGlobalList(global, s)); c.set(Settings.COMMANDWHITELIST.getPath(), OldSettings.getGlobalList(global, s));
pl.debug(Settings.COMMANDWHITELIST.getPath() + " <-- " + s.getString()); pl.debug(Settings.COMMANDWHITELIST.getPath() + " <-- " + s.getString());
count++; count++;
} }
break; break;
case CommandProtectionPenalty: case CommandProtectionPenalty:
if(global.contains(s.getString())) { if(global.contains(s.getString())) {
c.set(Settings.COMMANDPENALTY.getPath(), OldSettings.getGlobalInt(global, s)); c.set(Settings.COMMANDPENALTY.getPath(), OldSettings.getGlobalInt(global, s));
pl.debug(Settings.COMMANDPENALTY.getPath() + " <-- " + s.getString()); pl.debug(Settings.COMMANDPENALTY.getPath() + " <-- " + s.getString());
count++; count++;
} }
break; break;
case InteractionPenalty: case InteractionPenalty:
if(global.contains(s.getString())) { if(global.contains(s.getString())) {
c.set(Settings.PREVENTINTERACTIONITEMSPENALTY.getPath(), OldSettings.getGlobalInt(global, s)); c.set(Settings.PREVENTINTERACTIONITEMSPENALTY.getPath(), OldSettings.getGlobalInt(global, s));
pl.debug(Settings.PREVENTINTERACTIONITEMSPENALTY.getPath() + " <-- " + s.getString()); pl.debug(Settings.PREVENTINTERACTIONITEMSPENALTY.getPath() + " <-- " + s.getString());
count++; count++;
} }
break; break;
case EnableExplosionProtection: case EnableExplosionProtection:
if(global.contains(s.getString())) { if(global.contains(s.getString())) {
c.set(Settings.EXPLOSIONPROTECTION.getPath(), OldSettings.getGlobalBoolean(global, s)); c.set(Settings.EXPLOSIONPROTECTION.getPath(), OldSettings.getGlobalBoolean(global, s));
pl.debug(Settings.EXPLOSIONPROTECTION.getPath() + " <-- " + s.getString()); pl.debug(Settings.EXPLOSIONPROTECTION.getPath() + " <-- " + s.getString());
count++; count++;
} }
break; break;
case EnableFoodControl: case EnableFoodControl:
if(global.contains(s.getString())) { if(global.contains(s.getString())) {
c.set(Settings.FOODCONTROL.getPath(), OldSettings.getGlobalBoolean(global, s)); c.set(Settings.FOODCONTROL.getPath(), OldSettings.getGlobalBoolean(global, s));
pl.debug(Settings.FOODCONTROL.getPath() + " <-- " + s.getString()); pl.debug(Settings.FOODCONTROL.getPath() + " <-- " + s.getString());
count++; count++;
} }
break; break;
case FoodControlMinimumFood: case FoodControlMinimumFood:
if(global.contains(s.getString())) { if(global.contains(s.getString())) {
c.set(Settings.FOODCONTROLMIN.getPath(), OldSettings.getGlobalInt(global, s)); c.set(Settings.FOODCONTROLMIN.getPath(), OldSettings.getGlobalInt(global, s));
pl.debug(Settings.FOODCONTROLMIN.getPath() + " <-- " + s.getString()); pl.debug(Settings.FOODCONTROLMIN.getPath() + " <-- " + s.getString());
count++; count++;
} }
break; break;
case FoodControlMaximumFood: case FoodControlMaximumFood:
if(global.contains(s.getString())) { if(global.contains(s.getString())) {
c.set(Settings.FOODCONTROLMAX.getPath(), OldSettings.getGlobalInt(global, s)); c.set(Settings.FOODCONTROLMAX.getPath(), OldSettings.getGlobalInt(global, s));
pl.debug(Settings.FOODCONTROLMAX.getPath() + " <-- " + s.getString()); pl.debug(Settings.FOODCONTROLMAX.getPath() + " <-- " + s.getString());
count++; count++;
} }
break; break;
case PrisonersRecieveMessages: case PrisonersRecieveMessages:
if(global.contains(s.getString())) { if(global.contains(s.getString())) {
c.set(Settings.RECIEVEMESSAGES.getPath(), OldSettings.getGlobalBoolean(global, s)); c.set(Settings.RECIEVEMESSAGES.getPath(), OldSettings.getGlobalBoolean(global, s));
pl.debug(Settings.RECIEVEMESSAGES.getPath() + " <-- " + s.getString()); pl.debug(Settings.RECIEVEMESSAGES.getPath() + " <-- " + s.getString());
count++; count++;
} }
break; break;
case UseMySQL: case UseMySQL:
if(global.contains(s.getString())) { if(global.contains(s.getString())) {
c.set("storage.type", OldSettings.getGlobalBoolean(global, s) ? "mysql" : "sqlite"); c.set("storage.type", OldSettings.getGlobalBoolean(global, s) ? "mysql" : "sqlite");
pl.debug(Settings.RECIEVEMESSAGES.getPath() + " <-- " + s.getString()); pl.debug(Settings.RECIEVEMESSAGES.getPath() + " <-- " + s.getString());
count++; count++;
} }
break; break;
case MySQLConn: case MySQLConn:
if(global.contains(s.getString())) { if(global.contains(s.getString())) {
//jdbc:mysql://localhost:3306/minecraft //jdbc:mysql://localhost:3306/minecraft
String con = OldSettings.getGlobalString(global, s); String con = OldSettings.getGlobalString(global, s);
String a = con.split("//")[1]; String a = con.split("//")[1];
//localhost 3306/minecraft //localhost 3306/minecraft
String[] b1 = a.split(":"); String[] b1 = a.split(":");
//3306 minecraft //3306 minecraft
String[] b2 = b1[1].split("/"); String[] b2 = b1[1].split("/");
c.set("storage.mysql.host", b1[0]); c.set("storage.mysql.host", b1[0]);
c.set("storage.mysql.port", b2[0]); c.set("storage.mysql.port", b2[0]);
c.set("storage.mysql.database", b2[1]); c.set("storage.mysql.database", b2[1]);
pl.debug("storage.mysql <-- " + s.getString()); pl.debug("storage.mysql <-- " + s.getString());
count++; count++;
} }
break; break;
case MySQLUsername: case MySQLUsername:
if(global.contains(s.getString())) { if(global.contains(s.getString())) {
c.set("storage.mysql.username", OldSettings.getGlobalString(global, s)); c.set("storage.mysql.username", OldSettings.getGlobalString(global, s));
pl.debug("storage.mysql.username <-- " + s.getString()); pl.debug("storage.mysql.username <-- " + s.getString());
count++; count++;
} }
break; break;
case MySQLPassword: case MySQLPassword:
if(global.contains(s.getString())) { if(global.contains(s.getString())) {
c.set("storage.mysql.password", OldSettings.getGlobalString(global, s)); c.set("storage.mysql.password", OldSettings.getGlobalString(global, s));
pl.debug("storage.mysql.password <-- " + s.getString()); pl.debug("storage.mysql.password <-- " + s.getString());
count++; count++;
} }
break; break;
case PricePerMinute: case PricePerMinute:
if(global.contains(s.getString())) { if(global.contains(s.getString())) {
c.set(Settings.JAILPAYPRICEPERMINUTE.getPath(), OldSettings.getGlobalInt(global, s)); c.set(Settings.JAILPAYPRICEPERMINUTE.getPath(), OldSettings.getGlobalInt(global, s));
pl.debug(Settings.JAILPAYPRICEPERMINUTE.getPath() + " <-- " + s.getString()); pl.debug(Settings.JAILPAYPRICEPERMINUTE.getPath() + " <-- " + s.getString());
count++; count++;
} }
case PriceForInfiniteJail: case PriceForInfiniteJail:
if(global.contains(s.getString())) { if(global.contains(s.getString())) {
c.set(Settings.JAILPAYPRICEINFINITE.getPath(), OldSettings.getGlobalInt(global, s)); c.set(Settings.JAILPAYPRICEINFINITE.getPath(), OldSettings.getGlobalInt(global, s));
pl.debug(Settings.JAILPAYPRICEINFINITE.getPath() + " <-- " + s.getString()); pl.debug(Settings.JAILPAYPRICEINFINITE.getPath() + " <-- " + s.getString());
count++; count++;
} }
case JailPayCurrency: case JailPayCurrency:
if(global.contains(s.getString())) { if(global.contains(s.getString())) {
Material mat = Material.getMaterial(OldSettings.getGlobalInt(global, s)); Material mat = Material.getMaterial(OldSettings.getGlobalInt(global, s));
if(mat != null) { if(mat != null) {
c.set(Settings.JAILPAYITEM.getPath(), mat.toString().toLowerCase()); c.set(Settings.JAILPAYITEM.getPath(), mat.toString().toLowerCase());
pl.debug(Settings.JAILPAYPRICEINFINITE.getPath() + " <-- " + s.getString()); pl.debug(Settings.JAILPAYPRICEINFINITE.getPath() + " <-- " + s.getString());
count++; count++;
} }
} }
default: default:
break; break;
} }
} }
pl.saveConfig(); pl.saveConfig();
pl.getLogger().info("Converted " + count + " old config value" + (count == 1 ? "" : "s") + "."); pl.getLogger().info("Converted " + count + " old config value" + (count == 1 ? "" : "s") + ".");
} }
private void loadOldData() throws SQLException { private void loadOldData() throws SQLException {
OldInputOutput o = new OldInputOutput(pl, global); OldInputOutput o = new OldInputOutput(pl, global);
o.LoadJails(); o.LoadJails();
o.LoadPrisoners(); o.LoadPrisoners();
o.LoadCells(); o.LoadCells();
o.freeConnection(); o.freeConnection();
} }
private void moveOldConfigs() throws IOException { private void moveOldConfigs() throws IOException {
FileUtils.moveFileToDirectory(new File(pl.getDataFolder(), "global.yml"), new File(pl.getDataFolder() + File.separator + "preJail3Data"), true); FileUtils.moveFileToDirectory(new File(pl.getDataFolder(), "global.yml"), new File(pl.getDataFolder() + File.separator + "preJail3Data"), true);
FileUtils.moveFileToDirectory(new File(pl.getDataFolder(), "jails.yml"), new File(pl.getDataFolder() + File.separator + "preJail3Data"), true); FileUtils.moveFileToDirectory(new File(pl.getDataFolder(), "jails.yml"), new File(pl.getDataFolder() + File.separator + "preJail3Data"), true);
FileUtils.moveFileToDirectory(new File(pl.getDataFolder(), "jailLog.txt"), new File(pl.getDataFolder() + File.separator + "preJail3Data"), true); FileUtils.moveFileToDirectory(new File(pl.getDataFolder(), "jailLog.txt"), new File(pl.getDataFolder() + File.separator + "preJail3Data"), true);
File sqlite = new File(pl.getDataFolder(), "jail.sqlite"); File sqlite = new File(pl.getDataFolder(), "jail.sqlite");
if(sqlite.exists()) { if(sqlite.exists()) {
FileUtils.moveFileToDirectory(sqlite, new File(pl.getDataFolder() + File.separator + "oldData"), true); FileUtils.moveFileToDirectory(sqlite, new File(pl.getDataFolder() + File.separator + "oldData"), true);
} }
} }
} }

View File

@ -18,21 +18,21 @@ import com.graywolf336.jail.beans.Prisoner;
import com.graywolf336.jail.beans.SimpleLocation; import com.graywolf336.jail.beans.SimpleLocation;
public class OldInputOutput { public class OldInputOutput {
private JailMain pl; private JailMain pl;
private Connection connection; private Connection connection;
private YamlConfiguration global; private YamlConfiguration global;
public OldInputOutput(JailMain plugin, YamlConfiguration global) { public OldInputOutput(JailMain plugin, YamlConfiguration global) {
this.pl = plugin; this.pl = plugin;
this.global = global; this.global = global;
} }
public synchronized Connection getConnection() throws SQLException { public synchronized Connection getConnection() throws SQLException {
if (connection == null) connection = createConnection(); if (connection == null) connection = createConnection();
if(OldSettings.getGlobalBoolean(global, OldSetting.UseMySQL)) { if(OldSettings.getGlobalBoolean(global, OldSetting.UseMySQL)) {
if(!connection.isValid(10)) connection = createConnection(); if(!connection.isValid(10)) connection = createConnection();
} }
return connection; return connection;
} }
private Connection createConnection() { private Connection createConnection() {
@ -57,12 +57,12 @@ public class OldInputOutput {
} }
} }
public synchronized void freeConnection() throws SQLException { public synchronized void freeConnection() throws SQLException {
Connection conn = getConnection(); Connection conn = getConnection();
if(conn != null) { if(conn != null) {
try { try {
conn.close(); conn.close();
conn = null; conn = null;
} catch (SQLException e) { } catch (SQLException e) {
e.printStackTrace(); e.printStackTrace();
} }
@ -70,178 +70,178 @@ public class OldInputOutput {
} }
public void LoadJails() throws SQLException { public void LoadJails() throws SQLException {
PreparedStatement ps = getConnection().prepareStatement("SELECT * FROM jail_zones"); PreparedStatement ps = getConnection().prepareStatement("SELECT * FROM jail_zones");
ResultSet set = ps.executeQuery(); ResultSet set = ps.executeQuery();
while (set.next()) { while (set.next()) {
String name = set.getString("name").toLowerCase(); String name = set.getString("name").toLowerCase();
double X1 = set.getDouble("X1"); double X1 = set.getDouble("X1");
double Y1 = set.getDouble("Y1"); double Y1 = set.getDouble("Y1");
double Z1 = set.getDouble("Z1"); double Z1 = set.getDouble("Z1");
double X2 = set.getDouble("X2"); double X2 = set.getDouble("X2");
double Y2 = set.getDouble("Y2"); double Y2 = set.getDouble("Y2");
double Z2 = set.getDouble("Z2"); double Z2 = set.getDouble("Z2");
double teleX = set.getDouble("teleX"); double teleX = set.getDouble("teleX");
double teleY = set.getDouble("teleY"); double teleY = set.getDouble("teleY");
double teleZ = set.getDouble("teleZ"); double teleZ = set.getDouble("teleZ");
double freeX = set.getDouble("freeX"); double freeX = set.getDouble("freeX");
double freeY = set.getDouble("freeY"); double freeY = set.getDouble("freeY");
double freeZ = set.getDouble("freeZ"); double freeZ = set.getDouble("freeZ");
String teleWorld = set.getString("teleWorld"); String teleWorld = set.getString("teleWorld");
String freeWorld = set.getString("freeWorld"); String freeWorld = set.getString("freeWorld");
Jail j = new Jail(pl, name); Jail j = new Jail(pl, name);
j.setWorld(teleWorld); j.setWorld(teleWorld);
j.setMaxPoint(new Location(pl.getServer().getWorld(teleWorld), X1, Y1, Z1)); j.setMaxPoint(new Location(pl.getServer().getWorld(teleWorld), X1, Y1, Z1));
j.setMinPoint(new Location(pl.getServer().getWorld(teleWorld), X2, Y2, Z2)); j.setMinPoint(new Location(pl.getServer().getWorld(teleWorld), X2, Y2, Z2));
j.setTeleportIn(new Location(pl.getServer().getWorld(teleWorld), teleX, teleY, teleZ)); j.setTeleportIn(new Location(pl.getServer().getWorld(teleWorld), teleX, teleY, teleZ));
j.setTeleportFree(new Location(pl.getServer().getWorld(freeWorld), freeX, freeY, freeZ)); j.setTeleportFree(new Location(pl.getServer().getWorld(freeWorld), freeX, freeY, freeZ));
pl.getJailManager().addJail(j, false); pl.getJailManager().addJail(j, false);
} }
set.close(); set.close();
ps.close(); ps.close();
} }
public void LoadPrisoners() throws SQLException { public void LoadPrisoners() throws SQLException {
if(pl.getJailManager().getJails().size() != 0) { if(pl.getJailManager().getJails().size() != 0) {
PreparedStatement ps = getConnection().prepareStatement("SELECT * FROM jail_prisoners"); PreparedStatement ps = getConnection().prepareStatement("SELECT * FROM jail_prisoners");
ResultSet set = ps.executeQuery(); ResultSet set = ps.executeQuery();
while (set.next()) { while (set.next()) {
Jail j = pl.getJailManager().getJail(set.getString("JailName")); Jail j = pl.getJailManager().getJail(set.getString("JailName"));
String name = set.getString("PlayerName").toLowerCase(); String name = set.getString("PlayerName").toLowerCase();
String transferDest = set.getString("TransferDest"); String transferDest = set.getString("TransferDest");
boolean transfer = false; boolean transfer = false;
if(!transferDest.isEmpty()) { if(!transferDest.isEmpty()) {
j = pl.getJailManager().getJail(transferDest); j = pl.getJailManager().getJail(transferDest);
transfer = true; transfer = true;
} }
//In the event the jail is null (jail didn't transfer or the prisoner was jailed offline and no jail specified) //In the event the jail is null (jail didn't transfer or the prisoner was jailed offline and no jail specified)
//set their jail to the first one we have //set their jail to the first one we have
if(j == null) { if(j == null) {
j = pl.getJailManager().getJails().iterator().next(); j = pl.getJailManager().getJails().iterator().next();
} }
Prisoner p = new Prisoner(pl.getServer().getOfflinePlayer(name).getUniqueId().toString(), name, set.getBoolean("muted"), TimeUnit.MILLISECONDS.convert(set.getInt("RemainTime") / 6, TimeUnit.MINUTES), set.getString("Jailer"), set.getString("reason")); Prisoner p = new Prisoner(pl.getServer().getOfflinePlayer(name).getUniqueId().toString(), name, set.getBoolean("muted"), TimeUnit.MILLISECONDS.convert(set.getInt("RemainTime") / 6, TimeUnit.MINUTES), set.getString("Jailer"), set.getString("reason"));
p.setOfflinePending(set.getBoolean("Offline")); p.setOfflinePending(set.getBoolean("Offline"));
p.setToBeTransferred(transfer); p.setToBeTransferred(transfer);
String previousLoc = set.getString("PreviousPosition"); String previousLoc = set.getString("PreviousPosition");
if(!previousLoc.isEmpty()) { if(!previousLoc.isEmpty()) {
String[] l = previousLoc.split(","); String[] l = previousLoc.split(",");
p.setPreviousPosition(new Location(pl.getServer().getWorld(l[0]), Integer.parseInt(l[1]), Integer.parseInt(l[2]), Integer.parseInt(l[3]))); p.setPreviousPosition(new Location(pl.getServer().getWorld(l[0]), Integer.parseInt(l[1]), Integer.parseInt(l[2]), Integer.parseInt(l[3])));
} }
j.addPrisoner(p); j.addPrisoner(p);
//String permissions = set.getString("Permissions"); TODO //String permissions = set.getString("Permissions"); TODO
} }
set.close(); set.close();
ps.close(); ps.close();
}else { }else {
pl.getLogger().warning("No prisoners were transferred from the old database since there aren't any jails defined."); pl.getLogger().warning("No prisoners were transferred from the old database since there aren't any jails defined.");
} }
} }
public void LoadCells() throws SQLException { public void LoadCells() throws SQLException {
Connection conn; Connection conn;
PreparedStatement ps = null; PreparedStatement ps = null;
ResultSet set = null; ResultSet set = null;
conn = getConnection(); conn = getConnection();
ps = conn.prepareStatement("SELECT * FROM jail_cells"); ps = conn.prepareStatement("SELECT * FROM jail_cells");
set = ps.executeQuery(); set = ps.executeQuery();
while (set.next()) { while (set.next()) {
String jailname = set.getString("JailName"); String jailname = set.getString("JailName");
String teleport = set.getString("Teleport"); String teleport = set.getString("Teleport");
String sign = set.getString("Sign"); String sign = set.getString("Sign");
String chest = set.getString("Chest"); String chest = set.getString("Chest");
String player = set.getString("Player"); String player = set.getString("Player");
String name = set.getString("Name"); String name = set.getString("Name");
if(name.isEmpty()) { if(name.isEmpty()) {
pl.getLogger().warning("We need a cell name in Jail 3.0, refusing to load a cell due to this."); pl.getLogger().warning("We need a cell name in Jail 3.0, refusing to load a cell due to this.");
}else if(jailname.isEmpty()) { }else if(jailname.isEmpty()) {
pl.getLogger().warning("Refusing to load a cell (" + name + ") as it does not contain a reference to a valid Jail."); pl.getLogger().warning("Refusing to load a cell (" + name + ") as it does not contain a reference to a valid Jail.");
}else { }else {
Jail j = pl.getJailManager().getJail(jailname); Jail j = pl.getJailManager().getJail(jailname);
if(j == null) { if(j == null) {
pl.getLogger().warning("Refusing to load a cell (" + name + ") as it references a Jail which doesn't exist."); pl.getLogger().warning("Refusing to load a cell (" + name + ") as it references a Jail which doesn't exist.");
}else if(j.isValidCell(name)) { }else if(j.isValidCell(name)) {
pl.getLogger().warning("Refusing to load a duplicate named cell, " + name + ", as another one exists with that same name."); pl.getLogger().warning("Refusing to load a duplicate named cell, " + name + ", as another one exists with that same name.");
} else { } else {
Cell c = new Cell(name); Cell c = new Cell(name);
if(!teleport.isEmpty()) { if(!teleport.isEmpty()) {
String[] l = teleport.split(","); String[] l = teleport.split(",");
c.setTeleport(new SimpleLocation(j.getWorldName(), l[0], l[1], l[2])); c.setTeleport(new SimpleLocation(j.getWorldName(), l[0], l[1], l[2]));
}else { }else {
pl.getLogger().warning("Cell " + c.getName() + " in " + j.getName() + " has an empty teleport spot, might be buggy."); pl.getLogger().warning("Cell " + c.getName() + " in " + j.getName() + " has an empty teleport spot, might be buggy.");
} }
if(!chest.isEmpty()) { if(!chest.isEmpty()) {
String[] ch = chest.split(","); String[] ch = chest.split(",");
c.setChestLocation(new Location(j.getWorld(), Double.valueOf(ch[0]), Double.valueOf(ch[1]), Double.valueOf(ch[2]))); c.setChestLocation(new Location(j.getWorld(), Double.valueOf(ch[0]), Double.valueOf(ch[1]), Double.valueOf(ch[2])));
}else { }else {
pl.getLogger().warning("Cell " + c.getName() + " in " + j.getName() + " has no chest."); pl.getLogger().warning("Cell " + c.getName() + " in " + j.getName() + " has no chest.");
} }
if(!sign.isEmpty()) { if(!sign.isEmpty()) {
for(String s : sign.split(";")) { for(String s : sign.split(";")) {
pl.debug(s); pl.debug(s);
String[] si = s.split(","); String[] si = s.split(",");
c.addSign(new SimpleLocation(j.getWorldName(), si[0], si[1], si[2])); c.addSign(new SimpleLocation(j.getWorldName(), si[0], si[1], si[2]));
} }
} }
//Load the prisoner if he is a valid prisoner //Load the prisoner if he is a valid prisoner
if(!player.isEmpty()) { if(!player.isEmpty()) {
Prisoner p = j.getPrisonerByLastKnownName(player); Prisoner p = j.getPrisonerByLastKnownName(player);
if(p != null) { if(p != null) {
j.removePrisoner(p); j.removePrisoner(p);
c.setPrisoner(p); c.setPrisoner(p);
} }
} }
j.addCell(c, false); j.addCell(c, false);
} }
} }
} }
set.close(); set.close();
ps.close(); ps.close();
} }
public void DeleteZone(String z) throws SQLException { public void DeleteZone(String z) throws SQLException {
Connection conn = getConnection(); Connection conn = getConnection();
PreparedStatement ps = conn.prepareStatement("DELETE FROM jail_zones WHERE name = ?"); PreparedStatement ps = conn.prepareStatement("DELETE FROM jail_zones WHERE name = ?");
ps.setString(1, z); ps.setString(1, z);
ps.executeUpdate(); ps.executeUpdate();
conn.commit(); conn.commit();
ps.close(); ps.close();
} }
public void DeleteCell(int x, int y, int z) throws SQLException { public void DeleteCell(int x, int y, int z) throws SQLException {
Connection conn = getConnection(); Connection conn = getConnection();
PreparedStatement ps = conn.prepareStatement("DELETE FROM jail_cells WHERE Teleport = ?"); PreparedStatement ps = conn.prepareStatement("DELETE FROM jail_cells WHERE Teleport = ?");
ps.setString(1, String.valueOf(x) + "," + String.valueOf(y) + "," + String.valueOf(z)); ps.setString(1, String.valueOf(x) + "," + String.valueOf(y) + "," + String.valueOf(z));
ps.executeUpdate(); ps.executeUpdate();
conn.commit(); conn.commit();
ps.close(); ps.close();
} }
public void DeletePrisoner(String p) throws SQLException { public void DeletePrisoner(String p) throws SQLException {
Connection conn = getConnection(); Connection conn = getConnection();
PreparedStatement ps = conn.prepareStatement("DELETE FROM jail_prisoners WHERE PlayerName = ?"); PreparedStatement ps = conn.prepareStatement("DELETE FROM jail_prisoners WHERE PlayerName = ?");
ps.setString(1, p); ps.setString(1, p);
ps.executeUpdate(); ps.executeUpdate();
conn.commit(); conn.commit();
ps.close(); ps.close();
} }
} }

View File

@ -5,98 +5,98 @@ import java.util.Arrays;
public enum OldSetting { public enum OldSetting {
Debug("Debug", false),//done Debug("Debug", false),//done
BroadcastJailMessage("Broadcast Jail Message", false),//done BroadcastJailMessage("Broadcast Jail Message", false),//done
AllowUpdateNotifications("AllowUpdateNotifications", true),//done AllowUpdateNotifications("AllowUpdateNotifications", true),//done
ExecutedCommandsOnJail("ExecutedCommandsOnJail", new ArrayList<String>()),//done ExecutedCommandsOnJail("ExecutedCommandsOnJail", new ArrayList<String>()),//done
ExecutedCommandsOnRelease("ExecutedCommandsOnRelease", new ArrayList<String>()),//done ExecutedCommandsOnRelease("ExecutedCommandsOnRelease", new ArrayList<String>()),//done
AutomaticMute("AutomaticMute", false),//done AutomaticMute("AutomaticMute", false),//done
StoreInventory("StoreInventory", true),//done StoreInventory("StoreInventory", true),//done
CanPrisonerOpenHisChest("CanPrisonerOpenHisChest", true),//done CanPrisonerOpenHisChest("CanPrisonerOpenHisChest", true),//done
LogJailingIntoConsole("LogJailingIntoConsole", false),//done LogJailingIntoConsole("LogJailingIntoConsole", false),//done
CountdownTimeWhenOffline("CountdownTimeWhenOffline", false),//done CountdownTimeWhenOffline("CountdownTimeWhenOffline", false),//done
ReleaseBackToPreviousPosition("ReleaseBackToPreviousPosition", false),//done ReleaseBackToPreviousPosition("ReleaseBackToPreviousPosition", false),//done
IgnorePrisonersSleepingState("IgnorePrisonersSleepingState", true),//done IgnorePrisonersSleepingState("IgnorePrisonersSleepingState", true),//done
TeleportPrisonerOnRelease("TeleportPrisonerOnRelease", true),//done TeleportPrisonerOnRelease("TeleportPrisonerOnRelease", true),//done
DefaultJailTime("DefaultJailTime", -1),//done DefaultJailTime("DefaultJailTime", -1),//done
UseBukkitSchedulerTimer("UseBukkitSchedulerTimer", true),//done UseBukkitSchedulerTimer("UseBukkitSchedulerTimer", true),//done
JailCheckPrisonersPerPage("JailCheckPrisonersPerPage", 15),//TODO JailCheckPrisonersPerPage("JailCheckPrisonersPerPage", 15),//TODO
//JailStick //JailStick
EnableJailStick("EnableJailStick", false),//done EnableJailStick("EnableJailStick", false),//done
JailStickParameters("JailStickParameters", "280,5,10,,police;50,5,20,,admin"),//done JailStickParameters("JailStickParameters", "280,5,10,,police;50,5,20,,admin"),//done
//Protections //Protections
EnableBlockDestroyProtection("Protections.EnableBlockDestroyProtection", true),//done EnableBlockDestroyProtection("Protections.EnableBlockDestroyProtection", true),//done
BlockDestroyPenalty("Protections.BlockDestroyPenalty", 15),//done BlockDestroyPenalty("Protections.BlockDestroyPenalty", 15),//done
BlockDestroyProtectionExceptions("Protections.BlockDestroyProtectionExceptions", Arrays.asList(new String[]{"59"})),//done BlockDestroyProtectionExceptions("Protections.BlockDestroyProtectionExceptions", Arrays.asList(new String[]{"59"})),//done
EnableBlockPlaceProtection("Protections.EnableBlockPlaceProtection", true),//done EnableBlockPlaceProtection("Protections.EnableBlockPlaceProtection", true),//done
BlockPlacePenalty("Protections.BlockPlacePenalty", 10),//done BlockPlacePenalty("Protections.BlockPlacePenalty", 10),//done
BlockPlaceProtectionExceptions("Protections.BlockPlaceProtectionExceptions", Arrays.asList(new String[]{"59"})),//done BlockPlaceProtectionExceptions("Protections.BlockPlaceProtectionExceptions", Arrays.asList(new String[]{"59"})),//done
EnablePlayerMoveProtection("Protections.EnablePlayerMoveProtection", true),//done EnablePlayerMoveProtection("Protections.EnablePlayerMoveProtection", true),//done
PlayerMoveProtectionPenalty("Protections.PlayerMoveProtectionPenalty", 30),//done PlayerMoveProtectionPenalty("Protections.PlayerMoveProtectionPenalty", 30),//done
PlayerMoveProtectionAction("Protections.PlayerMoveProtectionAction", "teleport"),//TODO PlayerMoveProtectionAction("Protections.PlayerMoveProtectionAction", "teleport"),//TODO
WhitelistedCommands("Protections.WhitelistedCommands", new ArrayList<String>()),//done WhitelistedCommands("Protections.WhitelistedCommands", new ArrayList<String>()),//done
CommandProtectionPenalty("Protections.CommandProtectionPenalty", 10),//done CommandProtectionPenalty("Protections.CommandProtectionPenalty", 10),//done
InteractionPenalty("Protections.InteractionPenalty", 10),//done InteractionPenalty("Protections.InteractionPenalty", 10),//done
EnableExplosionProtection("Protections.EnableExplosionProtection", true),//done EnableExplosionProtection("Protections.EnableExplosionProtection", true),//done
EnablePVPProtection("Protections.EnablePVPProtection", true),//TODO: ??? I haven't even tested this out!!!! EnablePVPProtection("Protections.EnablePVPProtection", true),//TODO: ??? I haven't even tested this out!!!!
EnableChangingPermissions("Protections.EnableChangingPermissions", false),//TODO EnableChangingPermissions("Protections.EnableChangingPermissions", false),//TODO
PrisonersPermissionsGroups("Protections.PrisonersPermissionsGroups", Arrays.asList("prisoners")),//TODO PrisonersPermissionsGroups("Protections.PrisonersPermissionsGroups", Arrays.asList("prisoners")),//TODO
RestorePermissionsToEscapedPrisoners("Protections.RestorePermissionsToEscapedPrisoners", true),//TODO RestorePermissionsToEscapedPrisoners("Protections.RestorePermissionsToEscapedPrisoners", true),//TODO
EnableFoodControl("Protections.EnableFoodControl", true),//done EnableFoodControl("Protections.EnableFoodControl", true),//done
FoodControlMinimumFood("Protections.FoodControlMinimumFood", 10),//done FoodControlMinimumFood("Protections.FoodControlMinimumFood", 10),//done
FoodControlMaximumFood("Protections.FoodControlMaximumFood", 20),//done FoodControlMaximumFood("Protections.FoodControlMaximumFood", 20),//done
PrisonersRecieveMessages("Protections.PlayerRecievesMessages", true), //done PrisonersRecieveMessages("Protections.PlayerRecievesMessages", true), //done
//JailPay //JailPay
PricePerMinute("JailPay.PricePerMinute", 10),//done PricePerMinute("JailPay.PricePerMinute", 10),//done
PriceForInfiniteJail("JailPay.PriceForInfiniteJail", 9999),//done PriceForInfiniteJail("JailPay.PriceForInfiniteJail", 9999),//done
JailPayCurrency("JailPay.Currency", 0),//done JailPayCurrency("JailPay.Currency", 0),//done
//Guards //Guards
GuardHealth("Guards.GuardHealth", 8),//TODO GuardHealth("Guards.GuardHealth", 8),//TODO
GuardArmor("Guards.GuardArmor", 0),//TODO GuardArmor("Guards.GuardArmor", 0),//TODO
GuardDamage("Guards.GuardDamage", 2),//TODO GuardDamage("Guards.GuardDamage", 2),//TODO
NumbefOfGuards("Guards.NumberOfGuards", 3),//TODO NumbefOfGuards("Guards.NumberOfGuards", 3),//TODO
GuardInvincibility("Guards.GuardInvincibility", false),//TODO GuardInvincibility("Guards.GuardInvincibility", false),//TODO
GuardAttackSpeedPercent("Guards.GuardAttackSpeedPercent", 100),//TODO GuardAttackSpeedPercent("Guards.GuardAttackSpeedPercent", 100),//TODO
RespawnGuards("Guards.RespawnGuards", true),//TODO RespawnGuards("Guards.RespawnGuards", true),//TODO
GuardTeleportDistance("Guards.GuardTeleportDistance", 10),//TODO GuardTeleportDistance("Guards.GuardTeleportDistance", 10),//TODO
GuardTypes("Guards.GuardTypes", Arrays.asList(new String[] { "Zombie", "Silverfish" })),//TODO GuardTypes("Guards.GuardTypes", Arrays.asList(new String[] { "Zombie", "Silverfish" })),//TODO
//Database //Database
UseMySQL("Database.UseMySQL", false),//done UseMySQL("Database.UseMySQL", false),//done
MySQLConn("Database.MySQLConn", "jdbc:mysql://localhost:3306/minecraft"),//done MySQLConn("Database.MySQLConn", "jdbc:mysql://localhost:3306/minecraft"),//done
MySQLUsername("Database.MySQLUSername", "root"),//done MySQLUsername("Database.MySQLUSername", "root"),//done
MySQLPassword("Database.MySQLPassword", "password"),//done MySQLPassword("Database.MySQLPassword", "password"),//done
//Jail Vote //Jail Vote
VoteJailEnabled("Jail Vote.Enabled", true),//TODO VoteJailEnabled("Jail Vote.Enabled", true),//TODO
VoteJailTime("Jail Vote.Time", 5),//TODO VoteJailTime("Jail Vote.Time", 5),//TODO
VoteJailReason("Jail Vote.Reason", "Jailed by players"),//TODO VoteJailReason("Jail Vote.Reason", "Jailed by players"),//TODO
VoteJailVoteTime("Jail Vote.Vote Time", 60),//TODO VoteJailVoteTime("Jail Vote.Vote Time", 60),//TODO
//Jail swearing //Jail swearing
EnableJailSwear("Jail Swear.Enabled", false),//TODO EnableJailSwear("Jail Swear.Enabled", false),//TODO
JailSwearTime("Jail Swear.Time", 10),//TODO JailSwearTime("Jail Swear.Time", 10),//TODO
BannedWords("Jail Swear.Banned Words", Arrays.asList(new String[] {"shit", "crap", "fuck", "cunt"}));//TODO BannedWords("Jail Swear.Banned Words", Arrays.asList(new String[] {"shit", "crap", "fuck", "cunt"}));//TODO
private String name; private String name;
private Object def; private Object def;
private OldSetting(String Name, Object Def) { private OldSetting(String Name, Object Def) {
name = Name; name = Name;
def = Def; def = Def;
} }
/** The string of the node the value is stored at in the config. */ /** The string of the node the value is stored at in the config. */
public String getString() { public String getString() {
return name; return name;
} }
/** The default value for this config. */ /** The default value for this config. */
public Object getDefault() { public Object getDefault() {
return def; return def;
} }
} }

View File

@ -6,28 +6,28 @@ import org.bukkit.configuration.file.YamlConfiguration;
public class OldSettings { public class OldSettings {
public static Object getGlobalProperty(YamlConfiguration config, OldSetting setting) { public static Object getGlobalProperty(YamlConfiguration config, OldSetting setting) {
Object property = config.get(setting.getString()); Object property = config.get(setting.getString());
if (property == null) { if (property == null) {
property = setting.getDefault(); property = setting.getDefault();
} }
return property; return property;
} }
public static Boolean getGlobalBoolean(YamlConfiguration config, OldSetting setting) { public static Boolean getGlobalBoolean(YamlConfiguration config, OldSetting setting) {
return (Boolean) getGlobalProperty(config, setting); return (Boolean) getGlobalProperty(config, setting);
} }
public static Integer getGlobalInt(YamlConfiguration config, OldSetting setting) { public static Integer getGlobalInt(YamlConfiguration config, OldSetting setting) {
return (Integer) getGlobalProperty(config, setting); return (Integer) getGlobalProperty(config, setting);
} }
public static String getGlobalString(YamlConfiguration config, OldSetting setting) { public static String getGlobalString(YamlConfiguration config, OldSetting setting) {
return (String) getGlobalProperty(config, setting); return (String) getGlobalProperty(config, setting);
} }
public static List<?> getGlobalList(YamlConfiguration config, OldSetting setting) { public static List<?> getGlobalList(YamlConfiguration config, OldSetting setting) {
return (List<?>) getGlobalProperty(config, setting); return (List<?>) getGlobalProperty(config, setting);
} }
} }

View File

@ -10,51 +10,51 @@ import com.graywolf336.jail.JailMain;
import com.graywolf336.jail.enums.Settings; import com.graywolf336.jail.enums.Settings;
public class BlockListener implements Listener { public class BlockListener implements Listener {
private JailMain pl; private JailMain pl;
public BlockListener(JailMain plugin) { public BlockListener(JailMain plugin) {
this.pl = plugin; this.pl = plugin;
} }
@EventHandler(ignoreCancelled=true, priority = EventPriority.HIGHEST) @EventHandler(ignoreCancelled=true, priority = EventPriority.HIGHEST)
public void blockBreak(BlockBreakEvent event) { public void blockBreak(BlockBreakEvent event) {
//If we're in debugging mode, let's send the player what block they're breaking. //If we're in debugging mode, let's send the player what block they're breaking.
if(pl.inDebug()) event.getPlayer().sendMessage("[Jail Debug]: " + event.getBlock().getType().toString()); if(pl.inDebug()) event.getPlayer().sendMessage("[Jail Debug]: " + event.getBlock().getType().toString());
//If we are protecting against block breaking, then let's do the action. //If we are protecting against block breaking, then let's do the action.
//If we're not, let's not use any processing power to get the jail //If we're not, let's not use any processing power to get the jail
//where this block was broke at //where this block was broke at
if(pl.getConfig().getBoolean(Settings.BLOCKBREAKPROTECTION.getPath())) { if(pl.getConfig().getBoolean(Settings.BLOCKBREAKPROTECTION.getPath())) {
//If there is no jail let's skedaddle //If there is no jail let's skedaddle
if(pl.getJailManager().getJailFromLocation(event.getBlock().getLocation()) == null) return; if(pl.getJailManager().getJailFromLocation(event.getBlock().getLocation()) == null) return;
//If the player doesn't have permission to modify the jail, //If the player doesn't have permission to modify the jail,
//then we stop it here. We won't be doing any of the additions to //then we stop it here. We won't be doing any of the additions to
//a prisoner's sentence here as that's for the protections listener //a prisoner's sentence here as that's for the protections listener
if(!event.getPlayer().hasPermission("jail.modifyjail")) { if(!event.getPlayer().hasPermission("jail.modifyjail")) {
event.setCancelled(true); event.setCancelled(true);
} }
} }
} }
@EventHandler(ignoreCancelled=true, priority = EventPriority.HIGHEST) @EventHandler(ignoreCancelled=true, priority = EventPriority.HIGHEST)
public void blockPlace(BlockPlaceEvent event) { public void blockPlace(BlockPlaceEvent event) {
//If we're in debugging mode, let's send the player what block they're placing. //If we're in debugging mode, let's send the player what block they're placing.
if(pl.inDebug()) event.getPlayer().sendMessage("[Jail Debug]: " + event.getBlock().getType().toString()); if(pl.inDebug()) event.getPlayer().sendMessage("[Jail Debug]: " + event.getBlock().getType().toString());
//If we are protecting against block placing, then let's do the action. //If we are protecting against block placing, then let's do the action.
//If we're not, let's not use any processing power to get the jail //If we're not, let's not use any processing power to get the jail
//where this block was placed at //where this block was placed at
if(pl.getConfig().getBoolean(Settings.BLOCKPLACEPROTECTION.getPath())) { if(pl.getConfig().getBoolean(Settings.BLOCKPLACEPROTECTION.getPath())) {
//If there is no jail let's skedaddle //If there is no jail let's skedaddle
if(pl.getJailManager().getJailFromLocation(event.getBlock().getLocation()) == null) return; if(pl.getJailManager().getJailFromLocation(event.getBlock().getLocation()) == null) return;
//If the player doesn't have permission to modify the jail, //If the player doesn't have permission to modify the jail,
//then we stop it here. We won't be doing any of the additions to //then we stop it here. We won't be doing any of the additions to
//a prisoner's sentence here as that's for the protections listener //a prisoner's sentence here as that's for the protections listener
if(!event.getPlayer().hasPermission("jail.modifyjail")) { if(!event.getPlayer().hasPermission("jail.modifyjail")) {
event.setCancelled(true); event.setCancelled(true);
} }
} }
} }
} }

View File

@ -31,57 +31,57 @@ import com.graywolf336.jail.events.PrisonerTransferredEvent;
* *
*/ */
public class CacheListener implements Listener { public class CacheListener implements Listener {
private JailMain pl; private JailMain pl;
public CacheListener(JailMain plugin) { public CacheListener(JailMain plugin) {
this.pl = plugin; this.pl = plugin;
} }
@EventHandler(priority = EventPriority.LOWEST) @EventHandler(priority = EventPriority.LOWEST)
public void joinListener(PlayerJoinEvent event) { public void joinListener(PlayerJoinEvent event) {
if(pl.getJailManager().isPlayerJailed(event.getPlayer().getUniqueId())) { if(pl.getJailManager().isPlayerJailed(event.getPlayer().getUniqueId())) {
Jail j = pl.getJailManager().getJailPlayerIsIn(event.getPlayer().getUniqueId()); Jail j = pl.getJailManager().getJailPlayerIsIn(event.getPlayer().getUniqueId());
Prisoner p = j.getPrisoner(event.getPlayer().getUniqueId()); Prisoner p = j.getPrisoner(event.getPlayer().getUniqueId());
pl.getJailManager().addCacheObject(new CachePrisoner(j, p)); pl.getJailManager().addCacheObject(new CachePrisoner(j, p));
} }
} }
@EventHandler(priority = EventPriority.LOWEST) @EventHandler(priority = EventPriority.LOWEST)
public void leaveListener(PlayerQuitEvent event) { public void leaveListener(PlayerQuitEvent event) {
if(pl.getJailManager().inCache(event.getPlayer().getUniqueId())) { if(pl.getJailManager().inCache(event.getPlayer().getUniqueId())) {
pl.getJailManager().removeCacheObject(event.getPlayer().getUniqueId()); pl.getJailManager().removeCacheObject(event.getPlayer().getUniqueId());
} }
} }
@EventHandler(priority = EventPriority.LOWEST) @EventHandler(priority = EventPriority.LOWEST)
public void kickListener(PlayerKickEvent event) { public void kickListener(PlayerKickEvent event) {
if(pl.getJailManager().inCache(event.getPlayer().getUniqueId())) { if(pl.getJailManager().inCache(event.getPlayer().getUniqueId())) {
pl.getJailManager().removeCacheObject(event.getPlayer().getUniqueId()); pl.getJailManager().removeCacheObject(event.getPlayer().getUniqueId());
} }
} }
@EventHandler(priority = EventPriority.LOWEST) @EventHandler(priority = EventPriority.LOWEST)
public void jailListener(PrisonerJailedEvent event) { public void jailListener(PrisonerJailedEvent event) {
pl.getJailManager().addCacheObject(new CachePrisoner(event.getJail(), event.getPrisoner())); pl.getJailManager().addCacheObject(new CachePrisoner(event.getJail(), event.getPrisoner()));
} }
@EventHandler(priority = EventPriority.LOWEST) @EventHandler(priority = EventPriority.LOWEST)
public void beforeReleaseListener(PrePrisonerReleasedEvent event) { public void beforeReleaseListener(PrePrisonerReleasedEvent event) {
if(pl.getJailManager().inCache(event.getPlayer().getUniqueId())) { if(pl.getJailManager().inCache(event.getPlayer().getUniqueId())) {
pl.getJailManager().removeCacheObject(event.getPlayer().getUniqueId()); pl.getJailManager().removeCacheObject(event.getPlayer().getUniqueId());
} }
} }
@EventHandler(priority = EventPriority.LOWEST) @EventHandler(priority = EventPriority.LOWEST)
public void beforeTransferringListener(PrePrisonerTransferredEvent event) { public void beforeTransferringListener(PrePrisonerTransferredEvent event) {
if(pl.getJailManager().inCache(event.getPlayer().getUniqueId())) { if(pl.getJailManager().inCache(event.getPlayer().getUniqueId())) {
pl.getJailManager().removeCacheObject(event.getPlayer().getUniqueId()); pl.getJailManager().removeCacheObject(event.getPlayer().getUniqueId());
} }
} }
@EventHandler(priority = EventPriority.LOWEST) @EventHandler(priority = EventPriority.LOWEST)
public void transferListener(PrisonerTransferredEvent event) { public void transferListener(PrisonerTransferredEvent event) {
pl.getJailManager().addCacheObject(new CachePrisoner(event.getTargetJail(), event.getPrisoner())); pl.getJailManager().addCacheObject(new CachePrisoner(event.getTargetJail(), event.getPrisoner()));
} }
} }

View File

@ -10,39 +10,39 @@ import com.graywolf336.jail.JailMain;
import com.graywolf336.jail.enums.Settings; import com.graywolf336.jail.enums.Settings;
public class EntityListener implements Listener { public class EntityListener implements Listener {
private JailMain pl; private JailMain pl;
public EntityListener(JailMain plugin) { public EntityListener(JailMain plugin) {
this.pl = plugin; this.pl = plugin;
} }
@EventHandler(ignoreCancelled=true) @EventHandler(ignoreCancelled=true)
public void onEntityExplode(EntityExplodeEvent event) { public void onEntityExplode(EntityExplodeEvent event) {
//Only do the checking if plugin has it enabled //Only do the checking if plugin has it enabled
//otherwise let's not go through all the blocks //otherwise let's not go through all the blocks
if(pl.getConfig().getBoolean(Settings.EXPLOSIONPROTECTION.getPath())) { if(pl.getConfig().getBoolean(Settings.EXPLOSIONPROTECTION.getPath())) {
//Loop through the blocklist and do stuff //Loop through the blocklist and do stuff
for(Block b : event.blockList()) { for(Block b : event.blockList()) {
//Check the current block and if it is inside a jail, //Check the current block and if it is inside a jail,
//then let's do something else //then let's do something else
if(pl.getJailManager().getJailFromLocation(b.getLocation()) != null) { if(pl.getJailManager().getJailFromLocation(b.getLocation()) != null) {
//Clear the blocklist, this way the explosion effect still happens //Clear the blocklist, this way the explosion effect still happens
event.blockList().clear(); event.blockList().clear();
return; return;
} }
} }
} }
} }
@EventHandler(ignoreCancelled=true) @EventHandler(ignoreCancelled=true)
public void protectFromEndermen(EntityChangeBlockEvent event) { public void protectFromEndermen(EntityChangeBlockEvent event) {
//If we are protecting the jails from endermen protection //If we are protecting the jails from endermen protection
if(pl.getConfig().getBoolean(Settings.ENDERMENPROTECTION.getPath())) { if(pl.getConfig().getBoolean(Settings.ENDERMENPROTECTION.getPath())) {
//Check if there are any jails where the block's location is //Check if there are any jails where the block's location is
if(pl.getJailManager().getJailFromLocation(event.getBlock().getLocation()) != null) { if(pl.getJailManager().getJailFromLocation(event.getBlock().getLocation()) != null) {
//Let's cancel the event so it doesn't happen //Let's cancel the event so it doesn't happen
event.setCancelled(true); event.setCancelled(true);
} }
} }
} }
} }

View File

@ -16,97 +16,97 @@ import org.bukkit.event.player.PlayerTeleportEvent;
import com.graywolf336.jail.JailMain; import com.graywolf336.jail.JailMain;
public class HandCuffListener implements Listener { public class HandCuffListener implements Listener {
private JailMain pl; private JailMain pl;
private HashMap<String, Location> tos; private HashMap<String, Location> tos;
public HandCuffListener(JailMain plugin) { public HandCuffListener(JailMain plugin) {
this.pl = plugin; this.pl = plugin;
this.tos = new HashMap<String, Location>(); this.tos = new HashMap<String, Location>();
} }
@EventHandler(ignoreCancelled=true) @EventHandler(ignoreCancelled=true)
public void onPlayerMove(PlayerMoveEvent event) { public void onPlayerMove(PlayerMoveEvent event) {
if(event.isCancelled()) return; if(event.isCancelled()) return;
if (pl.getHandCuffManager().isHandCuffed(event.getPlayer().getUniqueId())) { if (pl.getHandCuffManager().isHandCuffed(event.getPlayer().getUniqueId())) {
Location to = pl.getHandCuffManager().getLocation(event.getPlayer().getUniqueId()); Location to = pl.getHandCuffManager().getLocation(event.getPlayer().getUniqueId());
to.setPitch(event.getTo().getPitch()); to.setPitch(event.getTo().getPitch());
to.setYaw(event.getTo().getYaw()); to.setYaw(event.getTo().getYaw());
tos.put(event.getPlayer().getName(), to); tos.put(event.getPlayer().getName(), to);
event.getPlayer().teleport(to); event.getPlayer().teleport(to);
if(System.currentTimeMillis() >= pl.getHandCuffManager().getNextMessageTime(event.getPlayer().getUniqueId())) { if(System.currentTimeMillis() >= pl.getHandCuffManager().getNextMessageTime(event.getPlayer().getUniqueId())) {
event.getPlayer().sendMessage(ChatColor.RED + "You are handcuffed and cant move!"); event.getPlayer().sendMessage(ChatColor.RED + "You are handcuffed and cant move!");
pl.getHandCuffManager().updateNextTime(event.getPlayer().getUniqueId()); pl.getHandCuffManager().updateNextTime(event.getPlayer().getUniqueId());
} }
} }
} }
@EventHandler(ignoreCancelled=true) @EventHandler(ignoreCancelled=true)
public void onPlayerTeleport(PlayerTeleportEvent event) { public void onPlayerTeleport(PlayerTeleportEvent event) {
if(event.isCancelled()) return; if(event.isCancelled()) return;
if (pl.getHandCuffManager().isHandCuffed(event.getPlayer().getUniqueId())) { if (pl.getHandCuffManager().isHandCuffed(event.getPlayer().getUniqueId())) {
if(event.getTo() != tos.get(event.getPlayer().getName())) { if(event.getTo() != tos.get(event.getPlayer().getName())) {
Location to = pl.getHandCuffManager().getLocation(event.getPlayer().getUniqueId()); Location to = pl.getHandCuffManager().getLocation(event.getPlayer().getUniqueId());
to.setPitch(event.getTo().getPitch()); to.setPitch(event.getTo().getPitch());
to.setYaw(event.getTo().getYaw()); to.setYaw(event.getTo().getYaw());
tos.put(event.getPlayer().getName(), to); tos.put(event.getPlayer().getName(), to);
event.getPlayer().teleport(to); event.getPlayer().teleport(to);
if(System.currentTimeMillis() >= pl.getHandCuffManager().getNextMessageTime(event.getPlayer().getUniqueId())) { if(System.currentTimeMillis() >= pl.getHandCuffManager().getNextMessageTime(event.getPlayer().getUniqueId())) {
event.getPlayer().sendMessage(ChatColor.RED + "You are handcuffed and cant move!"); event.getPlayer().sendMessage(ChatColor.RED + "You are handcuffed and cant move!");
pl.getHandCuffManager().updateNextTime(event.getPlayer().getUniqueId()); pl.getHandCuffManager().updateNextTime(event.getPlayer().getUniqueId());
} }
} }
} }
} }
@EventHandler(ignoreCancelled=true) @EventHandler(ignoreCancelled=true)
public void playerChat(AsyncPlayerChatEvent event) { public void playerChat(AsyncPlayerChatEvent event) {
if(event.isCancelled()) return; if(event.isCancelled()) return;
if (pl.getHandCuffManager().isHandCuffed(event.getPlayer().getUniqueId())) { if (pl.getHandCuffManager().isHandCuffed(event.getPlayer().getUniqueId())) {
if(!event.getPlayer().hasPermission("jail.command.handcuff")) { if(!event.getPlayer().hasPermission("jail.command.handcuff")) {
event.setCancelled(true); event.setCancelled(true);
event.getPlayer().sendMessage(ChatColor.RED + "You are handcuffed and aren't allowed to talk!"); event.getPlayer().sendMessage(ChatColor.RED + "You are handcuffed and aren't allowed to talk!");
} }
} }
} }
@EventHandler(ignoreCancelled=true) @EventHandler(ignoreCancelled=true)
public void blockBreak(BlockBreakEvent event) { public void blockBreak(BlockBreakEvent event) {
if(event.isCancelled()) return; if(event.isCancelled()) return;
if (pl.getHandCuffManager().isHandCuffed(event.getPlayer().getUniqueId())) { if (pl.getHandCuffManager().isHandCuffed(event.getPlayer().getUniqueId())) {
event.setCancelled(true); event.setCancelled(true);
event.getPlayer().sendMessage(ChatColor.RED + "You are handcuffed and aren't allowed to break blocks!"); event.getPlayer().sendMessage(ChatColor.RED + "You are handcuffed and aren't allowed to break blocks!");
} }
} }
@EventHandler(ignoreCancelled=true) @EventHandler(ignoreCancelled=true)
public void blockPlace(BlockPlaceEvent event) { public void blockPlace(BlockPlaceEvent event) {
if(event.isCancelled()) return; if(event.isCancelled()) return;
if (pl.getHandCuffManager().isHandCuffed(event.getPlayer().getUniqueId())) { if (pl.getHandCuffManager().isHandCuffed(event.getPlayer().getUniqueId())) {
event.setCancelled(true); event.setCancelled(true);
event.getPlayer().sendMessage(ChatColor.RED + "You are handcuffed and aren't allowed to place blocks!"); event.getPlayer().sendMessage(ChatColor.RED + "You are handcuffed and aren't allowed to place blocks!");
} }
} }
@EventHandler(ignoreCancelled=true) @EventHandler(ignoreCancelled=true)
public void preCommands(PlayerCommandPreprocessEvent event) { public void preCommands(PlayerCommandPreprocessEvent event) {
if(event.isCancelled()) return; if(event.isCancelled()) return;
if (pl.getHandCuffManager().isHandCuffed(event.getPlayer().getUniqueId())) { if (pl.getHandCuffManager().isHandCuffed(event.getPlayer().getUniqueId())) {
if(!event.getPlayer().hasPermission("jail.command.handcuff")) { if(!event.getPlayer().hasPermission("jail.command.handcuff")) {
if(!event.getMessage().startsWith("/r") || !event.getMessage().startsWith("/reply")) { if(!event.getMessage().startsWith("/r") || !event.getMessage().startsWith("/reply")) {
event.setCancelled(true); event.setCancelled(true);
event.getPlayer().sendMessage(ChatColor.RED + "You are handcuffed and aren't allowed to use commands!"); event.getPlayer().sendMessage(ChatColor.RED + "You are handcuffed and aren't allowed to use commands!");
} }
} }
} }
} }
} }

View File

@ -19,100 +19,100 @@ import com.graywolf336.jail.events.PrePrisonerJailedEvent;
import com.graywolf336.jail.events.PrisonerJailedEvent; import com.graywolf336.jail.events.PrisonerJailedEvent;
public class JailingListener implements Listener { public class JailingListener implements Listener {
private JailMain pl; private JailMain pl;
private DateFormat dateFormat; private DateFormat dateFormat;
public JailingListener(JailMain plugin) { public JailingListener(JailMain plugin) {
this.pl = plugin; this.pl = plugin;
this.dateFormat = new SimpleDateFormat(Lang.TIMEFORMAT.get()); this.dateFormat = new SimpleDateFormat(Lang.TIMEFORMAT.get());
} }
@EventHandler(ignoreCancelled=true) @EventHandler(ignoreCancelled=true)
public void preJailingListener(PrePrisonerJailedEvent event) { public void preJailingListener(PrePrisonerJailedEvent event) {
if(pl.getConfig().getBoolean(Settings.LOGJAILINGTOPROFILE.getPath())) { if(pl.getConfig().getBoolean(Settings.LOGJAILINGTOPROFILE.getPath())) {
pl.getJailIO().addRecordEntry(event.getPrisoner().getUUID().toString(), pl.getJailIO().addRecordEntry(event.getPrisoner().getUUID().toString(),
event.getPrisoner().getLastKnownName(), event.getPrisoner().getLastKnownName(),
event.getPrisoner().getJailer(), dateFormat.format(new Date()), event.getPrisoner().getJailer(), dateFormat.format(new Date()),
event.getPrisoner().getRemainingTimeInMinutes(), event.getPrisoner().getReason()); event.getPrisoner().getRemainingTimeInMinutes(), event.getPrisoner().getReason());
} }
} }
@EventHandler(ignoreCancelled=true) @EventHandler(ignoreCancelled=true)
public void preJailingListener(PrePrisonerJailedByJailStickEvent event) { public void preJailingListener(PrePrisonerJailedByJailStickEvent event) {
if(pl.getConfig().getBoolean(Settings.LOGJAILINGTOPROFILE.getPath())) { if(pl.getConfig().getBoolean(Settings.LOGJAILINGTOPROFILE.getPath())) {
pl.getJailIO().addRecordEntry(event.getPrisoner().getUUID().toString(), pl.getJailIO().addRecordEntry(event.getPrisoner().getUUID().toString(),
event.getPrisoner().getLastKnownName(), event.getPrisoner().getLastKnownName(),
event.getPrisoner().getJailer(), dateFormat.format(new Date()), event.getPrisoner().getJailer(), dateFormat.format(new Date()),
event.getPrisoner().getRemainingTimeInMinutes(), event.getPrisoner().getReason()); event.getPrisoner().getRemainingTimeInMinutes(), event.getPrisoner().getReason());
} }
} }
@EventHandler @EventHandler
public void setInmatesClothing(PrisonerJailedEvent event) { public void setInmatesClothing(PrisonerJailedEvent event) {
if(pl.getConfig().getBoolean(Settings.CLOTHINGENABLED.getPath())) { if(pl.getConfig().getBoolean(Settings.CLOTHINGENABLED.getPath())) {
String[] helmet = pl.getConfig().getString(Settings.CLOTHINGHELMET.getPath()).toUpperCase().split("~"); String[] helmet = pl.getConfig().getString(Settings.CLOTHINGHELMET.getPath()).toUpperCase().split("~");
switch(helmet.length) { switch(helmet.length) {
case 1: case 1:
event.getPlayer().getInventory().setHelmet(new ItemStack(Material.valueOf(helmet[0]))); event.getPlayer().getInventory().setHelmet(new ItemStack(Material.valueOf(helmet[0])));
break; break;
case 2: case 2:
ItemStack item = new ItemStack(Material.valueOf(helmet[0])); ItemStack item = new ItemStack(Material.valueOf(helmet[0]));
LeatherArmorMeta meta = (LeatherArmorMeta) item.getItemMeta(); LeatherArmorMeta meta = (LeatherArmorMeta) item.getItemMeta();
String[] colors = helmet[1].split(","); String[] colors = helmet[1].split(",");
meta.setColor(Color.fromBGR(Integer.parseInt(colors[2]), Integer.parseInt(colors[1]), Integer.parseInt(colors[0]))); meta.setColor(Color.fromBGR(Integer.parseInt(colors[2]), Integer.parseInt(colors[1]), Integer.parseInt(colors[0])));
item.setItemMeta(meta); item.setItemMeta(meta);
event.getPlayer().getInventory().setHelmet(item); event.getPlayer().getInventory().setHelmet(item);
default: default:
break; break;
} }
String[] chest = pl.getConfig().getString(Settings.CLOTHINGCHEST.getPath()).toUpperCase().split("~"); String[] chest = pl.getConfig().getString(Settings.CLOTHINGCHEST.getPath()).toUpperCase().split("~");
switch(chest.length) { switch(chest.length) {
case 1: case 1:
event.getPlayer().getInventory().setChestplate(new ItemStack(Material.valueOf(chest[0]))); event.getPlayer().getInventory().setChestplate(new ItemStack(Material.valueOf(chest[0])));
break; break;
case 2: case 2:
ItemStack item = new ItemStack(Material.valueOf(chest[0])); ItemStack item = new ItemStack(Material.valueOf(chest[0]));
LeatherArmorMeta meta = (LeatherArmorMeta) item.getItemMeta(); LeatherArmorMeta meta = (LeatherArmorMeta) item.getItemMeta();
String[] colors = chest[1].split(","); String[] colors = chest[1].split(",");
meta.setColor(Color.fromBGR(Integer.parseInt(colors[2]), Integer.parseInt(colors[1]), Integer.parseInt(colors[0]))); meta.setColor(Color.fromBGR(Integer.parseInt(colors[2]), Integer.parseInt(colors[1]), Integer.parseInt(colors[0])));
item.setItemMeta(meta); item.setItemMeta(meta);
event.getPlayer().getInventory().setChestplate(item); event.getPlayer().getInventory().setChestplate(item);
default: default:
break; break;
} }
String[] legs = pl.getConfig().getString(Settings.CLOTHINGLEGS.getPath()).toUpperCase().split("~"); String[] legs = pl.getConfig().getString(Settings.CLOTHINGLEGS.getPath()).toUpperCase().split("~");
switch(legs.length) { switch(legs.length) {
case 1: case 1:
event.getPlayer().getInventory().setLeggings(new ItemStack(Material.valueOf(legs[0]))); event.getPlayer().getInventory().setLeggings(new ItemStack(Material.valueOf(legs[0])));
break; break;
case 2: case 2:
ItemStack item = new ItemStack(Material.valueOf(legs[0])); ItemStack item = new ItemStack(Material.valueOf(legs[0]));
LeatherArmorMeta meta = (LeatherArmorMeta) item.getItemMeta(); LeatherArmorMeta meta = (LeatherArmorMeta) item.getItemMeta();
String[] colors = legs[1].split(","); String[] colors = legs[1].split(",");
meta.setColor(Color.fromBGR(Integer.parseInt(colors[2]), Integer.parseInt(colors[1]), Integer.parseInt(colors[0]))); meta.setColor(Color.fromBGR(Integer.parseInt(colors[2]), Integer.parseInt(colors[1]), Integer.parseInt(colors[0])));
item.setItemMeta(meta); item.setItemMeta(meta);
event.getPlayer().getInventory().setLeggings(item); event.getPlayer().getInventory().setLeggings(item);
default: default:
break; break;
} }
String[] boots = pl.getConfig().getString(Settings.CLOTHINGBOOTS.getPath()).toUpperCase().split("~"); String[] boots = pl.getConfig().getString(Settings.CLOTHINGBOOTS.getPath()).toUpperCase().split("~");
switch(boots.length) { switch(boots.length) {
case 1: case 1:
event.getPlayer().getInventory().setBoots(new ItemStack(Material.valueOf(boots[0]))); event.getPlayer().getInventory().setBoots(new ItemStack(Material.valueOf(boots[0])));
break; break;
case 2: case 2:
ItemStack item = new ItemStack(Material.valueOf(boots[0])); ItemStack item = new ItemStack(Material.valueOf(boots[0]));
LeatherArmorMeta meta = (LeatherArmorMeta) item.getItemMeta(); LeatherArmorMeta meta = (LeatherArmorMeta) item.getItemMeta();
String[] colors = boots[1].split(","); String[] colors = boots[1].split(",");
meta.setColor(Color.fromBGR(Integer.parseInt(colors[2]), Integer.parseInt(colors[1]), Integer.parseInt(colors[0]))); meta.setColor(Color.fromBGR(Integer.parseInt(colors[2]), Integer.parseInt(colors[1]), Integer.parseInt(colors[0])));
item.setItemMeta(meta); item.setItemMeta(meta);
event.getPlayer().getInventory().setBoots(item); event.getPlayer().getInventory().setBoots(item);
default: default:
break; break;
} }
} }
} }
} }

View File

@ -16,72 +16,72 @@ import com.graywolf336.jail.enums.Lang;
import com.graywolf336.jail.enums.Settings; import com.graywolf336.jail.enums.Settings;
public class MoveProtectionListener implements Listener { public class MoveProtectionListener implements Listener {
private JailMain pl; private JailMain pl;
public MoveProtectionListener(JailMain plugin) { public MoveProtectionListener(JailMain plugin) {
this.pl = plugin; this.pl = plugin;
} }
@EventHandler(ignoreCancelled=true) @EventHandler(ignoreCancelled=true)
public void moveProtection(PlayerMoveEvent event) { public void moveProtection(PlayerMoveEvent event) {
//If we have the move protection enabled, then let's do it. //If we have the move protection enabled, then let's do it.
//Other wise we don't need to deal with it. //Other wise we don't need to deal with it.
if(pl.getConfig().getBoolean(Settings.MOVEPROTECTION.getPath())) { if(pl.getConfig().getBoolean(Settings.MOVEPROTECTION.getPath())) {
//Let's be sure the player we're dealing with is in jail //Let's be sure the player we're dealing with is in jail
if(pl.getJailManager().inCache(event.getPlayer().getUniqueId())) { if(pl.getJailManager().inCache(event.getPlayer().getUniqueId())) {
CachePrisoner cp = pl.getJailManager().getCacheObject(event.getPlayer().getUniqueId()); CachePrisoner cp = pl.getJailManager().getCacheObject(event.getPlayer().getUniqueId());
Jail j = cp.getJail(); Jail j = cp.getJail();
Prisoner p = cp.getPrisoner(); Prisoner p = cp.getPrisoner();
//If the player is being teleported, let's ignore it //If the player is being teleported, let's ignore it
if(p.isTeleporting()) { if(p.isTeleporting()) {
return; return;
} }
//They moved, so they're no longer afk //They moved, so they're no longer afk
p.setAFKTime(0L); p.setAFKTime(0L);
//If the event's to location is NOT inside the jail, then let's do some action. //If the event's to location is NOT inside the jail, then let's do some action.
//For right now, we're only going to apply the time. Later we're going to do //For right now, we're only going to apply the time. Later we're going to do
//the guards, but first get a beta version out. //the guards, but first get a beta version out.
if (!j.isInside(event.getTo())) { if (!j.isInside(event.getTo())) {
try { try {
long add = Util.getTime(pl.getConfig().getString(Settings.MOVEPENALTY.getPath())); long add = Util.getTime(pl.getConfig().getString(Settings.MOVEPENALTY.getPath()));
p.addTime(add); p.addTime(add);
String msg = ""; String msg = "";
if(add == 0L) { if(add == 0L) {
//Generate the protection message, provide the method with one argument //Generate the protection message, provide the method with one argument
//which is the thing we are protecting against //which is the thing we are protecting against
msg = Lang.PROTECTIONMESSAGENOPENALTY.get(Lang.MOVING); msg = Lang.PROTECTIONMESSAGENOPENALTY.get(Lang.MOVING);
}else { }else {
//Generate the protection message, provide the method with two arguments //Generate the protection message, provide the method with two arguments
//First is the time in minutes and second is the thing we are protecting against //First is the time in minutes and second is the thing we are protecting against
msg = Lang.PROTECTIONMESSAGE.get(new String[] { String.valueOf(TimeUnit.MINUTES.convert(add, TimeUnit.MILLISECONDS)), Lang.MOVING.get() }); msg = Lang.PROTECTIONMESSAGE.get(new String[] { String.valueOf(TimeUnit.MINUTES.convert(add, TimeUnit.MILLISECONDS)), Lang.MOVING.get() });
} }
//Send the message //Send the message
event.getPlayer().sendMessage(msg); event.getPlayer().sendMessage(msg);
}catch(Exception e) { }catch(Exception e) {
pl.getLogger().severe("Moving (escaping) outside a jail penalty time is in the wrong format, please fix."); pl.getLogger().severe("Moving (escaping) outside a jail penalty time is in the wrong format, please fix.");
} }
//If the prisoner is in a cell, then let's teleport them to the cell's in location //If the prisoner is in a cell, then let's teleport them to the cell's in location
if(j.isJailedInACell(event.getPlayer().getUniqueId())) { if(j.isJailedInACell(event.getPlayer().getUniqueId())) {
event.setTo(j.getCellPrisonerIsIn(event.getPlayer().getUniqueId()).getTeleport()); event.setTo(j.getCellPrisonerIsIn(event.getPlayer().getUniqueId()).getTeleport());
}else { }else {
//Otherwise let's teleport them to the in location of the jail //Otherwise let's teleport them to the in location of the jail
event.setTo(j.getTeleportIn()); event.setTo(j.getTeleportIn());
} }
} }
} }
} }
} }
@EventHandler(ignoreCancelled=true) @EventHandler(ignoreCancelled=true)
public void onPlayerTeleport(PlayerTeleportEvent event) { public void onPlayerTeleport(PlayerTeleportEvent event) {
PlayerMoveEvent move = new PlayerMoveEvent(event.getPlayer(), event.getFrom(), event.getTo()); PlayerMoveEvent move = new PlayerMoveEvent(event.getPlayer(), event.getFrom(), event.getTo());
moveProtection(move); moveProtection(move);
} }
} }

View File

@ -33,252 +33,252 @@ import com.graywolf336.jail.events.PrePrisonerJailedByJailStickEvent;
import com.graywolf336.jail.events.PrisonerDeathEvent; import com.graywolf336.jail.events.PrisonerDeathEvent;
public class PlayerListener implements Listener { public class PlayerListener implements Listener {
private JailMain pl; private JailMain pl;
public PlayerListener(JailMain plugin) { public PlayerListener(JailMain plugin) {
this.pl = plugin; this.pl = plugin;
} }
@EventHandler(ignoreCancelled=true) @EventHandler(ignoreCancelled=true)
public void jailOrCellCreation(PlayerInteractEvent event) { public void jailOrCellCreation(PlayerInteractEvent event) {
if(event.getAction() == Action.RIGHT_CLICK_AIR || event.getAction() == Action.RIGHT_CLICK_BLOCK) { if(event.getAction() == Action.RIGHT_CLICK_AIR || event.getAction() == Action.RIGHT_CLICK_BLOCK) {
Player p = event.getPlayer(); Player p = event.getPlayer();
Location loc = event.getClickedBlock() == null ? p.getLocation() : event.getClickedBlock().getLocation(); Location loc = event.getClickedBlock() == null ? p.getLocation() : event.getClickedBlock().getLocation();
JailManager jm = pl.getJailManager(); JailManager jm = pl.getJailManager();
if(p.getItemInHand().isSimilar(Util.getWand())) { if(p.getItemInHand().isSimilar(Util.getWand())) {
if(jm.isCreatingSomething(p.getName())) { if(jm.isCreatingSomething(p.getName())) {
if(jm.isCreatingAJail(p.getName())) { if(jm.isCreatingAJail(p.getName())) {
pl.debug("Stepping into creating a jail."); pl.debug("Stepping into creating a jail.");
jm.getJailCreationSteps().step(jm, p, jm.getJailCreationPlayer(p.getName()), loc); jm.getJailCreationSteps().step(jm, p, jm.getJailCreationPlayer(p.getName()), loc);
}else if(jm.isCreatingACell(p.getName())) { }else if(jm.isCreatingACell(p.getName())) {
pl.debug("Stepping into creating a cell."); pl.debug("Stepping into creating a cell.");
jm.getCellCreationSteps().step(jm, p, jm.getCellCreationPlayer(p.getName()), loc); jm.getCellCreationSteps().step(jm, p, jm.getCellCreationPlayer(p.getName()), loc);
} }
event.setCancelled(true); event.setCancelled(true);
} }
} }
} }
} }
@EventHandler(ignoreCancelled=true, priority = EventPriority.LOW) @EventHandler(ignoreCancelled=true, priority = EventPriority.LOW)
public void chatting(AsyncPlayerChatEvent event) { public void chatting(AsyncPlayerChatEvent event) {
if(pl.getJailManager().isPlayerJailed(event.getPlayer().getUniqueId())) { if(pl.getJailManager().isPlayerJailed(event.getPlayer().getUniqueId())) {
if(pl.getJailManager().getPrisoner(event.getPlayer().getUniqueId()).isMuted()) { if(pl.getJailManager().getPrisoner(event.getPlayer().getUniqueId()).isMuted()) {
event.setCancelled(true); event.setCancelled(true);
event.getPlayer().sendMessage(Lang.MUTED.get()); event.getPlayer().sendMessage(Lang.MUTED.get());
} }
} }
//If the config has receive messages set to false, let's remove all the prisoners //If the config has receive messages set to false, let's remove all the prisoners
//from getting the chat messages. //from getting the chat messages.
if(!pl.getConfig().getBoolean(Settings.RECIEVEMESSAGES.getPath())) { if(!pl.getConfig().getBoolean(Settings.RECIEVEMESSAGES.getPath())) {
if(pl.inDebug()) pl.getLogger().info("Debug - There are " + event.getRecipients().size() + " players getting the message before."); if(pl.inDebug()) pl.getLogger().info("Debug - There are " + event.getRecipients().size() + " players getting the message before.");
Set<Player> rec = new HashSet<Player>(event.getRecipients()); Set<Player> rec = new HashSet<Player>(event.getRecipients());
for(Jail j : pl.getJailManager().getJails()) for(Jail j : pl.getJailManager().getJails())
for(Prisoner p : j.getAllPrisoners().values()) for(Prisoner p : j.getAllPrisoners().values())
rec.remove(pl.getServer().getPlayer(p.getUUID())); rec.remove(pl.getServer().getPlayer(p.getUUID()));
event.getRecipients().clear(); event.getRecipients().clear();
event.getRecipients().addAll(rec); event.getRecipients().addAll(rec);
if(pl.inDebug()) pl.getLogger().info("Debug - There are now " + event.getRecipients().size() + " players getting the message."); if(pl.inDebug()) pl.getLogger().info("Debug - There are now " + event.getRecipients().size() + " players getting the message.");
} }
} }
@EventHandler(priority = EventPriority.HIGHEST) @EventHandler(priority = EventPriority.HIGHEST)
public void checkForOfflineJailStuff(PlayerJoinEvent event) { public void checkForOfflineJailStuff(PlayerJoinEvent event) {
//Let's check if the player is jailed //Let's check if the player is jailed
if(pl.getJailManager().isPlayerJailed(event.getPlayer().getUniqueId())) { if(pl.getJailManager().isPlayerJailed(event.getPlayer().getUniqueId())) {
//Get the prisoner object //Get the prisoner object
Jail j = pl.getJailManager().getJailPlayerIsIn(event.getPlayer().getUniqueId()); Jail j = pl.getJailManager().getJailPlayerIsIn(event.getPlayer().getUniqueId());
if(!j.isEnabled()) { if(!j.isEnabled()) {
event.getPlayer().kickPlayer(Lang.WORLDUNLOADEDKICK.get()); event.getPlayer().kickPlayer(Lang.WORLDUNLOADEDKICK.get());
pl.getLogger().warning(j.getName() + " is located in a world which is unloaded and " + event.getPlayer().getName() + " (" + event.getPlayer().getUniqueId() + ") tried to join while jailed in it."); pl.getLogger().warning(j.getName() + " is located in a world which is unloaded and " + event.getPlayer().getName() + " (" + event.getPlayer().getUniqueId() + ") tried to join while jailed in it.");
return; return;
} }
Prisoner p = j.getPrisoner(event.getPlayer().getUniqueId()); Prisoner p = j.getPrisoner(event.getPlayer().getUniqueId());
//update their last known username when they login //update their last known username when they login
p.setLastKnownName(event.getPlayer().getName()); p.setLastKnownName(event.getPlayer().getName());
//Check if they're offline pending, as if this is true then they were jailed offline //Check if they're offline pending, as if this is true then they were jailed offline
if(p.isOfflinePending()) { if(p.isOfflinePending()) {
if(p.getRemainingTime() == 0L) { if(p.getRemainingTime() == 0L) {
//If their remaining time is 0, let's unjail them //If their remaining time is 0, let's unjail them
pl.getPrisonerManager().schedulePrisonerRelease(p); pl.getPrisonerManager().schedulePrisonerRelease(p);
}else if(p.isToBeTransferred()) { }else if(p.isToBeTransferred()) {
Cell c = j.getCellPrisonerIsIn(event.getPlayer().getUniqueId()); Cell c = j.getCellPrisonerIsIn(event.getPlayer().getUniqueId());
//If the player is not jailed in a cell, teleport them to the jail's in //If the player is not jailed in a cell, teleport them to the jail's in
if(c == null) { if(c == null) {
p.setTeleporting(true); p.setTeleporting(true);
event.getPlayer().teleport(j.getTeleportIn()); event.getPlayer().teleport(j.getTeleportIn());
p.setTeleporting(false); p.setTeleporting(false);
}else { }else {
//If they are in a cell, teleport them into that cell //If they are in a cell, teleport them into that cell
p.setTeleporting(true); p.setTeleporting(true);
event.getPlayer().teleport(c.getTeleport()); event.getPlayer().teleport(c.getTeleport());
p.setTeleporting(false); p.setTeleporting(false);
} }
p.setToBeTransferred(false); p.setToBeTransferred(false);
} else { } else {
//Their remaining time isn't 0 so let's proceed with jailing of the prisoner //Their remaining time isn't 0 so let's proceed with jailing of the prisoner
pl.getPrisonerManager().jailPlayer(event.getPlayer().getUniqueId()); pl.getPrisonerManager().jailPlayer(event.getPlayer().getUniqueId());
} }
} }
//Add the scoreboard to them if it is enabled //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(event.getPlayer(), p); pl.getScoreBoardManager().addScoreBoard(event.getPlayer(), p);
} }
//if we are ignoring a prisoner's sleeping state, then let's set that //if we are ignoring a prisoner's sleeping state, then let's set that
if(pl.getConfig().getBoolean(Settings.IGNORESLEEPINGSTATE.getPath())) { if(pl.getConfig().getBoolean(Settings.IGNORESLEEPINGSTATE.getPath())) {
event.getPlayer().setSleepingIgnored(true); event.getPlayer().setSleepingIgnored(true);
} }
} }
} }
@EventHandler @EventHandler
public void notifyUpdate(PlayerJoinEvent event) { public void notifyUpdate(PlayerJoinEvent event) {
if(pl.getConfig().getBoolean(Settings.UPDATENOTIFICATIONS.getPath())) { if(pl.getConfig().getBoolean(Settings.UPDATENOTIFICATIONS.getPath())) {
if(event.getPlayer().isOp() && pl.getUpdate().isAvailable()) { if(event.getPlayer().isOp() && pl.getUpdate().isAvailable()) {
event.getPlayer().sendMessage(ChatColor.BLUE + "" + ChatColor.BOLD + "An update for Jail is available: " + pl.getUpdate().getNewVersion()); event.getPlayer().sendMessage(ChatColor.BLUE + "" + ChatColor.BOLD + "An update for Jail is available: " + pl.getUpdate().getNewVersion());
event.getPlayer().sendMessage(ChatColor.BLUE + "" + ChatColor.BOLD + pl.getUpdate().getFileUrl()); event.getPlayer().sendMessage(ChatColor.BLUE + "" + ChatColor.BOLD + pl.getUpdate().getFileUrl());
} }
} }
} }
@EventHandler @EventHandler
public void handleGoingOffline(PlayerQuitEvent event) { public void handleGoingOffline(PlayerQuitEvent event) {
if(pl.getJailManager().isPlayerJailed(event.getPlayer().getUniqueId())) { if(pl.getJailManager().isPlayerJailed(event.getPlayer().getUniqueId())) {
//Remove the scoreboard to them if it is enabled //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(event.getPlayer()); pl.getScoreBoardManager().removeScoreBoard(event.getPlayer());
} }
} }
} }
@EventHandler(ignoreCancelled=true) @EventHandler(ignoreCancelled=true)
public void handleGettingKicked(PlayerKickEvent event) { public void handleGettingKicked(PlayerKickEvent event) {
if(pl.getJailManager().isPlayerJailed(event.getPlayer().getUniqueId())) { if(pl.getJailManager().isPlayerJailed(event.getPlayer().getUniqueId())) {
//Remove the scoreboard to them if it is enabled //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(event.getPlayer()); pl.getScoreBoardManager().removeScoreBoard(event.getPlayer());
} }
} }
} }
@EventHandler(priority = EventPriority.LOW) @EventHandler(priority = EventPriority.LOW)
public void foodControl(FoodLevelChangeEvent event) { public void foodControl(FoodLevelChangeEvent event) {
if(pl.getConfig().getBoolean(Settings.FOODCONTROL.getPath())) { if(pl.getConfig().getBoolean(Settings.FOODCONTROL.getPath())) {
if(pl.getJailManager().isPlayerJailed(event.getEntity().getUniqueId())) { if(pl.getJailManager().isPlayerJailed(event.getEntity().getUniqueId())) {
int min = pl.getConfig().getInt(Settings.FOODCONTROLMIN.getPath()); int min = pl.getConfig().getInt(Settings.FOODCONTROLMIN.getPath());
int max = pl.getConfig().getInt(Settings.FOODCONTROLMAX.getPath()); int max = pl.getConfig().getInt(Settings.FOODCONTROLMAX.getPath());
if (event.getFoodLevel() < min) { if (event.getFoodLevel() < min) {
event.setFoodLevel(min); event.setFoodLevel(min);
}else { }else {
event.setFoodLevel(max); event.setFoodLevel(max);
} }
} }
} }
} }
@EventHandler @EventHandler
public void onPlayerDeath(PlayerDeathEvent event) { public void onPlayerDeath(PlayerDeathEvent event) {
if(pl.getJailManager().isPlayerJailed(event.getEntity().getUniqueId())) { if(pl.getJailManager().isPlayerJailed(event.getEntity().getUniqueId())) {
Jail j = pl.getJailManager().getJailPlayerIsIn(event.getEntity().getUniqueId()); Jail j = pl.getJailManager().getJailPlayerIsIn(event.getEntity().getUniqueId());
PrisonerDeathEvent prisonerEvent = new PrisonerDeathEvent(event, j, j.getCellPrisonerIsIn(event.getEntity().getUniqueId()), j.getPrisoner(event.getEntity().getUniqueId()), event.getEntity()); PrisonerDeathEvent prisonerEvent = new PrisonerDeathEvent(event, j, j.getCellPrisonerIsIn(event.getEntity().getUniqueId()), j.getPrisoner(event.getEntity().getUniqueId()), event.getEntity());
pl.getServer().getPluginManager().callEvent(prisonerEvent); pl.getServer().getPluginManager().callEvent(prisonerEvent);
} }
} }
@EventHandler @EventHandler
public void onPlayerRespawn(PlayerRespawnEvent event) { public void onPlayerRespawn(PlayerRespawnEvent event) {
if(pl.getJailManager().isPlayerJailed(event.getPlayer().getUniqueId())) { if(pl.getJailManager().isPlayerJailed(event.getPlayer().getUniqueId())) {
Jail j = pl.getJailManager().getJailPlayerIsIn(event.getPlayer().getUniqueId()); Jail j = pl.getJailManager().getJailPlayerIsIn(event.getPlayer().getUniqueId());
if(j.isJailedInACell(event.getPlayer().getUniqueId())) { if(j.isJailedInACell(event.getPlayer().getUniqueId())) {
event.setRespawnLocation(j.getCellPrisonerIsIn(event.getPlayer().getUniqueId()).getTeleport()); event.setRespawnLocation(j.getCellPrisonerIsIn(event.getPlayer().getUniqueId()).getTeleport());
}else { }else {
event.setRespawnLocation(j.getTeleportIn()); event.setRespawnLocation(j.getTeleportIn());
} }
} }
} }
@EventHandler(ignoreCancelled=true) @EventHandler(ignoreCancelled=true)
public void jailStickHandling(EntityDamageByEntityEvent event) { public void jailStickHandling(EntityDamageByEntityEvent event) {
if(pl.getConfig().getBoolean(Settings.JAILSTICKENABLED.getPath())) { if(pl.getConfig().getBoolean(Settings.JAILSTICKENABLED.getPath())) {
//If the damager and the entity getting damage is not a player, //If the damager and the entity getting damage is not a player,
//we don't want to handle it in this method //we don't want to handle it in this method
if(!(event.getDamager() instanceof Player) || !(event.getEntity() instanceof Player)) return; if(!(event.getDamager() instanceof Player) || !(event.getEntity() instanceof Player)) return;
Player attacker = (Player) event.getDamager(); Player attacker = (Player) event.getDamager();
Player player = (Player) event.getEntity(); Player player = (Player) event.getEntity();
if(pl.getJailStickManager().isUsingJailStick(attacker.getUniqueId())) { if(pl.getJailStickManager().isUsingJailStick(attacker.getUniqueId())) {
if(pl.getJailStickManager().isValidStick(attacker.getItemInHand().getType())) { if(pl.getJailStickManager().isValidStick(attacker.getItemInHand().getType())) {
if(attacker.hasPermission("jail.usejailstick." + attacker.getItemInHand().getType().toString().toLowerCase())) { if(attacker.hasPermission("jail.usejailstick." + attacker.getItemInHand().getType().toString().toLowerCase())) {
//The person the attacker is trying to jail stick is already jailed, don't handle that //The person the attacker is trying to jail stick is already jailed, don't handle that
if(pl.getJailManager().isPlayerJailed(player.getUniqueId())) { if(pl.getJailManager().isPlayerJailed(player.getUniqueId())) {
attacker.sendMessage(Lang.ALREADYJAILED.get(player.getName())); attacker.sendMessage(Lang.ALREADYJAILED.get(player.getName()));
}else { }else {
if(player.hasPermission("jail.cantbejailed")) { if(player.hasPermission("jail.cantbejailed")) {
attacker.sendMessage(Lang.CANTBEJAILED.get()); attacker.sendMessage(Lang.CANTBEJAILED.get());
}else { }else {
Stick s = pl.getJailStickManager().getStick(attacker.getItemInHand().getType()); Stick s = pl.getJailStickManager().getStick(attacker.getItemInHand().getType());
if(player.getHealth() <= s.getHealth() || s.getHealth() == -1) { if(player.getHealth() <= s.getHealth() || s.getHealth() == -1) {
Prisoner p = new Prisoner(player.getUniqueId().toString(), player.getName(), Prisoner p = new Prisoner(player.getUniqueId().toString(), player.getName(),
pl.getConfig().getBoolean(Settings.AUTOMATICMUTE.getPath()), pl.getConfig().getBoolean(Settings.AUTOMATICMUTE.getPath()),
s.getTime(), attacker.getName(), s.getReason()); s.getTime(), attacker.getName(), s.getReason());
PrePrisonerJailedByJailStickEvent jEvent = new PrePrisonerJailedByJailStickEvent( PrePrisonerJailedByJailStickEvent jEvent = new PrePrisonerJailedByJailStickEvent(
pl.getJailManager().getJail(s.getJail()), null, p, player, attacker.getName(), s); pl.getJailManager().getJail(s.getJail()), null, p, player, attacker.getName(), s);
pl.getServer().getPluginManager().callEvent(jEvent); pl.getServer().getPluginManager().callEvent(jEvent);
if(jEvent.isCancelled()) { if(jEvent.isCancelled()) {
if(jEvent.getCancelledMessage().isEmpty()) if(jEvent.getCancelledMessage().isEmpty())
attacker.sendMessage(Lang.CANCELLEDBYANOTHERPLUGIN.get(player.getName())); attacker.sendMessage(Lang.CANCELLEDBYANOTHERPLUGIN.get(player.getName()));
else else
attacker.sendMessage(jEvent.getCancelledMessage()); attacker.sendMessage(jEvent.getCancelledMessage());
}else { }else {
//recall data from the event //recall data from the event
Jail j = jEvent.getJail(); Jail j = jEvent.getJail();
Cell c = jEvent.getCell(); Cell c = jEvent.getCell();
p = jEvent.getPrisoner(); p = jEvent.getPrisoner();
player = jEvent.getPlayer(); player = jEvent.getPlayer();
//Player is not online //Player is not online
if(player == null) { if(player == null) {
attacker.sendMessage(Lang.OFFLINEJAIL.get(new String[] { p.getLastKnownName(), String.valueOf(p.getRemainingTimeInMinutes()) })); attacker.sendMessage(Lang.OFFLINEJAIL.get(new String[] { p.getLastKnownName(), String.valueOf(p.getRemainingTimeInMinutes()) }));
}else { }else {
//Player *is* online //Player *is* online
attacker.sendMessage(Lang.ONLINEJAIL.get(new String[] { p.getLastKnownName(), String.valueOf(p.getRemainingTimeInMinutes()) })); attacker.sendMessage(Lang.ONLINEJAIL.get(new String[] { p.getLastKnownName(), String.valueOf(p.getRemainingTimeInMinutes()) }));
} }
try { try {
pl.getPrisonerManager().prepareJail(j, c, player, p); pl.getPrisonerManager().prepareJail(j, c, player, p);
} catch (Exception e) { } catch (Exception e) {
attacker.sendMessage(ChatColor.RED + e.getMessage()); attacker.sendMessage(ChatColor.RED + e.getMessage());
} }
} }
}else { }else {
attacker.sendMessage(Lang.RESISTEDARRESTJAILER.get(player.getName())); attacker.sendMessage(Lang.RESISTEDARRESTJAILER.get(player.getName()));
player.sendMessage(Lang.RESISTEDARRESTPLAYER.get(attacker.getName())); player.sendMessage(Lang.RESISTEDARRESTPLAYER.get(attacker.getName()));
} }
} }
} }
} }
} }
} }
} }
} }
} }

View File

@ -18,290 +18,290 @@ import com.graywolf336.jail.enums.Lang;
import com.graywolf336.jail.enums.Settings; import com.graywolf336.jail.enums.Settings;
public class ProtectionListener implements Listener { public class ProtectionListener implements Listener {
private JailMain pl; private JailMain pl;
public ProtectionListener(JailMain plugin) { public ProtectionListener(JailMain plugin) {
this.pl = plugin; this.pl = plugin;
} }
@EventHandler(ignoreCancelled=true, priority = EventPriority.LOW) @EventHandler(ignoreCancelled=true, priority = EventPriority.LOW)
public void protectionBlockBreaking(BlockBreakEvent event) { public void protectionBlockBreaking(BlockBreakEvent event) {
//Before we check if the player is jailed, let's save a //Before we check if the player is jailed, let's save a
//tiny bit of resources and check if this protection is enabled //tiny bit of resources and check if this protection is enabled
if(pl.getConfig().getBoolean(Settings.BLOCKBREAKPROTECTION.getPath())) { if(pl.getConfig().getBoolean(Settings.BLOCKBREAKPROTECTION.getPath())) {
//Let's check if the player is jailed, otherwise the other listener //Let's check if the player is jailed, otherwise the other listener
//in the BlockListener class will take care of protecting inside //in the BlockListener class will take care of protecting inside
//of the jails. //of the jails.
if(pl.getJailManager().isPlayerJailed(event.getPlayer().getUniqueId())) { if(pl.getJailManager().isPlayerJailed(event.getPlayer().getUniqueId())) {
//Get the breaking whitelist, check if the current item is in there //Get the breaking whitelist, check if the current item is in there
if(!Util.isStringInsideList(pl.getConfig().getStringList(Settings.BLOCKBREAKWHITELIST.getPath()), if(!Util.isStringInsideList(pl.getConfig().getStringList(Settings.BLOCKBREAKWHITELIST.getPath()),
event.getBlock().getType().toString().toLowerCase())) { event.getBlock().getType().toString().toLowerCase())) {
//As our Util.getTime throws an exception when the time is in an //As our Util.getTime throws an exception when the time is in an
//incorrect format, we catch the exception and don't add any time //incorrect format, we catch the exception and don't add any time
//as a fail safe, don't want us to go crazy adding tons of time. //as a fail safe, don't want us to go crazy adding tons of time.
try { try {
long add = Util.getTime(pl.getConfig().getString(Settings.BLOCKBREAKPENALTY.getPath())); long add = Util.getTime(pl.getConfig().getString(Settings.BLOCKBREAKPENALTY.getPath()));
pl.getJailManager().getPrisoner(event.getPlayer().getUniqueId()).addTime(add); pl.getJailManager().getPrisoner(event.getPlayer().getUniqueId()).addTime(add);
String msg = ""; String msg = "";
if(add == 0L) { if(add == 0L) {
//Generate the protection message, provide the method with one argument //Generate the protection message, provide the method with one argument
//which is the thing we are protecting against //which is the thing we are protecting against
msg = Lang.PROTECTIONMESSAGENOPENALTY.get(Lang.BLOCKBREAKING.get()); msg = Lang.PROTECTIONMESSAGENOPENALTY.get(Lang.BLOCKBREAKING.get());
}else { }else {
//Generate the protection message, provide the method with two arguments //Generate the protection message, provide the method with two arguments
//First is the time in minutes and second is the thing we are protecting against //First is the time in minutes and second is the thing we are protecting against
msg = Lang.PROTECTIONMESSAGE.get(new String[] { String.valueOf(TimeUnit.MINUTES.convert(add, TimeUnit.MILLISECONDS)), Lang.BLOCKBREAKING.get() }); msg = Lang.PROTECTIONMESSAGE.get(new String[] { String.valueOf(TimeUnit.MINUTES.convert(add, TimeUnit.MILLISECONDS)), Lang.BLOCKBREAKING.get() });
} }
//Send the message //Send the message
event.getPlayer().sendMessage(msg); event.getPlayer().sendMessage(msg);
}catch (Exception e) { }catch (Exception e) {
pl.getLogger().severe("Block break penalty's time is in the wrong format, please fix."); pl.getLogger().severe("Block break penalty's time is in the wrong format, please fix.");
} }
//Stop the event from happening, as the block wasn't in the whitelist //Stop the event from happening, as the block wasn't in the whitelist
event.setCancelled(true); event.setCancelled(true);
} }
} }
} }
} }
@EventHandler(ignoreCancelled=true, priority = EventPriority.LOW) @EventHandler(ignoreCancelled=true, priority = EventPriority.LOW)
public void protectionBlockPlacing(BlockPlaceEvent event) { public void protectionBlockPlacing(BlockPlaceEvent event) {
//Before we check if the player is jailed, let's save a //Before we check if the player is jailed, let's save a
//tiny bit of resources and check if this protection is enabled //tiny bit of resources and check if this protection is enabled
if(pl.getConfig().getBoolean(Settings.BLOCKPLACEPROTECTION.getPath())) { if(pl.getConfig().getBoolean(Settings.BLOCKPLACEPROTECTION.getPath())) {
//Let's check if the player is jailed, otherwise the other listener //Let's check if the player is jailed, otherwise the other listener
//in the BlockListener class will take care of protecting inside //in the BlockListener class will take care of protecting inside
//of the jails. //of the jails.
if(pl.getJailManager().isPlayerJailed(event.getPlayer().getUniqueId())) { if(pl.getJailManager().isPlayerJailed(event.getPlayer().getUniqueId())) {
//Get the placing whitelist, check if the current item is in there //Get the placing whitelist, check if the current item is in there
if(!Util.isStringInsideList(pl.getConfig().getStringList(Settings.BLOCKPLACEWHITELIST.getPath()), if(!Util.isStringInsideList(pl.getConfig().getStringList(Settings.BLOCKPLACEWHITELIST.getPath()),
event.getBlock().getType().toString().toLowerCase())) { event.getBlock().getType().toString().toLowerCase())) {
//As our Util.getTime throws an exception when the time is in an //As our Util.getTime throws an exception when the time is in an
//incorrect format, we catch the exception and don't add any time //incorrect format, we catch the exception and don't add any time
//as a fail safe, don't want us to go crazy adding tons of time. //as a fail safe, don't want us to go crazy adding tons of time.
try { try {
long add = Util.getTime(pl.getConfig().getString(Settings.BLOCKPLACEPENALTY.getPath())); long add = Util.getTime(pl.getConfig().getString(Settings.BLOCKPLACEPENALTY.getPath()));
pl.getJailManager().getPrisoner(event.getPlayer().getUniqueId()).addTime(add); pl.getJailManager().getPrisoner(event.getPlayer().getUniqueId()).addTime(add);
String msg = ""; String msg = "";
if(add == 0L) { if(add == 0L) {
//Generate the protection message, provide the method with one argument //Generate the protection message, provide the method with one argument
//which is the thing we are protecting against //which is the thing we are protecting against
msg = Lang.PROTECTIONMESSAGENOPENALTY.get(Lang.BLOCKPLACING); msg = Lang.PROTECTIONMESSAGENOPENALTY.get(Lang.BLOCKPLACING);
}else { }else {
//Generate the protection message, provide the method with two arguments //Generate the protection message, provide the method with two arguments
//First is the time in minutes and second is the thing we are protecting against //First is the time in minutes and second is the thing we are protecting against
msg = Lang.PROTECTIONMESSAGE.get(new String[] { String.valueOf(TimeUnit.MINUTES.convert(add, TimeUnit.MILLISECONDS)), Lang.BLOCKPLACING.get() }); msg = Lang.PROTECTIONMESSAGE.get(new String[] { String.valueOf(TimeUnit.MINUTES.convert(add, TimeUnit.MILLISECONDS)), Lang.BLOCKPLACING.get() });
} }
//Send the message //Send the message
event.getPlayer().sendMessage(msg); event.getPlayer().sendMessage(msg);
}catch (Exception e) { }catch (Exception e) {
pl.getLogger().severe("Block place penalty's time is in the wrong format, please fix."); pl.getLogger().severe("Block place penalty's time is in the wrong format, please fix.");
} }
//Stop the event from happening, as the block wasn't in the whitelist //Stop the event from happening, as the block wasn't in the whitelist
event.setCancelled(true); event.setCancelled(true);
} }
} }
} }
} }
@EventHandler(ignoreCancelled=true, priority = EventPriority.LOW) @EventHandler(ignoreCancelled=true, priority = EventPriority.LOW)
public void commandProtection(PlayerCommandPreprocessEvent event) { public void commandProtection(PlayerCommandPreprocessEvent event) {
//Before we check if the player is jailed, let's save a //Before we check if the player is jailed, let's save a
//tiny bit of resources and check if this protection is enabled //tiny bit of resources and check if this protection is enabled
if(pl.getConfig().getBoolean(Settings.COMMANDPROTECTION.getPath())) { if(pl.getConfig().getBoolean(Settings.COMMANDPROTECTION.getPath())) {
//Let's check if this player is jailed, if so then we continue //Let's check if this player is jailed, if so then we continue
//otherwise we don't care about commands in here //otherwise we don't care about commands in here
if(pl.getJailManager().isPlayerJailed(event.getPlayer().getUniqueId())) { if(pl.getJailManager().isPlayerJailed(event.getPlayer().getUniqueId())) {
boolean match = false; boolean match = false;
for(String whited : pl.getConfig().getStringList(Settings.COMMANDWHITELIST.getPath())) for(String whited : pl.getConfig().getStringList(Settings.COMMANDWHITELIST.getPath()))
if(event.getMessage().toLowerCase().startsWith(whited.toLowerCase())) if(event.getMessage().toLowerCase().startsWith(whited.toLowerCase()))
match = true; match = true;
//If no match found in the whitelist, then let's block this command. //If no match found in the whitelist, then let's block this command.
if(!match) { if(!match) {
try { try {
long add = Util.getTime(pl.getConfig().getString(Settings.COMMANDPENALTY.getPath())); long add = Util.getTime(pl.getConfig().getString(Settings.COMMANDPENALTY.getPath()));
pl.getJailManager().getPrisoner(event.getPlayer().getUniqueId()).addTime(add); pl.getJailManager().getPrisoner(event.getPlayer().getUniqueId()).addTime(add);
String msg = ""; String msg = "";
if(add == 0L) { if(add == 0L) {
//Generate the protection message, provide the method with one argument //Generate the protection message, provide the method with one argument
//which is the thing we are protecting against //which is the thing we are protecting against
msg = Lang.PROTECTIONMESSAGENOPENALTY.get(Lang.COMMAND); msg = Lang.PROTECTIONMESSAGENOPENALTY.get(Lang.COMMAND);
}else { }else {
//Generate the protection message, provide the method with two arguments //Generate the protection message, provide the method with two arguments
//First is the time in minutes and second is the thing we are protecting against //First is the time in minutes and second is the thing we are protecting against
msg = Lang.PROTECTIONMESSAGE.get(new String[] { String.valueOf(TimeUnit.MINUTES.convert(add, TimeUnit.MILLISECONDS)), Lang.COMMAND.get() }); msg = Lang.PROTECTIONMESSAGE.get(new String[] { String.valueOf(TimeUnit.MINUTES.convert(add, TimeUnit.MILLISECONDS)), Lang.COMMAND.get() });
} }
//Send the message //Send the message
event.getPlayer().sendMessage(msg); event.getPlayer().sendMessage(msg);
}catch (Exception e) { }catch (Exception e) {
pl.getLogger().severe("Command Protection penalty's time is in the wrong format, please fix."); pl.getLogger().severe("Command Protection penalty's time is in the wrong format, please fix.");
} }
//Stop the command from happening, as it wasn't whitelisted //Stop the command from happening, as it wasn't whitelisted
event.setCancelled(true); event.setCancelled(true);
} }
} }
} }
} }
@EventHandler(ignoreCancelled=true, priority = EventPriority.LOW) @EventHandler(ignoreCancelled=true, priority = EventPriority.LOW)
public void chestProtection(PlayerInteractEvent event) { public void chestProtection(PlayerInteractEvent event) {
//First thing is first, let's be sure the player we're dealing with is in jail //First thing is first, let's be sure the player we're dealing with is in jail
if(pl.getJailManager().isPlayerJailed(event.getPlayer().getUniqueId())) { if(pl.getJailManager().isPlayerJailed(event.getPlayer().getUniqueId())) {
//Next, let's check if it is a chest and if they're in a cell //Next, let's check if it is a chest and if they're in a cell
//If they are in a cell and are opening a chest, then we check //If they are in a cell and are opening a chest, then we check
//the config to see if they can open the chests //the config to see if they can open the chests
if(event.getAction() == Action.RIGHT_CLICK_BLOCK && event.getClickedBlock().getType() == Material.CHEST) { if(event.getAction() == Action.RIGHT_CLICK_BLOCK && event.getClickedBlock().getType() == Material.CHEST) {
//Let's get the cell the player is in, then check if it is null or not. //Let's get the cell the player is in, then check if it is null or not.
if(pl.getJailManager().getJailPlayerIsIn(event.getPlayer().getUniqueId()).isJailedInACell(event.getPlayer().getUniqueId())) { if(pl.getJailManager().getJailPlayerIsIn(event.getPlayer().getUniqueId()).isJailedInACell(event.getPlayer().getUniqueId())) {
if(pl.getConfig().getBoolean(Settings.PRISONEROPENCHEST.getPath())) { if(pl.getConfig().getBoolean(Settings.PRISONEROPENCHEST.getPath())) {
//The prisoner is in a cell, so let's check if it is a couple chest. //The prisoner is in a cell, so let's check if it is a couple chest.
Material bpos1 = event.getClickedBlock().getLocation().add(-1, 0, 0).getBlock().getType(); Material bpos1 = event.getClickedBlock().getLocation().add(-1, 0, 0).getBlock().getType();
Material bpos2 = event.getClickedBlock().getLocation().add(+1, 0, 0).getBlock().getType(); Material bpos2 = event.getClickedBlock().getLocation().add(+1, 0, 0).getBlock().getType();
Material bpos3 = event.getClickedBlock().getLocation().add(0, 0, -1).getBlock().getType(); Material bpos3 = event.getClickedBlock().getLocation().add(0, 0, -1).getBlock().getType();
Material bpos4 = event.getClickedBlock().getLocation().add(0, 0, +1).getBlock().getType(); Material bpos4 = event.getClickedBlock().getLocation().add(0, 0, +1).getBlock().getType();
boolean pos1 = bpos1 == Material.CHEST || bpos1 == Material.TRAPPED_CHEST; boolean pos1 = bpos1 == Material.CHEST || bpos1 == Material.TRAPPED_CHEST;
boolean pos2 = bpos2 == Material.CHEST || bpos2 == Material.TRAPPED_CHEST; boolean pos2 = bpos2 == Material.CHEST || bpos2 == Material.TRAPPED_CHEST;
boolean pos3 = bpos3 == Material.CHEST || bpos3 == Material.TRAPPED_CHEST; boolean pos3 = bpos3 == Material.CHEST || bpos3 == Material.TRAPPED_CHEST;
boolean pos4 = bpos4 == Material.CHEST || bpos4 == Material.TRAPPED_CHEST; boolean pos4 = bpos4 == Material.CHEST || bpos4 == Material.TRAPPED_CHEST;
if(pos1 || pos2 || pos3 || pos4) { if(pos1 || pos2 || pos3 || pos4) {
//it is a double chest, so they're free to go! //it is a double chest, so they're free to go!
if(pl.inDebug()) event.getPlayer().sendMessage("[Jail Debug]: You're opening up a double chest."); if(pl.inDebug()) event.getPlayer().sendMessage("[Jail Debug]: You're opening up a double chest.");
}else { }else {
//it is not a double chest, so we won't be allowing it. //it is not a double chest, so we won't be allowing it.
event.setCancelled(true); event.setCancelled(true);
return; return;
} }
}else { }else {
//the config has opening chests disabled //the config has opening chests disabled
event.setCancelled(true); event.setCancelled(true);
return; return;
} }
}else { }else {
//The prisoner is not in a cell, so let's not allow it. IF we get feedback from people who //The prisoner is not in a cell, so let's not allow it. IF we get feedback from people who
//use the plugin, this might get removed or permission node might be added. //use the plugin, this might get removed or permission node might be added.
event.setCancelled(true); event.setCancelled(true);
return; return;
} }
} }
} }
} }
@EventHandler(ignoreCancelled=true, priority = EventPriority.LOWEST) @EventHandler(ignoreCancelled=true, priority = EventPriority.LOWEST)
public void cropTramplingProtection(PlayerInteractEvent event) { public void cropTramplingProtection(PlayerInteractEvent event) {
//First thing is first, let's be sure the player we're dealing with is in jail //First thing is first, let's be sure the player we're dealing with is in jail
if(pl.getJailManager().isPlayerJailed(event.getPlayer().getUniqueId())) { if(pl.getJailManager().isPlayerJailed(event.getPlayer().getUniqueId())) {
//Next, check if crap trampling protection is enabled //Next, check if crap trampling protection is enabled
if(pl.getConfig().getBoolean(Settings.CROPTRAMPLINGPROTECTION.getPath())) { if(pl.getConfig().getBoolean(Settings.CROPTRAMPLINGPROTECTION.getPath())) {
if(event.getAction() == Action.PHYSICAL && event.getClickedBlock().getType() == Material.SOIL) { if(event.getAction() == Action.PHYSICAL && event.getClickedBlock().getType() == Material.SOIL) {
if(pl.getJailManager().getJailFromLocation(event.getClickedBlock().getLocation()) != null) { if(pl.getJailManager().getJailFromLocation(event.getClickedBlock().getLocation()) != null) {
try { try {
long add = Util.getTime(pl.getConfig().getString(Settings.CROPTRAMPLINGPENALTY.getPath())); long add = Util.getTime(pl.getConfig().getString(Settings.CROPTRAMPLINGPENALTY.getPath()));
pl.getJailManager().getPrisoner(event.getPlayer().getUniqueId()).addTime(add); pl.getJailManager().getPrisoner(event.getPlayer().getUniqueId()).addTime(add);
String msg = ""; String msg = "";
if(add == 0L) { if(add == 0L) {
//Generate the protection message, provide the method with one argument //Generate the protection message, provide the method with one argument
//which is the thing we are protecting against //which is the thing we are protecting against
msg = Lang.PROTECTIONMESSAGENOPENALTY.get(Lang.CROPTRAMPLING); msg = Lang.PROTECTIONMESSAGENOPENALTY.get(Lang.CROPTRAMPLING);
}else { }else {
//Generate the protection message, provide the method with two arguments //Generate the protection message, provide the method with two arguments
//First is the time in minutes and second is the thing we are protecting against //First is the time in minutes and second is the thing we are protecting against
msg = Lang.PROTECTIONMESSAGE.get(new String[] { String.valueOf(TimeUnit.MINUTES.convert(add, TimeUnit.MILLISECONDS)), Lang.CROPTRAMPLING.get() }); msg = Lang.PROTECTIONMESSAGE.get(new String[] { String.valueOf(TimeUnit.MINUTES.convert(add, TimeUnit.MILLISECONDS)), Lang.CROPTRAMPLING.get() });
} }
//Send the message //Send the message
event.getPlayer().sendMessage(msg); event.getPlayer().sendMessage(msg);
}catch (Exception e) { }catch (Exception e) {
pl.getLogger().severe("Crop Trampling penalty's time is in the wrong format, please fix."); pl.getLogger().severe("Crop Trampling penalty's time is in the wrong format, please fix.");
} }
event.setCancelled(true); event.setCancelled(true);
} }
} }
} }
} }
} }
@EventHandler(ignoreCancelled=true) @EventHandler(ignoreCancelled=true)
public void interactionProtection(PlayerInteractEvent event) { public void interactionProtection(PlayerInteractEvent event) {
//As the old version didn't do anything with Physical interactions, we won't either //As the old version didn't do anything with Physical interactions, we won't either
if (event.getAction() != Action.PHYSICAL) { if (event.getAction() != Action.PHYSICAL) {
//First thing is first, let's be sure the player we're dealing with is in jail //First thing is first, let's be sure the player we're dealing with is in jail
if(pl.getJailManager().isPlayerJailed(event.getPlayer().getUniqueId())) { if(pl.getJailManager().isPlayerJailed(event.getPlayer().getUniqueId())) {
//Let's check if they've interacted with a block //Let's check if they've interacted with a block
if (event.getClickedBlock() != null) { if (event.getClickedBlock() != null) {
//Get the interaction blacklist, check if the current block is in there //Get the interaction blacklist, check if the current block is in there
//if it is, then let's take action //if it is, then let's take action
if(Util.isStringInsideList(pl.getConfig().getStringList(Settings.PREVENTINTERACTIONBLOCKS.getPath()), if(Util.isStringInsideList(pl.getConfig().getStringList(Settings.PREVENTINTERACTIONBLOCKS.getPath()),
event.getClickedBlock().getType().toString().toLowerCase())) { event.getClickedBlock().getType().toString().toLowerCase())) {
try { try {
long add = Util.getTime(pl.getConfig().getString(Settings.PREVENTINTERACTIONBLOCKSPENALTY.getPath())); long add = Util.getTime(pl.getConfig().getString(Settings.PREVENTINTERACTIONBLOCKSPENALTY.getPath()));
pl.getJailManager().getPrisoner(event.getPlayer().getUniqueId()).addTime(add); pl.getJailManager().getPrisoner(event.getPlayer().getUniqueId()).addTime(add);
String msg = ""; String msg = "";
if(add == 0L) { if(add == 0L) {
//Generate the protection message, provide the method with one argument //Generate the protection message, provide the method with one argument
//which is the thing we are protecting against //which is the thing we are protecting against
msg = Lang.PROTECTIONMESSAGENOPENALTY.get(Lang.INTERACTIONBLOCKS); msg = Lang.PROTECTIONMESSAGENOPENALTY.get(Lang.INTERACTIONBLOCKS);
}else { }else {
//Generate the protection message, provide the method with two arguments //Generate the protection message, provide the method with two arguments
//First is the time in minutes and second is the thing we are protecting against //First is the time in minutes and second is the thing we are protecting against
msg = Lang.PROTECTIONMESSAGE.get(new String[] { String.valueOf(TimeUnit.MINUTES.convert(add, TimeUnit.MILLISECONDS)), Lang.INTERACTIONBLOCKS.get() }); msg = Lang.PROTECTIONMESSAGE.get(new String[] { String.valueOf(TimeUnit.MINUTES.convert(add, TimeUnit.MILLISECONDS)), Lang.INTERACTIONBLOCKS.get() });
} }
//Send the message //Send the message
event.getPlayer().sendMessage(msg); event.getPlayer().sendMessage(msg);
}catch(Exception e) { }catch(Exception e) {
pl.getLogger().severe("Prevent Interaction with Blocks penalty's time is in the wrong format, please fix."); pl.getLogger().severe("Prevent Interaction with Blocks penalty's time is in the wrong format, please fix.");
} }
event.setCancelled(true); event.setCancelled(true);
} }
}else if (event.getPlayer().getItemInHand() != null) { }else if (event.getPlayer().getItemInHand() != null) {
//Otherwise let's check if they have something in hand //Otherwise let's check if they have something in hand
//Get the interaction blacklist, check if the current item is in there //Get the interaction blacklist, check if the current item is in there
//if it is, then let's take action //if it is, then let's take action
if(Util.isStringInsideList(pl.getConfig().getStringList(Settings.PREVENTINTERACTIONITEMS.getPath()), if(Util.isStringInsideList(pl.getConfig().getStringList(Settings.PREVENTINTERACTIONITEMS.getPath()),
event.getClickedBlock().getType().toString().toLowerCase())) { event.getClickedBlock().getType().toString().toLowerCase())) {
try { try {
long add = Util.getTime(pl.getConfig().getString(Settings.PREVENTINTERACTIONITEMSPENALTY.getPath())); long add = Util.getTime(pl.getConfig().getString(Settings.PREVENTINTERACTIONITEMSPENALTY.getPath()));
pl.getJailManager().getPrisoner(event.getPlayer().getUniqueId()).addTime(add); pl.getJailManager().getPrisoner(event.getPlayer().getUniqueId()).addTime(add);
String msg = ""; String msg = "";
if(add == 0L) { if(add == 0L) {
//Generate the protection message, provide the method with one argument //Generate the protection message, provide the method with one argument
//which is the thing we are protecting against //which is the thing we are protecting against
msg = Lang.PROTECTIONMESSAGENOPENALTY.get(Lang.INTERACTIONITEMS); msg = Lang.PROTECTIONMESSAGENOPENALTY.get(Lang.INTERACTIONITEMS);
}else { }else {
//Generate the protection message, provide the method with two arguments //Generate the protection message, provide the method with two arguments
//First is the time in minutes and second is the thing we are protecting against //First is the time in minutes and second is the thing we are protecting against
msg = Lang.PROTECTIONMESSAGE.get(new String[] { String.valueOf(TimeUnit.MINUTES.convert(add, TimeUnit.MILLISECONDS)), Lang.INTERACTIONITEMS.get() }); msg = Lang.PROTECTIONMESSAGE.get(new String[] { String.valueOf(TimeUnit.MINUTES.convert(add, TimeUnit.MILLISECONDS)), Lang.INTERACTIONITEMS.get() });
} }
//Send the message //Send the message
event.getPlayer().sendMessage(msg); event.getPlayer().sendMessage(msg);
}catch(Exception e) { }catch(Exception e) {
pl.getLogger().severe("Prevent Interaction with Items penalty's time is in the wrong format, please fix."); pl.getLogger().severe("Prevent Interaction with Items penalty's time is in the wrong format, please fix.");
} }
event.setCancelled(true); event.setCancelled(true);
} }
} }
} }
} }
} }
} }

View File

@ -10,21 +10,21 @@ import com.graywolf336.jail.JailMain;
import com.graywolf336.jail.beans.Jail; import com.graywolf336.jail.beans.Jail;
public class WorldListener implements Listener { public class WorldListener implements Listener {
private JailMain pl; private JailMain pl;
public WorldListener(JailMain plugin) { public WorldListener(JailMain plugin) {
this.pl = plugin; this.pl = plugin;
} }
@EventHandler(ignoreCancelled=true, priority = EventPriority.LOW) @EventHandler(ignoreCancelled=true, priority = EventPriority.LOW)
public void worldLoaded(WorldLoadEvent event) { public void worldLoaded(WorldLoadEvent event) {
for(Jail j : pl.getJailManager().getJails()) for(Jail j : pl.getJailManager().getJails())
if(j.getWorldName().equalsIgnoreCase(event.getWorld().getName())) j.setEnabled(true); if(j.getWorldName().equalsIgnoreCase(event.getWorld().getName())) j.setEnabled(true);
} }
@EventHandler(ignoreCancelled=true, priority = EventPriority.LOW) @EventHandler(ignoreCancelled=true, priority = EventPriority.LOW)
public void worldUnload(WorldUnloadEvent event) { public void worldUnload(WorldUnloadEvent event) {
for(Jail j : pl.getJailManager().getJails()) for(Jail j : pl.getJailManager().getJails())
if(j.getWorldName().equalsIgnoreCase(event.getWorld().getName())) j.setEnabled(false); if(j.getWorldName().equalsIgnoreCase(event.getWorld().getName())) j.setEnabled(false);
} }
} }

View File

@ -24,134 +24,134 @@ import com.graywolf336.jail.beans.SimpleLocation;
*/ */
public class CellCreationSteps { public class CellCreationSteps {
/** Sends the Cell Creation message for starting out. */ /** Sends the Cell Creation message for starting out. */
public void startStepping(Player player){ public void startStepping(Player player){
player.sendMessage(ChatColor.AQUA + "---------- Jail Cell Creation (tp) ----------"); player.sendMessage(ChatColor.AQUA + "---------- Jail Cell Creation (tp) ----------");
player.sendMessage(ChatColor.GREEN + "First, you must select a teleport point for the cell! Move to the teleport point and then click anywhere with your wooden sword to set it."); player.sendMessage(ChatColor.GREEN + "First, you must select a teleport point for the cell! Move to the teleport point and then click anywhere with your wooden sword to set it.");
player.sendMessage(ChatColor.AQUA + "----------------------------------------"); player.sendMessage(ChatColor.AQUA + "----------------------------------------");
ItemStack wand = Util.getWand(); ItemStack wand = Util.getWand();
if(player.getInventory().contains(wand)) { if(player.getInventory().contains(wand)) {
int i = player.getInventory().first(wand); int i = player.getInventory().first(wand);
if(i != -1) { if(i != -1) {
player.getInventory().setItem(i, player.getItemInHand()); player.getInventory().setItem(i, player.getItemInHand());
player.setItemInHand(wand); player.setItemInHand(wand);
} }
}else { }else {
player.getInventory().addItem(wand); player.getInventory().addItem(wand);
} }
} }
/** /**
* Applies the next step in the Cell Creation process that involves a location, null if no location is needed. * Applies the next step in the Cell Creation process that involves a location, null if no location is needed.
* *
* @param jm The {@link JailManager} instance. * @param jm The {@link JailManager} instance.
* @param player The player who is doing the creating. * @param player The player who is doing the creating.
* @param cp The {@link CreationPlayer} instance * @param cp The {@link CreationPlayer} instance
* @param location The location, null if none, being set. * @param location The location, null if none, being set.
*/ */
public void step(JailManager jm, Player player, CreationPlayer cp, Location location) { public void step(JailManager jm, Player player, CreationPlayer cp, Location location) {
jm.getPlugin().debug("Stepping into step #" + cp.getStep()); jm.getPlugin().debug("Stepping into step #" + cp.getStep());
switch(cp.getStep()) { switch(cp.getStep()) {
case 1: case 1:
firstStep(jm, cp, player); firstStep(jm, cp, player);
break; break;
case 2: case 2:
secondStep(cp, player, location.getBlock()); secondStep(cp, player, location.getBlock());
break; break;
case 3: case 3:
thirdStep(jm, cp, player, location.getBlock()); thirdStep(jm, cp, player, location.getBlock());
break; break;
default: default:
player.sendMessage(ChatColor.RED + "Something went wrong with the creation of the Jail, please start over"); player.sendMessage(ChatColor.RED + "Something went wrong with the creation of the Jail, please start over");
jm.removeJailCreationPlayer(player.getName()); jm.removeJailCreationPlayer(player.getName());
break; break;
} }
} }
/** Applies the first step, which is setting the teleport in location. */ /** Applies the first step, which is setting the teleport in location. */
private void firstStep(JailManager jm, CreationPlayer cp, Player player) { private void firstStep(JailManager jm, CreationPlayer cp, Player player) {
Vector v1 = jm.getJail(cp.getJailName()).getMinPoint().toVector().clone(); Vector v1 = jm.getJail(cp.getJailName()).getMinPoint().toVector().clone();
Vector v2 = jm.getJail(cp.getJailName()).getMaxPoint().toVector().clone(); Vector v2 = jm.getJail(cp.getJailName()).getMaxPoint().toVector().clone();
Vector point = player.getLocation().toVector().clone(); Vector point = player.getLocation().toVector().clone();
if(Util.isInsideAB(point, v1, v2)) { if(Util.isInsideAB(point, v1, v2)) {
player.sendMessage(ChatColor.AQUA + "---------- Jail Cell Creation (signs) ----------"); player.sendMessage(ChatColor.AQUA + "---------- Jail Cell Creation (signs) ----------");
player.sendMessage(ChatColor.GREEN + "Teleport point selected. Now select signs associated with this cell. You may select multiple signs. After you are done with the sign selection, right click on any non-sign block."); player.sendMessage(ChatColor.GREEN + "Teleport point selected. Now select signs associated with this cell. You may select multiple signs. After you are done with the sign selection, right click on any non-sign block.");
player.sendMessage(ChatColor.AQUA + "----------------------------------------"); player.sendMessage(ChatColor.AQUA + "----------------------------------------");
cp.setTeleportIn(player.getLocation()); cp.setTeleportIn(player.getLocation());
cp.nextStep(); cp.nextStep();
}else { }else {
player.sendMessage(ChatColor.RED + "---------- Jail Cell Creation (tp) ----------"); player.sendMessage(ChatColor.RED + "---------- Jail Cell Creation (tp) ----------");
player.sendMessage(ChatColor.RED + "Teleport point NOT selected. Please make sure that you are setting the teleport point inside the Jail's corners."); player.sendMessage(ChatColor.RED + "Teleport point NOT selected. Please make sure that you are setting the teleport point inside the Jail's corners.");
player.sendMessage(ChatColor.RED + "----------------------------------------"); player.sendMessage(ChatColor.RED + "----------------------------------------");
} }
} }
/** Applies the second step, which is adding signs to the cell. */ /** Applies the second step, which is adding signs to the cell. */
private void secondStep(CreationPlayer cp, Player player, Block block) { private void secondStep(CreationPlayer cp, Player player, Block block) {
if (block.getType() == Material.SIGN_POST || block.getType() == Material.WALL_SIGN) { if (block.getType() == Material.SIGN_POST || block.getType() == Material.WALL_SIGN) {
cp.addSign(new SimpleLocation(block.getLocation())); cp.addSign(new SimpleLocation(block.getLocation()));
player.sendMessage(ChatColor.GREEN + "Sign added, if you want to select another go ahead otherwise right click on any non-sign block."); player.sendMessage(ChatColor.GREEN + "Sign added, if you want to select another go ahead otherwise right click on any non-sign block.");
}else { }else {
player.sendMessage(ChatColor.AQUA + "---------- Jail Cell Creation (chest) ----------"); player.sendMessage(ChatColor.AQUA + "---------- Jail Cell Creation (chest) ----------");
player.sendMessage(ChatColor.GREEN + (cp.getSigns().size() != 0 ? "Sign selection completed. " : "") + "Now select a double chest associated with this cell. If there is no chest click on any non-chest block. (Please note that having no chest may result in players items being lost.)"); player.sendMessage(ChatColor.GREEN + (cp.getSigns().size() != 0 ? "Sign selection completed. " : "") + "Now select a double chest associated with this cell. If there is no chest click on any non-chest block. (Please note that having no chest may result in players items being lost.)");
player.sendMessage(ChatColor.AQUA + "----------------------------------------"); player.sendMessage(ChatColor.AQUA + "----------------------------------------");
cp.nextStep(); cp.nextStep();
} }
} }
/** Applies the third step, which is adding a chest or select not to have a chest. */ /** Applies the third step, which is adding a chest or select not to have a chest. */
private void thirdStep(JailManager jm, CreationPlayer cp, Player player, Block block) { private void thirdStep(JailManager jm, CreationPlayer cp, Player player, Block block) {
Material bpos1 = block.getLocation().add(-1, 0, 0).getBlock().getType(); Material bpos1 = block.getLocation().add(-1, 0, 0).getBlock().getType();
Material bpos2 = block.getLocation().add(+1, 0, 0).getBlock().getType(); Material bpos2 = block.getLocation().add(+1, 0, 0).getBlock().getType();
Material bpos3 = block.getLocation().add(0, 0, -1).getBlock().getType(); Material bpos3 = block.getLocation().add(0, 0, -1).getBlock().getType();
Material bpos4 = block.getLocation().add(0, 0, +1).getBlock().getType(); Material bpos4 = block.getLocation().add(0, 0, +1).getBlock().getType();
boolean pos1 = bpos1 == Material.CHEST || bpos1 == Material.TRAPPED_CHEST; boolean pos1 = bpos1 == Material.CHEST || bpos1 == Material.TRAPPED_CHEST;
boolean pos2 = bpos2 == Material.CHEST || bpos2 == Material.TRAPPED_CHEST; boolean pos2 = bpos2 == Material.CHEST || bpos2 == Material.TRAPPED_CHEST;
boolean pos3 = bpos3 == Material.CHEST || bpos3 == Material.TRAPPED_CHEST; boolean pos3 = bpos3 == Material.CHEST || bpos3 == Material.TRAPPED_CHEST;
boolean pos4 = bpos4 == Material.CHEST || bpos4 == Material.TRAPPED_CHEST; boolean pos4 = bpos4 == Material.CHEST || bpos4 == Material.TRAPPED_CHEST;
if (block.getType() == Material.CHEST || block.getType() == Material.TRAPPED_CHEST) { if (block.getType() == Material.CHEST || block.getType() == Material.TRAPPED_CHEST) {
if(pos1 || pos2 || pos3 || pos4) { if(pos1 || pos2 || pos3 || pos4) {
cp.setChestLocation(block.getLocation()); cp.setChestLocation(block.getLocation());
player.sendMessage(ChatColor.AQUA + "---------- Jail Cell Creation ----------"); player.sendMessage(ChatColor.AQUA + "---------- Jail Cell Creation ----------");
player.sendMessage(ChatColor.GREEN + "Chest selected."); player.sendMessage(ChatColor.GREEN + "Chest selected.");
player.sendMessage(ChatColor.AQUA + "----------------------------------------"); player.sendMessage(ChatColor.AQUA + "----------------------------------------");
}else { }else {
player.sendMessage(ChatColor.RED + "---------- Jail Cell Creation (chest) ----------"); player.sendMessage(ChatColor.RED + "---------- Jail Cell Creation (chest) ----------");
player.sendMessage(ChatColor.RED + "Chest must be a double chest, chest not selected"); player.sendMessage(ChatColor.RED + "Chest must be a double chest, chest not selected");
player.sendMessage(ChatColor.RED + "----------------------------------------"); player.sendMessage(ChatColor.RED + "----------------------------------------");
return; return;
} }
}else { }else {
player.sendMessage(ChatColor.AQUA + "---------- Jail Cell Creation ----------"); player.sendMessage(ChatColor.AQUA + "---------- Jail Cell Creation ----------");
player.sendMessage(ChatColor.RED + "No chest selected."); player.sendMessage(ChatColor.RED + "No chest selected.");
player.sendMessage(ChatColor.AQUA + "----------------------------------------"); player.sendMessage(ChatColor.AQUA + "----------------------------------------");
} }
finalStep(jm, cp, player); finalStep(jm, cp, player);
} }
private void finalStep(JailManager jm, CreationPlayer cp, Player player) { private void finalStep(JailManager jm, CreationPlayer cp, Player player) {
Jail j = jm.getJail(cp.getJailName()); Jail j = jm.getJail(cp.getJailName());
Cell c = new Cell(cp.getCellName()); Cell c = new Cell(cp.getCellName());
c.addAllSigns(cp.getSigns()); c.addAllSigns(cp.getSigns());
c.setTeleport(cp.getTeleportInSL()); c.setTeleport(cp.getTeleportInSL());
if(cp.getChestLocation() != null) if(cp.getChestLocation() != null)
c.setChestLocation(cp.getChestLocation()); c.setChestLocation(cp.getChestLocation());
j.addCell(c, true); j.addCell(c, true);
jm.removeCellCreationPlayer(player.getName()); jm.removeCellCreationPlayer(player.getName());
jm.addCreatingCell(player.getName(), j.getName(), "cell_n" + (j.getCellCount() + 1)); jm.addCreatingCell(player.getName(), j.getName(), "cell_n" + (j.getCellCount() + 1));
player.sendMessage(ChatColor.AQUA + "---------- Jail Cell Creation ----------"); player.sendMessage(ChatColor.AQUA + "---------- Jail Cell Creation ----------");
player.sendMessage(ChatColor.GREEN + "Cell created. Now select the teleport point of the next cell, which is going to be named '" + jm.getCellCreationPlayer(player.getName()).getCellName() + "'. If you wish to stop creating cells, type /jail stop."); player.sendMessage(ChatColor.GREEN + "Cell created. Now select the teleport point of the next cell, which is going to be named '" + jm.getCellCreationPlayer(player.getName()).getCellName() + "'. If you wish to stop creating cells, type /jail stop.");
player.sendMessage(ChatColor.AQUA + "----------------------------------------"); player.sendMessage(ChatColor.AQUA + "----------------------------------------");
} }
} }

View File

@ -20,127 +20,127 @@ import com.graywolf336.jail.beans.Jail;
*/ */
public class JailCreationSteps { public class JailCreationSteps {
/** Sends the Jail Creation message for starting out. */ /** Sends the Jail Creation message for starting out. */
public void startStepping(Player player) { public void startStepping(Player player) {
player.sendMessage(ChatColor.AQUA + "----------Jail Zone Creation----------"); player.sendMessage(ChatColor.AQUA + "----------Jail Zone Creation----------");
player.sendMessage(ChatColor.GREEN + "First, you must select jail cuboid. Select the first point of the cuboid by right clicking on the block with your wooden sword. DO NOT FORGET TO MARK THE FLOOR AND CEILING TOO!"); player.sendMessage(ChatColor.GREEN + "First, you must select jail cuboid. Select the first point of the cuboid by right clicking on the block with your wooden sword. DO NOT FORGET TO MARK THE FLOOR AND CEILING TOO!");
player.sendMessage(ChatColor.AQUA + "--------------------------------------"); player.sendMessage(ChatColor.AQUA + "--------------------------------------");
ItemStack wand = Util.getWand(); ItemStack wand = Util.getWand();
if(player.getInventory().contains(wand)) { if(player.getInventory().contains(wand)) {
int i = player.getInventory().first(wand); int i = player.getInventory().first(wand);
if(i != -1) { if(i != -1) {
player.getInventory().setItem(i, player.getItemInHand()); player.getInventory().setItem(i, player.getItemInHand());
player.setItemInHand(wand); player.setItemInHand(wand);
} }
}else { }else {
player.getInventory().addItem(wand); player.getInventory().addItem(wand);
} }
} }
/** /**
* Applies the next step in the Jail Creation process that involves a location, null if no location is needed. * Applies the next step in the Jail Creation process that involves a location, null if no location is needed.
* *
* @param jm The {@link JailManager} instance. * @param jm The {@link JailManager} instance.
* @param player The player who is doing the creating. * @param player The player who is doing the creating.
* @param cp The {@link CreationPlayer} instance * @param cp The {@link CreationPlayer} instance
* @param location The location, null if none, being set. * @param location The location, null if none, being set.
*/ */
public void step(JailManager jm, Player player, CreationPlayer cp, Location location) { public void step(JailManager jm, Player player, CreationPlayer cp, Location location) {
jm.getPlugin().debug("Stepping into step #" + cp.getStep()); jm.getPlugin().debug("Stepping into step #" + cp.getStep());
switch(cp.getStep()) { switch(cp.getStep()) {
case 1: case 1:
firstStep(cp, player, location); firstStep(cp, player, location);
break; break;
case 2: case 2:
secondStep(cp, player, location); secondStep(cp, player, location);
break; break;
case 3: case 3:
thirdStep(cp, player); thirdStep(cp, player);
break; break;
case 4: case 4:
fourthStep(jm, cp, player); fourthStep(jm, cp, player);
break; break;
default: default:
player.sendMessage(ChatColor.RED + "Something went wrong with the creation of the Jail, please start over"); player.sendMessage(ChatColor.RED + "Something went wrong with the creation of the Jail, please start over");
jm.removeJailCreationPlayer(player.getName()); jm.removeJailCreationPlayer(player.getName());
break; break;
} }
} }
/** Applies the first step, which is setting the first corner. */ /** Applies the first step, which is setting the first corner. */
private void firstStep(CreationPlayer cp, Player p, Location location) { private void firstStep(CreationPlayer cp, Player p, Location location) {
p.sendMessage(ChatColor.AQUA + "---------- Jail Zone Creation----------"); p.sendMessage(ChatColor.AQUA + "---------- Jail Zone Creation----------");
p.sendMessage(ChatColor.GREEN + "First point selected. Now select the second point."); p.sendMessage(ChatColor.GREEN + "First point selected. Now select the second point.");
p.sendMessage(ChatColor.AQUA + "---------------------------------------"); p.sendMessage(ChatColor.AQUA + "---------------------------------------");
cp.setCornerOne(location); cp.setCornerOne(location);
cp.nextStep(); cp.nextStep();
} }
/** Applies the second step, which is setting the second corner. */ /** Applies the second step, which is setting the second corner. */
private void secondStep(CreationPlayer cp, Player p, Location location) { private void secondStep(CreationPlayer cp, Player p, Location location) {
p.sendMessage(ChatColor.AQUA + "---------- Jail Zone Creation ----------"); p.sendMessage(ChatColor.AQUA + "---------- Jail Zone Creation ----------");
p.sendMessage(ChatColor.GREEN + "Second point selected. Now go inside the jail and right click anywhere to select your current position as the teleport location for the jail."); p.sendMessage(ChatColor.GREEN + "Second point selected. Now go inside the jail and right click anywhere to select your current position as the teleport location for the jail.");
p.sendMessage(ChatColor.AQUA + "----------------------------------------"); p.sendMessage(ChatColor.AQUA + "----------------------------------------");
cp.setCornerTwo(location); cp.setCornerTwo(location);
cp.nextStep(); cp.nextStep();
} }
/** Applies the third step, which is setting the teleport in location. */ /** Applies the third step, which is setting the teleport in location. */
private void thirdStep(CreationPlayer cp, Player p) { private void thirdStep(CreationPlayer cp, Player p) {
int[] p1 = cp.getCornerOne(); int[] p1 = cp.getCornerOne();
int[] p2 = cp.getCornerTwo(); int[] p2 = cp.getCornerTwo();
Vector v1 = new Vector(p1[0], p1[1], p1[2]); Vector v1 = new Vector(p1[0], p1[1], p1[2]);
Vector v2 = new Vector(p2[0], p2[1], p2[2]); Vector v2 = new Vector(p2[0], p2[1], p2[2]);
Vector point = p.getLocation().toVector().clone(); Vector point = p.getLocation().toVector().clone();
if(Util.isInsideAB(point, v1, v2)) { if(Util.isInsideAB(point, v1, v2)) {
p.sendMessage(ChatColor.AQUA + "---------- Jail Zone Creation ----------"); p.sendMessage(ChatColor.AQUA + "---------- Jail Zone Creation ----------");
p.sendMessage(ChatColor.GREEN + "Teleport point selected. Now go outside of the jail and right click anywhere to select your current position as the location where people will be teleported after they are released from this jail."); p.sendMessage(ChatColor.GREEN + "Teleport point selected. Now go outside of the jail and right click anywhere to select your current position as the location where people will be teleported after they are released from this jail.");
p.sendMessage(ChatColor.AQUA + "----------------------------------------"); p.sendMessage(ChatColor.AQUA + "----------------------------------------");
cp.setTeleportIn(p.getLocation()); cp.setTeleportIn(p.getLocation());
cp.nextStep(); cp.nextStep();
} else { } else {
p.sendMessage(ChatColor.RED + "---------- Jail Zone Creation ----------"); p.sendMessage(ChatColor.RED + "---------- Jail Zone Creation ----------");
p.sendMessage(ChatColor.RED + "Teleport point NOT selected. Now go inside the jail and right click anywhere to select your current position as the teleport location for the jail. Point must be INSIDE the points selected for the Jail."); p.sendMessage(ChatColor.RED + "Teleport point NOT selected. Now go inside the jail and right click anywhere to select your current position as the teleport location for the jail. Point must be INSIDE the points selected for the Jail.");
p.sendMessage(ChatColor.RED + "----------------------------------------"); p.sendMessage(ChatColor.RED + "----------------------------------------");
} }
} }
private void fourthStep(JailManager jm, CreationPlayer cp, Player p) { private void fourthStep(JailManager jm, CreationPlayer cp, Player p) {
int[] p1 = cp.getCornerOne(); int[] p1 = cp.getCornerOne();
int[] p2 = cp.getCornerTwo(); int[] p2 = cp.getCornerTwo();
Vector v1 = new Vector(p1[0], p1[1], p1[2]); Vector v1 = new Vector(p1[0], p1[1], p1[2]);
Vector v2 = new Vector(p2[0], p2[1], p2[2]); Vector v2 = new Vector(p2[0], p2[1], p2[2]);
Vector point = p.getLocation().toVector().clone(); Vector point = p.getLocation().toVector().clone();
if(Util.isInsideAB(point, v1, v2)) { if(Util.isInsideAB(point, v1, v2)) {
p.sendMessage(ChatColor.RED + "---------- Jail Zone Creation ----------"); p.sendMessage(ChatColor.RED + "---------- Jail Zone Creation ----------");
p.sendMessage(ChatColor.RED + "Teleport out point NOT selected. Go outside of the jail and right click anywhere to select your current position as the location where people will be teleported after they are released from this jail."); p.sendMessage(ChatColor.RED + "Teleport out point NOT selected. Go outside of the jail and right click anywhere to select your current position as the location where people will be teleported after they are released from this jail.");
p.sendMessage(ChatColor.RED + "----------------------------------------"); p.sendMessage(ChatColor.RED + "----------------------------------------");
}else { }else {
cp.setTeleportFree(p.getLocation()); cp.setTeleportFree(p.getLocation());
finalStep(jm, cp, p); finalStep(jm, cp, p);
} }
} }
private void finalStep(JailManager jm, CreationPlayer cp, Player p) { private void finalStep(JailManager jm, CreationPlayer cp, Player p) {
Jail jail = new Jail(jm.getPlugin(), cp.getJailName()); Jail jail = new Jail(jm.getPlugin(), cp.getJailName());
jail.setMinPoint(cp.getCornerOne()); jail.setMinPoint(cp.getCornerOne());
jail.setMaxPoint(cp.getCornerTwo()); jail.setMaxPoint(cp.getCornerTwo());
jail.setTeleportIn(cp.getTeleportInSL().getLocation()); jail.setTeleportIn(cp.getTeleportInSL().getLocation());
jail.setTeleportFree(cp.getTeleportFreeSL().getLocation()); jail.setTeleportFree(cp.getTeleportFreeSL().getLocation());
jm.addJail(jail, true); jm.addJail(jail, true);
p.sendMessage(ChatColor.GREEN + "Jail (" + jail.getName() + ") created successfully!"); p.sendMessage(ChatColor.GREEN + "Jail (" + jail.getName() + ") created successfully!");
jm.removeJailCreationPlayer(p.getName()); jm.removeJailCreationPlayer(p.getName());
} }
} }

View File

@ -1,12 +1,12 @@
package test.java.com.graywolf336.jail; package test.java.com.graywolf336.jail;
import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertNotNull; import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertTrue; import static org.junit.Assert.assertTrue;
import static org.junit.Assert.assertFalse; import static org.mockito.Matchers.any;
import static org.mockito.Mockito.mock; import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.when; import static org.mockito.Mockito.when;
import static org.mockito.Matchers.any;
import java.util.Random; import java.util.Random;
import java.util.UUID; import java.util.UUID;
@ -22,6 +22,8 @@ import org.junit.runner.RunWith;
import org.powermock.core.classloader.annotations.PrepareForTest; import org.powermock.core.classloader.annotations.PrepareForTest;
import org.powermock.modules.junit4.PowerMockRunner; import org.powermock.modules.junit4.PowerMockRunner;
import test.java.com.graywolf336.jail.util.TestInstanceCreator;
import com.carrotsearch.junitbenchmarks.AbstractBenchmark; import com.carrotsearch.junitbenchmarks.AbstractBenchmark;
import com.carrotsearch.junitbenchmarks.BenchmarkOptions; import com.carrotsearch.junitbenchmarks.BenchmarkOptions;
import com.graywolf336.jail.JailMain; import com.graywolf336.jail.JailMain;
@ -29,71 +31,69 @@ import com.graywolf336.jail.beans.CachePrisoner;
import com.graywolf336.jail.beans.Jail; import com.graywolf336.jail.beans.Jail;
import com.graywolf336.jail.beans.Prisoner; import com.graywolf336.jail.beans.Prisoner;
import test.java.com.graywolf336.jail.util.TestInstanceCreator;
@RunWith(PowerMockRunner.class) @RunWith(PowerMockRunner.class)
@PrepareForTest({ JailMain.class, PluginDescriptionFile.class }) @PrepareForTest({ JailMain.class, PluginDescriptionFile.class })
public class BenchmarkTest extends AbstractBenchmark { public class BenchmarkTest extends AbstractBenchmark {
private static TestInstanceCreator creator; private static TestInstanceCreator creator;
private static JailMain main; private static JailMain main;
private static UUID use; private static UUID use;
private static Random r; private static Random r;
@BeforeClass @BeforeClass
public static void setUp() throws Exception { public static void setUp() throws Exception {
creator = new TestInstanceCreator(); creator = new TestInstanceCreator();
assertNotNull("The instance creator is null.", creator); assertNotNull("The instance creator is null.", creator);
assertTrue(creator.setup()); assertTrue(creator.setup());
main = creator.getMain(); main = creator.getMain();
assertNotNull("The JailMain class is null.", main); assertNotNull("The JailMain class is null.", main);
Jail j = new Jail(main, "testingJail"); Jail j = new Jail(main, "testingJail");
j.setWorld("world"); j.setWorld("world");
j.setMaxPoint(new int[] { 9, 63, -238 }); j.setMaxPoint(new int[] { 9, 63, -238 });
j.setMinPoint(new int[] { 23, 70, -242 }); j.setMinPoint(new int[] { 23, 70, -242 });
j.setTeleportIn(new Location(main.getServer().getWorld("world"), 11.469868464778077, 65.0, -239.27944647045672, Float.valueOf("38.499817"), Float.valueOf("2.0000453"))); j.setTeleportIn(new Location(main.getServer().getWorld("world"), 11.469868464778077, 65.0, -239.27944647045672, Float.valueOf("38.499817"), Float.valueOf("2.0000453")));
j.setTeleportFree(new Location(main.getServer().getWorld("world"), 27.947015843504765, 65.0, -218.8108042076112, Float.valueOf("90.54981"), Float.valueOf("12.500043"))); j.setTeleportFree(new Location(main.getServer().getWorld("world"), 27.947015843504765, 65.0, -218.8108042076112, Float.valueOf("90.54981"), Float.valueOf("12.500043")));
main.getJailManager().addJail(j, false); main.getJailManager().addJail(j, false);
assertFalse("There are no jails.", main.getJailManager().getJails().isEmpty()); assertFalse("There are no jails.", main.getJailManager().getJails().isEmpty());
for(int i = 0; i < 1000; i++) { for(int i = 0; i < 1000; i++) {
if(i == 555) if(i == 555)
use = UUID.randomUUID(); use = UUID.randomUUID();
main.getPrisonerManager().prepareJail(main.getJailManager().getJail("testingJail"), null, null, new Prisoner(i == 555 ? use.toString() : UUID.randomUUID().toString(), "mockPlayer" + i, true, 100000L, "testJailer", "Test jailing " + i)); main.getPrisonerManager().prepareJail(main.getJailManager().getJail("testingJail"), null, null, new Prisoner(i == 555 ? use.toString() : UUID.randomUUID().toString(), "mockPlayer" + i, true, 100000L, "testJailer", "Test jailing " + i));
} }
//This puts the cache object into the cache for the move event and others to use (move in this test) //This puts the cache object into the cache for the move event and others to use (move in this test)
main.getJailManager().addCacheObject(new CachePrisoner(main.getJailManager().getJailPlayerIsIn(use), main.getJailManager().getPrisoner(use))); main.getJailManager().addCacheObject(new CachePrisoner(main.getJailManager().getJailPlayerIsIn(use), main.getJailManager().getPrisoner(use)));
r = new Random(); r = new Random();
} }
@AfterClass @AfterClass
public static void tearDown() throws Exception { public static void tearDown() throws Exception {
creator.tearDown(); creator.tearDown();
main = null; main = null;
} }
@BenchmarkOptions(benchmarkRounds = 1000, warmupRounds = 0) @BenchmarkOptions(benchmarkRounds = 1000, warmupRounds = 0)
@Test @Test
public void testPrisonerSizeAndJailed() { public void testPrisonerSizeAndJailed() {
assertEquals("Prisoners not jailed?", 1000, main.getJailManager().getAllPrisoners().size()); assertEquals("Prisoners not jailed?", 1000, main.getJailManager().getAllPrisoners().size());
assertTrue("Prisoner 555 is not jailed", main.getJailManager().isPlayerJailed(use)); assertTrue("Prisoner 555 is not jailed", main.getJailManager().isPlayerJailed(use));
} }
@SuppressWarnings("deprecation") @SuppressWarnings("deprecation")
@BenchmarkOptions(benchmarkRounds = 5000, warmupRounds = 0) @BenchmarkOptions(benchmarkRounds = 5000, warmupRounds = 0)
@Test @Test
public void testPlayerMoveEvent() { public void testPlayerMoveEvent() {
Player p = mock(Player.class); Player p = mock(Player.class);
when(p.getUniqueId()).thenReturn(use); when(p.getUniqueId()).thenReturn(use);
when(p.getName()).thenReturn("mockPlayer555"); when(p.getName()).thenReturn("mockPlayer555");
when(p.teleport(any(Location.class))).thenReturn(true); when(p.teleport(any(Location.class))).thenReturn(true);
Location from = new Location(main.getServer().getWorld("world"), 15, 64, -239); Location from = new Location(main.getServer().getWorld("world"), 15, 64, -239);
Location to = new Location(main.getServer().getWorld("world"), r.nextInt(), r.nextInt(), r.nextInt()); Location to = new Location(main.getServer().getWorld("world"), r.nextInt(), r.nextInt(), r.nextInt());
PlayerMoveEvent e = new PlayerMoveEvent(p, from, to); PlayerMoveEvent e = new PlayerMoveEvent(p, from, to);
main.getPlayerMoveListener().moveProtection(e); main.getPlayerMoveListener().moveProtection(e);
} }
} }

View File

@ -1,11 +1,11 @@
package test.java.com.graywolf336.jail; package test.java.com.graywolf336.jail;
import static org.hamcrest.CoreMatchers.is;
import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertNotNull; import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertNull; import static org.junit.Assert.assertNull;
import static org.junit.Assert.assertThat; import static org.junit.Assert.assertThat;
import static org.junit.Assert.assertTrue; import static org.junit.Assert.assertTrue;
import static org.hamcrest.CoreMatchers.is;
import java.util.UUID; import java.util.UUID;
@ -26,44 +26,44 @@ import com.graywolf336.jail.JailsAPI;
@RunWith(PowerMockRunner.class) @RunWith(PowerMockRunner.class)
@PrepareForTest({ JailMain.class, PluginDescriptionFile.class }) @PrepareForTest({ JailMain.class, PluginDescriptionFile.class })
public class TestJailAPI { public class TestJailAPI {
private static TestInstanceCreator creator; private static TestInstanceCreator creator;
private static JailMain main; private static JailMain main;
@BeforeClass @BeforeClass
public static void setUp() throws Exception { public static void setUp() throws Exception {
creator = new TestInstanceCreator(); creator = new TestInstanceCreator();
assertNotNull("The instance creator is null.", creator); assertNotNull("The instance creator is null.", creator);
assertTrue(creator.setup()); assertTrue(creator.setup());
main = creator.getMain(); main = creator.getMain();
assertNotNull("The JailMain class is null.", main); assertNotNull("The JailMain class is null.", main);
} }
@AfterClass @AfterClass
public static void tearDown() throws Exception { public static void tearDown() throws Exception {
creator.tearDown(); creator.tearDown();
main = null; main = null;
} }
@Test @Test
public void testManagersAreThere() { public void testManagersAreThere() {
assertNotNull(main.getHandCuffManager()); assertNotNull(main.getHandCuffManager());
assertNotNull(main.getJailManager()); assertNotNull(main.getJailManager());
assertNotNull(main.getPrisonerManager()); assertNotNull(main.getPrisonerManager());
} }
@Test @Test
public void testHandCuffManagerAPI() { public void testHandCuffManagerAPI() {
UUID id = UUID.randomUUID(); UUID id = UUID.randomUUID();
Location loc = new Location(main.getServer().getWorld("world"), 11.469868464778077, 65.0, -239.27944647045672, Float.valueOf("38.499817"), Float.valueOf("2.0000453")); Location loc = new Location(main.getServer().getWorld("world"), 11.469868464778077, 65.0, -239.27944647045672, Float.valueOf("38.499817"), Float.valueOf("2.0000453"));
assertThat("The HandCuff Managers are different.", JailsAPI.getHandCuffManager(), is(main.getHandCuffManager())); assertThat("The HandCuff Managers are different.", JailsAPI.getHandCuffManager(), is(main.getHandCuffManager()));
assertFalse("The test id of someone is already handcuffed.", JailsAPI.getHandCuffManager().isHandCuffed(id)); assertFalse("The test id of someone is already handcuffed.", JailsAPI.getHandCuffManager().isHandCuffed(id));
JailsAPI.getHandCuffManager().addHandCuffs(id, loc); JailsAPI.getHandCuffManager().addHandCuffs(id, loc);
assertTrue(JailsAPI.getHandCuffManager().isHandCuffed(id)); assertTrue(JailsAPI.getHandCuffManager().isHandCuffed(id));
assertThat(JailsAPI.getHandCuffManager().getLocation(id), is(loc)); assertThat(JailsAPI.getHandCuffManager().getLocation(id), is(loc));
JailsAPI.getHandCuffManager().removeHandCuffs(id); JailsAPI.getHandCuffManager().removeHandCuffs(id);
assertFalse(JailsAPI.getHandCuffManager().isHandCuffed(id)); assertFalse(JailsAPI.getHandCuffManager().isHandCuffed(id));
assertNull(JailsAPI.getHandCuffManager().getLocation(id)); assertNull(JailsAPI.getHandCuffManager().getLocation(id));
} }
} }

View File

@ -1,6 +1,10 @@
package test.java.com.graywolf336.jail; package test.java.com.graywolf336.jail;
import static org.junit.Assert.*; import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertNull;
import static org.junit.Assert.assertTrue;
import static org.mockito.Mockito.atLeast; import static org.mockito.Mockito.atLeast;
import static org.mockito.Mockito.mock; import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.verify; import static org.mockito.Mockito.verify;
@ -27,116 +31,116 @@ import com.lexicalscope.jewel.cli.CliFactory;
@RunWith(PowerMockRunner.class) @RunWith(PowerMockRunner.class)
@PrepareForTest({ JailMain.class, PluginDescriptionFile.class }) @PrepareForTest({ JailMain.class, PluginDescriptionFile.class })
public class TestJailCommandInfo { public class TestJailCommandInfo {
private static TestInstanceCreator creator; private static TestInstanceCreator creator;
private static JailMain main; private static JailMain main;
@BeforeClass @BeforeClass
public static void setUp() throws Exception { public static void setUp() throws Exception {
creator = new TestInstanceCreator(); creator = new TestInstanceCreator();
assertNotNull("The instance creator is null.", creator); assertNotNull("The instance creator is null.", creator);
assertTrue(creator.setup()); assertTrue(creator.setup());
main = creator.getMain(); main = creator.getMain();
assertNotNull("The JailMain class is null.", main); assertNotNull("The JailMain class is null.", main);
} }
@AfterClass @AfterClass
public static void tearDown() throws Exception { public static void tearDown() throws Exception {
creator.tearDown(); creator.tearDown();
main = null; main = null;
} }
@Test @Test
public void testInvalidCommand() { public void testInvalidCommand() {
Command command = mock(Command.class); Command command = mock(Command.class);
when(command.getName()).thenReturn("thisisnotavalidcommand"); when(command.getName()).thenReturn("thisisnotavalidcommand");
String[] args = {}; String[] args = {};
CommandSender sender = creator.getCommandSender(); CommandSender sender = creator.getCommandSender();
assertTrue(main.onCommand(sender, command, "thisisnotavalidcommand", args)); assertTrue(main.onCommand(sender, command, "thisisnotavalidcommand", args));
verify(sender).sendMessage(ChatColor.RED + "No commands registered by the name of thisisnotavalidcommand."); verify(sender).sendMessage(ChatColor.RED + "No commands registered by the name of thisisnotavalidcommand.");
} }
@Test @Test
public void testForPlayerContext() { public void testForPlayerContext() {
Command command = mock(Command.class); Command command = mock(Command.class);
when(command.getName()).thenReturn("jail"); when(command.getName()).thenReturn("jail");
String[] args = { "create", "testJail" }; String[] args = { "create", "testJail" };
CommandSender sender = creator.getCommandSender(); CommandSender sender = creator.getCommandSender();
assertTrue(main.onCommand(sender, command, "jail", args)); assertTrue(main.onCommand(sender, command, "jail", args));
verify(sender).sendMessage(ChatColor.RED + "A player context is required for this."); verify(sender).sendMessage(ChatColor.RED + "A player context is required for this.");
} }
@Test @Test
public void testMinimumArgs() { public void testMinimumArgs() {
Command command = mock(Command.class); Command command = mock(Command.class);
when(command.getName()).thenReturn("jail"); when(command.getName()).thenReturn("jail");
String[] args = { "create" }; String[] args = { "create" };
CommandSender sender = creator.getPlayerCommandSender(); CommandSender sender = creator.getPlayerCommandSender();
assertTrue(main.onCommand(sender, command, "jail", args)); assertTrue(main.onCommand(sender, command, "jail", args));
verify(sender, atLeast(1)).sendMessage("/jail create [name]"); // If you change which command we test against, then change this verify(sender, atLeast(1)).sendMessage("/jail create [name]"); // If you change which command we test against, then change this
} }
@Test @Test
public void testMaximumArgs() { public void testMaximumArgs() {
Command command = mock(Command.class); Command command = mock(Command.class);
when(command.getName()).thenReturn("jail"); when(command.getName()).thenReturn("jail");
String[] args = { "create", "testing", "badarg", "reallyterribleone" }; String[] args = { "create", "testing", "badarg", "reallyterribleone" };
CommandSender sender = creator.getPlayerCommandSender(); CommandSender sender = creator.getPlayerCommandSender();
assertTrue(main.onCommand(sender, command, "jail", args)); assertTrue(main.onCommand(sender, command, "jail", args));
verify(sender, atLeast(1)).sendMessage("/jail create [name]"); // If you change which command we test against, then change this verify(sender, atLeast(1)).sendMessage("/jail create [name]"); // If you change which command we test against, then change this
} }
@Test @Test
public void testSuccessfulJailCreateCommand() { public void testSuccessfulJailCreateCommand() {
Command command = mock(Command.class); Command command = mock(Command.class);
when(command.getName()).thenReturn("jail"); when(command.getName()).thenReturn("jail");
String[] args = { "create", "testJail" }; String[] args = { "create", "testJail" };
CommandSender sender = creator.getPlayerCommandSender(); CommandSender sender = creator.getPlayerCommandSender();
assertTrue(main.onCommand(sender, command, "jail", args)); assertTrue(main.onCommand(sender, command, "jail", args));
verify(sender).sendMessage(ChatColor.AQUA + "----------Jail Zone Creation----------"); verify(sender).sendMessage(ChatColor.AQUA + "----------Jail Zone Creation----------");
verify(sender).sendMessage(ChatColor.GREEN + "First, you must select jail cuboid. Select the first point of the cuboid by right clicking on the block with your wooden sword. DO NOT FORGET TO MARK THE FLOOR AND CEILING TOO!"); verify(sender).sendMessage(ChatColor.GREEN + "First, you must select jail cuboid. Select the first point of the cuboid by right clicking on the block with your wooden sword. DO NOT FORGET TO MARK THE FLOOR AND CEILING TOO!");
verify(sender).sendMessage(ChatColor.AQUA + "--------------------------------------"); verify(sender).sendMessage(ChatColor.AQUA + "--------------------------------------");
} }
@Test @Test
public void testJailingCommand() { public void testJailingCommand() {
Command command = mock(Command.class); Command command = mock(Command.class);
when(command.getName()).thenReturn("jail"); when(command.getName()).thenReturn("jail");
String[] args = { "graywolf336", "-t", "30", "-j", "den", "-c", "cell_01", "-m", "-r", "He", "was", "a", "very", "bad", "boy." }; String[] args = { "graywolf336", "-t", "30", "-j", "den", "-c", "cell_01", "-m", "-r", "He", "was", "a", "very", "bad", "boy." };
CommandSender sender = creator.getPlayerCommandSender(); CommandSender sender = creator.getPlayerCommandSender();
assertTrue(main.onCommand(sender, command, "jail", args)); assertTrue(main.onCommand(sender, command, "jail", args));
verify(sender).sendMessage(ChatColor.RED + "There are currently no jails."); verify(sender).sendMessage(ChatColor.RED + "There are currently no jails.");
} }
@Test @Test
public void testJailJewel() { public void testJailJewel() {
String[] args = { "--player", "graywolf336", "-c", "testing", "-r", "This", "is", "a", "reason" }; String[] args = { "--player", "graywolf336", "-c", "testing", "-r", "This", "is", "a", "reason" };
Jailing j = CliFactory.parseArguments(Jailing.class, args); Jailing j = CliFactory.parseArguments(Jailing.class, args);
assertEquals("graywolf336", j.getPlayer()); assertEquals("graywolf336", j.getPlayer());
assertTrue("The cell wasn't provided.", j.isCell()); assertTrue("The cell wasn't provided.", j.isCell());
assertEquals("testing", j.getCell()); assertEquals("testing", j.getCell());
assertTrue("A reason wasn't provided.", j.isReason()); assertTrue("A reason wasn't provided.", j.isReason());
StringBuilder sb = new StringBuilder(); StringBuilder sb = new StringBuilder();
for(String s : j.getReason()) { for(String s : j.getReason()) {
sb.append(s).append(' '); sb.append(s).append(' ');
} }
sb.deleteCharAt(sb.length() - 1); sb.deleteCharAt(sb.length() - 1);
assertEquals("This is a reason", sb.toString()); assertEquals("This is a reason", sb.toString());
} }
@Test @Test
public void testJailWithAnyCellJewel() { public void testJailWithAnyCellJewel() {
@ -158,29 +162,29 @@ public class TestJailCommandInfo {
assertEquals("This is a reason", sb.toString()); assertEquals("This is a reason", sb.toString());
} }
@Test @Test
public void testTransferForJailAndCell() { public void testTransferForJailAndCell() {
String[] args = { "-p", "graywolf336", "-j", "hardcore", "-c", "cell_n01" }; String[] args = { "-p", "graywolf336", "-j", "hardcore", "-c", "cell_n01" };
Transfer t = CliFactory.parseArguments(Transfer.class, args); Transfer t = CliFactory.parseArguments(Transfer.class, args);
assertTrue("The player wasn't provided.", t.isPlayer()); assertTrue("The player wasn't provided.", t.isPlayer());
assertEquals("The player parsed is not what we expected.", "graywolf336", t.getPlayer()); assertEquals("The player parsed is not what we expected.", "graywolf336", t.getPlayer());
assertTrue("The jail wasn't provided.", t.isJail()); assertTrue("The jail wasn't provided.", t.isJail());
assertEquals("The jail parsed is not what we expected.", "hardcore", t.getJail()); assertEquals("The jail parsed is not what we expected.", "hardcore", t.getJail());
assertTrue("The cell wasn't provided.", t.isCell()); assertTrue("The cell wasn't provided.", t.isCell());
assertEquals("The cell parsed is not what we expected.", "cell_n01", t.getCell()); assertEquals("The cell parsed is not what we expected.", "cell_n01", t.getCell());
} }
@Test @Test
public void testTransferForNoCell() { public void testTransferForNoCell() {
String[] args = { "-p", "graywolf336", "-j", "hardcore" }; String[] args = { "-p", "graywolf336", "-j", "hardcore" };
Transfer t = CliFactory.parseArguments(Transfer.class, args); Transfer t = CliFactory.parseArguments(Transfer.class, args);
assertTrue("The player wasn't provided.", t.isPlayer()); assertTrue("The player wasn't provided.", t.isPlayer());
assertEquals("The player parsed is not what we expected.", "graywolf336", t.getPlayer()); assertEquals("The player parsed is not what we expected.", "graywolf336", t.getPlayer());
assertTrue("The jail wasn't provided.", t.isJail()); assertTrue("The jail wasn't provided.", t.isJail());
assertEquals("The jail parsed is not what we expected.", "hardcore", t.getJail()); assertEquals("The jail parsed is not what we expected.", "hardcore", t.getJail());
assertFalse("The cell was provided?", t.isCell()); assertFalse("The cell was provided?", t.isCell());
assertNull("The cell is not null?", t.getCell()); assertNull("The cell is not null?", t.getCell());
} }
} }

View File

@ -1,9 +1,9 @@
package test.java.com.graywolf336.jail; package test.java.com.graywolf336.jail;
import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertTrue;
import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertNotNull; import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertTrue;
import java.util.List; import java.util.List;
@ -23,150 +23,150 @@ import com.graywolf336.jail.enums.Settings;
@RunWith(PowerMockRunner.class) @RunWith(PowerMockRunner.class)
@PrepareForTest({ JailMain.class, PluginDescriptionFile.class }) @PrepareForTest({ JailMain.class, PluginDescriptionFile.class })
public class TestJailDefaultConfig { public class TestJailDefaultConfig {
private static TestInstanceCreator creator; private static TestInstanceCreator creator;
private static JailMain main; private static JailMain main;
@BeforeClass @BeforeClass
public static void setUp() throws Exception { public static void setUp() throws Exception {
creator = new TestInstanceCreator(); creator = new TestInstanceCreator();
assertNotNull("The instance creator is null.", creator); assertNotNull("The instance creator is null.", creator);
assertTrue(creator.setup()); assertTrue(creator.setup());
main = creator.getMain(); main = creator.getMain();
assertNotNull("The JailMain class is null.", main); assertNotNull("The JailMain class is null.", main);
} }
@AfterClass @AfterClass
public static void tearDown() throws Exception { public static void tearDown() throws Exception {
creator.tearDown(); creator.tearDown();
main = null; main = null;
} }
@Test @Test
public void testSystemDefaultConfig() { public void testSystemDefaultConfig() {
assertEquals("The config version is not 3.", 3, main.getConfig().getInt(Settings.CONFIGVERSION.getPath())); assertEquals("The config version is not 3.", 3, main.getConfig().getInt(Settings.CONFIGVERSION.getPath()));
assertTrue("Default debugging is off.", main.getConfig().getBoolean(Settings.DEBUG.getPath())); assertTrue("Default debugging is off.", main.getConfig().getBoolean(Settings.DEBUG.getPath()));
assertEquals("Default language is not 'en'.", "en", main.getConfig().getString(Settings.LANGUAGE.getPath())); assertEquals("Default language is not 'en'.", "en", main.getConfig().getString(Settings.LANGUAGE.getPath()));
assertEquals("Default updating channel is not bukkit.", "bukkit", main.getConfig().getString(Settings.UPDATECHANNEL.getPath())); assertEquals("Default updating channel is not bukkit.", "bukkit", main.getConfig().getString(Settings.UPDATECHANNEL.getPath()));
assertTrue("Default updating notifications is false.", main.getConfig().getBoolean(Settings.UPDATENOTIFICATIONS.getPath())); assertTrue("Default updating notifications is false.", main.getConfig().getBoolean(Settings.UPDATENOTIFICATIONS.getPath()));
assertEquals("Default updating time checking is not 1h.", "1h", main.getConfig().getString(Settings.UPDATETIME.getPath())); assertEquals("Default updating time checking is not 1h.", "1h", main.getConfig().getString(Settings.UPDATETIME.getPath()));
assertTrue("Default usage of bukkit timer is false.", main.getConfig().getBoolean(Settings.USEBUKKITTIMER.getPath())); assertTrue("Default usage of bukkit timer is false.", main.getConfig().getBoolean(Settings.USEBUKKITTIMER.getPath()));
} }
@Test @Test
public void testStorageDefaultConfig() { public void testStorageDefaultConfig() {
assertEquals("The default storage system is not flatfile.", "flatfile", main.getConfig().getString("storage.type")); assertEquals("The default storage system is not flatfile.", "flatfile", main.getConfig().getString("storage.type"));
assertEquals("The default mysql host is not localhost.", "localhost", main.getConfig().getString("storage.mysql.host")); assertEquals("The default mysql host is not localhost.", "localhost", main.getConfig().getString("storage.mysql.host"));
assertEquals("The default mysql port is not 3306.", 3306, main.getConfig().getInt("storage.mysql.port")); assertEquals("The default mysql port is not 3306.", 3306, main.getConfig().getInt("storage.mysql.port"));
assertEquals("The default mysql username is not root.", "root", main.getConfig().getString("storage.mysql.username")); assertEquals("The default mysql username is not root.", "root", main.getConfig().getString("storage.mysql.username"));
assertEquals("The default mysql password is not password.", "password", main.getConfig().getString("storage.mysql.password")); assertEquals("The default mysql password is not password.", "password", main.getConfig().getString("storage.mysql.password"));
assertEquals("The default mysql database is not jailDatabase.", "jailDatabase", main.getConfig().getString("storage.mysql.database")); assertEquals("The default mysql database is not jailDatabase.", "jailDatabase", main.getConfig().getString("storage.mysql.database"));
assertEquals("The default mysql prefix is not j3_.", "j3_", main.getConfig().getString("storage.mysql.prefix")); assertEquals("The default mysql prefix is not j3_.", "j3_", main.getConfig().getString("storage.mysql.prefix"));
} }
@Test @Test
public void testDuringJailingDefaultConfig() { public void testDuringJailingDefaultConfig() {
// block breaking section // block breaking section
assertEquals("Default setting for block break penalty is not 5m.", "5m", main.getConfig().getString(Settings.BLOCKBREAKPENALTY.getPath())); assertEquals("Default setting for block break penalty is not 5m.", "5m", main.getConfig().getString(Settings.BLOCKBREAKPENALTY.getPath()));
assertTrue("Default setting for block break proection is false.", main.getConfig().getBoolean(Settings.BLOCKBREAKPROTECTION.getPath())); assertTrue("Default setting for block break proection is false.", main.getConfig().getBoolean(Settings.BLOCKBREAKPROTECTION.getPath()));
List<String> blockbreakwhite = main.getConfig().getStringList(Settings.BLOCKBREAKWHITELIST.getPath()); List<String> blockbreakwhite = main.getConfig().getStringList(Settings.BLOCKBREAKWHITELIST.getPath());
assertTrue("Default block breaking doesn't contain crops.", blockbreakwhite.contains("crops")); assertTrue("Default block breaking doesn't contain crops.", blockbreakwhite.contains("crops"));
assertTrue("Default block breaking doesn't contain carrot.", blockbreakwhite.contains("carrot")); assertTrue("Default block breaking doesn't contain carrot.", blockbreakwhite.contains("carrot"));
assertTrue("Default block breaking doesn't contain potato.", blockbreakwhite.contains("potato")); assertTrue("Default block breaking doesn't contain potato.", blockbreakwhite.contains("potato"));
// block placing section // block placing section
assertEquals("Default setting for block place penalty is not 5m.", "5m", main.getConfig().getString(Settings.BLOCKPLACEPENALTY.getPath())); assertEquals("Default setting for block place penalty is not 5m.", "5m", main.getConfig().getString(Settings.BLOCKPLACEPENALTY.getPath()));
assertTrue("Default setting for block place proection is false.", main.getConfig().getBoolean(Settings.BLOCKPLACEPROTECTION.getPath())); assertTrue("Default setting for block place proection is false.", main.getConfig().getBoolean(Settings.BLOCKPLACEPROTECTION.getPath()));
List<String> blockplacewhite = main.getConfig().getStringList(Settings.BLOCKPLACEWHITELIST.getPath()); List<String> blockplacewhite = main.getConfig().getStringList(Settings.BLOCKPLACEWHITELIST.getPath());
assertTrue("Default block placing whitelist doesn't contain crops.", blockplacewhite.contains("crops")); assertTrue("Default block placing whitelist doesn't contain crops.", blockplacewhite.contains("crops"));
assertTrue("Default block placing whitelist doesn't contain carrot.", blockplacewhite.contains("carrot")); assertTrue("Default block placing whitelist doesn't contain carrot.", blockplacewhite.contains("carrot"));
assertTrue("Default block placing whitelist doesn't contain potato.", blockplacewhite.contains("potato")); assertTrue("Default block placing whitelist doesn't contain potato.", blockplacewhite.contains("potato"));
// command protection section // command protection section
assertEquals("Default setting for command penalty is not 5m.", "5m", main.getConfig().getString(Settings.COMMANDPENALTY.getPath())); assertEquals("Default setting for command penalty is not 5m.", "5m", main.getConfig().getString(Settings.COMMANDPENALTY.getPath()));
assertTrue("Default setting for command proection is false.", main.getConfig().getBoolean(Settings.COMMANDPROTECTION.getPath())); assertTrue("Default setting for command proection is false.", main.getConfig().getBoolean(Settings.COMMANDPROTECTION.getPath()));
List<String> commandwhite = main.getConfig().getStringList(Settings.COMMANDWHITELIST.getPath()); List<String> commandwhite = main.getConfig().getStringList(Settings.COMMANDWHITELIST.getPath());
assertTrue("Default command whitelist doesn't contain /ping.", commandwhite.contains("/ping")); assertTrue("Default command whitelist doesn't contain /ping.", commandwhite.contains("/ping"));
assertTrue("Default command whitelist doesn't contain /list.", commandwhite.contains("/list")); assertTrue("Default command whitelist doesn't contain /list.", commandwhite.contains("/list"));
assertTrue("Default command whitelist doesn't contain /jail status.", commandwhite.contains("/jail status")); assertTrue("Default command whitelist doesn't contain /jail status.", commandwhite.contains("/jail status"));
assertTrue("Default command whitelist doesn't contain /jail pay.", commandwhite.contains("/jail pay")); assertTrue("Default command whitelist doesn't contain /jail pay.", commandwhite.contains("/jail pay"));
assertFalse("Default setting for counting down time while prisoner is offline is true.", main.getConfig().getBoolean(Settings.COUNTDOWNTIMEOFFLINE.getPath())); assertFalse("Default setting for counting down time while prisoner is offline is true.", main.getConfig().getBoolean(Settings.COUNTDOWNTIMEOFFLINE.getPath()));
assertEquals("Default setting for crop trampling penalty is not 5m.", "5m", main.getConfig().getString(Settings.CROPTRAMPLINGPENALTY.getPath())); assertEquals("Default setting for crop trampling penalty is not 5m.", "5m", main.getConfig().getString(Settings.CROPTRAMPLINGPENALTY.getPath()));
assertTrue("Default setting for crop trampling proection is false.", main.getConfig().getBoolean(Settings.CROPTRAMPLINGPROTECTION.getPath())); assertTrue("Default setting for crop trampling proection is false.", main.getConfig().getBoolean(Settings.CROPTRAMPLINGPROTECTION.getPath()));
assertTrue("Default setting for food control enabled is false.", main.getConfig().getBoolean(Settings.FOODCONTROL.getPath())); assertTrue("Default setting for food control enabled is false.", main.getConfig().getBoolean(Settings.FOODCONTROL.getPath()));
assertEquals("Default setting for food control max is not 20.", 20, main.getConfig().getInt(Settings.FOODCONTROLMAX.getPath())); assertEquals("Default setting for food control max is not 20.", 20, main.getConfig().getInt(Settings.FOODCONTROLMAX.getPath()));
assertEquals("Default setting for food control min is not 10.", 10, main.getConfig().getInt(Settings.FOODCONTROLMIN.getPath())); assertEquals("Default setting for food control min is not 10.", 10, main.getConfig().getInt(Settings.FOODCONTROLMIN.getPath()));
assertTrue("Default setting for ignoring sleeping is false.", main.getConfig().getBoolean(Settings.IGNORESLEEPINGSTATE.getPath())); assertTrue("Default setting for ignoring sleeping is false.", main.getConfig().getBoolean(Settings.IGNORESLEEPINGSTATE.getPath()));
assertEquals("Default setting max afk time is not 10 minutes.", "10m", main.getConfig().getString(Settings.MAXAFKTIME.getPath())); assertEquals("Default setting max afk time is not 10 minutes.", "10m", main.getConfig().getString(Settings.MAXAFKTIME.getPath()));
assertEquals("Default setting move penalty is not 10 minutes.", "10m", main.getConfig().getString(Settings.MOVEPENALTY.getPath())); assertEquals("Default setting move penalty is not 10 minutes.", "10m", main.getConfig().getString(Settings.MOVEPENALTY.getPath()));
assertTrue("Default setting for move protection is false.", main.getConfig().getBoolean(Settings.MOVEPROTECTION.getPath())); assertTrue("Default setting for move protection is false.", main.getConfig().getBoolean(Settings.MOVEPROTECTION.getPath()));
assertTrue("Default setting for opening a chest is false.", main.getConfig().getBoolean(Settings.PRISONEROPENCHEST.getPath())); assertTrue("Default setting for opening a chest is false.", main.getConfig().getBoolean(Settings.PRISONEROPENCHEST.getPath()));
// interaction blocks protection section // interaction blocks protection section
List<String> interactionBlocks = main.getConfig().getStringList(Settings.PREVENTINTERACTIONBLOCKS.getPath()); List<String> interactionBlocks = main.getConfig().getStringList(Settings.PREVENTINTERACTIONBLOCKS.getPath());
assertTrue("Default interaction blocks whitelist doesn't contain wooden_door.", interactionBlocks.contains("wooden_door")); assertTrue("Default interaction blocks whitelist doesn't contain wooden_door.", interactionBlocks.contains("wooden_door"));
assertTrue("Default interaction blocks whitelist doesn't contain iron_door_block.", interactionBlocks.contains("iron_door_block")); assertTrue("Default interaction blocks whitelist doesn't contain iron_door_block.", interactionBlocks.contains("iron_door_block"));
assertEquals("Default setting for preventing interaction blocks penalty is not 5m.", "5m", main.getConfig().getString(Settings.PREVENTINTERACTIONBLOCKSPENALTY.getPath())); assertEquals("Default setting for preventing interaction blocks penalty is not 5m.", "5m", main.getConfig().getString(Settings.PREVENTINTERACTIONBLOCKSPENALTY.getPath()));
// interaction items protection section // interaction items protection section
assertTrue("Default interaction items whitelist isn't empty.", main.getConfig().getStringList(Settings.PREVENTINTERACTIONITEMS.getPath()).isEmpty()); assertTrue("Default interaction items whitelist isn't empty.", main.getConfig().getStringList(Settings.PREVENTINTERACTIONITEMS.getPath()).isEmpty());
assertEquals("Default setting for preventing interaction blocks penalty is not 5m.", "5m", main.getConfig().getString(Settings.PREVENTINTERACTIONBLOCKSPENALTY.getPath())); assertEquals("Default setting for preventing interaction blocks penalty is not 5m.", "5m", main.getConfig().getString(Settings.PREVENTINTERACTIONBLOCKSPENALTY.getPath()));
assertTrue("Default setting for recieving messages is false.", main.getConfig().getBoolean(Settings.RECIEVEMESSAGES.getPath())); assertTrue("Default setting for recieving messages is false.", main.getConfig().getBoolean(Settings.RECIEVEMESSAGES.getPath()));
assertFalse("Default setting for scoreboard being enabled is true.", main.getConfig().getBoolean(Settings.SCOREBOARDENABLED.getPath())); assertFalse("Default setting for scoreboard being enabled is true.", main.getConfig().getBoolean(Settings.SCOREBOARDENABLED.getPath()));
assertEquals("Default setting for the scoreboard title is not Jail Info.", "Jail Info", main.getConfig().getString(Settings.SCOREBOARDTITLE.getPath())); assertEquals("Default setting for the scoreboard title is not Jail Info.", "Jail Info", main.getConfig().getString(Settings.SCOREBOARDTITLE.getPath()));
assertEquals("Default setting for the scoreboard time language is not &aTime:", "&aTime:", main.getConfig().getString(Settings.SCOREBOARDTIME.getPath())); assertEquals("Default setting for the scoreboard time language is not &aTime:", "&aTime:", main.getConfig().getString(Settings.SCOREBOARDTIME.getPath()));
} }
@Test @Test
public void testJailingDefaultConfig() { public void testJailingDefaultConfig() {
assertTrue("Default setting for automatically muting is false.", main.getConfig().getBoolean(Settings.AUTOMATICMUTE.getPath())); assertTrue("Default setting for automatically muting is false.", main.getConfig().getBoolean(Settings.AUTOMATICMUTE.getPath()));
assertFalse("Default setting for broadcasting a jailing is true.", main.getConfig().getBoolean(Settings.BROADCASTJAILING.getPath())); assertFalse("Default setting for broadcasting a jailing is true.", main.getConfig().getBoolean(Settings.BROADCASTJAILING.getPath()));
assertTrue("Default setting for jail clothing is not enabled.", main.getConfig().getBoolean(Settings.CLOTHINGENABLED.getPath())); assertTrue("Default setting for jail clothing is not enabled.", main.getConfig().getBoolean(Settings.CLOTHINGENABLED.getPath()));
assertEquals("Default setting for jail clothing's helmet is not leather_helmet~175,105,33.", "leather_helmet~175,105,33", main.getConfig().getString(Settings.CLOTHINGHELMET.getPath())); assertEquals("Default setting for jail clothing's helmet is not leather_helmet~175,105,33.", "leather_helmet~175,105,33", main.getConfig().getString(Settings.CLOTHINGHELMET.getPath()));
assertEquals("Default setting for jail clothing's chestplate is not leather_chestplate~175,105,33.", "leather_chestplate~175,105,33", main.getConfig().getString(Settings.CLOTHINGCHEST.getPath())); assertEquals("Default setting for jail clothing's chestplate is not leather_chestplate~175,105,33.", "leather_chestplate~175,105,33", main.getConfig().getString(Settings.CLOTHINGCHEST.getPath()));
assertEquals("Default setting for jail clothing's legs is not leather_leggings~175,105,33.", "leather_leggings~175,105,33", main.getConfig().getString(Settings.CLOTHINGLEGS.getPath())); assertEquals("Default setting for jail clothing's legs is not leather_leggings~175,105,33.", "leather_leggings~175,105,33", main.getConfig().getString(Settings.CLOTHINGLEGS.getPath()));
assertEquals("Default setting for jail clothing's boots is not leather_boots~175,105,33.", "leather_boots~175,105,33", main.getConfig().getString(Settings.CLOTHINGBOOTS.getPath())); assertEquals("Default setting for jail clothing's boots is not leather_boots~175,105,33.", "leather_boots~175,105,33", main.getConfig().getString(Settings.CLOTHINGBOOTS.getPath()));
assertTrue("Default setting for commands is not empty.", main.getConfig().getStringList(Settings.COMMANDSONJAIL.getPath()).isEmpty()); assertTrue("Default setting for commands is not empty.", main.getConfig().getStringList(Settings.COMMANDSONJAIL.getPath()).isEmpty());
assertEquals("Default setting for default jail is not 'nearest' but something else.", "nearest", main.getConfig().getString(Settings.DEFAULTJAIL.getPath())); assertEquals("Default setting for default jail is not 'nearest' but something else.", "nearest", main.getConfig().getString(Settings.DEFAULTJAIL.getPath()));
assertEquals("Default setting for time is not 30 minutes.", "30m", main.getConfig().getString(Settings.DEFAULTTIME.getPath())); assertEquals("Default setting for time is not 30 minutes.", "30m", main.getConfig().getString(Settings.DEFAULTTIME.getPath()));
assertEquals("Default setting for the prisoner's default gamemode is not adventure.", "adventure", main.getConfig().getString(Settings.JAILEDGAMEMODE.getPath())); assertEquals("Default setting for the prisoner's default gamemode is not adventure.", "adventure", main.getConfig().getString(Settings.JAILEDGAMEMODE.getPath()));
assertTrue("Default setting for inventory storing blacklist is not empty.", main.getConfig().getStringList(Settings.JAILEDINVENTORYBLACKLIST.getPath()).isEmpty()); assertTrue("Default setting for inventory storing blacklist is not empty.", main.getConfig().getStringList(Settings.JAILEDINVENTORYBLACKLIST.getPath()).isEmpty());
assertTrue("Default setting for inventory storing is false.", main.getConfig().getBoolean(Settings.JAILEDSTOREINVENTORY.getPath())); assertTrue("Default setting for inventory storing is false.", main.getConfig().getBoolean(Settings.JAILEDSTOREINVENTORY.getPath()));
assertTrue("Default setting for logging to console when someone is jailed is false.", main.getConfig().getBoolean(Settings.LOGJAILINGTOCONSOLE.getPath())); assertTrue("Default setting for logging to console when someone is jailed is false.", main.getConfig().getBoolean(Settings.LOGJAILINGTOCONSOLE.getPath()));
assertTrue("Default setting for logging to prisoner's profile is false.", main.getConfig().getBoolean(Settings.LOGJAILINGTOPROFILE.getPath())); assertTrue("Default setting for logging to prisoner's profile is false.", main.getConfig().getBoolean(Settings.LOGJAILINGTOPROFILE.getPath()));
} }
@Test @Test
public void testReleaseDefaultConfig() { public void testReleaseDefaultConfig() {
assertFalse("Default setting for releasing back to previous position is true.", main.getConfig().getBoolean(Settings.RELEASETOPREVIOUSPOSITION.getPath())); assertFalse("Default setting for releasing back to previous position is true.", main.getConfig().getBoolean(Settings.RELEASETOPREVIOUSPOSITION.getPath()));
assertTrue("Default setting for commands is not empty.", main.getConfig().getStringList(Settings.COMMANDSONRELEASE.getPath()).isEmpty()); assertTrue("Default setting for commands is not empty.", main.getConfig().getStringList(Settings.COMMANDSONRELEASE.getPath()).isEmpty());
assertFalse("Default setting for restoring previous gamemode is true.", main.getConfig().getBoolean(Settings.RESTOREPREVIOUSGAMEMODE.getPath())); assertFalse("Default setting for restoring previous gamemode is true.", main.getConfig().getBoolean(Settings.RESTOREPREVIOUSGAMEMODE.getPath()));
assertTrue("Default setting for teleporting them out of the jail is false.", main.getConfig().getBoolean(Settings.TELEPORTONRELEASE.getPath())); assertTrue("Default setting for teleporting them out of the jail is false.", main.getConfig().getBoolean(Settings.TELEPORTONRELEASE.getPath()));
} }
@Test @Test
public void testJailsDefaultConfig() { public void testJailsDefaultConfig() {
assertTrue("Default setting for protecting jails from endermen is false.", main.getConfig().getBoolean(Settings.ENDERMENPROTECTION.getPath())); assertTrue("Default setting for protecting jails from endermen is false.", main.getConfig().getBoolean(Settings.ENDERMENPROTECTION.getPath()));
assertTrue("Default setting for protecting jails from explosions is false.", main.getConfig().getBoolean(Settings.EXPLOSIONPROTECTION.getPath())); assertTrue("Default setting for protecting jails from explosions is false.", main.getConfig().getBoolean(Settings.EXPLOSIONPROTECTION.getPath()));
} }
@Test @Test
public void testJailPayDefaultConfig() { public void testJailPayDefaultConfig() {
assertFalse("Default setting for jail pay enabled is true, meaning Jail Pay somehow got enabled in testing.", main.getConfig().getBoolean(Settings.JAILPAYENABLED.getPath())); assertFalse("Default setting for jail pay enabled is true, meaning Jail Pay somehow got enabled in testing.", main.getConfig().getBoolean(Settings.JAILPAYENABLED.getPath()));
assertEquals("Default setting for jail pay item is not air.", "air", main.getConfig().getString(Settings.JAILPAYITEM.getPath())); assertEquals("Default setting for jail pay item is not air.", "air", main.getConfig().getString(Settings.JAILPAYITEM.getPath()));
assertEquals("Default setting for jail pay price per minute is not 1.5.", 1.5, main.getConfig().getDouble(Settings.JAILPAYPRICEPERMINUTE.getPath()), 0); assertEquals("Default setting for jail pay price per minute is not 1.5.", 1.5, main.getConfig().getDouble(Settings.JAILPAYPRICEPERMINUTE.getPath()), 0);
assertEquals("Default setting for jail pay price for infinite is not 10000.", 10000, main.getConfig().getDouble(Settings.JAILPAYPRICEINFINITE.getPath()), 0); assertEquals("Default setting for jail pay price for infinite is not 10000.", 10000, main.getConfig().getDouble(Settings.JAILPAYPRICEINFINITE.getPath()), 0);
} }
@Test @Test
public void testJailStickDefaultConfig() { public void testJailStickDefaultConfig() {
assertTrue("Default setting for jail stick enabled is false.", main.getConfig().getBoolean(Settings.JAILSTICKENABLED.getPath())); assertTrue("Default setting for jail stick enabled is false.", main.getConfig().getBoolean(Settings.JAILSTICKENABLED.getPath()));
List<String> jailSticks = main.getConfig().getStringList(Settings.JAILSTICKSTICKS.getPath()); List<String> jailSticks = main.getConfig().getStringList(Settings.JAILSTICKSTICKS.getPath());
assertTrue("Default setting for jail sticks doesn't contain a stick with item of stick.", jailSticks.contains("stick,30m,,Running away,-1")); assertTrue("Default setting for jail sticks doesn't contain a stick with item of stick.", jailSticks.contains("stick,30m,,Running away,-1"));
assertTrue("Default setting for jail sticks doesn't contain a stick with item of blaze_rod.", jailSticks.contains("blaze_rod,15m,,Having too much fun,6")); assertTrue("Default setting for jail sticks doesn't contain a stick with item of blaze_rod.", jailSticks.contains("blaze_rod,15m,,Having too much fun,6"));
} }
} }

View File

@ -1,6 +1,8 @@
package test.java.com.graywolf336.jail; package test.java.com.graywolf336.jail;
import static org.junit.Assert.*; import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertTrue;
import java.util.UUID; import java.util.UUID;

View File

@ -1,6 +1,8 @@
package test.java.com.graywolf336.jail; package test.java.com.graywolf336.jail;
import static org.junit.Assert.*; import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertTrue;
import java.util.ArrayList; import java.util.ArrayList;
import java.util.List; import java.util.List;
@ -15,96 +17,96 @@ import org.junit.Test;
import com.graywolf336.jail.Util; import com.graywolf336.jail.Util;
public class TestUtilClass { public class TestUtilClass {
private static List<String> list; private static List<String> list;
private static Vector bottomCorner; private static Vector bottomCorner;
private static Vector topCorner; private static Vector topCorner;
@BeforeClass @BeforeClass
public static void setUp() throws Exception { public static void setUp() throws Exception {
list = new ArrayList<String>(); list = new ArrayList<String>();
list.add(Material.SEEDS.toString()); list.add(Material.SEEDS.toString());
list.add("coal_ore"); list.add("coal_ore");
list.add("torch"); list.add("torch");
bottomCorner = new Vector(-10.50, 50.25, 100.00); bottomCorner = new Vector(-10.50, 50.25, 100.00);
topCorner = new Vector(50, 100, 250); topCorner = new Vector(50, 100, 250);
} }
@AfterClass @AfterClass
public static void tearDown() throws Exception { public static void tearDown() throws Exception {
bottomCorner = null; bottomCorner = null;
topCorner = null; topCorner = null;
list = null; list = null;
} }
@Test @Test
public void testIsInsideAB() { public void testIsInsideAB() {
Vector inside = new Vector(35, 64, 110); Vector inside = new Vector(35, 64, 110);
assertTrue(Util.isInsideAB(inside, bottomCorner, topCorner)); assertTrue(Util.isInsideAB(inside, bottomCorner, topCorner));
} }
@Test @Test
public void testIsOutsideAB() { public void testIsOutsideAB() {
Vector outside = new Vector(350, 15, 350); Vector outside = new Vector(350, 15, 350);
assertFalse(Util.isInsideAB(outside, bottomCorner, topCorner)); assertFalse(Util.isInsideAB(outside, bottomCorner, topCorner));
} }
@Test @Test
public void testHalfInHalfOutsideAB() { public void testHalfInHalfOutsideAB() {
Vector halfAndHalf = new Vector(25, 75, 99); Vector halfAndHalf = new Vector(25, 75, 99);
assertFalse(Util.isInsideAB(halfAndHalf, bottomCorner, topCorner)); assertFalse(Util.isInsideAB(halfAndHalf, bottomCorner, topCorner));
} }
@Test @Test
public void testInList() { public void testInList() {
assertTrue(Util.isStringInsideList(list, "seeds")); assertTrue(Util.isStringInsideList(list, "seeds"));
assertTrue(Util.isStringInsideList(list, Material.COAL_ORE.toString())); assertTrue(Util.isStringInsideList(list, Material.COAL_ORE.toString()));
assertTrue(Util.isStringInsideList(list, "tOrCh")); assertTrue(Util.isStringInsideList(list, "tOrCh"));
} }
@Test @Test
public void testNotInList() { public void testNotInList() {
assertFalse(Util.isStringInsideList(list, "dirt")); assertFalse(Util.isStringInsideList(list, "dirt"));
assertFalse(Util.isStringInsideList(list, "SAND")); assertFalse(Util.isStringInsideList(list, "SAND"));
assertFalse(Util.isStringInsideList(list, Material.BEDROCK.toString())); assertFalse(Util.isStringInsideList(list, Material.BEDROCK.toString()));
} }
@Test @Test
public void testNoFormat() throws Exception { public void testNoFormat() throws Exception {
assertEquals(60000L, Util.getTime("1"), 0); assertEquals(60000L, Util.getTime("1"), 0);
assertEquals(360000L, Util.getTime("6"), 0); assertEquals(360000L, Util.getTime("6"), 0);
} }
@Test @Test
public void testTimeSeconds() throws Exception { public void testTimeSeconds() throws Exception {
assertEquals(2000L, Util.getTime("2s"), 0); assertEquals(2000L, Util.getTime("2s"), 0);
assertEquals(2000L, Util.getTime("2second"), 0); assertEquals(2000L, Util.getTime("2second"), 0);
assertEquals(2000L, Util.getTime("2seconds"), 0); assertEquals(2000L, Util.getTime("2seconds"), 0);
} }
@Test @Test
public void testTimeMinutes() throws Exception { public void testTimeMinutes() throws Exception {
assertEquals(60000L, Util.getTime("1m"), 0); assertEquals(60000L, Util.getTime("1m"), 0);
assertEquals(60000L, Util.getTime("1minute"), 0); assertEquals(60000L, Util.getTime("1minute"), 0);
assertEquals(60000L, Util.getTime("1minutes"), 0); assertEquals(60000L, Util.getTime("1minutes"), 0);
} }
@Test @Test
public void testTimeHours() throws Exception { public void testTimeHours() throws Exception {
assertEquals(3600000L, Util.getTime("1h"), 0); assertEquals(3600000L, Util.getTime("1h"), 0);
assertEquals(3600000L, Util.getTime("1hours"), 0); assertEquals(3600000L, Util.getTime("1hours"), 0);
} }
@Test @Test
public void testTimeDays() throws Exception { public void testTimeDays() throws Exception {
assertEquals(86400000L, Util.getTime("1d"), 0); assertEquals(86400000L, Util.getTime("1d"), 0);
assertEquals(86400000L, Util.getTime("1days"), 0); assertEquals(86400000L, Util.getTime("1days"), 0);
} }
@Test @Test
public void testTimeSecondsPassed() throws Exception { public void testTimeSecondsPassed() throws Exception {
assertEquals(60L, Util.getTime("60", TimeUnit.MINUTES), 0); assertEquals(60L, Util.getTime("60", TimeUnit.MINUTES), 0);
assertEquals(1L, Util.getTime("60s", TimeUnit.MINUTES), 0); assertEquals(1L, Util.getTime("60s", TimeUnit.MINUTES), 0);
assertEquals(1L, Util.getTime("60m", TimeUnit.HOURS), 0); assertEquals(1L, Util.getTime("60m", TimeUnit.HOURS), 0);
assertEquals(6L, Util.getTime("6d", TimeUnit.DAYS), 0); assertEquals(6L, Util.getTime("6d", TimeUnit.DAYS), 0);
} }
} }

View File

@ -1,301 +1,301 @@
package test.java.com.graywolf336.jail.util; package test.java.com.graywolf336.jail.util;
import org.bukkit.Material;
import org.bukkit.entity.HumanEntity;
import org.bukkit.event.inventory.InventoryType;
import org.bukkit.inventory.ItemStack;
import org.bukkit.inventory.PlayerInventory;
import java.util.HashMap; import java.util.HashMap;
import java.util.LinkedHashMap; import java.util.LinkedHashMap;
import java.util.List; import java.util.List;
import java.util.ListIterator; import java.util.ListIterator;
import java.util.Map; import java.util.Map;
import org.bukkit.Material;
import org.bukkit.entity.HumanEntity;
import org.bukkit.event.inventory.InventoryType;
import org.bukkit.inventory.ItemStack;
import org.bukkit.inventory.PlayerInventory;
public class MockPlayerInventory implements PlayerInventory { public class MockPlayerInventory implements PlayerInventory {
private int armorSize = 4, inventorySize = 36; private int armorSize = 4, inventorySize = 36;
ItemStack[] armorContents = new ItemStack[armorSize]; ItemStack[] armorContents = new ItemStack[armorSize];
ItemStack[] inventoryContents = new ItemStack[inventorySize]; ItemStack[] inventoryContents = new ItemStack[inventorySize];
@Override @Override
public ItemStack[] getArmorContents() { public ItemStack[] getArmorContents() {
return armorContents; return armorContents;
} }
@Override @Override
public ItemStack getHelmet() { public ItemStack getHelmet() {
return armorContents[0]; return armorContents[0];
} }
@Override @Override
public ItemStack getChestplate() { public ItemStack getChestplate() {
return armorContents[1]; return armorContents[1];
} }
@Override @Override
public ItemStack getLeggings() { public ItemStack getLeggings() {
return armorContents[2]; return armorContents[2];
} }
@Override @Override
public ItemStack getBoots() { public ItemStack getBoots() {
return armorContents[3]; return armorContents[3];
} }
@Override @Override
public void setArmorContents(ItemStack[] itemStacks) { public void setArmorContents(ItemStack[] itemStacks) {
this.armorContents = itemStacks; this.armorContents = itemStacks;
} }
@Override @Override
public void setHelmet(ItemStack itemStack) { public void setHelmet(ItemStack itemStack) {
this.armorContents[0] = itemStack; this.armorContents[0] = itemStack;
} }
@Override @Override
public void setChestplate(ItemStack itemStack) { public void setChestplate(ItemStack itemStack) {
this.armorContents[1] = itemStack; this.armorContents[1] = itemStack;
} }
@Override @Override
public void setLeggings(ItemStack itemStack) { public void setLeggings(ItemStack itemStack) {
this.armorContents[2] = itemStack; this.armorContents[2] = itemStack;
} }
@Override @Override
public void setBoots(ItemStack itemStack) { public void setBoots(ItemStack itemStack) {
this.armorContents[3] = itemStack; this.armorContents[3] = itemStack;
} }
@Override @Override
public ItemStack getItemInHand() { public ItemStack getItemInHand() {
return null; return null;
} }
@Override @Override
public void setItemInHand(ItemStack itemStack) { public void setItemInHand(ItemStack itemStack) {
} }
@Override @Override
public int getHeldItemSlot() { public int getHeldItemSlot() {
return 0; return 0;
} }
@Override @Override
public int clear(int i, int i2) { public int clear(int i, int i2) {
return 0; return 0;
} }
@Override @Override
public HumanEntity getHolder() { public HumanEntity getHolder() {
return null; return null;
} }
@Override @Override
public int getSize() { public int getSize() {
return inventoryContents.length + armorContents.length; return inventoryContents.length + armorContents.length;
} }
@Override @Override
public String getName() { public String getName() {
return null; return null;
} }
@Override @Override
public ItemStack getItem(int i) { public ItemStack getItem(int i) {
if (i >= 0 && i < inventorySize) { if (i >= 0 && i < inventorySize) {
return inventoryContents[i]; return inventoryContents[i];
} else if (i >= inventorySize } else if (i >= inventorySize
&& i < inventorySize + armorSize) { && i < inventorySize + armorSize) {
return armorContents[i - inventorySize]; return armorContents[i - inventorySize];
} else { } else {
throw new ArrayIndexOutOfBoundsException(); throw new ArrayIndexOutOfBoundsException();
} }
} }
@Override @Override
public void setItem(int i, ItemStack itemStack) { public void setItem(int i, ItemStack itemStack) {
if (i >= 0 && i < inventorySize) { if (i >= 0 && i < inventorySize) {
inventoryContents[i] = itemStack; inventoryContents[i] = itemStack;
} else if (i >= inventorySize } else if (i >= inventorySize
&& i < inventorySize + armorSize) { && i < inventorySize + armorSize) {
armorContents[i - inventorySize] = itemStack; armorContents[i - inventorySize] = itemStack;
} else { } else {
throw new ArrayIndexOutOfBoundsException(); throw new ArrayIndexOutOfBoundsException();
} }
} }
@Override @Override
public HashMap<Integer, ItemStack> addItem(ItemStack... itemStacks) { public HashMap<Integer, ItemStack> addItem(ItemStack... itemStacks) {
return null; return null;
} }
@Override @Override
public HashMap<Integer, ItemStack> removeItem(ItemStack... itemStacks) { public HashMap<Integer, ItemStack> removeItem(ItemStack... itemStacks) {
return null; return null;
} }
@Override @Override
public ItemStack[] getContents() { public ItemStack[] getContents() {
return this.inventoryContents; return this.inventoryContents;
} }
@Override @Override
public void setContents(ItemStack[] itemStacks) { public void setContents(ItemStack[] itemStacks) {
this.inventoryContents = itemStacks; this.inventoryContents = itemStacks;
} }
@Override @Override
public boolean contains(int i) { public boolean contains(int i) {
return false; return false;
} }
@Override @Override
public boolean contains(Material material) { public boolean contains(Material material) {
return false; return false;
} }
@Override @Override
public boolean contains(ItemStack itemStack) { public boolean contains(ItemStack itemStack) {
return false; return false;
} }
@Override @Override
public boolean contains(int i, int i1) { public boolean contains(int i, int i1) {
return false; return false;
} }
@Override @Override
public boolean contains(Material material, int i) { public boolean contains(Material material, int i) {
return false; return false;
} }
@Override @Override
public boolean contains(ItemStack itemStack, int i) { public boolean contains(ItemStack itemStack, int i) {
return false; return false;
} }
@Override @Override
public HashMap<Integer, ? extends ItemStack> all(int i) { public HashMap<Integer, ? extends ItemStack> all(int i) {
return null; return null;
} }
@Override @Override
public HashMap<Integer, ? extends ItemStack> all(Material material) { public HashMap<Integer, ? extends ItemStack> all(Material material) {
return null; return null;
} }
@Override @Override
public HashMap<Integer, ? extends ItemStack> all(ItemStack itemStack) { public HashMap<Integer, ? extends ItemStack> all(ItemStack itemStack) {
return null; return null;
} }
@Override @Override
public int first(int i) { public int first(int i) {
return 0; return 0;
} }
@Override @Override
public int first(Material material) { public int first(Material material) {
return 0; return 0;
} }
@Override @Override
public int first(ItemStack itemStack) { public int first(ItemStack itemStack) {
return 0; return 0;
} }
@Override @Override
public int firstEmpty() { public int firstEmpty() {
return 0; return 0;
} }
@Override @Override
public void remove(int i) { public void remove(int i) {
} }
@Override @Override
public void remove(Material material) { public void remove(Material material) {
} }
@Override @Override
public void remove(ItemStack itemStack) { public void remove(ItemStack itemStack) {
} }
@Override @Override
public void clear(int i) { public void clear(int i) {
inventoryContents[i] = null; inventoryContents[i] = null;
} }
@Override @Override
public void clear() { public void clear() {
} }
@Override @Override
public List<HumanEntity> getViewers() { public List<HumanEntity> getViewers() {
return null; return null;
} }
@Override @Override
public String getTitle() { public String getTitle() {
return null; return null;
} }
@Override @Override
public InventoryType getType() { public InventoryType getType() {
return null; return null;
} }
@Override @Override
public ListIterator<ItemStack> iterator() { public ListIterator<ItemStack> iterator() {
return null; return null;
} }
@Override @Override
public int getMaxStackSize() { public int getMaxStackSize() {
return 0; return 0;
} }
@Override @Override
public void setMaxStackSize(int i) { public void setMaxStackSize(int i) {
} }
@Override @Override
public ListIterator<ItemStack> iterator(int i) { public ListIterator<ItemStack> iterator(int i) {
return null; return null;
} }
@Override @Override
public boolean containsAtLeast(final ItemStack itemStack, final int i) { public boolean containsAtLeast(final ItemStack itemStack, final int i) {
return false; return false;
} }
@SuppressWarnings("deprecation") @SuppressWarnings("deprecation")
private static Map<String, Object> makeMap(ItemStack[] items) { private static Map<String, Object> makeMap(ItemStack[] items) {
Map<String, Object> contents = new LinkedHashMap<String, Object>( Map<String, Object> contents = new LinkedHashMap<String, Object>(
items.length); items.length);
for (int i = 0; i < items.length; i++) { for (int i = 0; i < items.length; i++) {
if (items[i] != null && items[i].getTypeId() != 0) { if (items[i] != null && items[i].getTypeId() != 0) {
contents.put(Integer.valueOf(i).toString(), items[i]); contents.put(Integer.valueOf(i).toString(), items[i]);
} }
} }
return contents; return contents;
} }
public String toString() { public String toString() {
return "{\"inventoryContents\":" + makeMap(getContents()) return "{\"inventoryContents\":" + makeMap(getContents())
+ ",\"armorContents\":" + makeMap(getArmorContents()) + "}"; + ",\"armorContents\":" + makeMap(getArmorContents()) + "}";
} }
@Override @Override
public void setHeldItemSlot(int slot) { public void setHeldItemSlot(int slot) {
} }
} }

View File

@ -1,5 +1,11 @@
package test.java.com.graywolf336.jail.util; package test.java.com.graywolf336.jail.util;
import static org.mockito.Matchers.any;
import static org.mockito.Matchers.anyBoolean;
import static org.mockito.Mockito.doAnswer;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.when;
import java.io.File; import java.io.File;
import java.util.ArrayList; import java.util.ArrayList;
import java.util.HashMap; import java.util.HashMap;
@ -18,8 +24,6 @@ import org.bukkit.generator.ChunkGenerator;
import org.mockito.invocation.InvocationOnMock; import org.mockito.invocation.InvocationOnMock;
import org.mockito.stubbing.Answer; import org.mockito.stubbing.Answer;
import static org.mockito.Mockito.*;
public class MockWorldFactory { public class MockWorldFactory {
private static final Map<String, World> createdWorlds = new HashMap<String, World>(); private static final Map<String, World> createdWorlds = new HashMap<String, World>();
@ -97,7 +101,7 @@ public class MockWorldFactory {
}); });
when(mockWorld.getBlockAt(any(Location.class))).thenAnswer(new Answer<Block>() { when(mockWorld.getBlockAt(any(Location.class))).thenAnswer(new Answer<Block>() {
@SuppressWarnings("deprecation") @SuppressWarnings("deprecation")
public Block answer(InvocationOnMock invocation) throws Throwable { public Block answer(InvocationOnMock invocation) throws Throwable {
Location loc; Location loc;
try { try {
loc = (Location) invocation.getArguments()[0]; loc = (Location) invocation.getArguments()[0];
@ -142,7 +146,7 @@ public class MockWorldFactory {
}); });
when(mockWorld.getBlockAt(any(Location.class))).thenAnswer(new Answer<Block>() { when(mockWorld.getBlockAt(any(Location.class))).thenAnswer(new Answer<Block>() {
@SuppressWarnings("deprecation") @SuppressWarnings("deprecation")
public Block answer(InvocationOnMock invocation) throws Throwable { public Block answer(InvocationOnMock invocation) throws Throwable {
Location loc; Location loc;
try { try {
loc = (Location) invocation.getArguments()[0]; loc = (Location) invocation.getArguments()[0];

View File

@ -1,5 +1,16 @@
package test.java.com.graywolf336.jail.util; package test.java.com.graywolf336.jail.util;
import static org.mockito.Matchers.any;
import static org.mockito.Matchers.anyBoolean;
import static org.mockito.Matchers.anyLong;
import static org.mockito.Matchers.anyString;
import static org.mockito.Mockito.doAnswer;
import static org.mockito.Mockito.doReturn;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.when;
import static org.powermock.api.support.membermodification.MemberMatcher.constructor;
import static org.powermock.api.support.membermodification.MemberModifier.suppress;
import java.io.File; import java.io.File;
import java.lang.reflect.Field; import java.lang.reflect.Field;
import java.util.ArrayList; import java.util.ArrayList;
@ -12,9 +23,9 @@ import org.bukkit.Bukkit;
import org.bukkit.ChatColor; import org.bukkit.ChatColor;
import org.bukkit.Server; import org.bukkit.Server;
import org.bukkit.World; import org.bukkit.World;
import org.bukkit.WorldType;
import org.bukkit.World.Environment; import org.bukkit.World.Environment;
import org.bukkit.WorldCreator; import org.bukkit.WorldCreator;
import org.bukkit.WorldType;
import org.bukkit.command.CommandSender; import org.bukkit.command.CommandSender;
import org.bukkit.command.ConsoleCommandSender; import org.bukkit.command.ConsoleCommandSender;
import org.bukkit.craftbukkit.v1_7_R3.inventory.CraftItemFactory; import org.bukkit.craftbukkit.v1_7_R3.inventory.CraftItemFactory;
@ -26,90 +37,82 @@ import org.bukkit.plugin.PluginLogger;
import org.bukkit.plugin.PluginManager; import org.bukkit.plugin.PluginManager;
import org.bukkit.plugin.java.JavaPlugin; import org.bukkit.plugin.java.JavaPlugin;
import org.bukkit.scheduler.BukkitScheduler; import org.bukkit.scheduler.BukkitScheduler;
import org.junit.Assert; import org.junit.Assert;
import org.mockito.Matchers; import org.mockito.Matchers;
import org.mockito.invocation.InvocationOnMock; import org.mockito.invocation.InvocationOnMock;
import org.mockito.stubbing.Answer; import org.mockito.stubbing.Answer;
import org.powermock.api.mockito.PowerMockito; import org.powermock.api.mockito.PowerMockito;
import org.powermock.core.MockGateway; import org.powermock.core.MockGateway;
import org.powermock.core.classloader.annotations.PrepareForTest; import org.powermock.core.classloader.annotations.PrepareForTest;
import static org.mockito.Matchers.anyString;
import static org.mockito.Mockito.*;
import static org.powermock.api.support.membermodification.MemberMatcher.constructor;
import static org.powermock.api.support.membermodification.MemberModifier.suppress;
import com.graywolf336.jail.JailMain; import com.graywolf336.jail.JailMain;
@PrepareForTest({ CraftItemFactory.class }) @PrepareForTest({ CraftItemFactory.class })
public class TestInstanceCreator { public class TestInstanceCreator {
private JailMain main; private JailMain main;
private Server mockServer; private Server mockServer;
private Player mockPlayer; private Player mockPlayer;
private CommandSender mockSender, mockPlayerSender; private CommandSender mockSender, mockPlayerSender;
private ConsoleCommandSender consoleSender; private ConsoleCommandSender consoleSender;
public static final File serverDirectory = new File("bin" + File.separator + "test" + File.separator + "server"); public static final File serverDirectory = new File("bin" + File.separator + "test" + File.separator + "server");
public static final File worldsDirectory = new File("bin" + File.separator + "test" + File.separator + "server"); public static final File worldsDirectory = new File("bin" + File.separator + "test" + File.separator + "server");
public static final File pluginDirectory = new File(serverDirectory + File.separator + "plugins" + File.separator + "JailTest"); public static final File pluginDirectory = new File(serverDirectory + File.separator + "plugins" + File.separator + "JailTest");
public boolean setup() { public boolean setup() {
try { try {
pluginDirectory.mkdirs(); pluginDirectory.mkdirs();
Assert.assertTrue(pluginDirectory.exists()); Assert.assertTrue(pluginDirectory.exists());
MockGateway.MOCK_STANDARD_METHODS = false; MockGateway.MOCK_STANDARD_METHODS = false;
// Initialize the Mock server. // Initialize the Mock server.
mockServer = mock(Server.class); mockServer = mock(Server.class);
when(mockServer.getName()).thenReturn("TestBukkit"); when(mockServer.getName()).thenReturn("TestBukkit");
when(mockServer.getVersion()).thenReturn("Jail-Testing-0.0.1"); when(mockServer.getVersion()).thenReturn("Jail-Testing-0.0.1");
when(mockServer.getBukkitVersion()).thenReturn("0.0.1"); when(mockServer.getBukkitVersion()).thenReturn("0.0.1");
Logger.getLogger("Minecraft").setParent(Util.logger); Logger.getLogger("Minecraft").setParent(Util.logger);
when(mockServer.getLogger()).thenReturn(Util.logger); when(mockServer.getLogger()).thenReturn(Util.logger);
when(mockServer.getWorldContainer()).thenReturn(worldsDirectory); when(mockServer.getWorldContainer()).thenReturn(worldsDirectory);
when(mockServer.getItemFactory()).thenReturn(CraftItemFactory.instance()); when(mockServer.getItemFactory()).thenReturn(CraftItemFactory.instance());
MockWorldFactory.makeNewMockWorld("world", Environment.NORMAL, WorldType.NORMAL); MockWorldFactory.makeNewMockWorld("world", Environment.NORMAL, WorldType.NORMAL);
suppress(constructor(JailMain.class)); suppress(constructor(JailMain.class));
main = PowerMockito.spy(new JailMain()); main = PowerMockito.spy(new JailMain());
PluginDescriptionFile pdf = PowerMockito.spy(new PluginDescriptionFile("Jail", "3.0.0-Test", "com.graywolf336.jail.JailMain")); PluginDescriptionFile pdf = PowerMockito.spy(new PluginDescriptionFile("Jail", "3.0.0-Test", "com.graywolf336.jail.JailMain"));
when(pdf.getPrefix()).thenReturn("Jail"); when(pdf.getPrefix()).thenReturn("Jail");
List<String> authors = new ArrayList<String>(); List<String> authors = new ArrayList<String>();
authors.add("matejdro"); authors.add("matejdro");
authors.add("multidude"); authors.add("multidude");
authors.add("graywolf336"); authors.add("graywolf336");
when(pdf.getAuthors()).thenReturn(authors); when(pdf.getAuthors()).thenReturn(authors);
when(main.getDescription()).thenReturn(pdf); when(main.getDescription()).thenReturn(pdf);
when(main.getDataFolder()).thenReturn(pluginDirectory); when(main.getDataFolder()).thenReturn(pluginDirectory);
when(main.isEnabled()).thenReturn(true); when(main.isEnabled()).thenReturn(true);
when(main.getLogger()).thenReturn(Util.logger); when(main.getLogger()).thenReturn(Util.logger);
when(main.getServer()).thenReturn(mockServer); when(main.getServer()).thenReturn(mockServer);
Field configFile = JavaPlugin.class.getDeclaredField("configFile"); Field configFile = JavaPlugin.class.getDeclaredField("configFile");
configFile.setAccessible(true); configFile.setAccessible(true);
configFile.set(main, new File(pluginDirectory, "config.yml")); configFile.set(main, new File(pluginDirectory, "config.yml"));
Field logger = JavaPlugin.class.getDeclaredField("logger"); Field logger = JavaPlugin.class.getDeclaredField("logger");
logger.setAccessible(true); logger.setAccessible(true);
logger.set(main, new PluginLogger(main)); logger.set(main, new PluginLogger(main));
doReturn(getClass().getClassLoader().getResourceAsStream("config.yml")).when(main).getResource("config.yml"); doReturn(getClass().getClassLoader().getResourceAsStream("config.yml")).when(main).getResource("config.yml");
doReturn(getClass().getClassLoader().getResourceAsStream("en.yml")).when(main).getResource("en.yml"); doReturn(getClass().getClassLoader().getResourceAsStream("en.yml")).when(main).getResource("en.yml");
// Add Jail to the list of loaded plugins // Add Jail to the list of loaded plugins
JavaPlugin[] plugins = new JavaPlugin[] { main }; JavaPlugin[] plugins = new JavaPlugin[] { main };
// Mock the Plugin Manager // Mock the Plugin Manager
PluginManager mockPluginManager = PowerMockito.mock(PluginManager.class); PluginManager mockPluginManager = PowerMockito.mock(PluginManager.class);
when(mockPluginManager.getPlugins()).thenReturn(plugins); when(mockPluginManager.getPlugins()).thenReturn(plugins);
when(mockPluginManager.getPlugin("Jail")).thenReturn(main); when(mockPluginManager.getPlugin("Jail")).thenReturn(main);
when(mockPluginManager.getPermission(anyString())).thenReturn(null); when(mockPluginManager.getPermission(anyString())).thenReturn(null);
// Give the server some worlds // Give the server some worlds
when(mockServer.getWorld(anyString())).thenAnswer(new Answer<World>() { when(mockServer.getWorld(anyString())).thenAnswer(new Answer<World>() {
@ -142,25 +145,25 @@ public class TestInstanceCreator {
} }
}); });
when(mockServer.getPluginManager()).thenReturn(mockPluginManager); when(mockServer.getPluginManager()).thenReturn(mockPluginManager);
when(mockServer.createWorld(Matchers.isA(WorldCreator.class))).thenAnswer( when(mockServer.createWorld(Matchers.isA(WorldCreator.class))).thenAnswer(
new Answer<World>() { new Answer<World>() {
public World answer(InvocationOnMock invocation) throws Throwable { public World answer(InvocationOnMock invocation) throws Throwable {
WorldCreator arg; WorldCreator arg;
try { try {
arg = (WorldCreator) invocation.getArguments()[0]; arg = (WorldCreator) invocation.getArguments()[0];
} catch (Exception e) { } catch (Exception e) {
return null; return null;
} }
// Add special case for creating null worlds. // Add special case for creating null worlds.
// Not sure I like doing it this way, but this is a special case // Not sure I like doing it this way, but this is a special case
if (arg.name().equalsIgnoreCase("nullworld")) { if (arg.name().equalsIgnoreCase("nullworld")) {
return MockWorldFactory.makeNewNullMockWorld(arg.name(), arg.environment(), arg.type()); return MockWorldFactory.makeNewNullMockWorld(arg.name(), arg.environment(), arg.type());
} }
return MockWorldFactory.makeNewMockWorld(arg.name(), arg.environment(), arg.type()); return MockWorldFactory.makeNewMockWorld(arg.name(), arg.environment(), arg.type());
} }
}); });
when(mockServer.unloadWorld(anyString(), anyBoolean())).thenReturn(true); when(mockServer.unloadWorld(anyString(), anyBoolean())).thenReturn(true);
@ -204,144 +207,144 @@ public class TestInstanceCreator {
}}); }});
when(mockServer.getScheduler()).thenReturn(mockScheduler); when(mockServer.getScheduler()).thenReturn(mockScheduler);
// Set server // Set server
Field serverField = JavaPlugin.class.getDeclaredField("server"); Field serverField = JavaPlugin.class.getDeclaredField("server");
serverField.setAccessible(true); serverField.setAccessible(true);
serverField.set(main, mockServer); serverField.set(main, mockServer);
// Init our command sender // Init our command sender
final Logger consoleSenderLogger = Logger.getLogger("ConsoleCommandSender"); final Logger consoleSenderLogger = Logger.getLogger("ConsoleCommandSender");
consoleSenderLogger.setParent(Util.logger); consoleSenderLogger.setParent(Util.logger);
consoleSender = mock(ConsoleCommandSender.class); consoleSender = mock(ConsoleCommandSender.class);
doAnswer(new Answer<Void>() { doAnswer(new Answer<Void>() {
public Void answer(InvocationOnMock invocation) throws Throwable { public Void answer(InvocationOnMock invocation) throws Throwable {
consoleSenderLogger.info(ChatColor.stripColor((String) invocation.getArguments()[0])); consoleSenderLogger.info(ChatColor.stripColor((String) invocation.getArguments()[0]));
return null; return null;
} }
}).when(consoleSender).sendMessage(anyString()); }).when(consoleSender).sendMessage(anyString());
when(consoleSender.getServer()).thenReturn(mockServer); when(consoleSender.getServer()).thenReturn(mockServer);
when(consoleSender.getName()).thenReturn("MockCommandSender"); when(consoleSender.getName()).thenReturn("MockCommandSender");
when(consoleSender.isPermissionSet(anyString())).thenReturn(true); when(consoleSender.isPermissionSet(anyString())).thenReturn(true);
when(consoleSender.isPermissionSet(Matchers.isA(Permission.class))).thenReturn(true); when(consoleSender.isPermissionSet(Matchers.isA(Permission.class))).thenReturn(true);
when(consoleSender.hasPermission(anyString())).thenReturn(true); when(consoleSender.hasPermission(anyString())).thenReturn(true);
when(consoleSender.hasPermission(Matchers.isA(Permission.class))).thenReturn(true); when(consoleSender.hasPermission(Matchers.isA(Permission.class))).thenReturn(true);
when(consoleSender.addAttachment(main)).thenReturn(null); when(consoleSender.addAttachment(main)).thenReturn(null);
when(consoleSender.isOp()).thenReturn(true); when(consoleSender.isOp()).thenReturn(true);
when(mockServer.getConsoleSender()).thenReturn(consoleSender); when(mockServer.getConsoleSender()).thenReturn(consoleSender);
// Init our command sender // Init our command sender
final Logger commandSenderLogger = Logger.getLogger("CommandSender"); final Logger commandSenderLogger = Logger.getLogger("CommandSender");
commandSenderLogger.setParent(Util.logger); commandSenderLogger.setParent(Util.logger);
mockSender = mock(CommandSender.class); mockSender = mock(CommandSender.class);
doAnswer(new Answer<Void>() { doAnswer(new Answer<Void>() {
public Void answer(InvocationOnMock invocation) throws Throwable { public Void answer(InvocationOnMock invocation) throws Throwable {
commandSenderLogger.info(ChatColor.stripColor((String) invocation.getArguments()[0])); commandSenderLogger.info(ChatColor.stripColor((String) invocation.getArguments()[0]));
return null; return null;
} }
}).when(mockSender).sendMessage(anyString()); }).when(mockSender).sendMessage(anyString());
when(mockSender.getServer()).thenReturn(mockServer); when(mockSender.getServer()).thenReturn(mockServer);
when(mockSender.getName()).thenReturn("MockCommandSender"); when(mockSender.getName()).thenReturn("MockCommandSender");
when(mockSender.isPermissionSet(anyString())).thenReturn(true); when(mockSender.isPermissionSet(anyString())).thenReturn(true);
when(mockSender.isPermissionSet(Matchers.isA(Permission.class))).thenReturn(true); when(mockSender.isPermissionSet(Matchers.isA(Permission.class))).thenReturn(true);
when(mockSender.hasPermission(anyString())).thenReturn(true); when(mockSender.hasPermission(anyString())).thenReturn(true);
when(mockSender.hasPermission(Matchers.isA(Permission.class))).thenReturn(true); when(mockSender.hasPermission(Matchers.isA(Permission.class))).thenReturn(true);
when(mockSender.addAttachment(main)).thenReturn(null); when(mockSender.addAttachment(main)).thenReturn(null);
when(mockSender.isOp()).thenReturn(true); when(mockSender.isOp()).thenReturn(true);
// Init our player, who is op and who has all permissions (with name of graywolf336) // Init our player, who is op and who has all permissions (with name of graywolf336)
mockPlayer = mock(Player.class); mockPlayer = mock(Player.class);
when(mockPlayer.getUniqueId()).thenReturn(UUID.fromString("062c14ba-4c47-4757-911b-bbf9a60dab7b")); when(mockPlayer.getUniqueId()).thenReturn(UUID.fromString("062c14ba-4c47-4757-911b-bbf9a60dab7b"));
when(mockPlayer.getName()).thenReturn("graywolf336"); when(mockPlayer.getName()).thenReturn("graywolf336");
when(mockPlayer.getDisplayName()).thenReturn("TheGrayWolf"); when(mockPlayer.getDisplayName()).thenReturn("TheGrayWolf");
when(mockPlayer.isPermissionSet(anyString())).thenReturn(true); when(mockPlayer.isPermissionSet(anyString())).thenReturn(true);
when(mockPlayer.isPermissionSet(Matchers.isA(Permission.class))).thenReturn(true); when(mockPlayer.isPermissionSet(Matchers.isA(Permission.class))).thenReturn(true);
when(mockPlayer.hasPermission(anyString())).thenReturn(true); when(mockPlayer.hasPermission(anyString())).thenReturn(true);
when(mockPlayer.hasPermission(Matchers.isA(Permission.class))).thenReturn(true); when(mockPlayer.hasPermission(Matchers.isA(Permission.class))).thenReturn(true);
when(mockPlayer.isOp()).thenReturn(true); when(mockPlayer.isOp()).thenReturn(true);
when(mockPlayer.getInventory()).thenReturn(new MockPlayerInventory()); when(mockPlayer.getInventory()).thenReturn(new MockPlayerInventory());
// Init our second command sender, but this time is an instance of a player // Init our second command sender, but this time is an instance of a player
mockPlayerSender = (CommandSender) mockPlayer; mockPlayerSender = mockPlayer;
when(mockPlayerSender.getServer()).thenReturn(mockServer); when(mockPlayerSender.getServer()).thenReturn(mockServer);
when(mockPlayerSender.getName()).thenReturn("graywolf336"); when(mockPlayerSender.getName()).thenReturn("graywolf336");
when(mockPlayerSender.isPermissionSet(anyString())).thenReturn(true); when(mockPlayerSender.isPermissionSet(anyString())).thenReturn(true);
when(mockPlayerSender.isPermissionSet(Matchers.isA(Permission.class))).thenReturn(true); when(mockPlayerSender.isPermissionSet(Matchers.isA(Permission.class))).thenReturn(true);
when(mockPlayerSender.hasPermission(anyString())).thenReturn(true); when(mockPlayerSender.hasPermission(anyString())).thenReturn(true);
when(mockPlayerSender.hasPermission(Matchers.isA(Permission.class))).thenReturn(true); when(mockPlayerSender.hasPermission(Matchers.isA(Permission.class))).thenReturn(true);
when(mockPlayerSender.addAttachment(main)).thenReturn(null); when(mockPlayerSender.addAttachment(main)).thenReturn(null);
when(mockPlayerSender.isOp()).thenReturn(true); when(mockPlayerSender.isOp()).thenReturn(true);
Bukkit.setServer(mockServer); Bukkit.setServer(mockServer);
// Load Jail // Load Jail
main.onLoad(); main.onLoad();
// Enable it and turn on debugging // Enable it and turn on debugging
main.onEnable(); main.onEnable();
main.setDebugging(true); main.setDebugging(true);
return true; return true;
} catch (Exception e) { } catch (Exception e) {
e.printStackTrace(); e.printStackTrace();
} }
return false; return false;
} }
public boolean tearDown() { public boolean tearDown() {
try { try {
Field serverField = Bukkit.class.getDeclaredField("server"); Field serverField = Bukkit.class.getDeclaredField("server");
serverField.setAccessible(true); serverField.setAccessible(true);
serverField.set(Class.forName("org.bukkit.Bukkit"), null); serverField.set(Class.forName("org.bukkit.Bukkit"), null);
} catch (Exception e) { } catch (Exception e) {
Util.log(Level.SEVERE, "Error while trying to unregister the server from Bukkit. Has Bukkit changed?"); Util.log(Level.SEVERE, "Error while trying to unregister the server from Bukkit. Has Bukkit changed?");
e.printStackTrace(); e.printStackTrace();
Assert.fail(e.getMessage()); Assert.fail(e.getMessage());
return false; return false;
} }
main.onDisable(); main.onDisable();
MockWorldFactory.clearWorlds(); MockWorldFactory.clearWorlds();
deleteFolder(pluginDirectory); deleteFolder(pluginDirectory);
deleteFolder(worldsDirectory); deleteFolder(worldsDirectory);
deleteFolder(serverDirectory); deleteFolder(serverDirectory);
return true; return true;
} }
public JailMain getMain() { public JailMain getMain() {
return this.main; return this.main;
} }
public Server getServer() { public Server getServer() {
return this.mockServer; return this.mockServer;
} }
public CommandSender getCommandSender() { public CommandSender getCommandSender() {
return this.mockSender; return this.mockSender;
} }
public Player getPlayer() { public Player getPlayer() {
return this.mockPlayer; return this.mockPlayer;
} }
public CommandSender getPlayerCommandSender() { public CommandSender getPlayerCommandSender() {
return this.mockPlayerSender; return this.mockPlayerSender;
} }
private void deleteFolder(File folder) { private void deleteFolder(File folder) {
File[] files = folder.listFiles(); File[] files = folder.listFiles();
if(files != null) { if(files != null) {
for(File f: files) { for(File f: files) {
if(f.isDirectory()) { if(f.isDirectory()) {
deleteFolder(f); deleteFolder(f);
}else { }else {
f.delete(); f.delete();
} }
} }
} }
folder.delete(); folder.delete();
} }
} }

View File

@ -15,8 +15,8 @@ public class TestLogFormatter extends Formatter {
StringBuilder ret = new StringBuilder(); StringBuilder ret = new StringBuilder();
ret.append("[").append(df.format(record.getMillis())).append("] [") ret.append("[").append(df.format(record.getMillis())).append("] [")
.append(record.getLoggerName()).append("] [") .append(record.getLoggerName()).append("] [")
.append(record.getLevel().getLocalizedName()).append("] "); .append(record.getLevel().getLocalizedName()).append("] ");
ret.append(record.getMessage()); ret.append(record.getMessage());
ret.append('\n'); ret.append('\n');