Improves formatting, removes broken comments and updates version to 1.17

This commit is contained in:
Kristian Knarvik 2021-10-21 15:13:55 +02:00
parent 820842932a
commit d5296c4314
110 changed files with 4038 additions and 5562 deletions

141
pom.xml
View File

@ -10,22 +10,6 @@
<description>Ban too harsh? Mute too weak? Kicking not enough? Jail them!</description>
<url>http://dev.bukkit.org/bukkit-plugins/jail/</url>
<ciManagement>
<url>https://ci.craftyn.com/job/Jail/</url>
<system>jenkins</system>
</ciManagement>
<issueManagement>
<url>https://github.com/graywolf336/Jail/issues</url>
<system>GitHub</system>
</issueManagement>
<scm>
<url>https://github.com/graywolf336/Jail</url>
<connection>scm:git:git://github.com/graywolf336/Jail.git</connection>
<developerConnection>scm:git:git:@github.com/graywolf336/Jail.git</developerConnection>
</scm>
<properties>
<project.build.number>0</project.build.number>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
@ -48,40 +32,31 @@
</repository>
<repository>
<id>gray-snapshot</id>
<url>https://repo.craftyn.com/repository/graywolf336-snapshots/</url>
<id>jitpack.io</id>
<url>https://jitpack.io</url>
</repository>
</repositories>
<dependencies>
<dependency>
<groupId>org.bukkit</groupId>
<artifactId>bukkit</artifactId>
<version>1.13.2-R0.1-SNAPSHOT</version>
<type>jar</type>
</dependency>
<dependency>
<groupId>org.bukkit</groupId>
<artifactId>craftbukkit</artifactId>
<version>1.13.2-R0.1-SNAPSHOT</version>
<type>jar</type>
<groupId>org.spigotmc</groupId>
<artifactId>spigot-api</artifactId>
<version>1.17.1-R0.1-SNAPSHOT</version>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>com.sk89q.worldedit</groupId>
<artifactId>worldedit-bukkit</artifactId>
<version>7.0.0-SNAPSHOT</version>
<version>7.2.6</version>
<scope>provided</scope>
<optional>true</optional>
</dependency>
<dependency>
<groupId>net.milkbowl.vault</groupId>
<artifactId>Vault</artifactId>
<version>1.5.6</version>
<type>jar</type>
<groupId>com.github.MilkBowl</groupId>
<artifactId>VaultAPI</artifactId>
<version>1.7</version>
<scope>provided</scope>
<optional>true</optional>
</dependency>
@ -96,31 +71,7 @@
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.13.1</version>
</dependency>
<dependency>
<groupId>org.powermock</groupId>
<artifactId>powermock-module-junit4</artifactId>
<version>1.5.5</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.powermock</groupId>
<artifactId>powermock-api-easymock</artifactId>
<version>1.5.5</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.powermock</groupId>
<artifactId>powermock-api-mockito</artifactId>
<version>1.5.5</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.easymock</groupId>
<artifactId>easymock</artifactId>
<version>3.2</version>
<scope>test</scope>
<version>4.13.2</version>
</dependency>
<dependency>
<groupId>com.carrotsearch</groupId>
@ -128,6 +79,12 @@
<version>0.7.2</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.spigotmc</groupId>
<artifactId>spigot</artifactId>
<version>1.17.1-R0.1-SNAPSHOT</version>
<scope>test</scope>
</dependency>
<!-- End of Test Dependencies -->
</dependencies>
@ -143,26 +100,6 @@
<project.build.number>${env.BUILD_NUMBER}</project.build.number>
</properties>
</profile>
<profile>
<id>doclint-java8-disable</id>
<activation>
<jdk>[1.8,)</jdk>
</activation>
<build>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-javadoc-plugin</artifactId>
<version>2.10.3</version>
<configuration>
<additionalparam>-Xdoclint:none</additionalparam>
</configuration>
</plugin>
</plugins>
</build>
</profile>
</profiles>
<build>
@ -201,10 +138,10 @@
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId>
<version>2.3.2</version>
<version>3.8.1</version>
<configuration>
<source>1.8</source>
<target>1.8</target>
<source>16</source>
<target>16</target>
</configuration>
</plugin>
@ -236,7 +173,7 @@
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-jar-plugin</artifactId>
<version>2.3.1</version>
<version>3.2.0</version>
<configuration>
<archive>
<manifestEntries />
@ -247,7 +184,7 @@
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-shade-plugin</artifactId>
<version>2.2</version>
<version>3.2.4</version>
<executions>
<execution>
<phase>package</phase>
@ -294,42 +231,6 @@
</execution>
</executions>
</plugin>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-surefire-plugin</artifactId>
<version>2.11</version>
<configuration>
<!-- Sets the VM argument line used when unit tests are run. -->
<argLine>${surefireArgLine}</argLine>
<parallel>methods</parallel>
<threadCount>10</threadCount>
<excludes>
<exclude>**/TestCommandSender.java</exclude>
<exclude>**/TestInstanceCreator.java</exclude>
</excludes>
</configuration>
<dependencies>
<dependency>
<groupId>org.apache.maven.surefire</groupId>
<artifactId>surefire-junit47</artifactId>
<version>2.11</version>
</dependency>
</dependencies>
</plugin>
</plugins>
</build>
<distributionManagement>
<repository>
<id>repo-release</id>
<name>Jail Releases</name>
<url>https://repo.craftyn.com/repository/internal/</url>
</repository>
<snapshotRepository>
<id>repo-snapshot</id>
<name>Jail Snapshots</name>
<url>https://repo.craftyn.com/repository/snapshots/</url>
</snapshotRepository>
</distributionManagement>
</project>

View File

@ -1,44 +1,46 @@
package com.graywolf336.jail;
import org.bukkit.Location;
import java.util.HashMap;
import java.util.UUID;
import org.bukkit.Location;
/**
* Manages the handcuffing of players.
*
*
* <p>&nbsp;</p>
*
* <p>
* Provides easy to use methods for adding,
* removing, and checking if someone has
* handcuffs.
*
*
* <ul>
* <li>{@link #addHandCuffs(UUID, Location) addHandCuffs}</li>
* <li>{@link #removeHandCuffs(UUID) removeHandCuffs}</li>
* <li>{@link #isHandCuffed(UUID) isHandCuffed}</li>
* <li>{@link #getLocation(UUID) getLocation}</li>
* </ul>
*
*
* @author graywolf336
* @since 2.6.3
* @version 1.0.2
* @since 2.6.3
*/
public class HandCuffManager {
private HashMap<UUID, Long> handcuffed;
private HashMap<UUID, Location> locs;
private final HashMap<UUID, Long> handcuffed;
private final HashMap<UUID, Location> locs;
/** Constructs a new HandCuff Manager, for handling all the handcuffing. */
/**
* Constructs a new HandCuff Manager, for handling all the handcuffing.
*/
protected HandCuffManager() {
this.handcuffed = new HashMap<UUID, Long>();
this.locs = new HashMap<UUID, Location>();
this.handcuffed = new HashMap<>();
this.locs = new HashMap<>();
}
/**
* Adds handcuffs to a player.
*
* @param uuid of the player
*
* @param uuid of the player
* @param location where the player was handcuffed, so they can't move
*/
public void addHandCuffs(UUID uuid, Location location) {
@ -48,7 +50,7 @@ public class HandCuffManager {
/**
* Removes the handcuffs from the given player.
*
*
* @param uuid of the person to remove the handcuffs from
*/
public void removeHandCuffs(UUID uuid) {
@ -58,7 +60,7 @@ public class HandCuffManager {
/**
* Gets if the player is handcuffed or not.
*
*
* @param uuid of the player to check
* @return true if they are handcuffed, false if not
*/
@ -68,7 +70,7 @@ public class HandCuffManager {
/**
* Gets the next Long time we should send a message to the player.
*
*
* @param uuid of the player to get the name we're supposed to message them next
* @return long value of the system time in milliseconds
*/
@ -78,7 +80,7 @@ public class HandCuffManager {
/**
* Updates the time to the next 10 seconds from now to when we should send them a message.
*
*
* @param uuid of the player we're setting the message time to
*/
public void updateNextTime(UUID uuid) {
@ -87,7 +89,7 @@ public class HandCuffManager {
/**
* Gets the location where the given player was handcuffed at.
*
*
* @param uuid of the player get the location for
* @return the location where the player was handcuffed at
*/

View File

@ -1,8 +1,18 @@
package com.graywolf336.jail;
import com.graywolf336.jail.beans.Cell;
import com.graywolf336.jail.beans.Jail;
import com.graywolf336.jail.beans.Prisoner;
import com.graywolf336.jail.beans.SimpleLocation;
import com.graywolf336.jail.enums.Lang;
import com.graywolf336.jail.enums.Settings;
import org.bukkit.Location;
import org.bukkit.configuration.file.FileConfiguration;
import org.bukkit.configuration.file.YamlConfiguration;
import java.io.File;
import java.io.InputStreamReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
@ -15,27 +25,15 @@ import java.util.List;
import java.util.Set;
import java.util.UUID;
import org.bukkit.Location;
import org.bukkit.configuration.file.FileConfiguration;
import org.bukkit.configuration.file.YamlConfiguration;
import com.graywolf336.jail.beans.Cell;
import com.graywolf336.jail.beans.Jail;
import com.graywolf336.jail.beans.Prisoner;
import com.graywolf336.jail.beans.SimpleLocation;
import com.graywolf336.jail.enums.Lang;
import com.graywolf336.jail.enums.Settings;
/**
* Handles all the saving and loading of the plugin's data.
*
* @author graywolf336
* @since 2.x.x
* @version 3.0.0
*
* @since 2.x.x
*/
public class JailIO {
private JailMain pl;
private final JailMain pl;
private FileConfiguration flat, records;
private Connection con;
private int storage = -1; //0 = flatfile, 1 = sqlite, 2 = mysql
@ -46,24 +44,26 @@ public class JailIO {
this.pl = plugin;
}
/** Loads the language file from disk, if there is none then we save the default one. */
/**
* Loads the language file from disk, if there is none then we save the default one.
*/
protected void loadLanguage() {
String language = pl.getConfig().getString(Settings.LANGUAGE.getPath());
boolean save = false;
File langFile = new File(pl.getDataFolder() + File.separator + "locales", language + ".yml");
//File or folder already exists, let's check
if(langFile.exists()) {
if(langFile.isFile()) {
if (langFile.exists()) {
if (langFile.isFile()) {
Lang.setFile(YamlConfiguration.loadConfiguration(langFile));
pl.getLogger().info("Loaded the language: " + language);
}else {
} else {
pl.getLogger().severe("The language file can not be a folder.");
pl.getLogger().severe("As a result, we are reverting back to English as the language.");
Lang.setFile(YamlConfiguration.loadConfiguration(new InputStreamReader(pl.getResource("locales/en.yml"))));
save = true;
}
}else {
} else {
pl.getLogger().warning("Loading the default language of: en");
pl.getLogger().warning("If you wish to change this, please rename 'en.yml' to whatever you wish and set the config value to the name of the file.");
Lang.setFile(YamlConfiguration.loadConfiguration(new InputStreamReader(pl.getResource("locales/en.yml"))));
@ -71,10 +71,11 @@ public class JailIO {
}
//Make sure we have all the new language settings loaded
if(!save) save = Lang.writeNewLanguage(YamlConfiguration.loadConfiguration(new InputStreamReader(pl.getResource("locales/en.yml"))));
if (!save)
save = Lang.writeNewLanguage(YamlConfiguration.loadConfiguration(new InputStreamReader(pl.getResource("locales/en.yml"))));
//If we have flagged to save the language file, let's save it as en.yml as this flag usually means they didn't have it loaded.
if(save) {
if (save) {
try {
Lang.getFile().save(new File(pl.getDataFolder() + File.separator + "locales", "en.yml"));
} catch (IOException e) {
@ -85,7 +86,7 @@ public class JailIO {
/**
* Prepares the storage engine to be used, returns true if everything went good.
*
*
* @param doInitialCreations whether to do the initial creations (database tables or files)
* @return Whether it was successful or not
*/
@ -93,38 +94,38 @@ public class JailIO {
int inital = storage == -1 ? -1 : storage;
String st = pl.getConfig().getString("storage.type", "flatfile");
if(st.equalsIgnoreCase("sqlite")) {
if (st.equalsIgnoreCase("sqlite")) {
storage = 1;
prefix = pl.getConfig().getString("storage.mysql.prefix");
}else if(st.equalsIgnoreCase("mysql")) {
} else if (st.equalsIgnoreCase("mysql")) {
storage = 2;
prefix = pl.getConfig().getString("storage.mysql.prefix");
}else {
} else {
storage = 0;
}
//Determine if we changed storage types midstream
//this way we can know whether to save EVERYTHING
//or not afterwards
if(inital != -1 && inital != storage) {
if (inital != -1 && inital != storage) {
pl.debug("We changed storage types! We used to be " + inital + " and changed to " + storage + ".");
changed = true;
}
pl.debug("The storage type " + st + " with the type being " + storage + ".");
if(!pl.inDebug()) pl.getLogger().info("Storage type selected: " + st);
if (!pl.inDebug()) pl.getLogger().info("Storage type selected: " + st);
switch(storage) {
switch (storage) {
case 1:
try {
Class.forName("org.sqlite.JDBC");
pl.getLogger().info("Connecting to the sqlite database.");
Connection sqliteConnection = DriverManager.getConnection("jdbc:sqlite:" + new File(pl.getDataFolder().getPath(), "jail3.sqlite").getPath());
Connection sqliteConnection = DriverManager.getConnection("jdbc:sqlite:" + new File(pl.getDataFolder().getPath(), "jail3.sqlite").getPath());
sqliteConnection.setAutoCommit(true);
this.con = sqliteConnection;
pl.debug("Connection created for sqlite.");
if(doInitialCreations) createTables();
if (doInitialCreations) createTables();
} catch (ClassNotFoundException e) {
e.printStackTrace();
pl.getLogger().severe("---------- Jail Error!!! ----------");
@ -149,8 +150,8 @@ public class JailIO {
this.con = mysqlConnection;
pl.debug("Connection created for MySQL.");
if(doInitialCreations) createTables();
} catch(ClassNotFoundException e) {
if (doInitialCreations) createTables();
} catch (ClassNotFoundException e) {
e.printStackTrace();
pl.getLogger().severe("---------- Jail Error!!! ----------");
pl.getLogger().severe("MySQL driver not found, disabling the plugin.");
@ -169,7 +170,7 @@ public class JailIO {
break;
}
if(changed) {
if (changed) {
changed = false;
this.saveEverything();
}
@ -183,11 +184,11 @@ public class JailIO {
* @return The connection for the sql database.
*/
private Connection getConnection() {
switch(storage) {
switch (storage) {
case 1:
if(con == null) this.prepareStorage(false);
if (con == null) this.prepareStorage(false);
try {
if(con.isClosed()) this.prepareStorage(false);
if (con.isClosed()) this.prepareStorage(false);
} catch (SQLException e) {
e.printStackTrace();
pl.getLogger().severe("---------- Jail Error!!! ----------");
@ -196,9 +197,9 @@ public class JailIO {
}
return con;
case 2:
if(con == null) this.prepareStorage(false);
if (con == null) this.prepareStorage(false);
try {
if(con.isClosed() || !con.isValid(10)) this.prepareStorage(false);
if (con.isClosed() || !con.isValid(10)) this.prepareStorage(false);
} catch (SQLException e) {
e.printStackTrace();
pl.getLogger().severe("---------- Jail Error!!! ----------");
@ -211,13 +212,15 @@ public class JailIO {
}
}
/** Closes the sql connection. */
/**
* Closes the sql connection.
*/
protected void closeConnection() {
switch(storage) {
switch (storage) {
case 1:
case 2:
try {
if(con != null) {
if (con != null) {
con.close();
con = null;
@ -236,14 +239,14 @@ public class JailIO {
}
private void createTables() {
if(getConnection() == null) {
if (getConnection() == null) {
pl.debug("The connection was null when we tried to create a table.");
return;
}
try {
Statement st = getConnection().createStatement();
switch(storage){
switch (storage) {
case 1:
String sqlJailCreateCmd = "CREATE TABLE IF NOT EXISTS `" + prefix + "jails` ("
+ "`name` VARCHAR PRIMARY KEY NOT NULL,"
@ -418,7 +421,7 @@ public class JailIO {
* Loads the jails, this should <strong>only</strong> be called after {@link #prepareStorage(boolean)}.
*/
protected void loadJails() {
switch(storage) {
switch (storage) {
case 1:
case 2:
//load the jails from mysql and sqlite
@ -428,12 +431,12 @@ public class JailIO {
PreparedStatement ps = getConnection().prepareStatement("SELECT * FROM " + prefix + "jails");
ResultSet set = ps.executeQuery();
while(set.next()) {
while (set.next()) {
Jail j = new Jail(pl, set.getString("name"));
j.setWorld(set.getString("world"));
j.setMaxPoint(new int[] { set.getInt("top.x"), set.getInt("top.y"), set.getInt("top.z") });
j.setMinPoint(new int[] { set.getInt("bottom.x"), set.getInt("bottom.y"), set.getInt("bottom.z") });
j.setMaxPoint(new int[]{set.getInt("top.x"), set.getInt("top.y"), set.getInt("top.z")});
j.setMinPoint(new int[]{set.getInt("bottom.x"), set.getInt("bottom.y"), set.getInt("bottom.z")});
j.setTeleportIn(new Location(pl.getServer().getWorld(j.getWorldName()), set.getDouble("tps.in.x"),
set.getDouble("tps.in.y"), set.getDouble("tps.in.z"),
set.getFloat("tps.in.yaw"), set.getFloat("tps.in.pitch")));
@ -455,27 +458,27 @@ public class JailIO {
//This list contains an integer which refers to the cellid column in sql
//this list only gets populated if there are cells which reference a jail
//that doesn't exist anymore
List<Integer> cellsToRemove = new LinkedList<Integer>();
List<Integer> cellsToRemove = new LinkedList<>();
try {
PreparedStatement ps = getConnection().prepareStatement("SELECT * FROM " + prefix + "cells");
ResultSet set = ps.executeQuery();
while(set.next()) {
while (set.next()) {
Jail j = pl.getJailManager().getJail(set.getString("jail"));
if(j != null) {
if(j.getWorld() != null) {
if (j != null) {
if (j.getWorld() != null) {
Cell c = new Cell(set.getInt("cellid"), set.getString("name"));
c.setTeleport(new SimpleLocation(j.getWorldName(), set.getDouble("tp.x"), set.getDouble("tp.y"), set.getDouble("tp.z"),
c.setTeleport(new SimpleLocation(j.getWorldName(), set.getDouble("tp.x"), set.getDouble("tp.y"), set.getDouble("tp.z"),
set.getFloat("tp.yaw"), set.getFloat("tp.pitch")));
c.setChestLocation(new SimpleLocation(j.getWorldName(), set.getInt("chest.x"), set.getInt("chest.y"), set.getInt("chest.z")));
String cSigns = set.getString("signs");
if(!cSigns.isEmpty()) {
if (!cSigns.isEmpty()) {
String[] signs = cSigns.split(";");
for(String s : signs) {
for (String s : signs) {
String[] co = s.split(",");
c.addSign(new SimpleLocation(co[0], co[1], co[2], co[3]));
}
@ -488,15 +491,15 @@ public class JailIO {
//if this method returns false then
//the cell already exists and needs
//to be removed from the database
if(!j.addCell(c, false)) {
if (!j.addCell(c, false)) {
int id = set.getInt("cellid");
cellsToRemove.add(id);
pl.debug("The cell, " + c.getName() + " (" + id + "), is already in jail " + j.getName() + " so we're removing it.");
}
}else {
} else {
pl.getLogger().warning("The cell, " + set.getString("name") + ", in " + j.getName() + " is located in a world that is not loaded.");
}
}else {
} else {
cellsToRemove.add(set.getInt("cellid"));
}
}
@ -512,17 +515,17 @@ public class JailIO {
}
//Remove the invalid prisoners
if(!cellsToRemove.isEmpty()) {
if (!cellsToRemove.isEmpty()) {
StringBuilder ids = new StringBuilder();
for(int c : cellsToRemove) {
if(ids.length() == 0) ids.append("'" + c + "'");
else ids.append("," + "'" + c + "'");
for (int c : cellsToRemove) {
if (ids.length() == 0) ids.append("'").append(c).append("'");
else ids.append("," + "'").append(c).append("'");
}
try {
PreparedStatement cds = getConnection().prepareStatement("delete from " + prefix + "cells where cellid in (" + ids.toString() + ");");
PreparedStatement cds = getConnection().prepareStatement("delete from " + prefix + "cells where cellid in (" + ids + ");");
pl.debug("Deleting old cells: `delete from " + prefix + "cells where cellid in (" + ids.toString() + ");`");
pl.debug("Deleting old cells: `delete from " + prefix + "cells where cellid in (" + ids + ");`");
int count = cds.executeUpdate();
pl.getLogger().info("Deleted " + count + " cells which were invalid, they either referenced a jail which are no longer valid or were duplicates.");
@ -537,16 +540,16 @@ public class JailIO {
//This list contains a string which refers to the name of the prisoner in sql
//this list only gets populated if there are prisoners which reference a jail
//that doesn't exist anymore
List<String> prisonersToRemove = new LinkedList<String>();
List<String> prisonersToRemove = new LinkedList<>();
try {
PreparedStatement ps = getConnection().prepareStatement("SELECT * FROM " + prefix + "prisoners");
ResultSet set = ps.executeQuery();
while(set.next()) {
while (set.next()) {
Jail j = pl.getJailManager().getJail(set.getString("jail"));
if(j != null) {
if (j != null) {
String cellname = set.getString("cell");
Cell c = j.getCell(cellname);
@ -559,12 +562,12 @@ public class JailIO {
p.setPreviousGameMode(set.getString("previousGameMode"));
p.setChanged(false);//Since we just loaded the prisoner, we really don't need to save them.
if(cellname == null || cellname.isEmpty()) {
if (cellname == null || cellname.isEmpty()) {
j.addPrisoner(p);
}else if(c != null) {
} else if (c != null) {
c.setPrisoner(p);
c.setChanged(false);
}else {
} else {
//the prisoner is assigned to a cell which doesn't exist, so just put them into the jail
j.addPrisoner(p);
}
@ -585,11 +588,11 @@ public class JailIO {
}
//Remove the invalid prisoners
if(!prisonersToRemove.isEmpty()) {
String names = "";
for(String s : prisonersToRemove) {
if(names.isEmpty()) names = "'" + s + "'";
else names += "," + "'" + s + "'";
if (!prisonersToRemove.isEmpty()) {
StringBuilder names = new StringBuilder();
for (String s : prisonersToRemove) {
if (names.length() == 0) names = new StringBuilder("'" + s + "'");
else names.append("," + "'").append(s).append("'");
}
try {
@ -611,10 +614,10 @@ public class JailIO {
break;
default:
//load the jails from flatfile
if(flat.isConfigurationSection("jails")) {
if (flat.isConfigurationSection("jails")) {
Set<String> jails = flat.getConfigurationSection("jails").getKeys(false);
if(!jails.isEmpty()) {
for(String name : jails) {
if (!jails.isEmpty()) {
for (String name : jails) {
loadJailFromFlatFile(name);
}
}
@ -638,14 +641,14 @@ public class JailIO {
pl.debug("Loading the jail " + name + "; " + node + "; " + cNode);
Jail j = new Jail(pl, name);
if(flat.getString(node + "world") == null || flat.getString(node + "world").isEmpty()) {
if (flat.getString(node + "world") == null || flat.getString(node + "world").isEmpty()) {
pl.getLogger().severe("Failed to load the jail, " + name + ", because the world is not set.");
return;
}
j.setWorld(flat.getString(node + "world"));
j.setMaxPoint(new int[] {flat.getInt(node + "top.x"), flat.getInt(node + "top.y"), flat.getInt(node + "top.z")});
j.setMinPoint(new int[] {flat.getInt(node + "bottom.x"), flat.getInt(node + "bottom.y"), flat.getInt(node + "bottom.z")});
j.setMaxPoint(new int[]{flat.getInt(node + "top.x"), flat.getInt(node + "top.y"), flat.getInt(node + "top.z")});
j.setMinPoint(new int[]{flat.getInt(node + "bottom.x"), flat.getInt(node + "bottom.y"), flat.getInt(node + "bottom.z")});
j.setTeleportIn(new Location(
pl.getServer().getWorld(j.getWorldName()),
@ -662,10 +665,10 @@ public class JailIO {
(float) flat.getDouble(node + "tps.free.yaw"),
(float) flat.getDouble(node + "tps.free.pitch")));
if(flat.isConfigurationSection(node + "cells")) {
if (flat.isConfigurationSection(node + "cells")) {
Set<String> cells = flat.getConfigurationSection(node + "cells").getKeys(false);
if(!cells.isEmpty()) {
for(String cell : cells) {
if (!cells.isEmpty()) {
for (String cell : cells) {
Cell c = new Cell(cell);
String cellNode = cNode + cell + ".";
@ -680,17 +683,17 @@ public class JailIO {
flat.getInt(cellNode + "chest.y"),
flat.getInt(cellNode + "chest.z")));
for(String sign : flat.getStringList(cellNode + "signs")) {
for (String sign : flat.getStringList(cellNode + "signs")) {
String[] arr = sign.split(",");
c.addSign(new SimpleLocation(arr[0],
Double.valueOf(arr[1]),
Double.valueOf(arr[2]),
Double.valueOf(arr[3]),
Float.valueOf(arr[4]),
Float.valueOf(arr[5])));
Double.parseDouble(arr[1]),
Double.parseDouble(arr[2]),
Double.parseDouble(arr[3]),
Float.parseFloat(arr[4]),
Float.parseFloat(arr[5])));
}
if(flat.contains(cellNode + "prisoner")) {
if (flat.contains(cellNode + "prisoner")) {
Prisoner p = new Prisoner(flat.getString(cellNode + "prisoner.uuid"),
flat.getString(cellNode + "prisoner.name"),
flat.getBoolean(cellNode + "prisoner.muted"),
@ -713,10 +716,10 @@ public class JailIO {
}
}
if(flat.isConfigurationSection(node + "prisoners")) {
if (flat.isConfigurationSection(node + "prisoners")) {
Set<String> prisoners = flat.getConfigurationSection(node + "prisoners").getKeys(false);
if(!prisoners.isEmpty()) {
for(String uuid : prisoners) {
if (!prisoners.isEmpty()) {
for (String uuid : prisoners) {
String pNode = node + "prisoners." + uuid + ".";
Prisoner pris = new Prisoner(uuid,
flat.getString(pNode + "name"),
@ -741,17 +744,19 @@ public class JailIO {
pl.getLogger().info("Loaded jail " + j.getName() + " with " + j.getAllPrisoners().size() + " prisoners and " + j.getCellCount() + " cells" + (j.isEnabled() ? "." : " but the jail is disabled as the world doesn't exist or isn't loaded."));
}
/** Saves everything about a jail, don't usually call this. */
/**
* Saves everything about a jail, don't usually call this.
*/
protected void saveEverything() {
long st = System.currentTimeMillis();
for(Jail j : pl.getJailManager().getJails()) {
for (Jail j : pl.getJailManager().getJails()) {
saveJail(j);
//Only save the cells individually
//when we are not using the flatfile storage
if(storage != 0) {
for(Cell c : j.getCells()) {
if (storage != 0) {
for (Cell c : j.getCells()) {
saveCell(j, c, true);
}
}
@ -766,8 +771,8 @@ public class JailIO {
* @param j The jail to save.
*/
protected void saveJail(Jail j) {
if(j.isEnabled()) {
switch(storage) {
if (j.isEnabled()) {
switch (storage) {
case 1:
case 2:
long st = System.currentTimeMillis();
@ -808,11 +813,11 @@ public class JailIO {
}
try {
for(Cell c : j.getCells()) {
if(c.getDatabaseID() != -1)
for (Cell c : j.getCells()) {
if (c.getDatabaseID() != -1)
saveCell(j, c, false);
if(c.hasPrisoner() && c.getPrisoner().wasChanged()) {
if (c.hasPrisoner() && c.getPrisoner().wasChanged()) {
Prisoner p = c.getPrisoner();
PreparedStatement pPS = getConnection().prepareStatement("REPLACE INTO `" + prefix + "prisoners` (`uuid`, `name`, `jail`, `cell`, `muted`, `time`,"
+ "`offlinePending`, `toBeTransferred`, `jailer`, `reason`, `inventory`, `armor`, `previousLocation`, `previousGameMode`)"
@ -845,8 +850,8 @@ public class JailIO {
}
try {
for(Prisoner p : j.getPrisonersNotInCells().values()) {
if(p.wasChanged()) {
for (Prisoner p : j.getPrisonersNotInCells().values()) {
if (p.wasChanged()) {
PreparedStatement pPS = getConnection().prepareStatement("REPLACE INTO `" + prefix + "prisoners` (`uuid`, `name`, `jail`, `cell`, `muted`, `time`,"
+ "`offlinePending`, `toBeTransferred`, `jailer`, `reason`, `inventory`, `armor`, `previousLocation`, `previousGameMode`) VALUES (?,?,?,?,?,?,?,?,?,?,?,?,?,?)");
pPS.setString(1, p.getUUID().toString());
@ -878,7 +883,7 @@ public class JailIO {
pl.debug("Took " + (System.currentTimeMillis() - st) + " millis to save the jail " + j.getName() + ".");
break;
default:
if(flat != null) {
if (flat != null) {
String node = "jails." + j.getName() + ".";
//Corners
@ -907,10 +912,10 @@ public class JailIO {
//Set all the cells to nothing, then we save each of them so no cells are left behind
flat.set(node + "cells", null);
for(Cell c : j.getCells()) {
for (Cell c : j.getCells()) {
String cNode = node + "cells." + c.getName() + ".";
if(c.getTeleport() != null) {
if (c.getTeleport() != null) {
flat.set(cNode + "tp.x", c.getTeleport().getX());
flat.set(cNode + "tp.y", c.getTeleport().getY());
flat.set(cNode + "tp.z", c.getTeleport().getZ());
@ -918,7 +923,7 @@ public class JailIO {
flat.set(cNode + "tp.pitch", c.getTeleport().getPitch());
}
if(c.getChestLocation() != null) {
if (c.getChestLocation() != null) {
flat.set(cNode + "chest.x", c.getChestLocation().getBlockX());
flat.set(cNode + "chest.y", c.getChestLocation().getBlockY());
flat.set(cNode + "chest.z", c.getChestLocation().getBlockZ());
@ -926,14 +931,14 @@ public class JailIO {
String[] signs = new String[c.getSigns().size()];
int count = 0;
for(SimpleLocation loc : c.getSigns()) {
for (SimpleLocation loc : c.getSigns()) {
signs[count] = loc.toString();
count++;
}
flat.set(cNode + "signs", signs);
if(c.getPrisoner() != null) {
if (c.getPrisoner() != null) {
Prisoner p = c.getPrisoner();
flat.set(cNode + "prisoner.uuid", p.getUUID().toString());
flat.set(cNode + "prisoner.name", p.getLastKnownName());
@ -945,9 +950,9 @@ public class JailIO {
flat.set(cNode + "prisoner.reason", p.getReason());
flat.set(cNode + "prisoner.inventory", p.getInventory());
flat.set(cNode + "prisoner.armor", p.getArmor());
if(p.getPreviousLocationString() != null)
if (p.getPreviousLocationString() != null)
flat.set(cNode + "prisoner.previousLocation", p.getPreviousLocationString());
if(p.getPreviousGameMode() != null)
if (p.getPreviousGameMode() != null)
flat.set(cNode + "prisoner.previousGameMode", p.getPreviousGameMode().toString());
}
@ -956,7 +961,7 @@ public class JailIO {
//Null all the prisoners out before we save them again, this way no prisoners are left behind
flat.set(node + "prisoners", null);
for(Prisoner p : j.getPrisonersNotInCells().values()) {
for (Prisoner p : j.getPrisonersNotInCells().values()) {
String pNode = node + "prisoners." + p.getUUID().toString() + ".";
flat.set(pNode + "name", p.getLastKnownName());
flat.set(pNode + "muted", p.isMuted());
@ -967,9 +972,9 @@ public class JailIO {
flat.set(pNode + "reason", p.getReason());
flat.set(pNode + "inventory", p.getInventory());
flat.set(pNode + "armor", p.getArmor());
if(p.getPreviousLocationString() != null)
if (p.getPreviousLocationString() != null)
flat.set(pNode + "previousLocation", p.getPreviousLocationString());
if(p.getPreviousGameMode() != null)
if (p.getPreviousGameMode() != null)
flat.set(pNode + "previousGameMode", p.getPreviousGameMode().toString());
}
@ -978,7 +983,7 @@ public class JailIO {
} catch (IOException e) {
pl.getLogger().severe("Unable to save the Jail data: " + e.getMessage());
}
}else {
} else {
pl.getLogger().severe("Storage not enabled, could not save the jail " + j.getName());
}
break;
@ -989,9 +994,9 @@ public class JailIO {
public void saveCell(Jail j, Cell c, boolean force) {
//if the cell hasn't changed, no need to save it again
//unless they're forcing the save
if(!c.hasChanged() && !force) return;
if (!c.hasChanged() && !force) return;
switch(storage) {
switch (storage) {
case 1:
case 2:
try {
@ -1017,11 +1022,11 @@ public class JailIO {
cPS.setDouble(6, c.getTeleport().getYaw());
cPS.setDouble(7, c.getTeleport().getPitch());
if(c.useChest()) {
if (c.useChest()) {
cPS.setInt(8, c.getChestLocation().getBlockX());
cPS.setInt(9, c.getChestLocation().getBlockY());
cPS.setInt(10, c.getChestLocation().getBlockZ());
}else {
} else {
cPS.setNull(8, java.sql.Types.INTEGER);
cPS.setNull(9, java.sql.Types.INTEGER);
cPS.setNull(10, java.sql.Types.INTEGER);
@ -1032,7 +1037,7 @@ public class JailIO {
cPS.executeUpdate();
cPS.close();
if(c.hasPrisoner()) {
if (c.hasPrisoner()) {
Prisoner p = c.getPrisoner();
PreparedStatement pPS = con.prepareStatement("REPLACE INTO `" + prefix + "prisoners` (`uuid`, `name`, `jail`, `cell`, `muted`, `time`,"
+ "`offlinePending`, `toBeTransferred`, `jailer`, `reason`, `inventory`, `armor`, `previousLocation`, `previousGameMode`) VALUES (?,?,?,?,?,?,?,?,?,?,?,?,?,?)");
@ -1087,7 +1092,7 @@ public class JailIO {
* @param p the prisoner data
*/
protected void removePrisoner(Jail j, Cell c, Prisoner p) {
switch(storage) {
switch (storage) {
case 1:
case 2:
try {
@ -1110,7 +1115,7 @@ public class JailIO {
}
break;
default:
if(c == null)
if (c == null)
flat.set("jails." + j.getName() + ".prisoners." + p.getUUID().toString(), null);
else
flat.set("jails." + j.getName() + ".cells." + c.getName() + ".prisoner", null);
@ -1132,15 +1137,15 @@ public class JailIO {
*/
public void removeCell(Jail j, Cell c) {
//Clear the inventory before we delete it
if(c.hasChest()) c.getChest().getInventory().clear();
if (c.hasChest()) c.getChest().getInventory().clear();
//transfer the prisoner if it has one
if(c.hasPrisoner()) {
if (c.hasPrisoner()) {
pl.getLogger().warning("Removing of cell '" + c.getName() + "' from the jail '" + j.getName() + "' failed as it has a prisoner.");
return;
}
switch(storage) {
switch (storage) {
case 1:
try {
Connection con = getConnection();
@ -1180,7 +1185,7 @@ public class JailIO {
}
break;
default:
if(flat != null) {
if (flat != null) {
flat.set("jails." + j.getName() + ".cells." + c.getName(), null);
try {
@ -1203,10 +1208,10 @@ public class JailIO {
protected void removeJail(Jail j) {
String name = j.getName();
switch(storage) {
switch (storage) {
case 1:
case 2:
for(Cell c : j.getCells()) {
for (Cell c : j.getCells()) {
removeCell(j, c);
}
@ -1244,15 +1249,15 @@ public class JailIO {
/**
* Adds an entry to the database/file for the user, logging when they was jailed.
*
* @param uuid of the player
* @param uuid of the player
* @param username of the player
* @param jailer who jailed them
* @param date string of when they are jailed
* @param time of the player's sentence
* @param reason the player is jailed
* @param jailer who jailed them
* @param date string of when they are jailed
* @param time of the player's sentence
* @param reason the player is jailed
*/
public void addRecordEntry(String uuid, String username, String jailer, String date, long time, String reason) {
switch(storage) {
switch (storage) {
case 1:
break;
case 2:
@ -1279,10 +1284,11 @@ public class JailIO {
}
break;
default:
if(records == null) records = YamlConfiguration.loadConfiguration(new File(pl.getDataFolder(), "records.yml"));
if (records == null)
records = YamlConfiguration.loadConfiguration(new File(pl.getDataFolder(), "records.yml"));
List<String> previous = records.getStringList(uuid);
previous.add(Lang.RECORDENTRY.get(new String[] { date, username, jailer, String.valueOf(time), reason, uuid }));
previous.add(Lang.RECORDENTRY.get(date, username, jailer, String.valueOf(time), reason, uuid));
records.set(uuid, previous);
@ -1306,9 +1312,9 @@ public class JailIO {
*/
public List<String> getRecordEntries(String username) {
UUID uuid = pl.getServer().getOfflinePlayer(username).getUniqueId();
List<String> entries = new ArrayList<String>();
List<String> entries = new ArrayList<>();
switch(storage) {
switch (storage) {
case 1:
break;
case 2:
@ -1322,8 +1328,8 @@ public class JailIO {
ps.setString(1, uuid.toString());
ResultSet set = ps.executeQuery();
while(set.next()) {
entries.add(Lang.RECORDENTRY.get(new String[] { set.getString("date"), set.getString("username"), set.getString("jailer"), String.valueOf(set.getLong("time")), set.getString("reason"), set.getString("uuid") }));
while (set.next()) {
entries.add(Lang.RECORDENTRY.get(set.getString("date"), set.getString("username"), set.getString("jailer"), String.valueOf(set.getLong("time")), set.getString("reason"), set.getString("uuid")));
}
set.close();
@ -1335,7 +1341,8 @@ public class JailIO {
}
break;
default:
if(records == null) records = YamlConfiguration.loadConfiguration(new File(pl.getDataFolder(), "records.yml"));
if (records == null)
records = YamlConfiguration.loadConfiguration(new File(pl.getDataFolder(), "records.yml"));
entries = records.getStringList(uuid.toString());
break;

View File

@ -1,15 +1,5 @@
package com.graywolf336.jail;
import java.util.Collections;
import java.util.List;
import java.util.concurrent.TimeUnit;
import org.bukkit.command.Command;
import org.bukkit.command.CommandSender;
import org.bukkit.event.HandlerList;
import org.bukkit.plugin.PluginManager;
import org.bukkit.plugin.java.JavaPlugin;
import com.graywolf336.jail.beans.Jail;
import com.graywolf336.jail.beans.Prisoner;
import com.graywolf336.jail.command.CommandHandler;
@ -28,13 +18,22 @@ import com.graywolf336.jail.listeners.MoveProtectionListener;
import com.graywolf336.jail.listeners.PlayerListener;
import com.graywolf336.jail.listeners.ProtectionListener;
import com.graywolf336.jail.listeners.WorldListener;
import org.bukkit.command.Command;
import org.bukkit.command.CommandSender;
import org.bukkit.event.HandlerList;
import org.bukkit.plugin.PluginManager;
import org.bukkit.plugin.java.JavaPlugin;
import java.util.Collections;
import java.util.List;
import java.util.concurrent.TimeUnit;
/**
* The main class for this Jail plugin, holds instances of vital classes.
*
*
* @author graywolf336
* @since 1.x.x
* @version 3.0.0
* @since 1.x.x
*/
public class JailMain extends JavaPlugin {
private CommandHandler cmdHand;
@ -58,7 +57,7 @@ public class JailMain extends JavaPlugin {
loadConfig();
debug = getConfig().getBoolean(Settings.DEBUG.getPath());
if(debug) getLogger().info("Debugging enabled.");
if (debug) getLogger().info("Debugging enabled.");
hcm = new HandCuffManager();
jm = new JailManager(this);
@ -66,7 +65,7 @@ public class JailMain extends JavaPlugin {
io.loadLanguage();
//If the prepareStorage returns false, we need to disable the plugin
if(!io.prepareStorage(true)) {
if (!io.prepareStorage(true)) {
this.getLogger().severe("An error occured while preparing the connection to the storage, please see the error above for more information.");
this.getServer().getPluginManager().disablePlugin(this);
return;
@ -77,10 +76,10 @@ public class JailMain extends JavaPlugin {
cmdHand = new CommandHandler(this);
jh = new JailHandler(this);
pm = new PrisonerManager(this);
try {
jvm = new JailVoteManager(this);
}catch(Exception e) {
} catch (Exception e) {
e.printStackTrace();
getLogger().severe("Failed to load the Jail Vote system, please see the stacktrace above (you probably misconfigured the time).");
}
@ -115,15 +114,15 @@ public class JailMain extends JavaPlugin {
}
public void onDisable() {
if(jm != null)
for(Jail j : jm.getJails())
if (jm != null)
for (Jail j : jm.getJails())
io.saveJail(j);
if(jt != null)
if(jt.getTimer() != null)
if (jt != null)
if (jt.getTimer() != null)
jt.getTimer().stop();
if(io != null)
if (io != null)
io.closeConnection();
getServer().getScheduler().cancelTasks(this);
@ -168,44 +167,44 @@ public class JailMain extends JavaPlugin {
* Send the command off to the CommandHandler class, that way this main class doesn't get clogged up.
*/
public boolean onCommand(CommandSender sender, Command command, String commandLabel, String[] args) {
if(jh == null || cmdHand == null) {
sender.sendMessage(Lang.PLUGINNOTLOADED.get());
getServer().getConsoleSender().sendMessage(Lang.PLUGINNOTLOADED.get());
}else {
if(commandLabel.equalsIgnoreCase("jail") || commandLabel.equalsIgnoreCase("j")) {
jh.parseCommand(jm, sender, args);
}else {
if (jh == null || cmdHand == null) {
sender.sendMessage(Lang.PLUGINNOTLOADED.get());
getServer().getConsoleSender().sendMessage(Lang.PLUGINNOTLOADED.get());
} else {
if (commandLabel.equalsIgnoreCase("jail") || commandLabel.equalsIgnoreCase("j")) {
jh.parseCommand(jm, sender, args);
} else {
cmdHand.handleCommand(jm, sender, command.getName().toLowerCase(), args);
}
}
}
return true;//Always return true here, that way we can handle the help and command usage ourself.
}
public List<String> onTabComplete(CommandSender sender, Command command, String commandLabel, String[] args) {
if(jh == null || cmdHand == null) {
if (jh == null || cmdHand == null) {
sender.sendMessage(Lang.PLUGINNOTLOADED.get());
getServer().getConsoleSender().sendMessage(Lang.PLUGINNOTLOADED.get());
}else {
} else {
debug("Tab Complete Args (" + args.length + ") for '" + commandLabel + "': " + Util.getStringFromArray(", ", args));
try {
if(commandLabel.equalsIgnoreCase("jail") || commandLabel.equalsIgnoreCase("j")) {
if (commandLabel.equalsIgnoreCase("jail") || commandLabel.equalsIgnoreCase("j")) {
return jh.parseTabComplete(jm, sender, args);
}else {
} else {
return cmdHand.parseTabComplete(jm, sender, command.getName().toLowerCase(), args);
}
}catch(Exception e) {
if(this.debug)
} catch (Exception e) {
if (this.debug)
e.printStackTrace();
debug(e.getClass().getSimpleName() + " occured while providing tab complete: " + e.getMessage());
return Collections.emptyList();
}
}
return Collections.emptyList();
}
public void reloadEverything() throws Exception {
//Reload the configuration file
reloadConfig();
@ -230,37 +229,41 @@ public class JailMain extends JavaPlugin {
//if they rely on any of the configuration settings (such as signs)
getServer().getPluginManager().callEvent(new JailPluginReloadedEvent(this));
}
/** Reloads/Loads the move protection listener based upon it's previous status and the config. */
/**
* Reloads/Loads the move protection listener based upon it's previous status and the config.
*/
private void reloadMoveProtection() {
boolean moveProtection = getConfig().getBoolean(Settings.MOVEPROTECTION.getPath());
//If move protection is not enabled and it used to be,
//unregister it.
if(!moveProtection && this.mpl != null) {
if (!moveProtection && this.mpl != null) {
HandlerList.unregisterAll(this.mpl);
this.mpl = null;
this.debug("The move protection listener is now disabled.");
}
//If it is enabled and it used to not be, then enable it.
if(moveProtection && this.mpl == null) {
if (moveProtection && this.mpl == null) {
this.mpl = new MoveProtectionListener(this);
getServer().getPluginManager().registerEvents(mpl, this);
this.debug("The move protection listener is now enabled.");
}
}
/** Reloads the scoreboard manager class, useful when something is changed in the config about it. */
/**
* Reloads the scoreboard manager class, useful when something is changed in the config about it.
*/
private void reloadScoreBoardManager() {
this.sbm.removeAllScoreboards();
this.sbm = null;
this.sbm = new ScoreBoardManager(this);
if(getConfig().getBoolean(Settings.SCOREBOARDENABLED.getPath())) {
for(Jail j : jm.getJails()) {
for(Prisoner p : j.getAllPrisoners().values()) {
if(getServer().getPlayer(p.getUUID()) != null) {
if (getConfig().getBoolean(Settings.SCOREBOARDENABLED.getPath())) {
for (Jail j : jm.getJails()) {
for (Prisoner p : j.getAllPrisoners().values()) {
if (getServer().getPlayer(p.getUUID()) != null) {
this.sbm.addScoreBoard(getServer().getPlayer(p.getUUID()), p);
}
}
@ -268,10 +271,12 @@ public class JailMain extends JavaPlugin {
}
}
/** Reloads the Jail Sticks, so the new ones can be loaded from the config. */
/**
* Reloads the Jail Sticks, so the new ones can be loaded from the config.
*/
private void reloadJailSticks() {
if(getConfig().getBoolean(Settings.JAILSTICKENABLED.getPath())) {
if(this.jsm != null) {
if (getConfig().getBoolean(Settings.JAILSTICKENABLED.getPath())) {
if (this.jsm != null) {
this.jsm.removeAllStickUsers();
this.jsm = null;
}
@ -280,46 +285,48 @@ public class JailMain extends JavaPlugin {
}
}
/** Reloads the {@link JailPayManager}. */
/**
* Reloads the {@link JailPayManager}.
*/
private void reloadJailPayManager() {
this.jpm = null;
if(getConfig().getBoolean(Settings.JAILPAYENABLED.getPath())) {
if(getServer().getPluginManager().isPluginEnabled("Vault")) {
if (getConfig().getBoolean(Settings.JAILPAYENABLED.getPath())) {
if (getServer().getPluginManager().isPluginEnabled("Vault")) {
this.jpm = new JailPayManager(this);
}else {
} else {
getConfig().set(Settings.JAILPAYENABLED.getPath(), false);
getLogger().severe("Jail Pay couldn't find an economy, disabling Jail Pay.");
}
}
}
/** Reloads the {@link JailVoteManager}. */
/**
* Reloads the {@link JailVoteManager}.
*/
private void reloadJailVoteManager() throws Exception {
if(this.jvm != null) {
for(Integer i : this.jvm.getRunningTasks().values()) {
if (this.jvm != null) {
for (Integer i : this.jvm.getRunningTasks().values()) {
this.getServer().getScheduler().cancelTask(i);
}
this.jvm.getRunningTasks().clear();
this.jvm.getVotes().clear();
}
this.jvm = null;
this.jvm = new JailVoteManager(this);
}
/** Reloads the update checker, in case they changed a setting about it. */
/**
* Reloads the update checker, in case they changed a setting about it.
*/
private void reloadUpdateCheck() {
getServer().getScheduler().cancelTask(updateCheckTask);
update = new Update(this);
if(getConfig().getBoolean(Settings.UPDATENOTIFICATIONS.getPath())) {
if (getConfig().getBoolean(Settings.UPDATENOTIFICATIONS.getPath())) {
try {
updateCheckTask = getServer().getScheduler().runTaskTimerAsynchronously(this, new Runnable() {
public void run() {
update.query();
}
}, 80L, Util.getTime(getConfig().getString(Settings.UPDATETIME.getPath()), TimeUnit.SECONDS) * 20).getTaskId();
updateCheckTask = getServer().getScheduler().runTaskTimerAsynchronously(this, () -> update.query(), 80L, Util.getTime(getConfig().getString(Settings.UPDATETIME.getPath()), TimeUnit.SECONDS) * 20).getTaskId();
} catch (Exception e) {
e.printStackTrace();
getLogger().severe("Was unable to schedule the update checking, please check your time format is correct.");
@ -329,7 +336,7 @@ public class JailMain extends JavaPlugin {
/**
* Gets the {@link HandCuffManager} instance.
*
*
* @return {@link HandCuffManager} instance
*/
public HandCuffManager getHandCuffManager() {
@ -338,7 +345,7 @@ public class JailMain extends JavaPlugin {
/**
* Gets the {@link JailIO} instance.
*
*
* @return {@link JailIO} instance
*/
public JailIO getJailIO() {
@ -347,7 +354,7 @@ public class JailMain extends JavaPlugin {
/**
* Gets the {@link JailManager} instance.
*
*
* @return {@link JailManager} instance
*/
public JailManager getJailManager() {
@ -356,7 +363,7 @@ public class JailMain extends JavaPlugin {
/**
* Gets an instance of the {@link IJailPayManager}.
*
*
* @return {@link IJailPayManager}
*/
public IJailPayManager getJailPayManager() {
@ -365,7 +372,7 @@ public class JailMain extends JavaPlugin {
/**
* Gets the {@link PrisonerManager} instance.
*
*
* @return {@link PrisonerManager} instance
*/
public PrisonerManager getPrisonerManager() {
@ -374,7 +381,7 @@ public class JailMain extends JavaPlugin {
/**
* Gets an instance of the {@link JailStickManager}.
*
*
* @return {@link JailStickManager}
*/
public IJailStickManager getJailStickManager() {
@ -383,16 +390,16 @@ public class JailMain extends JavaPlugin {
/**
* Gets the {@link ScoreBoardManager} instance.
*
*
* @return {@link ScoreBoardManager} instance
*/
public ScoreBoardManager getScoreBoardManager() {
return this.sbm;
}
/**
* Gets the {@link JailVoteManager} instance.
*
*
* @return {@link JailVoteManager} instance
*/
public JailVoteManager getJailVoteManager() {
@ -401,7 +408,7 @@ public class JailMain extends JavaPlugin {
/**
* Gets the {@link Update} instance.
*
*
* @return {@link Update} instance
*/
public Update getUpdate() {
@ -410,7 +417,7 @@ public class JailMain extends JavaPlugin {
/**
* Sets whether the plugin is in debugging or not.
*
*
* @param debug whether to be in debuggin or not
* @return Whether we we debugging or not.
*/
@ -426,7 +433,7 @@ public class JailMain extends JavaPlugin {
/**
* Returns if the plugin is in debug state or not.
*
*
* @return Whether we are debugging or not.
*/
public boolean inDebug() {
@ -435,16 +442,16 @@ public class JailMain extends JavaPlugin {
/**
* Logs a debugging message to the console if debugging is enabled.
*
*
* @param message the item to log as debugging
*/
public void debug(String message) {
if(inDebug()) getLogger().info("[Debug]: " + message);
if (inDebug()) getLogger().info("[Debug]: " + message);
}
/**
* This method is only for testing, there is no need to use this.
*
*
* @return the move protection listener
* @deprecated
*/

View File

@ -1,18 +1,5 @@
package com.graywolf336.jail;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.HashSet;
import java.util.LinkedList;
import java.util.List;
import java.util.UUID;
import org.bukkit.Location;
import org.bukkit.command.CommandSender;
import org.bukkit.entity.Player;
import org.bukkit.util.StringUtil;
import com.graywolf336.jail.beans.CachePrisoner;
import com.graywolf336.jail.beans.Cell;
import com.graywolf336.jail.beans.ConfirmPlayer;
@ -23,12 +10,24 @@ import com.graywolf336.jail.enums.Confirmation;
import com.graywolf336.jail.enums.Lang;
import com.graywolf336.jail.steps.CellCreationSteps;
import com.graywolf336.jail.steps.JailCreationSteps;
import org.bukkit.Location;
import org.bukkit.command.CommandSender;
import org.bukkit.entity.Player;
import org.bukkit.util.StringUtil;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.HashSet;
import java.util.LinkedList;
import java.util.List;
import java.util.UUID;
/**
* Handles all things related to jails.
*
*
* <p>
* <p>
*
* Stores the following:
* <ul>
* <li>The {@link Jail jails}, which contains the prisoners and cells.</li>
@ -36,35 +35,35 @@ import com.graywolf336.jail.steps.JailCreationSteps;
* <li>Players creating jail cells, see {@link CreationPlayer}.</li>
* <li>An instance of {@link JailCreationSteps} for stepping players through the Jail creation process.</li>
* </ul>
*
*
* @author graywolf336
* @since 3.0.0
* @version 1.1.0
* @since 3.0.0
*/
public class JailManager {
private JailMain plugin;
private HashMap<String, Jail> jails;
private HashMap<String, CreationPlayer> jailCreators;
private HashMap<String, CreationPlayer> cellCreators;
private HashMap<String, ConfirmPlayer> confirms;
private HashMap<UUID, CachePrisoner> cache;
private JailCreationSteps jcs;
private CellCreationSteps ccs;
private final JailMain plugin;
private final HashMap<String, Jail> jails;
private final HashMap<String, CreationPlayer> jailCreators;
private final HashMap<String, CreationPlayer> cellCreators;
private final HashMap<String, ConfirmPlayer> confirms;
private final HashMap<UUID, CachePrisoner> cache;
private final JailCreationSteps jcs;
private final CellCreationSteps ccs;
protected JailManager(JailMain plugin) {
this.plugin = plugin;
this.jails = new HashMap<String, Jail>();
this.jailCreators = new HashMap<String, CreationPlayer>();
this.cellCreators = new HashMap<String, CreationPlayer>();
this.confirms = new HashMap<String, ConfirmPlayer>();
this.cache = new HashMap<UUID, CachePrisoner>();
this.jails = new HashMap<>();
this.jailCreators = new HashMap<>();
this.cellCreators = new HashMap<>();
this.confirms = new HashMap<>();
this.cache = new HashMap<>();
this.jcs = new JailCreationSteps();
this.ccs = new CellCreationSteps();
}
/**
* Returns the instance of the plugin main class.
*
*
* @return {@link JailMain} instance
*/
public JailMain getPlugin() {
@ -73,66 +72,66 @@ public class JailManager {
/**
* Returns a HashSet of all the jails.
*
*
* @return HashSet of all the jail instances.
*/
public HashSet<Jail> getJails() {
return new HashSet<Jail>(jails.values());
return new HashSet<>(jails.values());
}
/**
* Returns an array of all the names of the jails.
*
*
* @return Array of the jail names
*/
public String[] getJailNames() {
String[] toReturn = new String[jails.size()];
int count = 0;
for(Jail j : this.jails.values()) {
for (Jail j : this.jails.values()) {
toReturn[count] = j.getName();
count++;
}
return toReturn;
}
/**
* Gets a list of Jail names that start with the provided prefix.
*
*
* <p>
* <p>
*
* If the provided prefix is empty, then we add all of the jails.
*
*
* @param prefix The start of the jails to get
* @return List of jails that matched the prefix
*/
public List<String> getJailsByPrefix(String prefix) {
List<String> results = new ArrayList<String>();
for(Jail j : this.jails.values())
if(prefix.isEmpty() || StringUtil.startsWithIgnoreCase(j.getName(), prefix))
List<String> results = new ArrayList<>();
for (Jail j : this.jails.values())
if (prefix.isEmpty() || StringUtil.startsWithIgnoreCase(j.getName(), prefix))
results.add(j.getName());
Collections.sort(results);
return results;
}
/**
* Adds a jail to the collection of them.
*
*
* @param jail The jail to add
* @param n True if this is a new jail, false if it isn't.
* @param n True if this is a new jail, false if it isn't.
*/
public void addJail(Jail jail, boolean n) {
this.jails.put(jail.getName().toLowerCase(), jail);
if(n) plugin.getJailIO().saveJail(jail);
if (n) plugin.getJailIO().saveJail(jail);
}
/**
* Removes a {@link Jail}.
*
*
* @param name of the jail to remove
*/
public void removeJail(String name) {
@ -142,12 +141,12 @@ public class JailManager {
/**
* Gets a jail by the given name.
*
*
* @param name The name of the jail to get.
* @return The {@link Jail} with the given name, if no jail found this <strong>will</strong> return null.
*/
public Jail getJail(String name) {
if(name.isEmpty() && jails.isEmpty())
if (name.isEmpty() && jails.isEmpty())
return null;
else
return name.isEmpty() ? this.jails.values().iterator().next() : this.jails.get(name.toLowerCase());
@ -155,20 +154,20 @@ public class JailManager {
/**
* Gets the nearest {@link Jail} to the player, if the sender is a player or else it will get the first jail defined.
*
*
* @param sender The sender who we are looking around.
* @return The nearest {@link Jail} to the sender if it is a player or else the first jail defined.
*/
public Jail getNearestJail(CommandSender sender) {
if(jails.isEmpty()) return null;
if(sender instanceof Player) {
if (jails.isEmpty()) return null;
if (sender instanceof Player) {
Location loc = ((Player) sender).getLocation();
Jail j = null;
double len = -1;
for(Jail jail : jails.values()) {
for (Jail jail : jails.values()) {
double clen = jail.getDistance(loc);
if (clen < len || len == -1) {
@ -178,20 +177,20 @@ public class JailManager {
}
return (j == null ? jails.values().iterator().next() : j);
}else {
} else {
return jails.values().iterator().next();
}
}
/**
* Gets the jail which this location is in, will return null if none exist.
*
*
* @param loc to get the jail from
* @return The jail this block is in, null if no jail found.
*/
public Jail getJailFromLocation(Location loc) {
for(Jail j : jails.values()) {
if(Util.isInsideAB(loc.toVector(), j.getMinPoint().toVector(), j.getMaxPoint().toVector())) {
for (Jail j : jails.values()) {
if (Util.isInsideAB(loc.toVector(), j.getMinPoint().toVector(), j.getMaxPoint().toVector())) {
return j;
}
}
@ -201,13 +200,13 @@ public class JailManager {
/**
* Gets whether the location is inside of a Jail.
*
*
* @param l to determine if is in a jail
* @return whether it is inside a jail or not
*/
public boolean isLocationAJail(Location l) {
for(Jail j : jails.values()) {
if(Util.isInsideAB(l.toVector(), j.getMinPoint().toVector(), j.getMaxPoint().toVector())) {
for (Jail j : jails.values()) {
if (Util.isInsideAB(l.toVector(), j.getMinPoint().toVector(), j.getMaxPoint().toVector())) {
return true;
}
}
@ -217,7 +216,7 @@ public class JailManager {
/**
* Checks to see if the given name for a {@link Jail} is valid, returns true if it is a valid jail.
*
*
* @param name The name of the jail to check.
* @return True if a valid jail was found, false if no jail was found.
*/
@ -227,13 +226,13 @@ public class JailManager {
/**
* Gets all the {@link Cell cells} in the jail system, best for system wide count of the cells or touching each cell.
*
*
* @return HashSet of all the Cells.
*/
public HashSet<Cell> getAllCells() {
HashSet<Cell> cells = new HashSet<Cell>();
HashSet<Cell> cells = new HashSet<>();
for(Jail j : jails.values())
for (Jail j : jails.values())
cells.addAll(j.getCells());
return cells;
@ -241,7 +240,7 @@ public class JailManager {
/**
* Adds a prisoner to the cache.
*
*
* @param cache object to store
* @return The same object given
*/
@ -253,7 +252,7 @@ public class JailManager {
/**
* Checks if the given uuid is in the cache.
*
*
* @param uuid of the player
* @return true if in cache, false if not
*/
@ -263,7 +262,7 @@ public class JailManager {
/**
* Gets a cached prisoner object.
*
*
* @param uuid of the prisoner to get
* @return the cahced prisoner object, will be null if it doesn't exist
*/
@ -273,7 +272,7 @@ public class JailManager {
/**
* Removes the cache object stored for this uuid.
*
*
* @param uuid of the prisoner to remove
*/
public void removeCacheObject(UUID uuid) {
@ -283,13 +282,13 @@ public class JailManager {
/**
* Gets all the prisoners in the system, best for a system wide count of the prisoners or accessing all the prisoners at once.
*
*
* @return HashSet of Prisoners.
*/
public HashMap<UUID, Prisoner> getAllPrisoners() {
HashMap<UUID, Prisoner> prisoners = new HashMap<UUID, Prisoner>();
HashMap<UUID, Prisoner> prisoners = new HashMap<>();
for(Jail j : jails.values())
for (Jail j : jails.values())
prisoners.putAll(j.getAllPrisoners());
return prisoners;
@ -297,33 +296,33 @@ public class JailManager {
/**
* Gets the {@link Jail jail} the given prisoner is in.
*
*
* @param prisoner The prisoner data for the prisoner we are checking
* @return The jail the player is in, <strong>CAN BE NULL</strong>.
*/
public Jail getJailPrisonerIsIn(Prisoner prisoner) {
if(prisoner == null) return null;
if (prisoner == null) return null;
else return getJailPlayerIsIn(prisoner.getUUID());
}
/**
* Gets the {@link Jail jail} the given player is in.
*
*
* <p>
* <p>
*
* Checks the cache first.
*
*
* @param uuid The uuid of the player who's jail we are getting.
* @return The jail the player is in, <strong>CAN BE NULL</strong>.
*/
public Jail getJailPlayerIsIn(UUID uuid) {
if(this.cache.containsKey(uuid)) {
if (this.cache.containsKey(uuid)) {
plugin.debug(uuid.toString() + " is in the cache (getJailPlayerIsIn).");
return this.cache.get(uuid).getJail();
}
for(Jail j : jails.values())
if(j.isPlayerJailed(uuid))
for (Jail j : jails.values())
if (j.isPlayerJailed(uuid))
return j;
return null;
@ -331,7 +330,7 @@ public class JailManager {
/**
* Gets if the given uuid of a player is jailed or not, in all the jails and cells.
*
*
* @param uuid The uuid of the player to check.
* @return true if they are jailed, false if not.
*/
@ -341,7 +340,7 @@ public class JailManager {
/**
* Gets the {@link Prisoner} data from for this user, if they are jailed.
*
*
* @param uuid The uuid of prisoner who's data to get
* @return {@link Prisoner prisoner} data.
*/
@ -353,14 +352,14 @@ public class JailManager {
/**
* Gets the {@link Jail} the player is in from their last known username, null if not jailed.
*
*
* @param username Last known username to search by
* @return {@link Jail jail} player is in
*/
public Jail getJailPlayerIsInByLastKnownName(String username) {
for(Jail j : jails.values())
for(Prisoner p : j.getAllPrisoners().values())
if(p.getLastKnownName().equalsIgnoreCase(username))
for (Jail j : jails.values())
for (Prisoner p : j.getAllPrisoners().values())
if (p.getLastKnownName().equalsIgnoreCase(username))
return j;
return null;
@ -368,13 +367,13 @@ public class JailManager {
/**
* Gets the {@link Prisoner}'s data from the last known username, returning null if no prisoner has that name.
*
*
* @param username Last known username to go by
* @return {@link Prisoner prisoner} data
*/
public Prisoner getPrisonerByLastKnownName(String username) {
for(Prisoner p : this.getAllPrisoners().values())
if(p.getLastKnownName().equalsIgnoreCase(username))
for (Prisoner p : this.getAllPrisoners().values())
if (p.getLastKnownName().equalsIgnoreCase(username))
return p;
return null;
@ -382,7 +381,7 @@ public class JailManager {
/**
* Checks if the provided username is jailed, using last known username.
*
*
* @param username Last known username to go by
* @return true if they are jailed, false if not
*/
@ -392,41 +391,41 @@ public class JailManager {
/**
* Clears a {@link Jail} of all its prisoners if the jail is provided, otherwise it releases all the prisoners in all the jails.
*
*
* @param jail The name of the jail to release the prisoners in, null if wanting to clear all.
* @return The resulting message to be sent to the caller of this method.
*/
public String clearJailOfPrisoners(String jail) {
//If they don't pass in a jail name, clear all the jails
if(jail != null) {
if (jail != null) {
Jail j = getJail(jail);
if(j != null) {
for(Prisoner p : j.getAllPrisoners().values()) {
if (j != null) {
for (Prisoner p : j.getAllPrisoners().values()) {
getPlugin().getPrisonerManager().schedulePrisonerRelease(p);
}
return Lang.PRISONERSCLEARED.get(j.getName());
}else {
} else {
return Lang.NOJAIL.get(jail);
}
}else {
} else {
return clearAllJailsOfAllPrisoners();
}
}
/**
* Clears all the {@link Jail jails} of prisoners by releasing them.
*
*
* @return The resulting message to be sent to the caller of this method.
*/
public String clearAllJailsOfAllPrisoners() {
//No name of a jail has been passed, so release all of the prisoners in all the jails
if(getJails().size() == 0) {
if (getJails().size() == 0) {
return Lang.NOJAILS.get();
}else {
for(Jail j : getJails()) {
for(Prisoner p : j.getAllPrisoners().values()) {
} else {
for (Jail j : getJails()) {
for (Prisoner p : j.getAllPrisoners().values()) {
getPlugin().getPrisonerManager().schedulePrisonerRelease(p);
}
}
@ -437,32 +436,32 @@ public class JailManager {
/**
* Forcefully clears all the jails if name provided is null.
*
*
* <p>
* <p>
*
* This method just clears them from the storage, doesn't release them.
*
*
* @param name of the jail to clear, null if all of them.
* @return The resulting message to be sent to the caller of this method.
*/
public String forcefullyClearJailOrJails(String name) {
if(name == null) {
if(getJails().size() == 0) {
if (name == null) {
if (getJails().size() == 0) {
return Lang.NOJAILS.get();
}else {
for(Jail j : getJails()) {
} else {
for (Jail j : getJails()) {
j.clearPrisoners();
}
return Lang.PRISONERSCLEARED.get(Lang.ALLJAILS);
}
}else {
} else {
Jail j = getJail(name);
if(j != null) {
if (j != null) {
j.clearPrisoners();
return Lang.PRISONERSCLEARED.get(j.getName());
}else {
} else {
return Lang.NOJAIL.get(name);
}
}
@ -470,31 +469,31 @@ public class JailManager {
/**
* Deletes a jail's cell, checking everything is setup right for it to be deleted.
*
*
* @param jail Name of the jail to delete a cell in.
* @param cell Name of the cell to delete.
* @return The resulting message to be sent to the caller of this method.
*/
public String deleteJailCell(String jail, String cell) {
//Check if the jail name provided is a valid jail
if(isValidJail(jail)) {
if (isValidJail(jail)) {
Jail j = getJail(jail);
//check if the cell is a valid cell
if(j.isValidCell(cell)) {
if(j.getCell(cell).hasPrisoner()) {
if (j.isValidCell(cell)) {
if (j.getCell(cell).hasPrisoner()) {
//The cell has a prisoner, so tell them to first transfer the prisoner
//or release the prisoner
return Lang.CELLREMOVALUNSUCCESSFUL.get(new String[] { cell, jail });
}else {
return Lang.CELLREMOVALUNSUCCESSFUL.get(cell, jail);
} else {
j.removeCell(cell);
return Lang.CELLREMOVED.get(new String[] { cell, jail });
return Lang.CELLREMOVED.get(cell, jail);
}
}else {
} else {
//No cell found by the provided name in the stated jail
return Lang.NOCELL.get(new String[] { cell, jail });
return Lang.NOCELL.get(cell, jail);
}
}else {
} else {
//No jail found by the provided name
return Lang.NOJAIL.get(jail);
}
@ -502,62 +501,62 @@ public class JailManager {
/**
* Deletes all the cells in a jail, returns a list of Strings.
*
*
* @param jail The name of the jail to delete all the jails in.
* @return An array of strings of messages to send.
*/
public String[] deleteAllJailCells(String jail) {
LinkedList<String> msgs = new LinkedList<String>();
LinkedList<String> msgs = new LinkedList<>();
//Check if the jail name provided is a valid jail
if(isValidJail(jail)) {
if (isValidJail(jail)) {
Jail j = getJail(jail);
if(j.getCellCount() == 0) {
if (j.getCellCount() == 0) {
//There are no cells in this jail, thus we can't delete them.
msgs.add(Lang.NOCELLS.get(j.getName()));
}else {
} else {
//Keep a local copy of the hashset so that we don't get any CMEs.
HashSet<Cell> cells = new HashSet<Cell>(j.getCells());
HashSet<Cell> cells = new HashSet<>(j.getCells());
for(Cell c : cells) {
if(c.hasPrisoner()) {
for (Cell c : cells) {
if (c.hasPrisoner()) {
//The cell has a prisoner, so tell them to first transfer the prisoner
//or release the prisoner
msgs.add(Lang.CELLREMOVALUNSUCCESSFUL.get(new String[] { c.getName(), j.getName() }));
}else {
msgs.add(Lang.CELLREMOVALUNSUCCESSFUL.get(c.getName(), j.getName()));
} else {
j.removeCell(c.getName());
msgs.add(Lang.CELLREMOVED.get(new String[] { c.getName(), j.getName() }));
msgs.add(Lang.CELLREMOVED.get(c.getName(), j.getName()));
}
}
}
}else {
} else {
//No jail found by the provided name
msgs.add(Lang.NOJAIL.get(jail));
}
return msgs.toArray(new String[msgs.size()]);
return msgs.toArray(new String[0]);
}
/**
* Deletes a jail while doing some checks to verify it can be deleted.
*
*
* @param jail The name of the jail to delete.
* @return The resulting message to be sent to the caller of this method.
*/
public String deleteJail(String jail) {
//Check if the jail name provided is a valid jail
if(isValidJail(jail)) {
if (isValidJail(jail)) {
//check if the jail doesn't contain prisoners
if(getJail(jail).getAllPrisoners().size() == 0) {
if (getJail(jail).getAllPrisoners().size() == 0) {
//There are no prisoners, so we can delete it
removeJail(jail);
return Lang.JAILREMOVED.get(jail);
}else {
} else {
//The jail has prisoners, they need to release them first
return Lang.JAILREMOVALUNSUCCESSFUL.get(jail);
}
}else {
} else {
//No jail found by the provided name
return Lang.NOJAIL.get(jail);
}
@ -565,11 +564,11 @@ public class JailManager {
/**
* Returns whether or not the player is creating a jail or a cell.
*
*
* <p>
* <p>
*
* If you want to check to see if they're just creating a jail then use {@link #isCreatingAJail(String) isCreatingAJail} or if you want to see if they're creating a cell then use {@link #isCreatingACell(String) isCreatingACell}.
*
*
* @param name The name of the player, in any case as we convert it to lowercase.
* @return True if the player is creating a jail or cell, false if they're not creating anything.
*/
@ -579,18 +578,18 @@ public class JailManager {
/**
* Returns a message used for telling them what they're creating and what step they're on.
*
*
* @param player the name of the player to check
* @return The details for the step they're on
*/
public String getStepMessage(String player) {
String message = "";
if(isCreatingACell(player)) {//Check whether it is a jail cell
if (isCreatingACell(player)) {//Check whether it is a jail cell
CreationPlayer cp = this.getCellCreationPlayer(player);
message = "You're already creating a Cell with the name '" + cp.getCellName() + "' and you still need to ";
switch(cp.getStep()) {
switch (cp.getStep()) {
case 1:
message += "set the teleport in location.";
break;
@ -602,11 +601,11 @@ public class JailManager {
break;
}
}else if(isCreatingAJail(player)) {//If not a cell, then check if a jail.
} else if (isCreatingAJail(player)) {//If not a cell, then check if a jail.
CreationPlayer cp = this.getJailCreationPlayer(player);
message = "You're already creating a Jail with the name '" + cp.getJailName() + "' and you still need to ";
switch(cp.getStep()) {
switch (cp.getStep()) {
case 1:
message += "select the first point.";
break;
@ -627,7 +626,7 @@ public class JailManager {
/**
* Returns whether or not someone is creating a <strong>Jail</strong>.
*
*
* @param name the player's name to check
* @return Whether they are creating a jail or not.
*/
@ -637,15 +636,15 @@ public class JailManager {
/**
* Method for setting a player to be creating a Jail, returns whether or not they were added successfully.
*
* @param player The player who is creating a jail.
*
* @param player The player who is creating a jail.
* @param jailName The name of the jail we are creating.
* @return True if they were added successfully, false if they are already creating a Jail.
*/
public boolean addCreatingJail(String player, String jailName) {
if(isCreatingAJail(player)) {
if (isCreatingAJail(player)) {
return false;
}else {
} else {
this.jailCreators.put(player.toLowerCase(), new CreationPlayer(jailName));
return true;
}
@ -653,7 +652,7 @@ public class JailManager {
/**
* Returns the instance of the CreationPlayer for this player, null if there was none found.
*
*
* @param name the player's name
* @return gets the player's {@link CreationPlayer} instance
*/
@ -663,7 +662,7 @@ public class JailManager {
/**
* Removes a CreationPlayer with the given name from the jail creators.
*
*
* @param name player's name to remove
*/
public void removeJailCreationPlayer(String name) {
@ -672,7 +671,7 @@ public class JailManager {
/**
* Returns whether or not someone is creating a <strong>Cell</strong>.
*
*
* @param name the player's name to check
* @return Whether they are creating a jail cell or not.
*/
@ -682,16 +681,16 @@ public class JailManager {
/**
* Method for setting a player to be creating a Cell, returns whether or not they were added successfully.
*
* @param player The player who is creating a jail.
*
* @param player The player who is creating a jail.
* @param jailName The name of the jail this cell is going.
* @param cellName The name of the cell we are creating.
* @return True if they were added successfully, false if they are already creating a Jail.
*/
public boolean addCreatingCell(String player, String jailName, String cellName) {
if(isCreatingACell(player)) {
if (isCreatingACell(player)) {
return false;
}else {
} else {
this.cellCreators.put(player.toLowerCase(), new CreationPlayer(jailName, cellName));
return true;
}
@ -699,7 +698,7 @@ public class JailManager {
/**
* Returns the instance of the CreationPlayer for this player, null if there was none found.
*
*
* @param name the player's name to get
* @return The player's {@link CreationPlayer} instance.
*/
@ -709,7 +708,7 @@ public class JailManager {
/**
* Removes a CreationPlayer with the given name from the cell creators.
*
*
* @param name player's name to remove
*/
public void removeCellCreationPlayer(String name) {
@ -718,7 +717,7 @@ public class JailManager {
/**
* Gets the instance of the {@link JailCreationSteps}.
*
*
* @return {@link JailCreationSteps} instance
*/
public JailCreationSteps getJailCreationSteps() {
@ -727,7 +726,7 @@ public class JailManager {
/**
* Gets the instance of the {@link CellCreationSteps}.
*
*
* @return the {@link CellCreationSteps} instance
*/
public CellCreationSteps getCellCreationSteps() {
@ -736,8 +735,8 @@ public class JailManager {
/**
* Adds something to the confirming list.
*
* @param name who to add
*
* @param name who to add
* @param confirmer {@link ConfirmPlayer} of what they're confirming
*/
public void addConfirming(String name, ConfirmPlayer confirmer) {
@ -747,7 +746,7 @@ public class JailManager {
/**
* Removes a name from the confirming list.
*
*
* @param name who to remove
*/
public void removeConfirming(String name) {
@ -756,7 +755,7 @@ public class JailManager {
/**
* Checks if the given name is confirming something.
*
*
* @param name the player's name
* @return Whether they are confirming something or not
*/
@ -766,7 +765,7 @@ public class JailManager {
/**
* Returns true if the confirmation has expired, false if it is still valid.
*
*
* @param name the player's name
* @return Whether their confirmation has expired or not.
*/
@ -777,7 +776,7 @@ public class JailManager {
/**
* Returns the original arguments for what we are confirming.
*
*
* @param name the player's name
* @return an array of strings which is their original arguments
*/
@ -787,7 +786,7 @@ public class JailManager {
/**
* Returns what the given name is confirming.
*
*
* @param name the player's name
* @return What they are confirming
*/

View File

@ -1,34 +1,34 @@
package com.graywolf336.jail;
import com.graywolf336.jail.beans.Prisoner;
import com.graywolf336.jail.enums.Settings;
import com.graywolf336.jail.interfaces.IJailPayManager;
import net.milkbowl.vault.economy.Economy;
import org.bukkit.Material;
import org.bukkit.entity.Player;
import org.bukkit.inventory.ItemStack;
import org.bukkit.plugin.RegisteredServiceProvider;
import com.graywolf336.jail.beans.Prisoner;
import com.graywolf336.jail.enums.Settings;
import com.graywolf336.jail.interfaces.IJailPayManager;
public class JailPayManager implements IJailPayManager {
private Economy economy = null;
private double minteCost, infiniteCost;
private final double minteCost;
private double infiniteCost;
private Material item;
private boolean infinite, timed;
private final boolean infinite;
private final boolean timed;
protected JailPayManager(JailMain plugin) {
this.item = Material.getMaterial(plugin.getConfig().getString(Settings.JAILPAYITEM.getPath()).toUpperCase());
if(this.item == null) {
plugin.getLogger().warning("Pay item is null, setting to air");
this.item = Material.AIR;
if (this.item == null) {
plugin.getLogger().warning("Pay item is null, setting to air");
this.item = Material.AIR;
}
this.minteCost = plugin.getConfig().getDouble(Settings.JAILPAYPRICEPERMINUTE.getPath());
if(!this.usingItemsForPayment()) {
if(!this.setupEconomy(plugin)) {
if (!this.usingItemsForPayment()) {
if (!this.setupEconomy(plugin)) {
plugin.getConfig().set(Settings.JAILPAYENABLED.getPath(), false);
}
}
@ -66,22 +66,22 @@ public class JailPayManager implements IJailPayManager {
}
public boolean hasEnoughToPay(Player p, double amt) {
if(this.usingItemsForPayment()) {
if (this.usingItemsForPayment()) {
return p.getInventory().contains(this.item, (int) Math.ceil(amt));
}else {
} else {
return this.economy.has(p, amt);
}
}
public void pay(Player p, double amt) {
if(this.usingItemsForPayment()) {
if (this.usingItemsForPayment()) {
int amtNeeded = (int) Math.ceil(amt);
for (int i = 0; i < p.getInventory().getSize(); i++) {
ItemStack it = p.getInventory().getItem(i);
//The item is either air or we doesn't match out needs
if(it == null || it.getType() != this.item) continue;
if (it == null || it.getType() != this.item) continue;
//If the itemstack has more than or equal to the amount
//that we need, remove it and subject from the amt needed
@ -97,33 +97,33 @@ public class JailPayManager implements IJailPayManager {
if (amtNeeded == 0) break;
}
}else {
} else {
this.economy.withdrawPlayer(p, amt);
}
}
public String getCurrencyName() {
if(this.usingItemsForPayment()) {
String name = item.toString().replaceAll("_", " ");
if (this.usingItemsForPayment()) {
StringBuilder name = new StringBuilder(item.toString().replaceAll("_", " "));
if(name.contains(" ")){
String[] split = name.split(" ");
for(int i=0; i < split.length; i++){
if (name.toString().contains(" ")) {
String[] split = name.toString().split(" ");
for (int i = 0; i < split.length; i++) {
split[i] = split[i].substring(0, 1).toUpperCase() + split[i].substring(1).toLowerCase();
}
name = "";
for(String s : split){
name += " " + s;
name = new StringBuilder();
for (String s : split) {
name.append(" ").append(s);
}
name = name.substring(1);
name = new StringBuilder(name.substring(1));
} else {
name = name.substring(0, 1).toUpperCase() + name.substring(1).toLowerCase();
name = new StringBuilder(name.substring(0, 1).toUpperCase() + name.substring(1).toLowerCase());
}
return name;
}else {
return name.toString();
} else {
return this.economy.currencyNamePlural();
}
}

View File

@ -1,49 +1,47 @@
package com.graywolf336.jail;
import com.graywolf336.jail.beans.Stick;
import com.graywolf336.jail.enums.Settings;
import com.graywolf336.jail.interfaces.IJailStickManager;
import org.bukkit.Material;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.UUID;
import org.bukkit.Material;
import com.graywolf336.jail.beans.Stick;
import com.graywolf336.jail.enums.Settings;
import com.graywolf336.jail.interfaces.IJailStickManager;
/**
* Manages the jail stick users.
*
*
* @author graywolf336
* @version 1.0.2
* @since 3.0.0
*
*/
public class JailStickManager implements IJailStickManager {
private ArrayList<UUID> stickers;
private HashMap<Material, Stick> sticks;
private final ArrayList<UUID> stickers;
private final HashMap<Material, Stick> sticks;
protected JailStickManager(JailMain plugin) {
this.stickers = new ArrayList<UUID>();
this.sticks = new HashMap<Material, Stick>();
this.stickers = new ArrayList<>();
this.sticks = new HashMap<>();
this.loadJailSticks(plugin);
}
private void loadJailSticks(JailMain pl) {
//item name,time,jail name,reason
if(pl.getJailManager().getJails().size() == 0) {
if (pl.getJailManager().getJails().size() == 0) {
pl.getLogger().warning("Can't have jail sticks without any jails.");
}else {
for(String s : pl.getConfig().getStringList(Settings.JAILSTICKSTICKS.getPath())) {
} else {
for (String s : pl.getConfig().getStringList(Settings.JAILSTICKSTICKS.getPath())) {
pl.debug(s);
String[] a = s.split(",");
String jail = a[2];
//Check if the jail given, if any, exists
if(jail.isEmpty()) {
if (jail.isEmpty()) {
jail = pl.getJailManager().getJail("").getName();
}else {
if(!pl.getJailManager().isValidJail(jail)) {
} else {
if (!pl.getJailManager().isValidJail(jail)) {
pl.getLogger().severe(s);
pl.getLogger().severe("The above jail stick configuration is invalid and references a jail that doesn't exist.");
continue;
@ -51,13 +49,13 @@ public class JailStickManager implements IJailStickManager {
}
Material m = Material.getMaterial(a[0].toUpperCase());
if(this.sticks.containsKey(m)) {
if (this.sticks.containsKey(m)) {
pl.getLogger().severe(s);
pl.getLogger().severe("You can not use the same item for two different Jail Sticks. This already exists as a Jail Stick: " + a[0]);
continue;
}
long time = 5;
long time;
try {
time = Util.getTime(a[1]);
} catch (Exception e) {
@ -67,12 +65,11 @@ public class JailStickManager implements IJailStickManager {
}
try {
this.sticks.put(m, new Stick(jail, a[3], time, a.length >= 5 ? Double.valueOf(a[4]) : -1));
}catch (Exception e) {
this.sticks.put(m, new Stick(jail, a[3], time, a.length >= 5 ? Double.parseDouble(a[4]) : -1));
} catch (Exception e) {
e.printStackTrace();
pl.getLogger().severe(s);
pl.getLogger().severe("Unable to create a new stick for " + a[0] + ", see the exception above for details.");
continue;
}
}
}
@ -80,7 +77,7 @@ public class JailStickManager implements IJailStickManager {
int c = sticks.size();
pl.getLogger().info("Loaded " + c + " jail stick" + (c == 1 ? "" : "s") + ".");
}
public Stick getStick(Material mat) {
return this.sticks.get(mat);
}
@ -102,17 +99,17 @@ public class JailStickManager implements IJailStickManager {
}
public boolean toggleUsingStick(UUID id) {
if(this.stickers.contains(id)) {
if (this.stickers.contains(id)) {
this.stickers.remove(id);
return false;
}else {
} else {
this.stickers.add(id);
return true;
}
}
public void removeAllStickUsers() {
for(UUID id : stickers) {
for (UUID id : stickers) {
this.removeUsingStick(id);
}
}

View File

@ -1,27 +1,23 @@
package com.graywolf336.jail;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.Timer;
import org.bukkit.entity.Player;
import com.graywolf336.jail.beans.Jail;
import com.graywolf336.jail.beans.Prisoner;
import com.graywolf336.jail.enums.Lang;
import com.graywolf336.jail.enums.Settings;
import com.graywolf336.jail.events.PrisonerTimeChangeEvent;
import org.bukkit.entity.Player;
import javax.swing.*;
/**
* Contains all the logic for counting down the time of the prisoners time.
*
*
* @author graywolf336
* @since 2.x.x
* @version 3.0.0
* @since 2.x.x
*/
public class JailTimer {
private JailMain pl;
private final JailMain pl;
private Timer timer;
private Long lastTime;
private Long afkTime = 0L;
@ -35,33 +31,27 @@ public class JailTimer {
}
this.lastTime = System.currentTimeMillis();
if(pl.getConfig().getBoolean(Settings.USEBUKKITTIMER.getPath())) {
if (pl.getConfig().getBoolean(Settings.USEBUKKITTIMER.getPath())) {
pl.getLogger().info("Using the Bukkit Scheduler.");
pl.getServer().getScheduler().runTaskTimerAsynchronously(pl, new TimeEvent(), 200, 200);
}else {
} else {
pl.getLogger().info("Using the Java Timer.");
timer = new Timer(10000, new ActionListener () {
public void actionPerformed (ActionEvent event) {
pl.getServer().getScheduler().scheduleSyncDelayedTask(pl, new TimeEvent());
};
});
timer = new Timer(10000, event -> pl.getServer().getScheduler().scheduleSyncDelayedTask(pl, new TimeEvent()));
timer.start();
}
//Save all the jail information every minute, not every 10 seconds
pl.getServer().getScheduler().runTaskTimerAsynchronously(pl, new Runnable() {
public void run() {
for(Jail j : pl.getJailManager().getJails()) {
pl.getJailIO().saveJail(j);
}
pl.getServer().getScheduler().runTaskTimerAsynchronously(pl, () -> {
for (Jail j : pl.getJailManager().getJails()) {
pl.getJailIO().saveJail(j);
}
}, 1200L, 1200L);
}
/**
* Returns the instance of this timer.
*
*
* @return the {@link Timer} instance
*/
public Timer getTimer() {
@ -73,60 +63,56 @@ public class JailTimer {
long timePassed = System.currentTimeMillis() - lastTime;
lastTime = System.currentTimeMillis();
for(Jail j : pl.getJailManager().getJails()) {
for(Prisoner p : j.getAllPrisoners().values()) {
for (Jail j : pl.getJailManager().getJails()) {
for (Prisoner p : j.getAllPrisoners().values()) {
//only execute this code if the prisoner's time is more than 0 milliseconds
//and they don't have any offline pending things
if(p.getRemainingTime() > 0 && !p.isOfflinePending()) {
if (p.getRemainingTime() > 0 && !p.isOfflinePending()) {
final Player player = pl.getServer().getPlayer(p.getUUID());
//Check if the player is offline
if(player == null) {
if (player == null) {
//if they are offline AND the config has counting down the time
//while the prisoner is offline, then let's do it
if(pl.getConfig().getBoolean(Settings.COUNTDOWNTIMEOFFLINE.getPath())) {
if (pl.getConfig().getBoolean(Settings.COUNTDOWNTIMEOFFLINE.getPath())) {
//Set their remaining time but if it is less than zero, set it to zero
long before = p.getRemainingTime();
long after = Math.max(0, p.getRemainingTime() - timePassed);
PrisonerTimeChangeEvent event = new PrisonerTimeChangeEvent(j, j.getCellPrisonerIsIn(p.getUUID()), p, player, before, after);
pl.getServer().getPluginManager().callEvent(event);
if(!event.isCancelled()) {
after = event.getTimeAfterChange();
p.setRemainingTime(after);
if(p.getRemainingTime() == 0) pl.getPrisonerManager().schedulePrisonerRelease(p);
}
long before = p.getRemainingTime();
long after = Math.max(0, p.getRemainingTime() - timePassed);
PrisonerTimeChangeEvent event = new PrisonerTimeChangeEvent(j, j.getCellPrisonerIsIn(p.getUUID()), p, player, before, after);
pl.getServer().getPluginManager().callEvent(event);
if (!event.isCancelled()) {
after = event.getTimeAfterChange();
p.setRemainingTime(after);
if (p.getRemainingTime() == 0) pl.getPrisonerManager().schedulePrisonerRelease(p);
}
}
}else {
if(afkTime > 0) {
} else {
if (afkTime > 0) {
p.setAFKTime(p.getAFKTime() + timePassed);
if(p.getAFKTime() > afkTime) {
if (p.getAFKTime() > afkTime) {
p.setAFKTime(0);
//This is so we kick players on the main thread
//instead of on the async thread(s), as spigot
//has a protection against this enabled.
pl.getServer().getScheduler().scheduleSyncDelayedTask(pl, new Runnable() {
public void run() {
player.kickPlayer(Lang.AFKKICKMESSAGE.get());
}
});
pl.getServer().getScheduler().scheduleSyncDelayedTask(pl, () -> player.kickPlayer(Lang.AFKKICKMESSAGE.get()));
}
}
//The prisoner isn't offline, so let's count down
//Set their remaining time but if it is less than zero, set it to zero
long before = p.getRemainingTime();
long after = Math.max(0, p.getRemainingTime() - timePassed);
PrisonerTimeChangeEvent event = new PrisonerTimeChangeEvent(j, j.getCellPrisonerIsIn(p.getUUID()), p, player, before, after);
pl.getServer().getPluginManager().callEvent(event);
if(!event.isCancelled()) {
after = event.getTimeAfterChange();
p.setRemainingTime(after);
if(p.getRemainingTime() == 0) pl.getPrisonerManager().schedulePrisonerRelease(p);
}
long after = Math.max(0, p.getRemainingTime() - timePassed);
PrisonerTimeChangeEvent event = new PrisonerTimeChangeEvent(j, j.getCellPrisonerIsIn(p.getUUID()), p, player, before, after);
pl.getServer().getPluginManager().callEvent(event);
if (!event.isCancelled()) {
after = event.getTimeAfterChange();
p.setRemainingTime(after);
if (p.getRemainingTime() == 0) pl.getPrisonerManager().schedulePrisonerRelease(p);
}
}
}
}

View File

@ -1,9 +1,5 @@
package com.graywolf336.jail;
import java.util.HashMap;
import java.util.UUID;
import java.util.concurrent.TimeUnit;
import com.graywolf336.jail.beans.Jail;
import com.graywolf336.jail.beans.JailVote;
import com.graywolf336.jail.beans.Prisoner;
@ -12,207 +8,211 @@ import com.graywolf336.jail.enums.Lang;
import com.graywolf336.jail.enums.Settings;
import com.graywolf336.jail.events.PrePrisonerJailedEvent;
import java.util.HashMap;
import java.util.UUID;
import java.util.concurrent.TimeUnit;
/**
* Manages all the votes to jail players.
*
*
* @author graywolf336
* @since 3.0.0
* @version 1.0.0
* @since 3.0.0
*/
public class JailVoteManager {
private JailMain pl;
private HashMap<String, JailVote> votes;
private HashMap<String, Integer> tasks;
private String timerDesc, reason;
private long timerTicks, jailTime;
private int minYes;
private final JailMain pl;
private final HashMap<String, JailVote> votes;
private final HashMap<String, Integer> tasks;
private final String timerDesc;
private final String reason;
private final long timerTicks;
private final long jailTime;
private final int minYes;
/**
* Creates a new instance of this Jail Vote manager.
*
*
* @param plugin the {@link JailMain} instance
* @throws Exception When it can't load the time correctly
*/
protected JailVoteManager(JailMain plugin) throws Exception {
this.pl = plugin;
this.votes = new HashMap<String, JailVote>();
this.tasks = new HashMap<String, Integer>();
this.votes = new HashMap<>();
this.tasks = new HashMap<>();
this.reason = plugin.getConfig().getString(Settings.JAILVOTEREASON.getPath());
String timer = plugin.getConfig().getString(Settings.JAILVOTETIMER.getPath());
this.timerDesc = Util.getDurationBreakdown(Util.getTime(timer));
this.timerTicks = Util.getTime(timer, TimeUnit.SECONDS) * 20;
this.jailTime = Util.getTime(plugin.getConfig().getString(Settings.JAILVOTETIME.getPath()));
this.minYes = plugin.getConfig().getInt(Settings.JAILMINYESVOTES.getPath());
}
/**
* Gets all the votes to jail someone.
*
*
* @return HashMap of all the votes
*/
public HashMap<String, JailVote> getVotes() {
return this.votes;
}
/**
* Gets the jail vote for the given player name, returning null if it doesn't exist.
*
*
* @param name of the player to get the jail vote for
* @return {@link JailVote} for the player
*/
public JailVote getVoteForPlayer(String name) {
return this.votes.get(name);
}
/**
* Adds a vote to jail someone.
*
*
* @param v the {@link JailVote} to add.
* @return true if the vote was added, false if a vote already exists for that player name.
*/
public boolean addVote(JailVote v) {
if(this.votes.containsKey(v.getPlayerName())) {
if (this.votes.containsKey(v.getPlayerName())) {
return false;
}else {
} else {
this.votes.put(v.getPlayerName(), v);
return true;
}
}
/**
* Adds a vote for the given player's name.
*
* @param name the name of the player the vote is for.
* @param id the uuid of the player voting.
*
* @param name the name of the player the vote is for.
* @param id the uuid of the player voting.
* @param which whether they are voting yes or no, true if yes false if no.
* @return True if the vote was successful, false if it was unsuccessful.
*/
public boolean addVote(String name, UUID id, boolean which) {
if(this.votes.containsKey(name)) {
if (this.votes.containsKey(name)) {
pl.debug(id.toString() + " voted " + (which ? "yes" : "no") + " to jail " + name);
if(which) {
if (which) {
return this.votes.get(name).voteYes(id);
}else {
} else {
return this.votes.get(name).voteNo(id);
}
}else {
} else {
return false;
}
}
/**
* Checks if the uuid provided has voted for the player name provided.
*
*
* @param name of the vote for to check against
* @param id of the player voting
* @param id of the player voting
* @return whether the player has voted for the username provided.
*/
public boolean hasVotedAlready(String name, UUID id) {
if(this.votes.containsKey(name)) {
if (this.votes.containsKey(name)) {
return this.votes.get(name).hasVoted(id);
}else {
} else {
return false;
}
}
/**
* Checks if a player is voted for or not.
*
*
* @param name of the player to check for.
* @return true if they were voted for, false if not.
*/
public boolean isVotedFor(String name) {
return this.votes.containsKey(name);
}
/**
* Returns the nice formatted time of how long a vote is open.
*
*
* @return The vote length description
*/
public String getTimerLengthDescription() {
return this.timerDesc;
}
/**
* Returns the minimum amount of yes votes required to jail someone.
*
*
* @return Minimum amount of votes required.
*/
public int getMinimumYesVotes() {
return this.minYes;
}
/**
* Gets the current running tasks ids.
*
*
* @return HashMap of all the current current tasks
*/
public HashMap<String, Integer> getRunningTasks() {
return this.tasks;
}
/**
* Schedules the calculation of whether a jail vote should jail or not jail.
*
*
* @param name the name of the person who is being voted to be jailed
*/
public void scheduleCalculating(final String name) {
int taskId = pl.getServer().getScheduler().runTaskLater(pl, new Runnable() {
public void run() {
doTheVoteCalculation(votes.get(name));
tasks.remove(name);
}
int taskId = pl.getServer().getScheduler().runTaskLater(pl, () -> {
doTheVoteCalculation(votes.get(name));
tasks.remove(name);
}, timerTicks).getTaskId();
this.tasks.put(name, taskId);
}
/**
* Calculates the votes, determining whether there are enough votes to jail the person or not.
*
*
* @param v the {@link JailVote} to do the calculation of.
* @return the {@link JailVoteResult} of the vote.
*/
public JailVoteResult doTheVoteCalculation(JailVote v) {
JailVoteResult result;
if(v.getPlayer() == null) {
if (v.getPlayer() == null) {
pl.getServer().broadcastMessage(Lang.VOTEPLAYERNOLONGERONLINE.get(v.getPlayerName()));
result = JailVoteResult.NOTONLINE;
}else {
if(v.getYesVotes() > v.getNoVotes()) {
if(v.getYesVotes() >= getMinimumYesVotes()) {
} else {
if (v.getYesVotes() > v.getNoVotes()) {
if (v.getYesVotes() >= getMinimumYesVotes()) {
Prisoner p = new Prisoner(v.getPlayer().getUniqueId().toString(), v.getPlayerName(), pl.getConfig().getBoolean(Settings.AUTOMATICMUTE.getPath()), jailTime, "[JailVote]", reason);
//Get the jail name, check for the nearest one
String jailName = pl.getConfig().getString(Settings.DEFAULTJAIL.getPath());
if(jailName.equalsIgnoreCase("nearest")) {
if (jailName.equalsIgnoreCase("nearest")) {
Jail j = pl.getJailManager().getNearestJail(v.getPlayer());
if(j != null) {
if (j != null) {
jailName = j.getName();
}
}
//Get the jail instance from the name of jail in the params.
Jail j = pl.getJailManager().getJail(jailName);
if(j == null) {
if (j == null) {
pl.getLogger().warning("Jail Vote Failed: no jail was found?");
result = JailVoteResult.NOJAIL;
}else if(!j.isEnabled()) {
} else if (!j.isEnabled()) {
pl.getLogger().warning("Jail Vote Failed: " + Lang.WORLDUNLOADED.get(j.getName()));
result = JailVoteResult.JAILNOTENABLED;
}else {
} else {
//call the event
PrePrisonerJailedEvent event = new PrePrisonerJailedEvent(j, null, p, v.getPlayer(), v.getPlayer() == null, p.getJailer());
pl.getServer().getPluginManager().callEvent(event);
//check if the event is cancelled
if(event.isCancelled()) {
if (event.isCancelled()) {
pl.getLogger().warning("Jail Vote Failed: The PrePrisonerJailedEvent was cancelled for some reason.");
result = JailVoteResult.EVENTCANCELLED;
}else {
} else {
try {
pl.getPrisonerManager().prepareJail(j, null, v.getPlayer(), p);
result = JailVoteResult.YES;
@ -223,19 +223,19 @@ public class JailVoteManager {
}
}
}
}else {
pl.getServer().broadcastMessage(Lang.VOTESNOTENOUGHYES.get(new String[] { v.getPlayerName(), String.valueOf(v.getYesVotes()), String.valueOf(minYes) }));
} else {
pl.getServer().broadcastMessage(Lang.VOTESNOTENOUGHYES.get(v.getPlayerName(), String.valueOf(v.getYesVotes()), String.valueOf(minYes)));
result = JailVoteResult.NOTENOUGHYESVOTES;
}
}else if(v.getYesVotes() == v.getNoVotes()) {
} else if (v.getYesVotes() == v.getNoVotes()) {
pl.getServer().broadcastMessage(Lang.VOTESTIED.get(v.getPlayerName()));
result = JailVoteResult.TIED;
}else {
} else {
pl.getServer().broadcastMessage(Lang.VOTESSAIDNO.get(v.getPlayerName()));
result = JailVoteResult.NO;
}
}
votes.remove(v.getPlayerName());
return result;
}

View File

@ -6,7 +6,7 @@ import com.graywolf336.jail.interfaces.IJailStickManager;
* The static api interface for Jail plugin.
*
* <p>
*
* <p>
* If you're looking for non-static methods, please see the
* {@link JailMain} interface.
*
@ -20,19 +20,19 @@ public class JailsAPI {
protected JailsAPI(JailMain plugin) {
pl = plugin;
}
/**
* Returns the build number, it will return <strong>-1</strong> if an errors occurs.
*
*
* @return the build number of jail or -1 if an error occurred.
*/
public static int getBuildNumber() {
String v = pl.getDescription().getVersion();
String[] split = v.split("-");
try {
return Integer.parseInt(split[split.length - 1].replace("b", ""));
}catch(NumberFormatException e) {
} catch (NumberFormatException e) {
return -1;
}
}

View File

@ -1,16 +1,5 @@
package com.graywolf336.jail;
import java.util.ArrayList;
import java.util.List;
import java.util.UUID;
import org.bukkit.GameMode;
import org.bukkit.Material;
import org.bukkit.command.CommandSender;
import org.bukkit.entity.Player;
import org.bukkit.inventory.Inventory;
import org.bukkit.inventory.ItemStack;
import com.graywolf336.jail.beans.AnyCell;
import com.graywolf336.jail.beans.Cell;
import com.graywolf336.jail.beans.Jail;
@ -28,6 +17,16 @@ import com.graywolf336.jail.exceptions.JailRequiredException;
import com.graywolf336.jail.exceptions.PrisonerAlreadyJailedException;
import com.graywolf336.jail.exceptions.PrisonerRequiredException;
import com.graywolf336.jail.interfaces.ICell;
import org.bukkit.GameMode;
import org.bukkit.Material;
import org.bukkit.command.CommandSender;
import org.bukkit.entity.Player;
import org.bukkit.inventory.Inventory;
import org.bukkit.inventory.ItemStack;
import java.util.ArrayList;
import java.util.List;
import java.util.UUID;
/**
* Provides methods, non-statically, that do the preparing of jails, jailing, etc.
@ -44,30 +43,26 @@ import com.graywolf336.jail.interfaces.ICell;
* </ul>
*
* @author graywolf336
* @since 2.x.x
* @version 3.0.0
* @since 2.x.x
*/
public class PrisonerManager {
private JailMain pl;
private ArrayList<Prisoner> releases;
private final JailMain pl;
private final ArrayList<Prisoner> releases;
protected PrisonerManager(JailMain plugin) {
this.pl = plugin;
this.releases = new ArrayList<Prisoner>();
this.releases = new ArrayList<>();
// Schedule the releasing of prisoners
plugin.getServer().getScheduler().scheduleSyncRepeatingTask(plugin, new Runnable() {
public void run() {
releaseScheduledPrisoners();
}
}, 100L, 20L);
plugin.getServer().getScheduler().scheduleSyncRepeatingTask(plugin, this::releaseScheduledPrisoners, 100L, 20L);
}
/**
* Does everything preparing for the jailing of the provided prisoner, if they are online it forwards it to {@link #jailPrisoner(Jail, ICell, Player, Prisoner)}.
*
* <p>
*
* <p>
* In this we do the following:
* <ol>
* <li>Checks if the jail is null, if so it throws an Exception</li>
@ -81,75 +76,71 @@ public class PrisonerManager {
* <li>If we log the jailing to console <em>and</em> we haven't broadcasted it, then we log it to the console.</li>
* </ol>
*
* @param jail The {@link Jail jail instance} we are sending this prisoner to
* @param cell The name of the {@link ICell cell} we are sending this prisoner to
* @param player The {@link Player player} we are preparing the jail for.
* @param jail The {@link Jail jail instance} we are sending this prisoner to
* @param cell The name of the {@link ICell cell} we are sending this prisoner to
* @param player The {@link Player player} we are preparing the jail for.
* @param prisoner The {@link Prisoner prisoner} file.
* @throws JailRequiredException if the jail provided is null.
* @throws JailRequiredException if the jail provided is null.
* @throws PrisonerAlreadyJailedException if the prisoner is already jailed.
* @throws PrisonerRequiredException if the prisoner's data provided is null.
* @throws PrisonerRequiredException if the prisoner's data provided is null.
*/
public void prepareJail(final Jail jail, ICell cell, final Player player, final Prisoner prisoner) throws JailRequiredException, PrisonerAlreadyJailedException, PrisonerRequiredException {
//Do some checks of whether the passed params are null.
if(jail == null)
if (jail == null)
throw new JailRequiredException("jailing a prisoner");
if(cell == null)
if (cell == null)
cell = new NoCell();
if(prisoner == null)
if (prisoner == null)
throw new PrisonerRequiredException("jailing a prisoner");
if(this.pl.getJailManager().isPlayerJailed(prisoner.getUUID()))
if (this.pl.getJailManager().isPlayerJailed(prisoner.getUUID()))
throw new PrisonerAlreadyJailedException(prisoner.getLastKnownName(), prisoner.getUUID().toString());
//Set whether the prisoner is offline or not.
prisoner.setOfflinePending(player == null);
//Now that we've got those checks out of the way, let's start preparing.
if(cell instanceof NoCell) {
if (cell instanceof NoCell) {
jail.addPrisoner(prisoner);
cell = null;
}else if(cell instanceof AnyCell) {
} else if (cell instanceof AnyCell) {
cell = jail.getFirstEmptyCell();
if(cell == null)
if (cell == null)
jail.addPrisoner(prisoner);
else
cell.setPrisoner(prisoner);
}else {
} else {
cell.setPrisoner(prisoner);
}
//If they are are offline then throw the event otherwise jail them
if(prisoner.isOfflinePending()) {
if (prisoner.isOfflinePending()) {
pl.getServer().getPluginManager().callEvent(new OfflinePrisonerJailedEvent(jail, cell, prisoner));
}else {
} else {
final ICell c = cell;
pl.getServer().getScheduler().runTask(pl, new Runnable() {
public void run() {
jailPrisoner(jail, c, player, prisoner);
}
});
pl.getServer().getScheduler().runTask(pl, () -> jailPrisoner(jail, c, player, prisoner));
}
//Get a message ready for broadcasting or logging.
String msg = "";
String msg;
if(prisoner.getRemainingTime() < 0L)
msg = Lang.BROADCASTMESSAGEFOREVER.get(new String[] { prisoner.getLastKnownName(), prisoner.getReason(), jail.getName(), cell == null ? "" : cell.getName() });
if (prisoner.getRemainingTime() < 0L)
msg = Lang.BROADCASTMESSAGEFOREVER.get(prisoner.getLastKnownName(), prisoner.getReason(), jail.getName(), cell == null ? "" : cell.getName());
else
msg = Lang.BROADCASTMESSAGEFORMINUTES.get(new String[] { prisoner.getLastKnownName(), String.valueOf(prisoner.getRemainingTimeInMinutes()), prisoner.getReason(), jail.getName(), cell == null ? "" : cell.getName() });
msg = Lang.BROADCASTMESSAGEFORMINUTES.get(prisoner.getLastKnownName(), String.valueOf(prisoner.getRemainingTimeInMinutes()), prisoner.getReason(), jail.getName(), cell == null ? "" : cell.getName());
boolean broadcasted = false;
//Broadcast the message, if it is enabled
if(pl.getConfig().getBoolean(Settings.BROADCASTJAILING.getPath(), false)) {
if (pl.getConfig().getBoolean(Settings.BROADCASTJAILING.getPath(), false)) {
pl.getServer().broadcast(msg, "jail.see.broadcast");
broadcasted = true;
}
//Log the message, if it is enabled
if(pl.getConfig().getBoolean(Settings.LOGJAILINGTOCONSOLE.getPath(), true) && !broadcasted) {
if (pl.getConfig().getBoolean(Settings.LOGJAILINGTOCONSOLE.getPath(), true) && !broadcasted) {
pl.getServer().getConsoleSender().sendMessage(msg);
}
}
@ -167,20 +158,20 @@ public class PrisonerManager {
/**
* Jails the prisoner with the proper information given.
*
* @param jail where they are going
* @param cell where they are being placed in, can be null
* @param player who is the prisoner
* @param jail where they are going
* @param cell where they are being placed in, can be null
* @param player who is the prisoner
* @param prisoner data containing everything pertaining to them
*/
protected void jailPrisoner(final Jail jail, ICell cell, final Player player, final Prisoner prisoner) {
if(cell instanceof NoCell)
if (cell instanceof NoCell)
cell = null;
else if(cell instanceof AnyCell)
else if (cell instanceof AnyCell)
cell = null;
//If they have handcuffs on them, then let's remove them before we continue
//this way the handcuff listeners and this aren't battleing each other
if(pl.getHandCuffManager().isHandCuffed(player.getUniqueId())) {
if (pl.getHandCuffManager().isHandCuffed(player.getUniqueId())) {
pl.getHandCuffManager().removeHandCuffs(player.getUniqueId());
}
@ -192,21 +183,21 @@ public class PrisonerManager {
prisoner.setTeleporting(true);
//If their reason is empty send proper message, else send other proper message
if(prisoner.getReason().isEmpty()) {
if (prisoner.getReason().isEmpty()) {
player.sendMessage(Lang.JAILED.get());
}else {
} else {
player.sendMessage(Lang.JAILEDWITHREASON.get(prisoner.getReason()));
}
//If the config has releasing them back to their previous position,
//then let's set it in the prisoner data.
if(pl.getConfig().getBoolean(Settings.RELEASETOPREVIOUSPOSITION.getPath(), false)) {
if (pl.getConfig().getBoolean(Settings.RELEASETOPREVIOUSPOSITION.getPath(), false)) {
prisoner.setPreviousPosition(player.getLocation());
}
//If the config has restoring their previous gamemode enabled,
//then let's set it in their prisoner data.
if(pl.getConfig().getBoolean(Settings.RESTOREPREVIOUSGAMEMODE.getPath(), false)) {
if (pl.getConfig().getBoolean(Settings.RESTOREPREVIOUSGAMEMODE.getPath(), false)) {
prisoner.setPreviousGameMode(player.getGameMode());
}
@ -214,10 +205,10 @@ public class PrisonerManager {
//from the parsing then we set theirs to adventure
try {
player.setGameMode(GameMode.valueOf(pl.getConfig().getString(Settings.JAILEDGAMEMODE.getPath(), "ADVENTURE").toUpperCase()));
}catch(Exception e) {
} catch (Exception e) {
StringBuilder gamemodes = new StringBuilder();
for(GameMode m : GameMode.values()) {
if(gamemodes.length() != 0)
for (GameMode m : GameMode.values()) {
if (gamemodes.length() != 0)
gamemodes.append(", ");
gamemodes.append(m.toString().toLowerCase());
@ -225,19 +216,19 @@ public class PrisonerManager {
pl.getLogger().warning("Your jailed gamemode setting is problematic. It is currently '"
+ pl.getConfig().getString(Settings.JAILEDGAMEMODE.getPath())
+ "' and should be one of the following: " + gamemodes.toString());
+ "' and should be one of the following: " + gamemodes);
player.setGameMode(GameMode.ADVENTURE);
}
//only eject them if they're inside a vehicle and also eject anyone else on top of them
if(player.isInsideVehicle()) {
if (player.isInsideVehicle()) {
player.getVehicle().eject();
player.eject();
}
//If we are ignoring the sleeping state of prisoners,
//then let's set that
if(pl.getConfig().getBoolean(Settings.IGNORESLEEPINGSTATE.getPath(), true)) {
if (pl.getConfig().getBoolean(Settings.IGNORESLEEPINGSTATE.getPath(), true)) {
player.setSleepingIgnored(true);
}
@ -247,92 +238,88 @@ public class PrisonerManager {
//If their food level is less than the min food level, set it to the min
//but if it is higher than the max, set it to the max
if (player.getFoodLevel() < minFood) {
if (player.getFoodLevel() < minFood) {
player.setFoodLevel(minFood);
} else if (player.getFoodLevel() > maxFood) {
player.setFoodLevel(maxFood);
}
//If the cell doesn't equal null, then let's put them in the jail
if(cell != null) {
if (cell != null) {
//Teleport them to the cell's teleport location
//they will now be placed in jail.
pl.debug("Teleporting " + player.getName() + " to " + jail.getName() + " in the cell " + cell.getName() + "'s in: " + jail.getTeleportIn().toString());
player.teleport(cell.getTeleport());
//check if we store the inventory
if(pl.getConfig().getBoolean(Settings.JAILEDSTOREINVENTORY.getPath(), true)) {
if (pl.getConfig().getBoolean(Settings.JAILEDSTOREINVENTORY.getPath(), true)) {
final ICell theCell = cell;
pl.getServer().getScheduler().runTaskLater(pl, new Runnable() {
public void run() {
List<String> blacklist = pl.getConfig().getStringList(Settings.JAILEDINVENTORYBLACKLIST.getPath());
//Check if there is a chest to store our items to and if it is a double chest, if not we will then serialize it
if(theCell.hasChest()) {
//Get the chest's inventory and then clear it
Inventory chest = theCell.getChest().getInventory();
chest.clear();
pl.getServer().getScheduler().runTaskLater(pl, () -> {
List<String> blacklist = pl.getConfig().getStringList(Settings.JAILEDINVENTORYBLACKLIST.getPath());
//Check if there is a chest to store our items to and if it is a double chest, if not we will then serialize it
if (theCell.hasChest()) {
//Get the chest's inventory and then clear it
Inventory chest = theCell.getChest().getInventory();
chest.clear();
//Get the separate inventory, so we can iterate of them
ItemStack[] inventory = player.getInventory().getContents();
//Get the separate inventory, so we can iterate of them
ItemStack[] inventory = player.getInventory().getContents();
for(ItemStack item : inventory) {
if(item != null) {
if(!Util.isStringInsideList(item.getType().toString(), blacklist)) {
int i = chest.firstEmpty();
if(i != -1) {//Check that we have got a free spot, should never happen but just in case
chest.setItem(i, item);
}
for (ItemStack item : inventory) {
if (item != null) {
if (!Util.isStringInsideList(item.getType().toString(), blacklist)) {
int i = chest.firstEmpty();
if (i != -1) {//Check that we have got a free spot, should never happen but just in case
chest.setItem(i, item);
}
}
}
player.getInventory().clear();
}else {
for(ItemStack item : player.getInventory().getContents())
if(item != null)
if(Util.isStringInsideList(item.getType().toString(), blacklist))
player.getInventory().remove(item);
for(ItemStack item : player.getInventory().getArmorContents())
if(item != null)
if(Util.isStringInsideList(item.getType().toString(), blacklist))
player.getInventory().remove(item);
prisoner.setInventory(Util.toBase64(player.getInventory()));
player.getInventory().setArmorContents(null);
player.getInventory().clear();
}
};
}, 10);
}
}else {
//Teleport them to the jail's teleport in location
//They will now be placed in jail.
pl.debug("Teleporting " + player.getName() + " to " + jail.getName() + "'s in: " + jail.getTeleportIn().toString());
player.teleport(jail.getTeleportIn());
//There is no cell we're jailing them to, so stick them in the jail
if(pl.getConfig().getBoolean(Settings.JAILEDSTOREINVENTORY.getPath(), true)) {
pl.getServer().getScheduler().runTaskLater(pl, new Runnable() {
public void run() {
List<String> blacklist = pl.getConfig().getStringList(Settings.JAILEDINVENTORYBLACKLIST.getPath());
for(ItemStack item : player.getInventory().getContents())
if(item != null)
if(Util.isStringInsideList(item.getType().toString(), blacklist))
player.getInventory().clear();
} else {
for (ItemStack item : player.getInventory().getContents())
if (item != null)
if (Util.isStringInsideList(item.getType().toString(), blacklist))
player.getInventory().remove(item);
for(ItemStack item : player.getInventory().getArmorContents())
if(item != null)
if(Util.isStringInsideList(item.getType().toString(), blacklist))
for (ItemStack item : player.getInventory().getArmorContents())
if (item != null)
if (Util.isStringInsideList(item.getType().toString(), blacklist))
player.getInventory().remove(item);
prisoner.setInventory(Util.toBase64(player.getInventory()));
player.getInventory().setArmorContents(null);
player.getInventory().clear();
};
}
}, 10);
}
} else {
//Teleport them to the jail's teleport in location
//They will now be placed in jail.
pl.debug("Teleporting " + player.getName() + " to " + jail.getName() + "'s in: " + jail.getTeleportIn().toString());
player.teleport(jail.getTeleportIn());
//There is no cell we're jailing them to, so stick them in the jail
if (pl.getConfig().getBoolean(Settings.JAILEDSTOREINVENTORY.getPath(), true)) {
pl.getServer().getScheduler().runTaskLater(pl, () -> {
List<String> blacklist = pl.getConfig().getStringList(Settings.JAILEDINVENTORYBLACKLIST.getPath());
for (ItemStack item : player.getInventory().getContents())
if (item != null)
if (Util.isStringInsideList(item.getType().toString(), blacklist))
player.getInventory().remove(item);
for (ItemStack item : player.getInventory().getArmorContents())
if (item != null)
if (Util.isStringInsideList(item.getType().toString(), blacklist))
player.getInventory().remove(item);
prisoner.setInventory(Util.toBase64(player.getInventory()));
player.getInventory().setArmorContents(null);
player.getInventory().clear();
}, 10);
}
}
@ -343,7 +330,7 @@ public class PrisonerManager {
//Get the commands to execute after they are jailed
//replace all of the %p% so that the commands can have a player name in them
for(String command : pl.getConfig().getStringList(Settings.COMMANDSONJAIL.getPath())) {
for (String command : pl.getConfig().getStringList(Settings.COMMANDSONJAIL.getPath())) {
command = command.replaceAll("%p%", player.getName());
command = command.replaceAll("%player%", player.getName());
command = command.replaceAll("%uuid%", player.getUniqueId().toString());
@ -352,7 +339,7 @@ public class PrisonerManager {
}
//Add the scoreboard to them if it is enabled
if(pl.getConfig().getBoolean(Settings.SCOREBOARDENABLED.getPath())) {
if (pl.getConfig().getBoolean(Settings.SCOREBOARDENABLED.getPath())) {
pl.getScoreBoardManager().addScoreBoard(player, prisoner);
}
@ -360,15 +347,15 @@ public class PrisonerManager {
pl.getJailIO().saveJail(jail);
//Call our custom event for when a prisoner is actually jailed.
PrisonerJailedEvent event = new PrisonerJailedEvent(jail, cell == null ? null : (Cell)cell, prisoner, player);
PrisonerJailedEvent event = new PrisonerJailedEvent(jail, cell == null ? null : (Cell) cell, prisoner, player);
pl.getServer().getPluginManager().callEvent(event);
}
/**
* Schedules a prisoner to be released, this method is to be used <strong>async</strong>.
*
*
* <p>
* <p>
*
* If you're wanting to unjail a prisoner, see the {@link #unJail(Jail, ICell, Player, Prisoner, CommandSender)} method.
*
* @param prisoner to be released.
@ -378,8 +365,8 @@ public class PrisonerManager {
}
private void releaseScheduledPrisoners() {
ArrayList<Prisoner> lettingGo = new ArrayList<Prisoner>(releases);
for(Prisoner p : lettingGo) {
ArrayList<Prisoner> lettingGo = new ArrayList<>(releases);
for (Prisoner p : lettingGo) {
releases.remove(p);
releasePrisoner(pl.getServer().getPlayer(p.getUUID()), p);
}
@ -388,20 +375,20 @@ public class PrisonerManager {
/**
* Release the given prisoner from jailing, does the checks if they are offline or not.
*
* @param player we are releasing, can be null and if so they'll be treated as offline.
* @param player we are releasing, can be null and if so they'll be treated as offline.
* @param prisoner data to handle.
*/
private void releasePrisoner(Player player, Prisoner prisoner) {
if(player == null) {
if (player == null) {
prisoner.setOfflinePending(true);
prisoner.setRemainingTime(0);
}else {
} else {
Jail j = pl.getJailManager().getJailPlayerIsIn(player.getUniqueId());
try {
unJail(j, j.getCellPrisonerIsIn(player.getUniqueId()), player, prisoner, null);
}catch(Exception e) {
if(pl.inDebug()) {
} catch (Exception e) {
if (pl.inDebug()) {
e.printStackTrace();
}
@ -415,32 +402,31 @@ public class PrisonerManager {
* Unjails a prisoner, <strong>sync</strong>, from jail, removing all their data.
*
* <p>
*
* <p>
* Throws an exception if either the jail is null or the prisoner is null.
*
* @param jail where the prisoner is located at
* @param cell which the prisoner is in, can be null
* @param player instance for the prisoner we're unjailing
* @param jail where the prisoner is located at
* @param cell which the prisoner is in, can be null
* @param player instance for the prisoner we're unjailing
* @param prisoner data where everything resides
* @param sender The {@link CommandSender} who unjailed this player, can be null.
* @param sender The {@link CommandSender} who unjailed this player, can be null.
* @throws AsyncUnJailingNotSupportedException when this method is called via a thread that is <strong>not</strong> the primary thread.
* @throws JailRequiredException when the jail provided is null.
* @throws PrisonerRequiredException when the provided prisoner data is null.
*
* @throws JailRequiredException when the jail provided is null.
* @throws PrisonerRequiredException when the provided prisoner data is null.
*/
public void unJail(final Jail jail, ICell cell, final Player player, final Prisoner prisoner, final CommandSender sender) throws AsyncUnJailingNotSupportedException, JailRequiredException, PrisonerRequiredException {
if(!pl.getServer().isPrimaryThread()) throw new AsyncUnJailingNotSupportedException();
public void unJail(final Jail jail, ICell cell, final Player player, final Prisoner prisoner, final CommandSender sender) throws AsyncUnJailingNotSupportedException, JailRequiredException, PrisonerRequiredException {
if (!pl.getServer().isPrimaryThread()) throw new AsyncUnJailingNotSupportedException();
//Do some checks of whether the passed params are null.
if(jail == null)
if (jail == null)
throw new JailRequiredException("unjailing a prisoner");
if(cell instanceof NoCell)
if (cell instanceof NoCell)
cell = null;
else if(cell instanceof AnyCell)
else if (cell instanceof AnyCell)
cell = null;
if(prisoner == null)
if (prisoner == null)
throw new PrisonerRequiredException("unjailing a prisoner");
//Throw the custom event which is called before we start releasing them
@ -453,37 +439,37 @@ public class PrisonerManager {
//In case they have somehow got in a vehicle, let's unmount
//them so we can possibly teleport them
if(player.isInsideVehicle()) {
if (player.isInsideVehicle()) {
player.getVehicle().eject();
player.eject();
}
//Now, let's restore their inventory if we can store it but
//first up is clearing their inventory...if we can store it
boolean store = pl.getConfig().getBoolean(Settings.JAILEDSTOREINVENTORY.getPath(), true);
if(store) {
if (store) {
player.closeInventory();
player.getInventory().setArmorContents(null);
player.getInventory().clear();
}
//if the cell isn't null, let's check if the cell has a chest and if so then try out best to restore
//the prisoner's inventory from that
if(cell != null) {
if(store) {
if(cell.hasChest()) {
if (cell != null) {
if (store) {
if (cell.hasChest()) {
Inventory chest = cell.getChest().getInventory();
for (ItemStack item : chest.getContents()) {
if (item == null || item.getType() == Material.AIR) continue;
if(item.getType().toString().toLowerCase().contains("helmet") && (player.getInventory().getHelmet() == null || player.getInventory().getHelmet().getType() == Material.AIR)) {
if (item.getType().toString().toLowerCase().contains("helmet") && (player.getInventory().getHelmet() == null || player.getInventory().getHelmet().getType() == Material.AIR)) {
player.getInventory().setHelmet(item);
} else if(item.getType().toString().toLowerCase().contains("chestplate") && (player.getInventory().getChestplate() == null || player.getInventory().getChestplate().getType() == Material.AIR)) {
} else if (item.getType().toString().toLowerCase().contains("chestplate") && (player.getInventory().getChestplate() == null || player.getInventory().getChestplate().getType() == Material.AIR)) {
player.getInventory().setChestplate(item);
} else if(item.getType().toString().toLowerCase().contains("leg") && (player.getInventory().getLeggings() == null || player.getInventory().getLeggings().getType() == Material.AIR)) {
} else if (item.getType().toString().toLowerCase().contains("leg") && (player.getInventory().getLeggings() == null || player.getInventory().getLeggings().getType() == Material.AIR)) {
player.getInventory().setLeggings(item);
} else if(item.getType().toString().toLowerCase().contains("boots") && (player.getInventory().getBoots() == null || player.getInventory().getBoots().getType() == Material.AIR)) {
} else if (item.getType().toString().toLowerCase().contains("boots") && (player.getInventory().getBoots() == null || player.getInventory().getBoots().getType() == Material.AIR)) {
player.getInventory().setBoots(item);
} else if (player.getInventory().firstEmpty() == -1) {
player.getWorld().dropItem(player.getLocation(), item);
@ -493,19 +479,19 @@ public class PrisonerManager {
}
chest.clear();
}else {
} else {
Util.restoreInventory(player, prisoner);
}
}else {
} else {
//Clear out the cell's chest just in case
//they decided to store something there
if(cell.hasChest()) cell.getChest().getInventory().clear();
if (cell.hasChest()) cell.getChest().getInventory().clear();
}
pl.getJailIO().removePrisoner(jail, (Cell)cell, prisoner);
pl.getJailIO().removePrisoner(jail, (Cell) cell, prisoner);
cell.removePrisoner();
}else {
if(store) Util.restoreInventory(player, prisoner);
} else {
if (store) Util.restoreInventory(player, prisoner);
pl.getJailIO().removePrisoner(jail, prisoner);
jail.removePrisoner(prisoner);
@ -514,34 +500,32 @@ public class PrisonerManager {
//In case we had set their sleeping state to be ignored
//let's enable their sleeping state taking place again
player.setSleepingIgnored(false);
pl.getServer().getScheduler().runTaskLater(pl, new Runnable() {
public void run() {
//If the config has us teleporting them back to their
//previous position then let's do that
boolean tpd = false;
if(pl.getConfig().getBoolean(Settings.RELEASETOPREVIOUSPOSITION.getPath(), false)) {
if(prisoner.getPreviousLocation() != null)
tpd = player.teleport(prisoner.getPreviousLocation());
}
//If they haven't already been teleported and the config has us to teleport on release,
//then we teleport players to the jail's free spot
if(!tpd && pl.getConfig().getBoolean(Settings.TELEPORTONRELEASE.getPath(), true)) {
player.teleport(jail.getTeleportFree());
}
pl.getServer().getScheduler().runTaskLater(pl, () -> {
//If the config has us teleporting them back to their
//previous position then let's do that
boolean tpd = false;
if (pl.getConfig().getBoolean(Settings.RELEASETOPREVIOUSPOSITION.getPath(), false)) {
if (prisoner.getPreviousLocation() != null)
tpd = player.teleport(prisoner.getPreviousLocation());
}
//If we are to restore their previous gamemode and we have it stored,
//then by all means let's restore it
if(pl.getConfig().getBoolean(Settings.RESTOREPREVIOUSGAMEMODE.getPath(), false)) {
player.setGameMode(prisoner.getPreviousGameMode());
}
};
//If they haven't already been teleported and the config has us to teleport on release,
//then we teleport players to the jail's free spot
if (!tpd && pl.getConfig().getBoolean(Settings.TELEPORTONRELEASE.getPath(), true)) {
player.teleport(jail.getTeleportFree());
}
//If we are to restore their previous gamemode and we have it stored,
//then by all means let's restore it
if (pl.getConfig().getBoolean(Settings.RESTOREPREVIOUSGAMEMODE.getPath(), false)) {
player.setGameMode(prisoner.getPreviousGameMode());
}
}, 5);
//Get the commands to execute prisoners are unjailed
//replace all of the %p% so that the commands can have a player name in them
for(String command : pl.getConfig().getStringList(Settings.COMMANDSONRELEASE.getPath())) {
for (String command : pl.getConfig().getStringList(Settings.COMMANDSONRELEASE.getPath())) {
command = command.replaceAll("%p%", player.getName());
command = command.replaceAll("%player%", player.getName());
command = command.replaceAll("%uuid%", player.getUniqueId().toString());
@ -550,23 +534,23 @@ public class PrisonerManager {
}
//Remove the scoreboard to them if it is enabled
if(pl.getConfig().getBoolean(Settings.SCOREBOARDENABLED.getPath())) {
if (pl.getConfig().getBoolean(Settings.SCOREBOARDENABLED.getPath())) {
pl.getScoreBoardManager().removeScoreBoard(player);
}
//Call the prisoner released event as we have released them.
PrisonerReleasedEvent event = new PrisonerReleasedEvent(jail, cell == null ? null : (Cell)cell, prisoner, player);
PrisonerReleasedEvent event = new PrisonerReleasedEvent(jail, cell == null ? null : (Cell) cell, prisoner, player);
pl.getServer().getPluginManager().callEvent(event);
player.sendMessage(Lang.UNJAILED.get());
if(sender != null) sender.sendMessage(Lang.UNJAILSUCCESS.get(player.getName()));
if (sender != null) sender.sendMessage(Lang.UNJAILSUCCESS.get(player.getName()));
}
/**
* Forcefully unjails a {@link Prisoner prisoner} from {@link Jail}.
*
* <p>
*
* <p>
* This method forcefully removes all the references to this prisoner,
* meaning if they're offline the following won't happened:
* <ul>
@ -574,15 +558,15 @@ public class PrisonerManager {
* <li>Teleported anywhere</li>
* <li>No messages sent, they'll be clueless.</li>
* </ul>
*
* <p>
* But if they're online, it goes through the regular unjailing methods.
*
* <p>
*
* @param prisoner to release
* @param sender who is releasing the prisoner, <em>can be null</em>
* @param sender who is releasing the prisoner, <em>can be null</em>
* @throws PrisonerRequiredException when the prisoner data doesn't exist.
* @throws JailRequiredException when the prisoner isn't jailed
* @throws JailRequiredException when the prisoner isn't jailed
*/
public void forceRelease(Prisoner prisoner, CommandSender sender) throws JailRequiredException, PrisonerRequiredException {
Jail j = pl.getJailManager().getJailPrisonerIsIn(prisoner);
@ -594,7 +578,7 @@ public class PrisonerManager {
*
*
* <p>
*
* <p>
* This method forcefully removes all the references to this prisoner,
* meaning if they're offline the following won't happened:
* <ul>
@ -602,33 +586,33 @@ public class PrisonerManager {
* <li>Teleported anywhere</li>
* <li>No messages sent, they'll be clueless.</li>
* </ul>
*
* <p>
* But if they're online, it goes through the regular unjailing methods.
*
* <p>
*
* @param jail the prisoner is in
* @param cell the prisoner is in, <em>can be null</em>
* @param player of the prisoner, if this is null then the player won't be teleported when they come back on.
* @param jail the prisoner is in
* @param cell the prisoner is in, <em>can be null</em>
* @param player of the prisoner, if this is null then the player won't be teleported when they come back on.
* @param prisoner to release and remove data
* @param sender who is releasing the prisoner, <em>can be null</em>
* @throws JailRequiredException when the provided jail is null.
* @param sender who is releasing the prisoner, <em>can be null</em>
* @throws JailRequiredException when the provided jail is null.
* @throws PrisonerRequiredException when the provided prisoner data is null.
*/
public void forceUnJail(Jail jail, Cell cell, Player player, Prisoner prisoner, CommandSender sender) throws JailRequiredException, PrisonerRequiredException {
if(jail == null)
if (jail == null)
throw new JailRequiredException("jailing a prisoner");
if(prisoner == null)
if (prisoner == null)
throw new PrisonerRequiredException("jailing a prisoner");
if(player == null) {
if (player == null) {
//Player is offline, we just forcefully remove them from the database
pl.getJailIO().removePrisoner(jail, cell, prisoner);
if(cell == null) {
if (cell == null) {
jail.removePrisoner(prisoner);
}else {
} else {
cell.removePrisoner();
}
@ -636,8 +620,8 @@ public class PrisonerManager {
PrisonerReleasedEvent event = new PrisonerReleasedEvent(jail, cell, prisoner, player);
pl.getServer().getPluginManager().callEvent(event);
if(sender != null) sender.sendMessage(Lang.FORCEUNJAILED.get(prisoner.getLastKnownName()));
}else {
if (sender != null) sender.sendMessage(Lang.FORCEUNJAILED.get(prisoner.getLastKnownName()));
} else {
try {
unJail(jail, cell, player, prisoner, sender);
} catch (Exception e) {
@ -653,15 +637,15 @@ public class PrisonerManager {
* @param originCell The cell where they are coming from.
* @param targetJail The jail we're transferring them from.
* @param targetCell The cell we're putting them into.
* @param prisoner The prisoner data we're handling.
* @param prisoner The prisoner data we're handling.
*/
public void transferPrisoner(Jail originJail, Cell originCell, Jail targetJail, Cell targetCell, Prisoner prisoner) {
Player player = pl.getServer().getPlayer(prisoner.getUUID());
//If there is no origin cell, then we need to basically just put them to their targetJail
if(originCell == null) {
if (originCell == null) {
//But first thing is first, let's check if there is a targetCell we're putting them in
if(targetCell == null) {
if (targetCell == null) {
//There is no cell, so we're just going to be putting them into
//the target jail and that's it
targetJail.addPrisoner(prisoner);
@ -670,41 +654,41 @@ public class PrisonerManager {
//If the player is not online, trigger them to be teleported when they
//come online again
if(player == null) {
if (player == null) {
//Set them to have an action on offline pending, so it gets triggered
prisoner.setOfflinePending(true);
//Now let's set them to be transferred when they come online next
prisoner.setToBeTransferred(true);
}else {
} else {
prisoner.setTeleporting(true);
player.teleport(targetJail.getTeleportIn());
prisoner.setTeleporting(false);
player.sendMessage(Lang.TRANSFERRED.get(targetJail.getName()));
}
}else {
} else {
//They are set to go to the targetCell, so handle accordingly
targetCell.setPrisoner(prisoner);
//If the player is not online, trigger them to be teleported when they
//come online again
if(player == null) {
if (player == null) {
//Set them to have an action on offline pending, so it gets triggered
prisoner.setOfflinePending(true);
//Now let's set them to be transferred when they come online next
prisoner.setToBeTransferred(true);
}else {
} else {
prisoner.setTeleporting(true);
player.teleport(targetCell.getTeleport());
prisoner.setTeleporting(false);
player.sendMessage(Lang.TRANSFERRED.get(targetJail.getName()));
}
}
}else {
} else {
//They are being transferred from a cell, so we need to handle getting the inventory
//and all that sort of stuff from the old cell before we transfer them over to the new cell
//If they're not being sent to a cell any more, handle that differently as well
if(targetCell == null) {
if (targetCell == null) {
//Add them to the target jail
targetJail.addPrisoner(prisoner);
//Next, remove them from the cell
@ -712,13 +696,13 @@ public class PrisonerManager {
//If the cell they came from has any items from their inventory,
//let's get it all and store it
if(originCell.hasChest()) {
if (originCell.hasChest()) {
//Convert the inventory to base64 string and store it in the prisoner's file
prisoner.setInventory(Util.toBase64(originCell.getChest().getInventory()));
//Clear the origin cell's inventory so nothing is left behind
originCell.getChest().getInventory().clear();
}
}else {
} else {
//They are being transferred to a cell in another cell,
//we aren't going to do any sanity checks as we hope the method that is
//calling this one does those sanity checks for us.
@ -729,17 +713,17 @@ public class PrisonerManager {
originCell.removePrisoner();
//Check if the origin cell has a chest, put all the player's inventory into it
if(originCell.hasChest()) {
if (originCell.hasChest()) {
//If the targetCell has a chest
if(targetCell.hasChest()) {
if (targetCell.hasChest()) {
//Loop through the origin's chest inventory and add it to the target cell's chest
for(ItemStack i : originCell.getChest().getInventory().getContents())
if(i != null)
for (ItemStack i : originCell.getChest().getInventory().getContents())
if (i != null)
targetCell.getChest().getInventory().addItem(i);
//Clear the origin cell's chest as it is clear now
originCell.getChest().getInventory().clear();
}else {
} else {
//targetCell has no chest so we aren't going to try and put anything into it
//Convert the inventory to base64 string and store it in the prisoner's file
@ -750,11 +734,11 @@ public class PrisonerManager {
}
}
}
//Update the signs of both cells
if(originCell != null)
if (originCell != null)
originCell.updateSigns();
if(targetCell != null)
if (targetCell != null)
targetCell.updateSigns();
//Throw our custom event PrisonerTransferredEvent to say it was successful

View File

@ -1,8 +1,8 @@
package com.graywolf336.jail;
import java.util.HashMap;
import java.util.UUID;
import com.graywolf336.jail.beans.Jail;
import com.graywolf336.jail.beans.Prisoner;
import com.graywolf336.jail.enums.Settings;
import org.bukkit.OfflinePlayer;
import org.bukkit.entity.Player;
import org.bukkit.scoreboard.DisplaySlot;
@ -10,56 +10,51 @@ import org.bukkit.scoreboard.Objective;
import org.bukkit.scoreboard.Scoreboard;
import org.bukkit.scoreboard.ScoreboardManager;
import com.graywolf336.jail.beans.Jail;
import com.graywolf336.jail.beans.Prisoner;
import com.graywolf336.jail.enums.Settings;
import java.util.HashMap;
import java.util.UUID;
public class ScoreBoardManager {
private JailMain pl;
private ScoreboardManager man;
private HashMap<UUID, Scoreboard> boards;
private OfflinePlayer time;
private final JailMain pl;
private final ScoreboardManager man;
private final HashMap<UUID, Scoreboard> boards;
private final OfflinePlayer time;
@SuppressWarnings("deprecation")
protected ScoreBoardManager(JailMain plugin) {
this.pl = plugin;
this.man = plugin.getServer().getScoreboardManager();
this.boards = new HashMap<UUID, Scoreboard>();
this.boards = new HashMap<>();
this.time = plugin.getServer().getOfflinePlayer(Util.getColorfulMessage(pl.getConfig().getString(Settings.SCOREBOARDTIME.getPath())));
//Start the task if it is enabled
if(plugin.getConfig().getBoolean(Settings.SCOREBOARDENABLED.getPath())) {
plugin.getServer().getScheduler().scheduleSyncRepeatingTask(plugin, new Runnable() {
public void run() {
updatePrisonersTime();
}
}, 200L, 100L);
if (plugin.getConfig().getBoolean(Settings.SCOREBOARDENABLED.getPath())) {
plugin.getServer().getScheduler().scheduleSyncRepeatingTask(plugin, this::updatePrisonersTime, 200L, 100L);
}
}
/**
* Adds the jailing score board to the player if they don't have one, otherwise it just updates it.
*
*
* @param player of whom to add the scoreboard to.
* @param pris data for the provided prisoner
* @param pris data for the provided prisoner
*/
@SuppressWarnings("deprecation")
public void addScoreBoard(Player player, Prisoner pris) {
if(!boards.containsKey(player.getUniqueId())) {
if (!boards.containsKey(player.getUniqueId())) {
boards.put(player.getUniqueId(), man.getNewScoreboard());
Objective o = boards.get(player.getUniqueId()).registerNewObjective("test", "dummy");
o.setDisplaySlot(DisplaySlot.SIDEBAR);
o.setDisplayName(Util.getColorfulMessage(pl.getConfig().getString(Settings.SCOREBOARDTITLE.getPath())));
o.getScore(time).setScore(pris.getRemainingTimeInMinutesInt());
player.setScoreboard(boards.get(player.getUniqueId()));
}else {
} else {
updatePrisonersBoard(player, pris);
}
}
/**
* Removes a player's jail scoreboard for their jail time and sets it to the main one.
*
*
* @param player of whom to remove the scoreboard for.
*/
public void removeScoreBoard(Player player) {
@ -68,14 +63,16 @@ public class ScoreBoardManager {
player.setScoreboard(man.getMainScoreboard());
}
/** Removes all of the scoreboards from the prisoners. */
/**
* Removes all of the scoreboards from the prisoners.
*/
public void removeAllScoreboards() {
HashMap<UUID, Scoreboard> temp = new HashMap<UUID, Scoreboard>(boards);
HashMap<UUID, Scoreboard> temp = new HashMap<>(boards);
for(UUID id : temp.keySet()) {
for (UUID id : temp.keySet()) {
Player p = pl.getServer().getPlayer(id);
if(p != null) {
if (p != null) {
p.setScoreboard(man.getMainScoreboard());
}
@ -83,11 +80,13 @@ public class ScoreBoardManager {
}
}
/** Updates the prisoners time on their scoreboard. */
/**
* Updates the prisoners time on their scoreboard.
*/
private void updatePrisonersTime() {
for(Jail j : pl.getJailManager().getJails()) {
for(Prisoner p : j.getAllPrisoners().values()) {
if(pl.getServer().getPlayer(p.getUUID()) != null) {
for (Jail j : pl.getJailManager().getJails()) {
for (Prisoner p : j.getAllPrisoners().values()) {
if (pl.getServer().getPlayer(p.getUUID()) != null) {
addScoreBoard(pl.getServer().getPlayer(p.getUUID()), p);
}
}
@ -96,9 +95,9 @@ public class ScoreBoardManager {
/**
* Updates a player's time in the scoreboard.
*
*
* @param player of whom to update the scoreboard for.
* @param pris data for the player
* @param pris data for the player
*/
@SuppressWarnings("deprecation")
private void updatePrisonersBoard(Player player, Prisoner pris) {

View File

@ -1,5 +1,10 @@
package com.graywolf336.jail;
import com.graywolf336.jail.enums.Settings;
import org.json.simple.JSONArray;
import org.json.simple.JSONObject;
import org.json.simple.JSONValue;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
@ -7,14 +12,8 @@ import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLConnection;
import org.json.simple.JSONArray;
import org.json.simple.JSONObject;
import org.json.simple.JSONValue;
import com.graywolf336.jail.enums.Settings;
public class Update {
private JailMain plugin;
private final JailMain plugin;
// The project's unique ID
private static final int projectID = 31139;
@ -34,14 +33,14 @@ public class Update {
public void query() {
String channel = plugin.getConfig().getString(Settings.UPDATECHANNEL.getPath(), "bukkit");
URL url = null;
URL url;
try {
if(channel.equalsIgnoreCase("stable-dev")) {
if (channel.equalsIgnoreCase("stable-dev")) {
url = new URL(CI_STABLEDEV_API_QUERY);
}else if(channel.equalsIgnoreCase("dev")) {
} else if (channel.equalsIgnoreCase("dev")) {
url = new URL(CI_DEV_API_QUERY);
}else {
} else {
url = new URL(BUKKIT_API_QUERY);
}
} catch (MalformedURLException e) {
@ -61,7 +60,7 @@ public class Update {
final BufferedReader reader = new BufferedReader(new InputStreamReader(conn.getInputStream()));
String response = reader.readLine();
if(channel.equalsIgnoreCase("stable-dev") || channel.equalsIgnoreCase("dev")) {
if (channel.equalsIgnoreCase("stable-dev") || channel.equalsIgnoreCase("dev")) {
// Parse the object from the response from the CI server
JSONObject obj = (JSONObject) JSONValue.parse(response);
// Get the latest build number
@ -69,7 +68,7 @@ public class Update {
// Get the current running version
String[] ver = plugin.getDescription().getVersion().split("-b");
// Let them know they're on a custom version when on build #0.
if(ver[ver.length - 1].equalsIgnoreCase("0")) {
if (ver[ver.length - 1].equalsIgnoreCase("0")) {
plugin.getLogger().info("You are using a custom version, you can disable update checking.");
}
@ -80,13 +79,13 @@ public class Update {
needed = number > curr;
// Alert the console that an update is needed, if it is needed
if(needed) {
if (needed) {
this.version = obj.get("fullDisplayName").toString();
this.fileUrl = obj.get("url").toString();
plugin.getLogger().info("New development version of Jail is available: " + this.version);
plugin.getLogger().info(this.fileUrl);
}
}else {
} else {
// Parse the array of files from the query's response
JSONArray array = (JSONArray) JSONValue.parse(response);
@ -104,7 +103,7 @@ public class Update {
plugin.debug(remoteVer + " verus " + currentVer);
this.needed = this.versionCompare(remoteVer, currentVer) > 0;
if(needed) {
if (needed) {
this.version = latest.get("name").toString();
this.fileUrl = latest.get("fileUrl").toString();
plugin.getLogger().info("New stable version of Jail is available: " + this.version);
@ -116,23 +115,21 @@ public class Update {
// There was an error reading the query
e.printStackTrace();
plugin.getLogger().severe("There was an error checking for an update, please see the above stacktrace for details before reporting.");
return;
}
}
/**
* Compares two version strings.
*
* <p>
* Use this instead of String.compareTo() for a non-lexicographical
* comparison that works for version strings. e.g. "1.10".compareTo("1.6").
*
* @note It does not work if "1.10" is supposed to be equal to "1.10.0".
*
*
* @param str1 a string of ordinal numbers separated by decimal points.
* @param str2 a string of ordinal numbers separated by decimal points.
* @return The result is a negative integer if str1 is _numerically_ less than str2.
* The result is a positive integer if str1 is _numerically_ greater than str2.
* The result is zero if the strings are _numerically_ equal.
* The result is a positive integer if str1 is _numerically_ greater than str2.
* The result is zero if the strings are _numerically_ equal.
* @note It does not work if "1.10" is supposed to be equal to "1.10.0".
*/
private Integer versionCompare(String str1, String str2) {
String[] vals1 = str1.split("\\.");
@ -157,7 +154,7 @@ public class Update {
/**
* Returns true if there is an update needed, false if not.
*
*
* @return Whether an update is available
*/
public boolean isAvailable() {
@ -166,7 +163,7 @@ public class Update {
/**
* Returns the new version.
*
*
* @return The string name of the new version
*/
public String getNewVersion() {
@ -175,7 +172,7 @@ public class Update {
/**
* Returns the new file url.
*
*
* @return New file's url
*/
public String getFileUrl() {

View File

@ -1,16 +1,7 @@
package com.graywolf336.jail;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Collections;
import java.util.LinkedList;
import java.util.List;
import java.util.concurrent.TimeUnit;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import com.graywolf336.jail.beans.Prisoner;
import com.graywolf336.jail.enums.Lang;
import org.bukkit.Bukkit;
import org.bukkit.ChatColor;
import org.bukkit.Material;
@ -23,26 +14,34 @@ import org.bukkit.util.io.BukkitObjectInputStream;
import org.bukkit.util.io.BukkitObjectOutputStream;
import org.yaml.snakeyaml.external.biz.base64Coder.Base64Coder;
import com.graywolf336.jail.beans.Prisoner;
import com.graywolf336.jail.enums.Lang;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Collections;
import java.util.LinkedList;
import java.util.List;
import java.util.concurrent.TimeUnit;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
/**
* Provides a variety of methods, static, that are used throughout the plugin.
*
* @author graywolf336
* @since 2.x.x
* @version 3.1.0
* @since 2.x.x
*/
public class Util {
private final static Pattern DURATION_PATTERN = Pattern.compile("^(\\d+)\\s*(m(?:inute)?s?|h(?:ours?)?|d(?:ays?)?|s(?:econd)?s?)?$", Pattern.CASE_INSENSITIVE);
private static String[] signLines = new String[] { "", "", "", "" };
private static String[] signLines = new String[]{"", "", "", ""};
private final static int inventoryMultipule = 9;
/**
* Checks if the first {@link Vector} is inside this region.
*
* @param point The point to check
* @param first point of the region
* @param point The point to check
* @param first point of the region
* @param second second point of the region
* @return True if all the coords of the first vector are in the entire region.
*/
@ -59,14 +58,14 @@ public class Util {
*
* <p>
*
* @param loc The location.
* @param first The first point
* @param loc The location.
* @param first The first point
* @param second The second point
* @return true if they are inside, false if not.
*/
private static boolean isInside(int loc, int first, int second) {
int point1 = 0;
int point2 = 0;
int point1;
int point2;
if (first < second) {
point1 = first;
point2 = second;
@ -80,16 +79,16 @@ public class Util {
/**
* Checks if the given string is inside the array, ignoring the casing.
*
* <p />
* <p>
* <p/>
*
* @param value to check
* @param array of strings to check
* @return true if the array contains the provided value, false if it doesn't
*/
public static boolean isStringInsideArray(String value, String... array) {
for(String s : array)
if(s.equalsIgnoreCase(value))
for (String s : array)
if (s.equalsIgnoreCase(value))
return true;
return false;
@ -97,16 +96,16 @@ public class Util {
/**
* Checks if the given string is inside the list, ignoring the casing.
*
* <p />
* <p>
* <p/>
*
* @param value to check
* @param list of strings to check
* @param list of strings to check
* @return true if the list contains the provided value, false if it doesn't
*/
public static boolean isStringInsideList(String value, List<String> list) {
for(String s : list)
if(s.equalsIgnoreCase(value))
for (String s : list)
if (s.equalsIgnoreCase(value))
return true;
return false;
@ -116,14 +115,14 @@ public class Util {
* Gets a single string from an array of strings, separated by the separator.
*
* @param separator The item to separate the items
* @param array The array of strings to combine
* @param array The array of strings to combine
* @return the resulting combined string
*/
public static String getStringFromArray(String separator, String... array) {
StringBuilder result = new StringBuilder();
for(String s : array) {
if(result.length() != 0) result.append(separator);
for (String s : array) {
if (result.length() != 0) result.append(separator);
result.append(s);
}
@ -134,14 +133,14 @@ public class Util {
* Gets a single string from a list of strings, separated by the separator.
*
* @param separator The item to separate the items
* @param list The list of strings to combine
* @param list The list of strings to combine
* @return the resulting combined string
*/
public static String getStringFromList(String separator, List<String> list) {
StringBuilder result = new StringBuilder();
for(String s : list) {
if(result.length() != 0) result.append(separator);
for (String s : list) {
if (result.length() != 0) result.append(separator);
result.append(s);
}
@ -150,7 +149,7 @@ public class Util {
/**
* Returns a colorful message from the color codes.
*
*
* @param message the message to colorize
* @return the colorized message
*/
@ -160,8 +159,8 @@ public class Util {
/**
* Returns a message with all the possible variables replaced.
*
* @param p the {@link Prisoner} data
*
* @param p the {@link Prisoner} data
* @param msg the message to replace everything in
* @return The message with everything replaced and colorized.
*/
@ -172,10 +171,10 @@ public class Util {
.replace("%jailer%", p.getJailer())
.replace("%afktime%", Util.getDurationBreakdown(p.getAFKTime()));
if(p.getRemainingTime() >= 0) {
if (p.getRemainingTime() >= 0) {
msg = msg.replace("%timeinminutes%", String.valueOf(p.getRemainingTimeInMinutes()));
msg = msg.replace("%prettytime%", Util.getDurationBreakdown(p.getRemainingTime()));
}else {
} else {
msg = msg.replace("%timeinminutes%", String.valueOf(-1));
msg = msg.replace("%prettytime%", Lang.JAILEDFOREVERSIGN.get());
}
@ -185,15 +184,15 @@ public class Util {
/**
* Replaces all the variables in the messages with their possible values.
*
* @param p the {@link Prisoner} data.
*
* @param p the {@link Prisoner} data.
* @param msgs the messages
* @return the messages but variables replaced and colorized
*/
public static String[] replaceAllVariables(Prisoner p, String... msgs) {
String[] results = new String[msgs.length];
for(int i = 0; i < msgs.length; i++)
for (int i = 0; i < msgs.length; i++)
results[i] = replaceAllVariables(p, msgs[i]);
return results;
@ -201,14 +200,14 @@ public class Util {
/**
* Returns the wand used throughout the different creation steps.
*
*
* @return The {@link ItemStack} to use for creation
*/
public static ItemStack getWand() {
ItemStack wand = new ItemStack(Material.BRICK);
ItemMeta meta = wand.getItemMeta();
meta.setDisplayName(ChatColor.AQUA + "Jail Wand");
LinkedList<String> lore = new LinkedList<String>();
LinkedList<String> lore = new LinkedList<>();
lore.add(ChatColor.BLUE + "The wand for creating");
lore.add(ChatColor.BLUE + "a jail or cell.");
meta.setLore(lore);
@ -237,29 +236,29 @@ public class Util {
* @throws Exception if there are no matches
*/
public static Long getTime(String time) throws Exception {
if(time.equalsIgnoreCase("-1")) return -1L;
if (time.equalsIgnoreCase("-1")) return -1L;
Long t = 10L;
long t;
Matcher match = DURATION_PATTERN.matcher(time);
if (match.matches()) {
String units = match.group(2);
if ("seconds".equals(units) || "second".equals(units) || "s".equals(units))
t = TimeUnit.MILLISECONDS.convert(Long.valueOf(match.group(1)), TimeUnit.SECONDS);
t = TimeUnit.MILLISECONDS.convert(Long.parseLong(match.group(1)), TimeUnit.SECONDS);
else if ("minutes".equals(units) || "minute".equals(units) || "mins".equals(units) || "min".equals(units) || "m".equals(units))
t = TimeUnit.MILLISECONDS.convert(Long.valueOf(match.group(1)), TimeUnit.MINUTES);
t = TimeUnit.MILLISECONDS.convert(Long.parseLong(match.group(1)), TimeUnit.MINUTES);
else if ("hours".equals(units) || "hour".equals(units) || "h".equals(units))
t = TimeUnit.MILLISECONDS.convert(Long.valueOf(match.group(1)), TimeUnit.HOURS);
t = TimeUnit.MILLISECONDS.convert(Long.parseLong(match.group(1)), TimeUnit.HOURS);
else if ("days".equals(units) || "day".equals(units) || "d".equals(units))
t = TimeUnit.MILLISECONDS.convert(Long.valueOf(match.group(1)), TimeUnit.DAYS);
t = TimeUnit.MILLISECONDS.convert(Long.parseLong(match.group(1)), TimeUnit.DAYS);
else {
try {
t = TimeUnit.MILLISECONDS.convert(Long.parseLong(time), TimeUnit.MINUTES);
}catch(NumberFormatException e) {
} catch (NumberFormatException e) {
throw new Exception("Invalid format.");
}
}
}else {
} else {
throw new Exception("Invalid format.");
}
@ -273,7 +272,7 @@ public class Util {
* @return A string of the form "XdYhZAs".
*/
public static String getDurationBreakdown(long millis) {
if(millis < 0) {
if (millis < 0) {
return Lang.JAILEDFOREVERSIGN.get();
}
@ -286,17 +285,17 @@ public class Util {
long seconds = TimeUnit.MILLISECONDS.toSeconds(millis);
StringBuilder sb = new StringBuilder(64);
if(days > 0) {
if (days > 0) {
sb.append(days);
sb.append("d");
}
if(days > 0 || hours > 0) {
if (days > 0 || hours > 0) {
sb.append(hours);
sb.append("h");
}
if(days > 0 || hours > 0 || minutes > 0) {
if (days > 0 || hours > 0 || minutes > 0) {
sb.append(minutes);
sb.append("m");
}
@ -314,42 +313,41 @@ public class Util {
* @throws Exception Throws an exception if there aren't exactly four lines.
*/
public static void updateSignLinesCache(String[] lines) throws Exception {
if(lines.length != 4) throw new Exception("Exactly four lines are required for the signs.");
if (lines.length != 4) throw new Exception("Exactly four lines are required for the signs.");
signLines = lines;
}
/**
* Gets all the lines which go on the cell signs.
*
*
* @return the strings for the signs
*/
public static String[] getSignLines() {
return signLines;
}
public static List<String> getUnusedItems(List<String> items, String[] args, boolean useP) {
List<String> used = new ArrayList<String>();
for(String s : args)
if(s.contains("-"))
List<String> used = new ArrayList<>();
for (String s : args)
if (s.contains("-"))
used.add(s.replace("-", ""));
List<String> unused = new ArrayList<String>();
for(String t : items)
if(!used.contains(t)) //don't add it if it is already used
if(!t.equalsIgnoreCase("p") || (useP && t.equalsIgnoreCase("p")))//don't add -p unless otherwise stated
unused.add("-" + t);
List<String> unused = new ArrayList<>();
for (String t : items)
if (!used.contains(t)) //don't add it if it is already used
if (!t.equalsIgnoreCase("p") || (useP && t.equalsIgnoreCase("p")))//don't add -p unless otherwise stated
unused.add("-" + t);
Collections.sort(unused);
return unused;
}
/**
*
* A method to serialize an {@link ItemStack} array to Base64 String.
*
* <p>
*
* <p>
* Based off of {@link #toBase64(Inventory)}.
*
* @param items to turn into a Base64 String.
@ -381,7 +379,7 @@ public class Util {
* A method to serialize an inventory to Base64 string.
*
* <p>
*
* <p>
* Special thanks to Comphenix in the Bukkit forums or also known
* as aadnk on GitHub. <a href="https://gist.github.com/aadnk/8138186">Original Source</a>
*
@ -411,11 +409,10 @@ public class Util {
}
/**
*
* A method to get an {@link Inventory} from an encoded, Base64, string.
*
* <p>
*
* <p>
* Special thanks to Comphenix in the Bukkit forums or also known
* as aadnk on GitHub.
*
@ -426,13 +423,13 @@ public class Util {
* @throws IOException if we were unable to parse the base64 string
*/
public static Inventory fromBase64(String data) throws IOException {
if(data.isEmpty()) return Bukkit.getServer().createInventory(null, 0);
if (data.isEmpty()) return Bukkit.getServer().createInventory(null, 0);
try {
ByteArrayInputStream inputStream = new ByteArrayInputStream(Base64Coder.decodeLines(data));
BukkitObjectInputStream dataInput = new BukkitObjectInputStream(inputStream);
int size = dataInput.readInt();
Inventory inventory = Bukkit.getServer().createInventory(null, (int)Math.ceil((double)size / inventoryMultipule) * inventoryMultipule);
Inventory inventory = Bukkit.getServer().createInventory(null, (int) Math.ceil((double) size / inventoryMultipule) * inventoryMultipule);
// Read the serialized inventory
for (int i = 0; i < size; i++) {
@ -451,7 +448,7 @@ public class Util {
* Gets an array of ItemStacks from Base64 string.
*
* <p>
*
* <p>
* Base off of {@link #fromBase64(String)}.
*
* @param data Base64 string to convert to ItemStack array.
@ -459,7 +456,7 @@ public class Util {
* @throws IOException if we was unable to parse the base64 string
*/
public static ItemStack[] itemStackArrayFromBase64(String data) throws IOException {
if(data.isEmpty()) return new ItemStack[] {};
if (data.isEmpty()) return new ItemStack[]{};
try {
ByteArrayInputStream inputStream = new ByteArrayInputStream(Base64Coder.decodeLines(data));
@ -483,16 +480,16 @@ public class Util {
Inventory content = Util.fromBase64(prisoner.getInventory());
ItemStack[] armor = Util.itemStackArrayFromBase64(prisoner.getArmor());
for(ItemStack item : armor) {
if(item == null)
continue;
else if(item.getType().toString().toLowerCase().contains("helmet"))
for (ItemStack item : armor) {
if (item == null) {
}
else if (item.getType().toString().toLowerCase().contains("helmet"))
player.getInventory().setHelmet(item);
else if(item.getType().toString().toLowerCase().contains("chestplate"))
else if (item.getType().toString().toLowerCase().contains("chestplate"))
player.getInventory().setChestplate(item);
else if(item.getType().toString().toLowerCase().contains("leg"))
else if (item.getType().toString().toLowerCase().contains("leg"))
player.getInventory().setLeggings(item);
else if(item.getType().toString().toLowerCase().contains("boots"))
else if (item.getType().toString().toLowerCase().contains("boots"))
player.getInventory().setBoots(item);
else if (player.getInventory().firstEmpty() == -1)
player.getWorld().dropItem(player.getLocation(), item);
@ -500,9 +497,10 @@ public class Util {
player.getInventory().addItem(item);
}
for(ItemStack item : content.getContents()) {
if(item == null) continue;
else if(player.getInventory().firstEmpty() == -1)
for (ItemStack item : content.getContents()) {
if (item == null) {
}
else if (player.getInventory().firstEmpty() == -1)
player.getWorld().dropItem(player.getLocation(), item);
else
player.getInventory().addItem(item);
@ -516,7 +514,7 @@ public class Util {
/**
* Checks if the provided class has the provided method.
*
* @param c The {@link Class} to check on.
* @param c The {@link Class} to check on.
* @param method The name of the method to check for
* @return whether the method exists or not.
*/

View File

@ -1,111 +1,133 @@
package com.graywolf336.jail.beans;
import com.graywolf336.jail.interfaces.ICell;
import org.bukkit.Location;
import org.bukkit.block.Chest;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import org.bukkit.Location;
import org.bukkit.block.Chest;
import com.graywolf336.jail.interfaces.ICell;
/**
* Pass this an instance of this class into the jailing of a player and they go to any open cell.
* Pass this an instance of this class into the jailing of a player, and they go to any open cell.
*
* @author graywolf336
* @since 3.0.0
* @version 1.0.0
*
* @since 3.0.0
*/
public class AnyCell implements ICell {
@Override
public int getDatabaseID() {
throw new UnsupportedOperationException();
}
@Override
public String getName() {
throw new UnsupportedOperationException();
}
@Override
public void setPrisoner(Prisoner prisoner) {
throw new UnsupportedOperationException();
}
@Override
public Prisoner getPrisoner() {
throw new UnsupportedOperationException();
}
@Override
public void removePrisoner() {
throw new UnsupportedOperationException();
}
@Override
public boolean hasPrisoner() {
throw new UnsupportedOperationException();
}
@Override
public void addAllSigns(HashSet<SimpleLocation> signs) {
throw new UnsupportedOperationException();
}
@Override
public void addSign(SimpleLocation sign) {
throw new UnsupportedOperationException();
}
@Override
public HashSet<SimpleLocation> getSigns() {
throw new UnsupportedOperationException();
}
@Override
public boolean hasSigns() {
throw new UnsupportedOperationException();
}
@Override
public String getSignString() {
throw new UnsupportedOperationException();
}
@Override
public List<String> getInvalidSigns() {
throw new UnsupportedOperationException();
}
@Override
public List<String> cleanSigns() {
throw new UnsupportedOperationException();
}
@Override
public HashMap<String, List<String>> updateSigns() {
throw new UnsupportedOperationException();
}
@Override
public void setTeleport(SimpleLocation location) {
throw new UnsupportedOperationException();
}
@Override
public Location getTeleport() {
throw new UnsupportedOperationException();
}
@Override
public void setChestLocation(SimpleLocation simpleLocation) {
throw new UnsupportedOperationException();
}
@Override
public Location getChestLocation() {
throw new UnsupportedOperationException();
}
@Override
public Chest getChest() {
throw new UnsupportedOperationException();
}
@Override
public boolean hasChest() {
throw new UnsupportedOperationException();
}
@Override
public boolean useChest() {
throw new UnsupportedOperationException();
}
@Override
public boolean setChanged(boolean changed) {
throw new UnsupportedOperationException();
}
@Override
public boolean hasChanged() {
throw new UnsupportedOperationException();
}

View File

@ -2,14 +2,14 @@ package com.graywolf336.jail.beans;
/**
* An object for storing online cached prisoners.
*
*
* @author graywolf336
* @since 3.0.0
* @version 1.0.0
* @since 3.0.0
*/
public class CachePrisoner {
private Jail jail;
private Prisoner p;
private final Jail jail;
private final Prisoner p;
public CachePrisoner(Jail jail, Prisoner prisoner) {
this.jail = jail;
@ -18,7 +18,7 @@ public class CachePrisoner {
/**
* Gets the {@link Jail} this cache is in.
*
*
* @return the {@link Jail} instance
*/
public Jail getJail() {
@ -27,7 +27,7 @@ public class CachePrisoner {
/**
* Gets the {@link Prisoner} in this cache.
*
*
* @return the {@link Prisoner} instance
*/
public Prisoner getPrisoner() {

View File

@ -1,10 +1,8 @@
package com.graywolf336.jail.beans;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import com.graywolf336.jail.Util;
import com.graywolf336.jail.enums.Lang;
import com.graywolf336.jail.interfaces.ICell;
import org.bukkit.Bukkit;
import org.bukkit.Location;
import org.bukkit.Material;
@ -12,48 +10,51 @@ import org.bukkit.block.BlockState;
import org.bukkit.block.Chest;
import org.bukkit.block.Sign;
import com.graywolf336.jail.Util;
import com.graywolf336.jail.enums.Lang;
import com.graywolf336.jail.interfaces.ICell;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
/** Represents a Cell inside of a {@link Jail}.
/**
* Represents a Cell inside of a {@link Jail}.
*
* @author graywolf336
* @since 3.0.0
* @version 1.2.0
* @since 3.0.0
*/
public class Cell implements ICell {
private int databaseid;
private String name;
private final int databaseid;
private final String name;
private Prisoner p;
private HashSet<SimpleLocation> signs;
private final HashSet<SimpleLocation> signs;
private SimpleLocation teleport, chest;
private boolean changed;
/** Creates a new Cell with the given name
/**
* Creates a new Cell with the given name
*
* @param name The name of the cell.
*/
public Cell(String name) {
this.databaseid = -1;
this.name = name;
this.signs = new HashSet<SimpleLocation>();
this.signs = new HashSet<>();
this.changed = false;
}
/**
* Creates a new Cell with the id in the database and the name.
*
* @param id The id of the cell in the database.
*
* @param id The id of the cell in the database.
* @param name The name of the cell.
*/
public Cell(int id, String name) {
this.databaseid = id;
this.name = name;
this.signs = new HashSet<SimpleLocation>();
this.signs = new HashSet<>();
this.changed = false;
}
public int getDatabaseID() {
return this.databaseid;
}
@ -99,38 +100,37 @@ public class Cell implements ICell {
}
public String getSignString() {
String r = "";
StringBuilder r = new StringBuilder();
for(SimpleLocation s : signs) {
if(r.isEmpty()) {
r = s.toString();
}else {
r += ";" + s.toString();
for (SimpleLocation s : signs) {
if (r.length() == 0) {
r = new StringBuilder(s.toString());
} else {
r.append(";").append(s.toString());
}
}
return r;
return r.toString();
}
public List<String> getInvalidSigns() {
List<String> invalid = new ArrayList<String>();
for(SimpleLocation s : new HashSet<SimpleLocation>(signs))
if (s.getLocation().getBlock().getState() instanceof Sign)
continue;
else
public List<String> getInvalidSigns() {
List<String> invalid = new ArrayList<>();
for (SimpleLocation s : new HashSet<>(signs))
if (s.getLocation().getBlock().getState() instanceof Sign) {
}
else
invalid.add(s.toString());
return invalid;
}
public List<String> cleanSigns() {
List<String> cleaned = new ArrayList<String>();
List<String> cleaned = new ArrayList<>();
for(SimpleLocation s : new HashSet<SimpleLocation>(signs)) {
for (SimpleLocation s : new HashSet<>(signs)) {
if (s.getLocation().getBlock().getState() instanceof Sign) {
continue;
}else {
} else {
changed = true;
signs.remove(s);
cleaned.add(s.toString());
@ -141,16 +141,16 @@ public class Cell implements ICell {
}
public HashMap<String, List<String>> updateSigns() {
List<String> removed = new ArrayList<String>();
List<String> updated = new ArrayList<String>();
List<String> removed = new ArrayList<>();
List<String> updated = new ArrayList<>();
for(SimpleLocation s : new HashSet<SimpleLocation>(signs)) {
for (SimpleLocation s : new HashSet<>(signs)) {
BlockState bs = s.getLocation().getBlock().getState();
if (bs instanceof Sign) {
Sign sign = (Sign) bs;
if(hasPrisoner()) {
if (hasPrisoner()) {
String[] lines = Util.replaceAllVariables(p, Util.getSignLines());
sign.setLine(0, lines[0]);
@ -158,7 +158,7 @@ public class Cell implements ICell {
sign.setLine(2, lines[2]);
sign.setLine(3, lines[3]);
sign.update(true, false);
}else {
} else {
sign.setLine(0, "");
sign.setLine(1, Lang.CELLEMPTYSIGN.get());
sign.setLine(2, "");
@ -167,14 +167,14 @@ public class Cell implements ICell {
}
updated.add(s.toString());
}else {
} else {
changed = true;
signs.remove(s);
removed.add(s.toString());
}
}
HashMap<String, List<String>> results = new HashMap<String, List<String>>();
HashMap<String, List<String>> results = new HashMap<>();
results.put("removed", removed);
results.put("updated", updated);
@ -200,8 +200,8 @@ public class Cell implements ICell {
}
public Chest getChest() {
if(this.chest == null) return null;
if(this.chest.getLocation().getBlock() == null
if (this.chest == null) return null;
if (this.chest.getLocation().getBlock() == null
|| (this.chest.getLocation().getBlock().getType() != Material.CHEST
&& this.chest.getLocation().getBlock().getType() != Material.TRAPPED_CHEST)) return null;
@ -210,17 +210,17 @@ public class Cell implements ICell {
public boolean hasChest() {
Chest c = getChest();
if(c != null) {
if(c.getInventory().getSize() >= 40)
if (c != null) {
if (c.getInventory().getSize() >= 40)
return true;
else {
Bukkit.getLogger().severe("The cell " + this.name + " has chest that isn't a double chest, please fix.");
return false;
}
}else
} else
return false;
}
public boolean useChest() {
return this.chest != null;
}

View File

@ -4,16 +4,16 @@ import com.graywolf336.jail.enums.Confirmation;
/**
* Holds data for when a player is confirming a command.
*
*
* @author graywolf336
* @version 1.0.0
* @since 3.0.0
*/
public class ConfirmPlayer {
private String name;
private String[] args;
private Confirmation confirm;
private Long expires;
private final String name;
private final String[] args;
private final Confirmation confirm;
private final Long expires;
public ConfirmPlayer(String name, String[] args, Confirmation confirm) {
this.name = name;
@ -24,7 +24,7 @@ public class ConfirmPlayer {
/**
* Returns the name of the thing needing to confirm.
*
*
* @return the name of what is being confirmed
*/
public String getName() {
@ -33,7 +33,7 @@ public class ConfirmPlayer {
/**
* Returns the initial arguments they sent with their command.
*
*
* @return the initial arguments of the original command
*/
public String[] getArguments() {
@ -42,7 +42,7 @@ public class ConfirmPlayer {
/**
* Returns what they are {@link Confirmation confirming}.
*
*
* @return the {@link Confirmation} of what they're confirming
*/
public Confirmation getConfirming() {
@ -51,7 +51,7 @@ public class ConfirmPlayer {
/**
* Returns the time in milliseconds their confirmation time frame expires.
*
*
* @return the time their confirming expires
*/
public Long getExpiryTime() {

View File

@ -1,20 +1,20 @@
package com.graywolf336.jail.beans;
import java.util.HashSet;
import org.bukkit.Bukkit;
import org.bukkit.Location;
import java.util.HashSet;
/**
* Represents an instance of a player creating something, whether it be a jail or cell.
*
* @author graywolf336
* @since 3.0.0
* @version 1.1.0
*
* @author graywolf336
* @version 1.1.0
* @since 3.0.0
*/
public class CreationPlayer {
private String jailName, cellName;
private final String jailName;
private String cellName;
private int step;
private int x1, y1, z1, x2, y2, z2;
private String inWorld, freeWorld;
@ -25,7 +25,7 @@ public class CreationPlayer {
/**
* Create a new instance of a CreationPlayer, given the name of the jail.
*
*
* @param jailName The name of the jail.
*/
public CreationPlayer(String jailName) {
@ -35,20 +35,20 @@ public class CreationPlayer {
/**
* Creates a new instance of a CreationPlayer, give the name of the jail and cell.
*
*
* @param jailName The name of the jail.
* @param cellName The name of the cell.
*/
public CreationPlayer(String jailName, String cellName) {
this.jailName = jailName;
this.cellName = cellName;
this.signs = new HashSet<SimpleLocation>();
this.signs = new HashSet<>();
this.step = 1;
}
/**
* Gets the name of the jail.
*
*
* @return the name of the jail the player is creating
*/
public String getJailName() {
@ -57,7 +57,7 @@ public class CreationPlayer {
/**
* Gets the name of the cell.
*
*
* @return the name of the cell the player is creating
*/
public String getCellName() {
@ -66,9 +66,9 @@ public class CreationPlayer {
/**
* Returns the step the creation is in.
*
*
* <p>
* <p>
*
* If it is a <strong>Jail</strong>, then when these numbers are returned it means the following:
* <ol>
* <li>Creating the first block of the Jail region.</li>
@ -76,14 +76,14 @@ public class CreationPlayer {
* <li>Creating the teleport in location.</li>
* <li>Creating the teleport out location.</li>
* </ol>
*
* <p>
* If it is a <strong>Cell</strong>, then when these numbers are returned it means the following:
* <ol>
* <li>Setting the teleport in location.</li>
* <li>Setting all the signs.</li>
* <li>Setting the double chest.</li>
* </ol>
*
*
* @return The step of the Jail/Cell Creation, as an integer.
*/
public int getStep() {
@ -92,7 +92,7 @@ public class CreationPlayer {
/**
* Sets the step of the creation.
*
*
* @param step The state of the creation, see {@link #getStep() getStep} for more information.
*/
public void setStep(int step) {
@ -101,13 +101,12 @@ public class CreationPlayer {
/**
* Increments the current step up one.
*
*
* <p>
*
*
* <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
* be used again or you know for a fact that the next step is not above four (three for cell).
*
*/
public void nextStep() {
this.step++;
@ -115,7 +114,7 @@ public class CreationPlayer {
/**
* Sets the first corner with the given location.
*
*
* @param loc the location of the first corner
*/
public void setCornerOne(Location loc) {
@ -126,7 +125,7 @@ public class CreationPlayer {
/**
* Sets the first corner with the given x, y, and z.
*
*
* @param x coordinate of the first corner's x
* @param y coordinate of the first corner's x
* @param z coordinate of the first corner's x
@ -139,16 +138,16 @@ public class CreationPlayer {
/**
* Returns the <strong>first corner</strong> coords an array of int. <strong>0 = x</strong>, <strong>1 = y</strong>, <strong>2 = z</strong>
*
*
* @return the first corner coords
*/
public int[] getCornerOne() {
return new int[] {x1, y1, z1};
return new int[]{x1, y1, z1};
}
/**
* Sets the second corner with the given location.
*
*
* @param loc The second corner's location
*/
public void setCornerTwo(Location loc) {
@ -157,29 +156,31 @@ public class CreationPlayer {
this.z2 = loc.getBlockZ();
}
/** Sets the second corner with the given x, y, and z.
*
/**
* Sets the second corner with the given x, y, and z.
*
* @param x coordinate of the second corner's x
* @param y coordinate of the second corner's x
* @param z coordinate of the second corner's x
*/
*/
public void setCornerTwo(int x, int y, int z) {
this.x2 = x;
this.y2 = y;
this.z2 = z;
}
/** Returns the <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>
*
* @return the first corner coords
*/
public int[] getCornerTwo() {
return new int[] {x2, y2, z2};
return new int[]{x2, y2, z2};
}
/**
* Sets the teleport in coords from the given location.
*
*
* @param location the in location
*/
public void setTeleportIn(Location location) {
@ -193,12 +194,12 @@ public class CreationPlayer {
/**
* Sets the teleport in coords from the given params.
*
*
* @param world the name of the world
* @param x the coordinate for x
* @param y the coordinate for y
* @param z the coordinate for z
* @param yaw the yaw of the teleport in
* @param x the coordinate for x
* @param y the coordinate for y
* @param z the coordinate for z
* @param yaw the yaw of the teleport in
* @param pitch the pitch of the teleport in
*/
public void setTeleportIn(String world, double x, double y, double z, float yaw, float pitch) {
@ -212,7 +213,7 @@ public class CreationPlayer {
/**
* Gets the teleport in location in a {@link Location}.
*
*
* @return the teleport in {@link Location}
*/
public Location getTeleportIn() {
@ -221,7 +222,7 @@ public class CreationPlayer {
/**
* Gets the teleport in location in a {@link SimpleLocation}.
*
*
* @return the {@link SimpleLocation} for the teleportin
*/
public SimpleLocation getTeleportInSL() {
@ -230,7 +231,7 @@ public class CreationPlayer {
/**
* Sets the teleport free coords from the given location.
*
*
* @param location Sets the teleport free {@link Location}
*/
public void setTeleportFree(Location location) {
@ -244,12 +245,12 @@ public class CreationPlayer {
/**
* Sets the teleport free coords from the given params.
*
*
* @param world the name of the world
* @param x the coordinate for x
* @param y the coordinate for y
* @param z the coordinate for z
* @param yaw the yaw of the teleport free
* @param x the coordinate for x
* @param y the coordinate for y
* @param z the coordinate for z
* @param yaw the yaw of the teleport free
* @param pitch the pitch of the teleport free
*/
public void setTeleportFree(String world, double x, double y, double z, float yaw, float pitch) {
@ -263,7 +264,7 @@ public class CreationPlayer {
/**
* Gets the teleport free location in a {@link Location}.
*
*
* @return the teleport free {@link Location}
*/
public Location getTeleportFree() {
@ -272,7 +273,7 @@ public class CreationPlayer {
/**
* Gets the teleport free location in a {@link SimpleLocation}.
*
*
* @return the teleport free {@link SimpleLocation}
*/
public SimpleLocation getTeleportFreeSL() {
@ -281,7 +282,7 @@ public class CreationPlayer {
/**
* Adds a sign to this cell.
*
*
* @param sign the {@link SimpleLocation} of the sign to add
*/
public void addSign(SimpleLocation sign) {
@ -290,16 +291,16 @@ public class CreationPlayer {
/**
* Returns all the signs, null if none (usually null when a jail is being created).
*
*
* @return all of the signs, null if none.
*/
public HashSet<SimpleLocation> getSigns() {
return this.signs == null ? null : new HashSet<SimpleLocation>(this.signs);
return this.signs == null ? null : new HashSet<>(this.signs);
}
/**
* Sets the chest's location, used mainly for cells.
*
*
* @param loc the {@link SimpleLocation} of the cheset
*/
public void setChestLocation(SimpleLocation loc) {
@ -308,7 +309,7 @@ public class CreationPlayer {
/**
* Gets the chest's location.
*
*
* @return the {@link SimpleLocation} of the cheset
*/
public SimpleLocation getChestLocation() {

View File

@ -1,30 +1,30 @@
package com.graywolf336.jail.beans;
import java.util.HashMap;
import java.util.HashSet;
import java.util.UUID;
import com.graywolf336.jail.JailMain;
import com.graywolf336.jail.Util;
import org.bukkit.Location;
import org.bukkit.World;
import org.bukkit.block.Sign;
import org.bukkit.entity.Player;
import org.bukkit.util.Vector;
import com.graywolf336.jail.JailMain;
import com.graywolf336.jail.Util;
import java.util.HashMap;
import java.util.HashSet;
import java.util.UUID;
/** Represents a Jail, contains the prisoners and the cells.
*
/**
* Represents a Jail, contains the prisoners and the cells.
*
* @author graywolf336
* @since 3.0.0
* @version 1.0.3
* @since 3.0.0
*/
public class Jail {
private JailMain plugin;
private final JailMain plugin;
private boolean enabled;
private HashMap<String, Cell> cells;
private final HashMap<String, Cell> cells;
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 Location in, free;
@ -32,13 +32,13 @@ public class Jail {
this.plugin = plugin;
this.enabled = true;
this.name = name;
cells = new HashMap<String, Cell>();
nocellPrisoners = new HashMap<UUID, Prisoner>();
cells = new HashMap<>();
nocellPrisoners = new HashMap<>();
}
/**
* Gets the instance of the plugin's main class.
*
*
* @return the {@link JailMain} instance
*/
public JailMain getPlugin() {
@ -47,7 +47,7 @@ public class Jail {
/**
* Sets whether this jail can be used or not.
*
*
* @param enabled Whether to set if this Jail is enabled or not
*/
public void setEnabled(boolean enabled) {
@ -56,7 +56,7 @@ public class Jail {
/**
* Gets whether this jail is enabled or not.
*
*
* @return Whether the Jail is enabled or not
*/
public boolean isEnabled() {
@ -65,7 +65,7 @@ public class Jail {
/**
* Sets the name of the jail.
*
*
* @param name the name of the jail to set
*/
public void setName(String name) {
@ -74,7 +74,7 @@ public class Jail {
/**
* Gets the name of the jail.
*
*
* @return the name of the jail
*/
public String getName() {
@ -83,11 +83,11 @@ public class Jail {
/**
* Sets the location of the <b>minimum</b> point to the given location's coordinates.
*
*
* @param location the {@link Location} of the lowest point
*/
public void setMinPoint(Location location) {
if(this.world.isEmpty()) this.world = location.getWorld().getName();
if (this.world.isEmpty()) this.world = location.getWorld().getName();
this.minX = location.getBlockX();
this.minY = location.getBlockY();
@ -96,11 +96,11 @@ public class Jail {
/**
* Accepts an array of ints as the coord, where <strong>0 = x</strong>, <strong>1 = y</strong>, <strong>2 = z</strong>.
*
*
* @param coords the coordinates of the minimum point
*/
public void setMinPoint(int[] coords) {
if(coords.length != 3) return;
if (coords.length != 3) return;
this.minX = coords[0];
this.minY = coords[1];
@ -109,7 +109,7 @@ public class Jail {
/**
* Gets the minimum point as a Bukkit Location class.
*
*
* @return the {@link Location} of the minimum point.
*/
public Location getMinPoint() {
@ -118,11 +118,11 @@ public class Jail {
/**
* Sets the location of the <b>maximum</b> point to the given location's coordinates.
*
*
* @param location the {@link Location} of the maximum point
*/
public void setMaxPoint(Location location) {
if(this.world.isEmpty()) this.world = location.getWorld().getName();
if (this.world.isEmpty()) this.world = location.getWorld().getName();
this.maxX = location.getBlockX();
this.maxY = location.getBlockY();
@ -131,107 +131,137 @@ public class Jail {
/**
* Gets the minimum point as a Bukkit Location class.
*
*
* @return the {@link Location} of the maximum point
*/
public Location getMaxPoint() {
return new Location(plugin.getServer().getWorld(world), maxX, maxY, maxZ);
}
/** Accepts an array of ints as the coord, where <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) {
if(coords.length != 3) return;
if (coords.length != 3) return;
this.maxX = coords[0];
this.maxY = coords[1];
this.maxZ = coords[2];
}
/** Sets the name of the world this Jail is in. */
/**
* Sets the name of the world this Jail is in.
*/
public void setWorld(String name) {
this.world = name;
}
/** Gets the name of the world this Jail is in. */
/**
* Gets the name of the world this Jail is in.
*/
public String getWorldName() {
return this.world;
}
/** Gets the instance of the {@link World world} this Jail is in. */
/**
* Gets the instance of the {@link World world} this Jail is in.
*/
public World getWorld() {
return plugin.getServer().getWorld(world);
}
/** Sets the {@link Location location} of the teleport <strong>in</strong>. */
/**
* Sets the {@link Location location} of the teleport <strong>in</strong>.
*/
public void setTeleportIn(Location location) {
if(this.world.isEmpty()) this.world = location.getWorld().getName();
if (this.world.isEmpty()) this.world = location.getWorld().getName();
this.in = location;
}
/** Gets the {@link Location location} of the teleport in. */
/**
* Gets the {@link Location location} of the teleport in.
*/
public Location getTeleportIn() {
return this.in;
}
/** Sets the {@link Location location} of the teleport for the <strong>free</strong> spot. */
/**
* Sets the {@link Location location} of the teleport for the <strong>free</strong> spot.
*/
public void setTeleportFree(Location location) {
this.free = location;
}
/** Gets the {@link Location location} of the teleport free spot.*/
/**
* Gets the {@link Location location} of the teleport free spot.
*/
public Location getTeleportFree() {
return this.free;
}
/** Add a prisoner to this jail. */
/**
* Add a prisoner to this jail.
*/
public void addPrisoner(Prisoner p) {
this.nocellPrisoners.put(p.getUUID(), p);
}
/** Removes a prisoner from this jail, doesn't remove it from the cell. */
/**
* Removes a prisoner from this jail, doesn't remove it from the cell.
*/
public void removePrisoner(Prisoner p) {
this.nocellPrisoners.remove(p.getUUID());
}
/** Returns if there are any cells or not. */
/**
* Returns if there are any cells or not.
*/
public boolean hasCells() {
return !this.cells.isEmpty();
}
/** Adds a cell to the Jail. */
/**
* Adds a cell to the Jail.
*/
public boolean addCell(Cell cell, boolean save) {
if(save) plugin.getJailIO().saveCell(this, cell, false);
if (save) plugin.getJailIO().saveCell(this, cell, false);
//Check if it already exists or not
if(this.cells.containsKey(cell.getName())) return false;
if (this.cells.containsKey(cell.getName())) return false;
else this.cells.put(cell.getName(), cell);
return true;
}
/** Gets the cell with the given name. */
/**
* Gets the cell with the given name.
*/
public Cell getCell(String name) {
return this.cells.get(name);
}
/** Checks if the given name is a valid cell. */
/**
* Checks if the given name is a valid cell.
*/
public boolean isValidCell(String name) {
return this.cells.get(name) != null;
}
/** Removes the cell from the jail. */
/**
* Removes the cell from the jail.
*/
public void removeCell(String name) {
Cell c = this.cells.get(name);
//If we have a chest, clear the inventory
if(c.hasChest()) {
if (c.hasChest()) {
c.getChest().getInventory().clear();
}
//For each sign, clear the lines on the sign
for(SimpleLocation s : c.getSigns()) {
if(s.getLocation().getBlock() instanceof Sign) {
for (SimpleLocation s : c.getSigns()) {
if (s.getLocation().getBlock() instanceof Sign) {
Sign sign = (Sign) s.getLocation().getBlock();
for(int i = 0; i < 4; i++) {
for (int i = 0; i < 4; i++) {
sign.setLine(i, "");
}
}
@ -243,61 +273,73 @@ public class Jail {
this.cells.remove(name);
}
/** Returns the cell which the given player name is jailed in, null if not. */
/**
* Returns the cell which the given player name is jailed in, null if not.
*/
public Cell getCellPrisonerIsIn(UUID uuid) {
for(Cell c : cells.values())
if(c.hasPrisoner())
if(c.getPrisoner().getUUID().equals(uuid))
for (Cell c : cells.values())
if (c.hasPrisoner())
if (c.getPrisoner().getUUID().equals(uuid))
return c;
return null;
}
/** Returns the first empty cell, returns null if there aren't any cells or any free cells. */
/**
* Returns the first empty cell, returns null if there aren't any cells or any free cells.
*/
public Cell getFirstEmptyCell() {
for(Cell c : getCells())
if(c.hasPrisoner())
continue;
for (Cell c : getCells())
if (c.hasPrisoner()) {
}
else
return c;
return null;
}
/** Checks if there is an empty cell in this Jail. */
/**
* Checks if there is an empty cell in this Jail.
*/
public boolean hasEmptyCell() {
for(Cell c : getCells())
if(!c.hasPrisoner())
for (Cell c : getCells())
if (!c.hasPrisoner())
return true;
return false;
}
/** Gets the amount of cells the jail. */
/**
* Gets the amount of cells the jail.
*/
public int getCellCount() {
return this.cells.size();
}
/** Gets all the cells in the jail. */
/**
* Gets all the cells in the jail.
*/
public HashSet<Cell> getCells() {
return new HashSet<Cell>(this.cells.values());
return new HashSet<>(this.cells.values());
}
/** Gets the closest cell to the provided location, via the teleport in location of the cells. */
/**
* Gets the closest cell to the provided location, via the teleport in location of the cells.
*/
public Cell getNearestCell(Location loc) {
Cell cell = null;
double distance = -1;
for(Cell c : getCells()) {
for (Cell c : getCells()) {
//Check if the worlds are the same, if not we can't calculate anything
if(c.getTeleport().getWorld().getName().equalsIgnoreCase(loc.getWorld().getName())) {
if (c.getTeleport().getWorld().getName().equalsIgnoreCase(loc.getWorld().getName())) {
//They are in the same world
double dist = c.getTeleport().distance(loc);
if (dist < distance || distance < 0) {
cell = c;
distance = dist;
}
}else {
} else {
//If they aren't, return the first cell found.
return c;
}
@ -306,48 +348,56 @@ public class Jail {
return cell;
}
/** Clears all the prisoners from this Jail. */
/**
* Clears all the prisoners from this Jail.
*/
public void clearPrisoners() {
//Remove the prisoners from all the cells
for(Cell c : getCells()) {
for (Cell c : getCells()) {
c.removePrisoner();
}
//Replace all the current no cell prisoners with
//a new hashset of prisoners.
this.nocellPrisoners = new HashMap<UUID, Prisoner>();
this.nocellPrisoners = new HashMap<>();
}
/** 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() {
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<>(nocellPrisoners); //initalize the temp one to return with the prisoners not in any cells
for(Cell c : cells.values())
if(c.hasPrisoner())
for (Cell c : cells.values())
if (c.hasPrisoner())
all.put(c.getPrisoner().getUUID(), c.getPrisoner());
return all;
}
/** Gets a HashSet of the prisoners <b>in cells</b>. */
/**
* Gets a HashSet of the prisoners <b>in cells</b>.
*/
public HashSet<Prisoner> getPrisonersInCells() {
HashSet<Prisoner> all = new HashSet<Prisoner>();
HashSet<Prisoner> all = new HashSet<>();
for(Cell c : getCells())
if(c.hasPrisoner())
for (Cell c : getCells())
if (c.hasPrisoner())
all.add(c.getPrisoner());
return all;
}
/** Gets a HashSet of the prisoners <b>not</b> in cells.*/
/**
* Gets a HashSet of the prisoners <b>not</b> in cells.
*/
public HashMap<UUID, Prisoner> getPrisonersNotInCells() {
return this.nocellPrisoners;
}
/**
* Returns whether the player is a prisoner in the system, whether in a cell or no cell.
*
*
* @param player The {@link Player player instance} of the person we're checking.
* @return true if is jailed, false if not.
*/
@ -357,7 +407,7 @@ public class Jail {
/**
* Returns whether the uuid of a player is a prisoner in the system, whether in a cell or no cell.
*
*
* @param uuid The uuid of the person we're checking.
* @return true if is jailed, false if not.
*/
@ -367,7 +417,7 @@ public class Jail {
/**
* Returns whether the uuid of a player is a prisoner in this jail, no matter if they're in a cell or not.
*
*
* @param uuid The name of the person we're checking.
* @return true if is a prisoner, false if not.
*/
@ -377,16 +427,16 @@ public class Jail {
/**
* Checks if the given uuid of a player is a prisoner in a cell.
*
*
* @param uuid of the prisoner to check.
* @return true if is jailed in a cell, false if not.
*/
public boolean isJailedInACell(UUID uuid) {
if(this.nocellPrisoners.containsKey(uuid)) return false;
if (this.nocellPrisoners.containsKey(uuid)) return false;
for(Cell c : cells.values())
if(c.getPrisoner() != null)
if(c.getPrisoner().getUUID().equals(uuid))
for (Cell c : cells.values())
if (c.getPrisoner() != null)
if (c.getPrisoner().getUUID().equals(uuid))
return true;
return false;
@ -394,13 +444,13 @@ public class Jail {
/**
* Gets the {@link Prisoner prisoner} instance for the given name.
*
*
* @param name The name of the prisoner to get.
* @return the prisoner instance, can be null
*/
public Prisoner getPrisonerByLastKnownName(String name) {
for(Prisoner p : this.getAllPrisoners().values())
if(p.getLastKnownName().equalsIgnoreCase(name))
for (Prisoner p : this.getAllPrisoners().values())
if (p.getLastKnownName().equalsIgnoreCase(name))
return p;
return null;
@ -408,16 +458,16 @@ public class Jail {
/**
* Gets the {@link Prisoner prisoner} instance for the given uuid.
*
*
* @param uuid The uuid of the prisoner to get.
* @return the prisoner instance, can be null
*/
public Prisoner getPrisoner(UUID uuid) {
if(this.nocellPrisoners.containsKey(uuid)) return this.nocellPrisoners.get(uuid);
if (this.nocellPrisoners.containsKey(uuid)) return this.nocellPrisoners.get(uuid);
for(Cell c : cells.values())
if(c.hasPrisoner())
if(c.getPrisoner().getUUID().equals(uuid))
for (Cell c : cells.values())
if (c.hasPrisoner())
if (c.getPrisoner().getUUID().equals(uuid))
return c.getPrisoner();
return null;
@ -427,7 +477,7 @@ public class Jail {
* Returns the squared distance between teleport location of this jail
* and specified location in blocks. If locations are not in same world,
* distance cannot be calculated and it will return Integer.MAX_VALUE.
*
*
* @param loc The location to check
* @return Distance between the location provided and the teleport in location.
*/
@ -438,14 +488,14 @@ public class Jail {
/**
* Returns whether the given location is inside this Jail.
*
*
* @param loc to check whether is inside this jail
* @return True if the location is in the jail, false if it isn't
*/
public boolean isInside(Location loc) {
if(loc.getWorld().getName().equalsIgnoreCase(world)) {
if (loc.getWorld().getName().equalsIgnoreCase(world)) {
return Util.isInsideAB(loc.toVector(), new Vector(minX, minY, minZ), new Vector(maxX, maxY, maxZ));
}else {
} else {
return false;
}
}

View File

@ -1,93 +1,100 @@
package com.graywolf336.jail.beans;
import java.util.ArrayList;
import java.util.UUID;
import org.bukkit.Bukkit;
import org.bukkit.entity.Player;
import java.util.ArrayList;
import java.util.UUID;
/**
* Represents a vote to jail someone.
*
*
* @author graywolf336
* @since 3.0.0
* @version 1.0.0
* @since 3.0.0
*/
public class JailVote {
private String name;
private ArrayList<UUID> voters;
private final String name;
private final ArrayList<UUID> voters;
private int yes, no;
/**
* Initiates a vote to jail someone, with the vote being for the given player.
*
*
* @param player the name of the player the vote is for
*/
public JailVote(String player) {
this.name = player;
this.voters = new ArrayList<UUID>();
this.voters = new ArrayList<>();
this.yes = 0;
this.no = 0;
}
/** The name of the player the vote is for. */
/**
* The name of the player the vote is for.
*/
public String getPlayerName() {
return this.name;
}
/**
* Gets the player who the vote is for, from the player name.
*
*
* @return the player who the vote is for to jail
*/
@SuppressWarnings("deprecation")
public Player getPlayer() {
return Bukkit.getPlayer(name);
}
/** Checks if the player with the given id has voted already. */
/**
* Checks if the player with the given id has voted already.
*/
public boolean hasVoted(UUID id) {
return this.voters.contains(id);
}
/**
* Method to vote yes, providing the uuid of the person doing the voting.
*
*
* @param id the uuid of the voter
* @return true if it was success, false if they already voted
*/
public boolean voteYes(UUID id) {
if(this.voters.contains(id)) {
if (this.voters.contains(id)) {
return false;
}else {
} else {
this.voters.add(id);
this.yes++;
return true;
}
}
/**
* Method to vote no, providing the uuid of the person doing the voting.
*
*
* @param id the uuid of the voter
* @return true if it was success, false if they already voted
*/
public boolean voteNo(UUID id) {
if(this.voters.contains(id)) {
if (this.voters.contains(id)) {
return false;
}else {
} else {
this.voters.add(id);
this.no++;
return true;
}
}
/** Get the amount of yes votes. */
/**
* Get the amount of yes votes.
*/
public int getYesVotes() {
return this.yes;
}
/** Get the amount of no votes. */
/**
* Get the amount of no votes.
*/
public int getNoVotes() {
return this.no;
}

View File

@ -1,21 +1,19 @@
package com.graywolf336.jail.beans;
import com.graywolf336.jail.interfaces.ICell;
import org.bukkit.Location;
import org.bukkit.block.Chest;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import org.bukkit.Location;
import org.bukkit.block.Chest;
import com.graywolf336.jail.interfaces.ICell;
/**
* Pass this an instance of this class into the jailing of a player and they won't go into a cell.
*
* @author graywolf336
* @since 3.0.0
* @version 1.0.0
*
* @since 3.0.0
*/
public class NoCell implements ICell {
public int getDatabaseID() {
@ -97,7 +95,7 @@ public class NoCell implements ICell {
public boolean hasChest() {
throw new UnsupportedOperationException();
}
public boolean useChest() {
throw new UnsupportedOperationException();
}

View File

@ -1,36 +1,40 @@
package com.graywolf336.jail.beans;
import java.util.UUID;
import java.util.concurrent.TimeUnit;
import com.graywolf336.jail.enums.Lang;
import org.bukkit.Bukkit;
import org.bukkit.GameMode;
import org.bukkit.Location;
import org.bukkit.entity.Player;
import com.graywolf336.jail.enums.Lang;
import java.util.UUID;
import java.util.concurrent.TimeUnit;
/**
* Represents a Prisoner, player who is jailed, and contains all the information about him/her.
*
* @author graywolf336
* @since 2.x.x
* @version 3.1.1
* @since 2.x.x
*/
public class Prisoner {
private String uuid, name, jailer, reason, inventory, armor;
private final String uuid;
private String name;
private String jailer;
private String reason;
private String inventory;
private String armor;
private boolean muted = true, offlinePending = false, teleporting = false, toBeTransferred = false, changed = false;
private long time = -1L, afk = 0L;
private long time, afk = 0L;
private Location previousPosition;
private GameMode previousGameMode;
/**
* Creates the prisoner instance with the lot of data provided.
*
* @param uuid The uuid of the prisoner
* @param name The name of the prisoner
* @param muted Whether the prisoner is muted or not
* @param time The amount of remaining time the prisoner has
* @param uuid The uuid of the prisoner
* @param name The name of the prisoner
* @param muted Whether the prisoner is muted or not
* @param time The amount of remaining time the prisoner has
* @param jailer The name of the person who jailed this prisoner
* @param reason The reason why this prisoner is in jail
*/
@ -47,9 +51,9 @@ public class Prisoner {
/**
* Creates the prisoner instance with the lot of data provided.
*
* @param uuid The uuid of the prisoner
* @param name The name of the prisoner
* @param time The amount of remaining time the prisoner has
* @param uuid The uuid of the prisoner
* @param name The name of the prisoner
* @param time The amount of remaining time the prisoner has
* @param jailer The name of the person who jailed this prisoner
* @param reason The reason why this prisoner is in jail
*/
@ -65,9 +69,9 @@ public class Prisoner {
/**
* Creates the prisoner instance with the lot of data provided.
*
* @param uuid The uuid of the prisoner
* @param name The name of the prisoner
* @param time The amount of remaining time the prisoner has
* @param uuid The uuid of the prisoner
* @param name The name of the prisoner
* @param time The amount of remaining time the prisoner has
* @param reason The reason why this prisoner is in jail
*/
public Prisoner(String uuid, String name, long time, String reason) {
@ -96,8 +100,8 @@ public class Prisoner {
* Creates the prisoner instance with the data provided.
*
* @param player The instance of the player who is to be jailed
* @param muted Whether the prisoner is muted or not
* @param time The amount of remaining time the prisoner has
* @param muted Whether the prisoner is muted or not
* @param time The amount of remaining time the prisoner has
* @param jailer The jailer who jailed the prisoner
* @param reason The reason why this prisoner is in jail
*/
@ -115,7 +119,7 @@ public class Prisoner {
* Creates the prisoner instance with the data provided.
*
* @param player The instance of the player who is to be jailed
* @param time The amount of remaining time the prisoner has
* @param time The amount of remaining time the prisoner has
* @param jailer The jailer who jailed the prisoner
* @param reason The reason why this prisoner is in jail
*/
@ -132,7 +136,7 @@ public class Prisoner {
* The most basic prisoner instance creation via providing the player, time, and reason.
*
* @param player The instance of the player who is to be jailed
* @param time The amount of remaining time the prisoner has
* @param time The amount of remaining time the prisoner has
* @param reason The reason why this prisoner is in jail
*/
public Prisoner(Player player, long time, String reason) {
@ -147,7 +151,7 @@ public class Prisoner {
* The most basic prisoner instance creation via providing the player and time.
*
* @param player The instance of the player who is to be jailed
* @param time The amount of remaining time the prisoner has
* @param time The amount of remaining time the prisoner has
*/
public Prisoner(Player player, long time) {
this.uuid = player.getUniqueId().toString();
@ -156,39 +160,49 @@ public class Prisoner {
finishSetup();
}
/** Finishes the setup of the prisoner data, set to defaults. */
/**
* Finishes the setup of the prisoner data, set to defaults.
*/
private void finishSetup() {
if(jailer == null)
if (jailer == null)
jailer = Lang.DEFAULTJAILER.get();
if(reason == null)
if (reason == null)
Lang.DEFAULTJAILEDREASON.get();
if(inventory == null)
if (inventory == null)
inventory = "";
if(armor == null)
if (armor == null)
armor = "";
if(previousGameMode == null)
if (previousGameMode == null)
previousGameMode = GameMode.SURVIVAL;
previousPosition = null;
}
/** Returns the UUID of the prisoner. */
/**
* Returns the UUID of the prisoner.
*/
public UUID getUUID() {
return UUID.fromString(this.uuid);
}
/** Gets the name of this prisoner. */
/**
* Gets the name of this prisoner.
*/
public String getLastKnownName() {
return this.name;
}
/** Sets the name of this prisoner. */
/**
* Sets the name of this prisoner.
*/
public String setLastKnownName(String username) {
this.name = username;
this.changed = true;
return this.name;
}
/** Gets the reason this player was jailed for. */
/**
* Gets the reason this player was jailed for.
*/
public String getReason() {
return this.reason;
}
@ -205,44 +219,60 @@ public class Prisoner {
return this.reason;
}
/** Gets the person who jailed this prisoner. */
/**
* Gets the person who jailed this prisoner.
*/
public String getJailer() {
return this.jailer;
}
/** Sets the person who jailed this prisoner. */
/**
* Sets the person who jailed this prisoner.
*/
public void setJailer(String jailer) {
this.jailer = jailer;
this.changed = true;
}
/** Gets whether the prisoner is muted or not. */
/**
* Gets whether the prisoner is muted or not.
*/
public boolean isMuted() {
return this.muted;
}
/** Sets whether the prisoner is muted or not. */
/**
* Sets whether the prisoner is muted or not.
*/
public void setMuted(boolean muted) {
this.muted = muted;
this.changed = true;
}
/** Gets whether the prisoner is jailed forever or not. */
/**
* Gets whether the prisoner is jailed forever or not.
*/
public boolean isJailedForever() {
return this.time == -1;
}
/** Gets the remaining time the prisoner has. */
/**
* Gets the remaining time the prisoner has.
*/
public long getRemainingTime() {
return this.time;
}
/** Gets the remaining time the prisoner has in minutes. */
/**
* Gets the remaining time the prisoner has in minutes.
*/
public long getRemainingTimeInMinutes() {
return TimeUnit.MINUTES.convert(time, TimeUnit.MILLISECONDS);
}
/** Gets the remaining time the prison has in minutes except only in int format. */
/**
* Gets the remaining time the prison has in minutes except only in int format.
*/
public int getRemainingTimeInMinutesInt() {
return (int) this.getRemainingTimeInMinutes();
}
@ -264,7 +294,7 @@ public class Prisoner {
* @return the new remaining time the prisoner has
*/
public long addTime(long time) {
if(this.time != -1L) {
if (this.time != -1L) {
this.time += time;
this.changed = true;
}
@ -279,7 +309,7 @@ public class Prisoner {
* @return the new remaining time the prisoner has
*/
public long subtractTime(long time) {
if(this.time != -1L) {
if (this.time != -1L) {
this.time -= time;
this.changed = true;
}
@ -287,132 +317,174 @@ public class Prisoner {
return this.time;
}
/** Gets whether the player is offline or not. */
/**
* Gets whether the player is offline or not.
*/
public boolean isOfflinePending() {
return this.offlinePending;
}
/** Sets whether the player is offline or not. */
/**
* Sets whether the player is offline or not.
*/
public void setOfflinePending(boolean offline) {
this.offlinePending = offline;
this.changed = true;
}
/** Gets whether the player is being teleported or not. */
/**
* Gets whether the player is being teleported or not.
*/
public boolean isTeleporting() {
return this.teleporting;
}
/** Sets whether the player is being teleported or not. */
/**
* Sets whether the player is being teleported or not.
*/
public void setTeleporting(boolean teleport) {
this.teleporting = teleport;
}
/** Gets whether the prisoner is going to be transferred or not, mainly for teleporting on join purposes. */
/**
* Gets whether the prisoner is going to be transferred or not, mainly for teleporting on join purposes.
*/
public boolean isToBeTransferred() {
return this.toBeTransferred;
}
/** Sets whether the prisoner is going to be transferred or not, mainly for teleporting on join purposes. */
/**
* Sets whether the prisoner is going to be transferred or not, mainly for teleporting on join purposes.
*/
public void setToBeTransferred(boolean transferred) {
this.toBeTransferred = transferred;
this.changed = true;
}
/** Gets the previous location of this player, can be null. */
/**
* Gets the previous location of this player, can be null.
*/
public Location getPreviousLocation() {
return this.previousPosition;
}
/** Gets the previous location of this player, separated by a comma. */
/**
* Gets the previous location of this player, separated by a comma.
*/
public String getPreviousLocationString() {
if(previousPosition == null) return "";
else if(previousPosition.getWorld() == null) return "";
if (previousPosition == null) return "";
else if (previousPosition.getWorld() == null) return "";
else return previousPosition.getWorld().getName() + "," +
previousPosition.getX() + "," +
previousPosition.getY() + "," +
previousPosition.getZ() + "," +
previousPosition.getYaw() + "," +
previousPosition.getPitch();
previousPosition.getX() + "," +
previousPosition.getY() + "," +
previousPosition.getZ() + "," +
previousPosition.getYaw() + "," +
previousPosition.getPitch();
}
/** Sets the previous location of this player. */
/**
* Sets the previous location of this player.
*/
public void setPreviousPosition(Location location) {
this.previousPosition = location;
}
/** Sets the previous location of this player from a comma separated string. */
/**
* Sets the previous location of this player from a comma separated string.
*/
public void setPreviousPosition(String location) {
if(location == null) return;
if(location.isEmpty()) return;
if (location == null) return;
if (location.isEmpty()) return;
this.changed = true;
String[] s = location.split(",");
this.previousPosition = new Location(Bukkit.getWorld(s[0]),
Double.valueOf(s[1]),
Double.valueOf(s[2]),
Double.valueOf(s[3]),
Float.valueOf(s[4]),
Float.valueOf(s[5]));
Double.parseDouble(s[1]),
Double.parseDouble(s[2]),
Double.parseDouble(s[3]),
Float.parseFloat(s[4]),
Float.parseFloat(s[5]));
}
/** Gets the previous gamemode of this player. */
/**
* Gets the previous gamemode of this player.
*/
public GameMode getPreviousGameMode() {
return this.previousGameMode;
}
/** Sets the previous gamemode of this player. */
/**
* Sets the previous gamemode of this player.
*/
public void setPreviousGameMode(GameMode previous) {
this.previousGameMode = previous;
this.changed = true;
}
/** Sets the previous gamemode of this player based upon the provided string. */
/**
* Sets the previous gamemode of this player based upon the provided string.
*/
public void setPreviousGameMode(String previous) {
if(previous == null) return;
else if(previous.isEmpty()) return;
if (previous == null) return;
else if (previous.isEmpty()) return;
else this.previousGameMode = GameMode.valueOf(previous);
this.changed = true;
}
/** Gets the inventory string for this player, it is encoded in Base64 string. */
/**
* Gets the inventory string for this player, it is encoded in Base64 string.
*/
public String getInventory() {
return this.inventory;
}
/** Sets the inventory Base64 string. */
/**
* Sets the inventory Base64 string.
*/
public void setInventory(String inventory) {
this.inventory = inventory;
this.changed = true;
}
/** Gets the armor content, encoded in Base64 string. */
/**
* Gets the armor content, encoded in Base64 string.
*/
public String getArmor() {
return this.armor;
}
/** Sets the armor inventory Base64 string. */
/**
* Sets the armor inventory Base64 string.
*/
public void setArmor(String armor) {
this.armor = armor;
this.changed = true;
}
/** Gets the time, in milliseconds, this prisoner has been afk. */
/**
* Gets the time, in milliseconds, this prisoner has been afk.
*/
public long getAFKTime() {
return this.afk;
}
/** Sets the time, in milliseconds, this prisoner has been afk. */
/**
* Sets the time, in milliseconds, this prisoner has been afk.
*/
public void setAFKTime(long time) {
this.afk = time;
}
/** Checks if the prisoner was changed or not. */
/**
* Checks if the prisoner was changed or not.
*/
public boolean wasChanged() {
return this.changed;
}
/** Sets whether the prisoner was changed or not. */
/**
* Sets whether the prisoner was changed or not.
*/
public boolean setChanged(boolean change) {
this.changed = change;
return this.changed;

View File

@ -6,24 +6,26 @@ import org.bukkit.World;
/**
* Simple location class which doesn't store any instances of {@link World worlds} or {@link org.bukkit.block.Block blocks}, just uses strings, floats, and doubles.
*
*
* @author graywolf336
* @since 3.0.0
* @version 1.1.1
* @since 3.0.0
*/
public class SimpleLocation {
private String world;
private double x, y, z;
private final String world;
private final double x;
private final double y;
private final double z;
private float yaw, pitch;
/**
* Creates a new SimpleLocation with each detail provided separately.
*
*
* @param world as a string
* @param x coordinate as a double
* @param y coordinate as a double
* @param z coordinate as a double
* @param yaw as a float
* @param x coordinate as a double
* @param y coordinate as a double
* @param z coordinate as a double
* @param yaw as a float
* @param pitch as a float
*/
public SimpleLocation(String world, double x, double y, double z, float yaw, float pitch) {
@ -37,7 +39,7 @@ public class SimpleLocation {
/**
* Creates a new SimpleLocation with all the detail provided from {@link Location}.
*
*
* @param location to convert to a SimpleLocation
*/
public SimpleLocation(Location location) {
@ -51,28 +53,28 @@ public class SimpleLocation {
/**
* Creates a new Simple Location with all the inputs being in string.
*
*
* @param world the name of the world
* @param x coordinate as a string
* @param y coordinate as a string
* @param z coordinate as a string
* @param x coordinate as a string
* @param y coordinate as a string
* @param z coordinate as a string
*/
public SimpleLocation(String world, String x, String y, String z) {
this.world = world;
this.x = Double.valueOf(x);
this.y = Double.valueOf(y);
this.z = Double.valueOf(z);
this.x = Double.parseDouble(x);
this.y = Double.parseDouble(y);
this.z = Double.parseDouble(z);
this.yaw = 0;
this.pitch = 0;
}
/**
* Creates a new SimpleLocation with each detail provided separately.
*
*
* @param world as a string
* @param x coordinate as a double
* @param y coordinate as a double
* @param z coordinate as a double
* @param x coordinate as a double
* @param y coordinate as a double
* @param z coordinate as a double
*/
public SimpleLocation(String world, double x, double y, double z) {
this.world = world;
@ -81,17 +83,23 @@ public class SimpleLocation {
this.z = z;
}
/** Returns the instance from Bukkit of the world this location is in. */
/**
* Returns the instance from Bukkit of the world this location is in.
*/
public World getWorld() {
return Bukkit.getWorld(world);
}
/** Returns the name of the world this location is in. */
/**
* Returns the name of the world this location is in.
*/
public String getWorldName() {
return this.world;
}
/** Returns a new {@link Location} from this SimpleLocation. */
/**
* Returns a new {@link Location} from this SimpleLocation.
*/
public Location getLocation() {
return new Location(Bukkit.getWorld(world), x, y, z, yaw, pitch);
}

View File

@ -2,22 +2,23 @@ package com.graywolf336.jail.beans;
/**
* Represents a Jail Stick, contains all the information.
*
*
* @author graywolf336
* @version 1.0.1
* @since 3.0.0
*/
public class Stick {
private String jail, reason;
private long time;
private double health;
private final String jail;
private final String reason;
private final long time;
private final double health;
/**
* Creates a new Jail Stick instance.
*
* @param jail the player will be jailed in.
*
* @param jail the player will be jailed in.
* @param reason the player will be jailed for.
* @param time the player will be jailed for.
* @param time the player will be jailed for.
* @param health a player must have, at the least, before being able to be jailed with this stick, -1 disables this feature
*/
public Stick(String jail, String reason, long time, double health) {
@ -29,7 +30,7 @@ public class Stick {
/**
* Gets the name of the jail a player will be sent when jailed via this jail stick.
*
*
* @return the name of the jail this stick puts people in
*/
public String getJail() {
@ -38,7 +39,7 @@ public class Stick {
/**
* Gets the reason a player will be jailed for when jailed via this stick.
*
*
* @return the reason of jailing used by this stick
*/
public String getReason() {
@ -47,17 +48,18 @@ public class Stick {
/**
* Gets the amount of time a player has to serve when they are jailed via this stick.
*
*
* @return the amount of time someone is jailed via this stick
*/
public long getTime() {
return this.time;
}
/** Gets the amount of health a player has to have before getting jailed via this stick.
*
/**
* Gets the amount of health a player has to have before getting jailed via this stick.
*
* <p>
* <p>
*
* See here for reference: http://dev.bukkit.org/bukkit-plugins/jail/tickets/415/
*/
public double getHealth() {

View File

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

View File

@ -1,14 +1,5 @@
package com.graywolf336.jail.command;
import java.util.ArrayList;
import java.util.Collections;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map.Entry;
import org.bukkit.command.CommandSender;
import org.bukkit.entity.Player;
import com.graywolf336.jail.JailMain;
import com.graywolf336.jail.JailManager;
import com.graywolf336.jail.command.commands.HandCuffCommand;
@ -17,42 +8,50 @@ import com.graywolf336.jail.command.commands.UnHandCuffCommand;
import com.graywolf336.jail.command.commands.UnJailCommand;
import com.graywolf336.jail.command.commands.UnJailForceCommand;
import com.graywolf336.jail.enums.Lang;
import org.bukkit.command.CommandSender;
import org.bukkit.entity.Player;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map.Entry;
/**
* Where all the commands are registered, handled, and processed.
*
* @author graywolf336
* @since 3.0.0
* @version 1.0.2
*
* @author graywolf336
* @version 1.0.2
* @since 3.0.0
*/
public class CommandHandler {
private LinkedHashMap<String, Command> commands;
private final LinkedHashMap<String, Command> commands;
public CommandHandler(JailMain plugin) {
commands = new LinkedHashMap<String, Command>();
commands = new LinkedHashMap<>();
loadCommands();
plugin.debug("Loaded " + commands.size() + " commands.");
}
public List<String> parseTabComplete(JailManager jm, CommandSender sender, String commandLine, String[] args) throws Exception {
public List<String> parseTabComplete(JailManager jm, CommandSender sender, String commandLine, String[] args) {
List<Command> matches = getMatches(commandLine);
if(matches.isEmpty() || matches.size() > 1) return Collections.emptyList();
if (matches.size() != 1) return Collections.emptyList();
else {
CommandInfo i = matches.get(0).getClass().getAnnotation(CommandInfo.class);
//Sender provided too many arguments which means there
//is nothing to tab complete
if(i.maxArgs() != -1 && i.maxArgs() < args.length) return Collections.emptyList();
if (i.maxArgs() != -1 && i.maxArgs() < args.length) return Collections.emptyList();
//Don't return anything if a player is required and they're not a player
if(i.needsPlayer() && !(sender instanceof Player)) return Collections.emptyList();
if (i.needsPlayer() && !(sender instanceof Player)) return Collections.emptyList();
//Don't return anything if they don't have permission
if(!sender.hasPermission(i.permission())) return Collections.emptyList();
if (!sender.hasPermission(i.permission())) return Collections.emptyList();
//Let the command handle the rest of it
return matches.get(0).provideTabCompletions(jm, sender, args);
}
@ -60,9 +59,9 @@ public class CommandHandler {
/**
* Handles the given command and checks that the command is in valid form.
*
*
* <p>
* <p>
*
* It checks in the following order:
* <ol>
* <li>If the command is registered or not.</li>
@ -73,27 +72,25 @@ public class CommandHandler {
* <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>
* </ol>
*
*
* @param jailmanager The instance of {@link JailManager}.
* @param sender The sender of the command.
* @param sender The sender of the command.
* @param commandLine The name of the command.
* @param args The arguments passed to the command.
* @param args The arguments passed to the command.
*/
public void handleCommand(JailManager jailmanager, CommandSender sender, String commandLine, String[] args) {
List<Command> matches = getMatches(commandLine);
//If no matches were found, send them the unknown command message.
if(matches.isEmpty()) {
if(commandLine.startsWith("jail")) {
if (matches.isEmpty()) {
if (commandLine.startsWith("jail")) {
String j = commandLine.substring(0, 4);
String a0 = commandLine.substring(4, commandLine.length());
String a0 = commandLine.substring(4);
ArrayList<String> args2 = new ArrayList<String>();
for(String s : args)
args2.add(s);
ArrayList<String> args2 = new ArrayList<>(Arrays.asList(args));
args2.add(a0);
if(jailmanager.getPlugin().onCommand(sender, null, j, args2.toArray(new String[args2.size()])))
if (jailmanager.getPlugin().onCommand(sender, null, j, args2.toArray(new String[0])))
return;
}
@ -102,8 +99,8 @@ public class CommandHandler {
}
//If more than one command was found, send them each command's help message.
if(matches.size() > 1) {
for(Command c : matches)
if (matches.size() > 1) {
for (Command c : matches)
showUsage(sender, c);
return;
}
@ -112,25 +109,25 @@ public class CommandHandler {
CommandInfo i = c.getClass().getAnnotation(CommandInfo.class);
// First, let's check if the sender has permission for the command.
if(!sender.hasPermission(i.permission())) {
if (!sender.hasPermission(i.permission())) {
sender.sendMessage(Lang.NOPERMISSION.get());
return;
}
// Next, let's check if we need a player and then if the sender is actually a player
if(i.needsPlayer() && !(sender instanceof Player)) {
if (i.needsPlayer() && !(sender instanceof Player)) {
sender.sendMessage(Lang.PLAYERCONTEXTREQUIRED.get());
return;
}
// Now, let's check the size of the arguments passed. If it is shorter than the minimum required args, let's show the usage.
if(args.length < i.minimumArgs()) {
if (args.length < i.minimumArgs()) {
showUsage(sender, c);
return;
}
// Then, if the maximumArgs doesn't equal -1, we need to check if the size of the arguments passed is greater than the maximum args.
if(i.maxArgs() != -1 && i.maxArgs() < args.length) {
if (i.maxArgs() != -1 && i.maxArgs() < args.length) {
showUsage(sender, c);
return;
}
@ -138,9 +135,8 @@ public class CommandHandler {
// Since everything has been checked and we're all clear, let's execute it.
// But if get back false, let's show the usage message.
try {
if(!c.execute(jailmanager, sender, args)) {
if (!c.execute(jailmanager, sender, args)) {
showUsage(sender, c);
return;
}
} catch (Exception e) {
e.printStackTrace();
@ -150,10 +146,10 @@ public class CommandHandler {
}
private List<Command> getMatches(String command) {
List<Command> result = new ArrayList<Command>();
List<Command> result = new ArrayList<>();
for(Entry<String, Command> entry : commands.entrySet()) {
if(command.matches(entry.getKey())) {
for (Entry<String, Command> entry : commands.entrySet()) {
if (command.matches(entry.getKey())) {
result.add(entry.getValue());
}
}
@ -163,18 +159,20 @@ public class CommandHandler {
/**
* Shows the usage information to the sender, if they have permission.
*
* @param sender The sender of the command
*
* @param sender The sender of the command
* @param command The command to send usage of.
*/
private void showUsage(CommandSender sender, Command command) {
CommandInfo info = command.getClass().getAnnotation(CommandInfo.class);
if(!sender.hasPermission(info.permission())) return;
if (!sender.hasPermission(info.permission())) return;
sender.sendMessage(info.usage());
}
/** Loads all the commands into the hashmap. */
/**
* Loads all the commands into the hashmap.
*/
private void loadCommands() {
load(HandCuffCommand.class);
load(ToggleJailDebugCommand.class);
@ -185,11 +183,11 @@ public class CommandHandler {
private void load(Class<? extends Command> c) {
CommandInfo info = c.getAnnotation(CommandInfo.class);
if(info == null) return;
if (info == null) return;
try {
commands.put(info.pattern(), c.newInstance());
}catch(Exception e) {
} catch (Exception e) {
e.printStackTrace();
}
}

View File

@ -5,9 +5,9 @@ import java.lang.annotation.RetentionPolicy;
/**
* Contains a definition of all the annotations {@link Command commands} should have, if a {@link Command command} doesn't have any then it isn't registered.
*
*
* <p>
* <p>
*
* This helps make loading and registering and verifying commands a lot
* easier, makes sure that before we really process a command that it
* is structured correctly and all the right information is passed. If
@ -23,56 +23,55 @@ import java.lang.annotation.RetentionPolicy;
* for that command. Finally we have the usage string, which is sent
* when the sender of the command sends an incorrectly formatted
* command. The order of checking is as defined in {@link CommandHandler#handleCommand(com.graywolf336.jail.JailManager, org.bukkit.command.CommandSender, String, String[]) CommandHandler.handleCommand}.
*
* @author graywolf336
* @since 3.0.0
* @version 1.0.0
*
* @author graywolf336
* @version 1.0.0
* @since 3.0.0
*/
@Retention (RetentionPolicy.RUNTIME)
@Retention(RetentionPolicy.RUNTIME)
public @interface CommandInfo {
/**
* Gets the maximum amount of arguments required, -1 if no maximum (ex: Jailing someone with a reason or editing a reason).
*
*
* @return The maximum number of arguments required, -1 if no maximum.
*/
public int maxArgs();
int maxArgs();
/**
* Gets the minimum amount of arguments required.
*
*
* @return The minimum number of arguments required.
*/
public int minimumArgs();
int minimumArgs();
/**
* Whether the command needs a player context or not.
*
*
* @return True if requires a player, false if not.
*/
public boolean needsPlayer();
boolean needsPlayer();
/**
* A regex pattern that allows for alternatives to the command (ex: /jail or /j, /jailstatus or /js).
*
*
* @return The regex pattern to match.
*/
public String pattern();
String pattern();
/**
* Gets the permission required to execute this command.
*
*
* @return The permission required.
*/
public String permission();
String permission();
/**
* Gets the usage message for this command.
*
*
* @return The usage message.
*/
public String usage();
String usage();
// /**
// * Gets the help messages for this command, color codes enabled.
// *

View File

@ -1,14 +1,5 @@
package com.graywolf336.jail.command;
import java.util.ArrayList;
import java.util.Collections;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map.Entry;
import org.bukkit.command.CommandSender;
import org.bukkit.entity.Player;
import com.graywolf336.jail.JailMain;
import com.graywolf336.jail.JailManager;
import com.graywolf336.jail.command.subcommands.JailCheckCommand;
@ -39,104 +30,111 @@ import com.graywolf336.jail.command.subcommands.JailTransferCommand;
import com.graywolf336.jail.command.subcommands.JailVersionCommand;
import com.graywolf336.jail.command.subcommands.JailVoteCommand;
import com.graywolf336.jail.enums.Lang;
import org.bukkit.command.CommandSender;
import org.bukkit.entity.Player;
import java.util.ArrayList;
import java.util.Collections;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map.Entry;
/**
* Where all the <strong>jail</strong> commands are registered, handled, and processed at.
*
* @author graywolf336
* @since 3.0.0
* @version 1.1.0
*
* @author graywolf336
* @version 1.1.0
* @since 3.0.0
*/
public class JailHandler {
private LinkedHashMap<String, Command> commands;
private final LinkedHashMap<String, Command> commands;
public JailHandler(JailMain plugin) {
commands = new LinkedHashMap<String, Command>();
commands = new LinkedHashMap<>();
loadCommands();
plugin.debug("Loaded " + commands.size() + " sub-commands of /jail.");
}
public List<String> parseTabComplete(JailManager jm, CommandSender sender, String[] args) throws Exception {
if(args[0].isEmpty() || args.length == 1) {
List<String> results = new ArrayList<String>();
public List<String> parseTabComplete(JailManager jm, CommandSender sender, String[] args) {
if (args[0].isEmpty() || args.length == 1) {
List<String> results = new ArrayList<>();
String arg0 = args[0].toLowerCase();
boolean hasJailPermission = false;
for(Command c : commands.values()) {
for (Command c : commands.values()) {
CommandInfo i = c.getClass().getAnnotation(CommandInfo.class);
//Skip the jail subcommand instance, since it is unique
if(i.pattern().equalsIgnoreCase("jail|j")) {
if (i.pattern().equalsIgnoreCase("jail|j")) {
hasJailPermission = sender.hasPermission(i.permission());
continue;
}
//Skip if the command requires a player and the sender isn't a player
if(i.needsPlayer() && !(sender instanceof Player)) continue;
if (i.needsPlayer() && !(sender instanceof Player)) continue;
//If the sender has permission to the command
//and the first argument (sub command) is empty OR
//the first argument matches the command or starts with the string
if(sender.hasPermission(i.permission()) && (arg0.isEmpty() || (arg0.toLowerCase().matches(i.pattern()) || i.pattern().startsWith(arg0)))) {
if (sender.hasPermission(i.permission()) && (arg0.isEmpty() || (arg0.toLowerCase().matches(i.pattern()) || i.pattern().startsWith(arg0)))) {
results.add(i.pattern().split("\\|")[0]);
}
}
//Sort the results before adding the player names
Collections.sort(results);
//If the results doesn't contain anything and they have permission to jail someone
//then send let the jail command provide the tab completion
if(results.isEmpty() && hasJailPermission)
if (results.isEmpty() && hasJailPermission)
return getMatches("jail").get(0).provideTabCompletions(jm, sender, args);
else
return results;
}else {
} else {
String arg0 = args[0].toLowerCase();
boolean hasJailPermission = false;
for(Command c : commands.values()) {
for (Command c : commands.values()) {
CommandInfo i = c.getClass().getAnnotation(CommandInfo.class);
//since the pattern won't ever match the jail plugin
//we can skip it but first we need to see if they have
//permission to do the jailing
if(i.pattern().equalsIgnoreCase("jail|j")) {
if (i.pattern().equalsIgnoreCase("jail|j")) {
hasJailPermission = sender.hasPermission(i.permission());
continue;
}
if(!arg0.toLowerCase().matches(i.pattern())) continue;
if (!arg0.toLowerCase().matches(i.pattern())) continue;
//Sender provided too many arguments which means there
//is nothing to tab complete
if(i.maxArgs() != -1 && i.maxArgs() < args.length - 1) continue;
if (i.maxArgs() != -1 && i.maxArgs() < args.length - 1) continue;
//Skip if the command requires a player and the sender isn't a player
if(i.needsPlayer() && !(sender instanceof Player)) continue;
if (i.needsPlayer() && !(sender instanceof Player)) continue;
//If the sender doesn't have permission, we won't send them further
if(!sender.hasPermission(i.permission())) continue;
if (!sender.hasPermission(i.permission())) continue;
return c.provideTabCompletions(jm, sender, args);
}
//By the time it has reached here no other command matched
//which means they are probably jailing someone, or trying to
//so let's check permission first and go from there.
if(hasJailPermission)
if (hasJailPermission)
return getMatches("jail").get(0).provideTabCompletions(jm, sender, args);
}
return Collections.emptyList();
}
/**
* Handles the given command and checks that the command is in valid form.
*
*
* <p>
* <p>
*
* It checks in the following order:
* <ol>
* <li>If they have permission for it, if they don't then we send them a message stating so.</li>
@ -145,35 +143,35 @@ public class JailHandler {
* <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>
* </ol>
*
*
* @param jailmanager The instance of {@link JailManager}.
* @param sender The sender of the command.
* @param args The arguments passed to the command.
* @param sender The sender of the command.
* @param args The arguments passed to the command.
*/
public boolean parseCommand(JailManager jailmanager, CommandSender sender, String[] args) {
Command c = null;
Command c;
//If they didn't provide any arguments (aka just: /jail) then we will need to send them some help
if(args.length == 0) {
if (args.length == 0) {
//TODO: Create the help page(s)
c = getMatches("jail").get(0);
}else {
} else {
//Get the matches from the first argument passed
List<Command> matches = getMatches(args[0].toLowerCase());
if(matches.isEmpty()) {
if (matches.isEmpty()) {
//No matches found, thus it is more likely than not they are trying to jail someone
c = getMatches("jail").get(0);
} else if(matches.size() > 1) {
} else if (matches.size() > 1) {
//If there was found more than one match
//then let's send the usage of each match to the sender
for(Command cmd : matches)
for (Command cmd : matches)
showUsage(sender, cmd);
return true;
}else {
} else {
//Only one match was found, so let's continue
c = matches.get(0);
}
@ -182,14 +180,14 @@ public class JailHandler {
CommandInfo i = c.getClass().getAnnotation(CommandInfo.class);
// First, let's check if the sender has permission for the command.
if(!i.permission().isEmpty() && !sender.hasPermission(i.permission())) {
jailmanager.getPlugin().debug("Sender has no permission: " + i.permission());
if (!i.permission().isEmpty() && !sender.hasPermission(i.permission())) {
jailmanager.getPlugin().debug("Sender has no permission: " + i.permission());
sender.sendMessage(Lang.NOPERMISSION.get() + (jailmanager.getPlugin().inDebug() ? " (" + i.permission() + ")" : ""));
return true;
}
// Next, let's check if we need a player and then if the sender is actually a player
if(i.needsPlayer() && !(sender instanceof Player)) {
if (i.needsPlayer() && !(sender instanceof Player)) {
jailmanager.getPlugin().debug("Sender is not a player.");
sender.sendMessage(Lang.PLAYERCONTEXTREQUIRED.get());
return true;
@ -197,7 +195,7 @@ public class JailHandler {
// Now, let's check the size of the arguments passed. If it is shorter than the minimum required args, let's show the usage.
// The reason we are subtracting one is because the command is now `/jail <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.");
showUsage(sender, c);
return true;
@ -205,7 +203,7 @@ public class JailHandler {
// Then, if the maximumArgs doesn't equal -1, we need to check if the size of the arguments passed is greater than the maximum args.
// The reason we are subtracting one is because the command is now `/jail <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.");
showUsage(sender, c);
return true;
@ -214,14 +212,14 @@ public class JailHandler {
// Since everything has been checked and we're all clear, let's execute it.
// But if get back false, let's show the usage message.
try {
if(!c.execute(jailmanager, sender, args)) {
if (!c.execute(jailmanager, sender, args)) {
showUsage(sender, c);
return true;
}else {
} else {
return true;
}
} catch (Exception e) {
if(jailmanager.getPlugin().inDebug()) {
if (jailmanager.getPlugin().inDebug()) {
e.printStackTrace();
}
@ -232,10 +230,10 @@ public class JailHandler {
}
private List<Command> getMatches(String command) {
List<Command> result = new ArrayList<Command>();
List<Command> result = new ArrayList<>();
for(Entry<String, Command> entry : commands.entrySet()) {
if(command.matches(entry.getKey())) {
for (Entry<String, Command> entry : commands.entrySet()) {
if (command.matches(entry.getKey())) {
result.add(entry.getValue());
}
}
@ -245,13 +243,13 @@ public class JailHandler {
/**
* Shows the usage information to the sender, if they have permission.
*
* @param sender The sender of the command
*
* @param sender The sender of the command
* @param command The command to send usage of.
*/
private void showUsage(CommandSender sender, Command command) {
CommandInfo info = command.getClass().getAnnotation(CommandInfo.class);
if(!sender.hasPermission(info.permission())) return;
if (!sender.hasPermission(info.permission())) return;
sender.sendMessage(info.usage());
}
@ -286,13 +284,13 @@ public class JailHandler {
load(JailVoteCommand.class);
}
private void load(Class<? extends Command> c) {
CommandInfo info = c.getAnnotation(CommandInfo.class);
if(info == null) return;
private void load(Class<? extends Command> command) {
CommandInfo info = command.getAnnotation(CommandInfo.class);
if (info == null) return;
try {
commands.put(info.pattern(), c.newInstance());
}catch(Exception e) {
commands.put(info.pattern(), command.newInstance());
} catch (Exception e) {
e.printStackTrace();
}
}

View File

@ -1,17 +1,16 @@
package com.graywolf336.jail.command.commands;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import org.bukkit.command.CommandSender;
import org.bukkit.entity.Player;
import org.bukkit.util.StringUtil;
import com.graywolf336.jail.JailManager;
import com.graywolf336.jail.command.Command;
import com.graywolf336.jail.command.CommandInfo;
import com.graywolf336.jail.enums.Lang;
import org.bukkit.command.CommandSender;
import org.bukkit.entity.Player;
import org.bukkit.util.StringUtil;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
@CommandInfo(
maxArgs = 1,
@ -20,23 +19,22 @@ import com.graywolf336.jail.enums.Lang;
pattern = "handcuff|hc",
permission = "jail.command.handcuff",
usage = "/handcuff [player]"
)
)
public class HandCuffCommand implements Command {
@SuppressWarnings("deprecation")
public boolean execute(JailManager jm, CommandSender sender, String... args) {
Player player = jm.getPlugin().getServer().getPlayer(args[0]);
if(player == null) {
if (player == null) {
sender.sendMessage(Lang.PLAYERNOTONLINE.get());
}else if(player.hasPermission("jail.cantbehandcuffed")) {
} else if (player.hasPermission("jail.cantbehandcuffed")) {
sender.sendMessage(Lang.CANTBEHANDCUFFED.get(player.getName()));
}else if(jm.isPlayerJailed(player.getUniqueId())) {
} else if (jm.isPlayerJailed(player.getUniqueId())) {
sender.sendMessage(Lang.CURRENTLYJAILEDHANDCUFF.get(player.getName()));
}else if(jm.getPlugin().getHandCuffManager().isHandCuffed(player.getUniqueId())) {
} else if (jm.getPlugin().getHandCuffManager().isHandCuffed(player.getUniqueId())) {
sender.sendMessage(Lang.HANDCUFFSRELEASED.get(player.getName()));
jm.getPlugin().getHandCuffManager().removeHandCuffs(player.getUniqueId());
player.sendMessage(Lang.UNHANDCUFFED.get());
}else {
} else {
jm.getPlugin().getHandCuffManager().addHandCuffs(player.getUniqueId(), player.getLocation());
sender.sendMessage(Lang.HANDCUFFSON.get(player.getName()));
player.sendMessage(Lang.HANDCUFFED.get());
@ -45,17 +43,17 @@ public class HandCuffCommand implements Command {
return true;
}
public List<String> provideTabCompletions(JailManager jm, CommandSender sender, String... args) throws Exception {
List<String> results = new ArrayList<String>();
for(Player p : jm.getPlugin().getServer().getOnlinePlayers())
if(!jm.getPlugin().getHandCuffManager().isHandCuffed(p.getUniqueId())) //don't send someone who is already handcuffed
if(!p.hasPermission("jail.cantbehandcuffed")) //don't send someone who can't be handcuffed
if(args[0].isEmpty() || StringUtil.startsWithIgnoreCase(p.getName(), args[0]))
public List<String> provideTabCompletions(JailManager jm, CommandSender sender, String... args) {
List<String> results = new ArrayList<>();
for (Player p : jm.getPlugin().getServer().getOnlinePlayers())
if (!jm.getPlugin().getHandCuffManager().isHandCuffed(p.getUniqueId())) //don't send someone who is already handcuffed
if (!p.hasPermission("jail.cantbehandcuffed")) //don't send someone who can't be handcuffed
if (args[0].isEmpty() || StringUtil.startsWithIgnoreCase(p.getName(), args[0]))
results.add(p.getName());
Collections.sort(results);
return results;
}
}

View File

@ -1,14 +1,13 @@
package com.graywolf336.jail.command.commands;
import java.util.Collections;
import java.util.List;
import org.bukkit.ChatColor;
import org.bukkit.command.CommandSender;
import com.graywolf336.jail.JailManager;
import com.graywolf336.jail.command.Command;
import com.graywolf336.jail.command.CommandInfo;
import org.bukkit.ChatColor;
import org.bukkit.command.CommandSender;
import java.util.Collections;
import java.util.List;
@CommandInfo(
maxArgs = 0,
@ -17,7 +16,7 @@ import com.graywolf336.jail.command.CommandInfo;
pattern = "togglejaildebug|tjd",
permission = "jail.command.toggledebug",
usage = "/togglejaildebug"
)
)
public class ToggleJailDebugCommand implements Command {
public boolean execute(JailManager jm, CommandSender sender, String... args) {
boolean debug = jm.getPlugin().setDebugging(!jm.getPlugin().inDebug());
@ -25,7 +24,7 @@ public class ToggleJailDebugCommand implements Command {
return true;
}
public List<String> provideTabCompletions(JailManager jm, CommandSender sender, String... args) throws Exception {
public List<String> provideTabCompletions(JailManager jm, CommandSender sender, String... args) {
//No tab completion required for toggling debug command
return Collections.emptyList();
}

View File

@ -1,17 +1,16 @@
package com.graywolf336.jail.command.commands;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import org.bukkit.command.CommandSender;
import org.bukkit.entity.Player;
import org.bukkit.util.StringUtil;
import com.graywolf336.jail.JailManager;
import com.graywolf336.jail.command.Command;
import com.graywolf336.jail.command.CommandInfo;
import com.graywolf336.jail.enums.Lang;
import org.bukkit.command.CommandSender;
import org.bukkit.entity.Player;
import org.bukkit.util.StringUtil;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
@CommandInfo(
maxArgs = 1,
@ -20,35 +19,34 @@ import com.graywolf336.jail.enums.Lang;
pattern = "unhandcuff|uhc",
permission = "jail.command.handcuff",
usage = "/unhandcuff [player]"
)
)
public class UnHandCuffCommand implements Command {
@SuppressWarnings("deprecation")
public boolean execute(JailManager jm, CommandSender sender, String... args) {
Player player = jm.getPlugin().getServer().getPlayerExact(args[0]);
if(player == null) {
if (player == null) {
sender.sendMessage(Lang.PLAYERNOTONLINE.get());
}else if(jm.getPlugin().getHandCuffManager().isHandCuffed(player.getUniqueId())) {
} else if (jm.getPlugin().getHandCuffManager().isHandCuffed(player.getUniqueId())) {
sender.sendMessage(Lang.HANDCUFFSRELEASED.get(player.getName()));
jm.getPlugin().getHandCuffManager().removeHandCuffs(player.getUniqueId());
player.sendMessage(Lang.UNHANDCUFFED.get());
}else {
} else {
sender.sendMessage(Lang.NOTHANDCUFFED.get(player.getName()));
}
return true;
}
public List<String> provideTabCompletions(JailManager jm, CommandSender sender, String... args) throws Exception {
List<String> results = new ArrayList<String>();
for(Player p : jm.getPlugin().getServer().getOnlinePlayers())
if(jm.getPlugin().getHandCuffManager().isHandCuffed(p.getUniqueId())) //don't send someone who isn't already handcuffed
if(args[0].isEmpty() || StringUtil.startsWithIgnoreCase(p.getName(), args[0]))
public List<String> provideTabCompletions(JailManager jm, CommandSender sender, String... args) {
List<String> results = new ArrayList<>();
for (Player p : jm.getPlugin().getServer().getOnlinePlayers())
if (jm.getPlugin().getHandCuffManager().isHandCuffed(p.getUniqueId())) //don't send someone who isn't already handcuffed
if (args[0].isEmpty() || StringUtil.startsWithIgnoreCase(p.getName(), args[0]))
results.add(p.getName());
Collections.sort(results);
return results;
}
}

View File

@ -1,14 +1,5 @@
package com.graywolf336.jail.command.commands;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import org.bukkit.ChatColor;
import org.bukkit.command.CommandSender;
import org.bukkit.entity.Player;
import org.bukkit.util.StringUtil;
import com.graywolf336.jail.JailManager;
import com.graywolf336.jail.beans.Jail;
import com.graywolf336.jail.beans.Prisoner;
@ -18,6 +9,14 @@ import com.graywolf336.jail.enums.Lang;
import com.graywolf336.jail.enums.Settings;
import com.graywolf336.jail.exceptions.JailRequiredException;
import com.graywolf336.jail.exceptions.PrisonerRequiredException;
import org.bukkit.ChatColor;
import org.bukkit.command.CommandSender;
import org.bukkit.entity.Player;
import org.bukkit.util.StringUtil;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
@CommandInfo(
maxArgs = 1,
@ -26,29 +25,29 @@ import com.graywolf336.jail.exceptions.PrisonerRequiredException;
pattern = "unjail|uj",
permission = "jail.command.unjail",
usage = "/unjail [player]"
)
)
public class UnJailCommand implements Command {
public boolean execute(JailManager jm, CommandSender sender, String... args) throws JailRequiredException, PrisonerRequiredException {
//Check if the player is jailed
if(jm.isPlayerJailedByLastKnownUsername(args[0])) {
if (jm.isPlayerJailedByLastKnownUsername(args[0])) {
Jail j = jm.getJailPlayerIsInByLastKnownName(args[0]);
Prisoner pris = j.getPrisonerByLastKnownName(args[0]);
Player p = jm.getPlugin().getServer().getPlayer(pris.getUUID());
//Check if the player is on the server or not
if(p == null) {
if (p == null) {
//Check if the player has offline pending and their remaining time is above 0, if so then
//forceably unjail them
if(pris.isOfflinePending() && pris.getRemainingTime() != 0L) {
if (pris.isOfflinePending() && pris.getRemainingTime() != 0L) {
jm.getPlugin().getPrisonerManager().forceUnJail(j, j.getCellPrisonerIsIn(pris.getUUID()), p, pris, sender);
}else {
} else {
//The player is not, so we'll set the remaining time to zero and do it when they login next
pris.setRemainingTime(0L);
pris.setOfflinePending(true);
sender.sendMessage(Lang.WILLBEUNJAILED.get(args[0]));
}
}else {
} else {
//Player is online, so let's try unjailing them
try {
jm.getPlugin().getPrisonerManager().unJail(j, j.getCellPrisonerIsIn(pris.getUUID()), p, pris, sender);
@ -57,10 +56,10 @@ public class UnJailCommand implements Command {
}
}
if(jm.getPlugin().getConfig().getBoolean(Settings.LOGJAILINGTOCONSOLE.getPath())) {
jm.getPlugin().getLogger().info(ChatColor.stripColor(Lang.BROADCASTUNJAILING.get(new String[] { args[0], sender.getName() })));
if (jm.getPlugin().getConfig().getBoolean(Settings.LOGJAILINGTOCONSOLE.getPath())) {
jm.getPlugin().getLogger().info(ChatColor.stripColor(Lang.BROADCASTUNJAILING.get(args[0], sender.getName())));
}
}else {
} else {
//The player is not currently jailed
sender.sendMessage(Lang.NOTJAILED.get(args[0]));
}
@ -68,15 +67,15 @@ public class UnJailCommand implements Command {
return true;
}
public List<String> provideTabCompletions(JailManager jm, CommandSender sender, String... args) throws Exception {
List<String> results = new ArrayList<String>();
for(Prisoner p : jm.getAllPrisoners().values())
if(args[0].isEmpty() || StringUtil.startsWithIgnoreCase(p.getLastKnownName(), args[0]))
public List<String> provideTabCompletions(JailManager jm, CommandSender sender, String... args) {
List<String> results = new ArrayList<>();
for (Prisoner p : jm.getAllPrisoners().values())
if (args[0].isEmpty() || StringUtil.startsWithIgnoreCase(p.getLastKnownName(), args[0]))
results.add(p.getLastKnownName());
Collections.sort(results);
return results;
}
}

View File

@ -1,13 +1,5 @@
package com.graywolf336.jail.command.commands;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import org.bukkit.ChatColor;
import org.bukkit.command.CommandSender;
import org.bukkit.util.StringUtil;
import com.graywolf336.jail.JailManager;
import com.graywolf336.jail.beans.Prisoner;
import com.graywolf336.jail.command.Command;
@ -16,6 +8,13 @@ import com.graywolf336.jail.enums.Lang;
import com.graywolf336.jail.enums.Settings;
import com.graywolf336.jail.exceptions.JailRequiredException;
import com.graywolf336.jail.exceptions.PrisonerRequiredException;
import org.bukkit.ChatColor;
import org.bukkit.command.CommandSender;
import org.bukkit.util.StringUtil;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
@CommandInfo(
maxArgs = 1,
@ -24,18 +23,18 @@ import com.graywolf336.jail.exceptions.PrisonerRequiredException;
pattern = "unjailforce|ujf",
permission = "jail.command.unjailforce",
usage = "/unjailforce [player]"
)
)
public class UnJailForceCommand implements Command {
public boolean execute(JailManager jm, CommandSender sender, String... args) throws JailRequiredException, PrisonerRequiredException {
//Check if the player is jailed
if(jm.isPlayerJailedByLastKnownUsername(args[0])) {
if (jm.isPlayerJailedByLastKnownUsername(args[0])) {
jm.getPlugin().getPrisonerManager().forceRelease(jm.getPrisonerByLastKnownName(args[0]), sender);
if(jm.getPlugin().getConfig().getBoolean(Settings.LOGJAILINGTOCONSOLE.getPath())) {
jm.getPlugin().getLogger().info(ChatColor.stripColor(Lang.BROADCASTUNJAILING.get(new String[] { args[0], sender.getName() })));
if (jm.getPlugin().getConfig().getBoolean(Settings.LOGJAILINGTOCONSOLE.getPath())) {
jm.getPlugin().getLogger().info(ChatColor.stripColor(Lang.BROADCASTUNJAILING.get(args[0], sender.getName())));
}
}else {
} else {
//The player is not currently jailed
sender.sendMessage(Lang.NOTJAILED.get(args[0]));
}
@ -43,15 +42,15 @@ public class UnJailForceCommand implements Command {
return true;
}
public List<String> provideTabCompletions(JailManager jm, CommandSender sender, String... args) throws Exception {
List<String> results = new ArrayList<String>();
for(Prisoner p : jm.getAllPrisoners().values())
if(args[0].isEmpty() || StringUtil.startsWithIgnoreCase(p.getLastKnownName(), args[0]))
public List<String> provideTabCompletions(JailManager jm, CommandSender sender, String... args) {
List<String> results = new ArrayList<>();
for (Prisoner p : jm.getAllPrisoners().values())
if (args[0].isEmpty() || StringUtil.startsWithIgnoreCase(p.getLastKnownName(), args[0]))
results.add(p.getLastKnownName());
Collections.sort(results);
return results;
}
}

View File

@ -1,44 +1,51 @@
package com.graywolf336.jail.command.commands.jewels;
import java.util.List;
import com.lexicalscope.jewel.cli.Option;
import java.util.List;
public interface Jailing {
@Option(longName={"player", "pl"}, shortName="p", description = "the player's name")
public String getPlayer();
@Option(longName={"force"}, shortName="f", description = "force jailing someone who has never been online")
public boolean getForce();
@Option(longName = {"player", "pl"}, shortName = "p", description = "the player's name")
String getPlayer();
@Option(longName={"time", "length"}, shortName="t", description = "the amount of time")
public String getTime();
@Option(longName={"forever", "eternity", "infinite"}, shortName="i", description = "jail the player for eternity")
public boolean getInfinite();
@Option(longName = {"force"}, shortName = "f", description = "force jailing someone who has never been online")
boolean getForce();
@Option(longName={"jail", "prison"}, shortName="j", description = "the jail")
public String getJail();
@Option(longName = {"time", "length"}, shortName = "t", description = "the amount of time")
String getTime();
@Option(longName={"cell"}, shortName="c", description = "the cell")
public String getCell();
@Option(longName = {"forever", "eternity", "infinite"}, shortName = "i", description = "jail the player for eternity")
boolean getInfinite();
@Option(longName={"anycell"}, shortName="a", description = "decides whether the plugin will pick any open cell")
public boolean getAnyCell();
@Option(longName = {"jail", "prison"}, shortName = "j", description = "the jail")
String getJail();
@Option(longName={"muted", "canttalk"}, shortName="m", description = "whether the prisoner is muted or not")
public boolean getMuted();
@Option(longName = {"cell"}, shortName = "c", description = "the cell")
String getCell();
@Option(longName={"reason"}, shortName="r", description = "the reason this player is being jailed")
public List<String> getReason();
@Option(longName = {"anycell"}, shortName = "a", description = "decides whether the plugin will pick any open cell")
boolean getAnyCell();
public boolean isForce();
public boolean isInfinite();
public boolean isTime();
public boolean isJail();
public boolean isCell();
public boolean isAnyCell();
public boolean isMuted();
public boolean isReason();
@Option(longName = {"muted", "canttalk"}, shortName = "m", description = "whether the prisoner is muted or not")
boolean getMuted();
@Option(longName = {"reason"}, shortName = "r", description = "the reason this player is being jailed")
List<String> getReason();
boolean isForce();
boolean isInfinite();
boolean isTime();
boolean isJail();
boolean isCell();
boolean isAnyCell();
boolean isMuted();
boolean isReason();
}

View File

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

View File

@ -1,20 +1,19 @@
package com.graywolf336.jail.command.subcommands;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import com.graywolf336.jail.JailManager;
import com.graywolf336.jail.Util;
import com.graywolf336.jail.beans.Prisoner;
import com.graywolf336.jail.command.Command;
import com.graywolf336.jail.command.CommandInfo;
import com.graywolf336.jail.enums.Lang;
import org.bukkit.ChatColor;
import org.bukkit.command.CommandSender;
import org.bukkit.entity.Player;
import org.bukkit.util.StringUtil;
import com.graywolf336.jail.JailManager;
import com.graywolf336.jail.beans.Prisoner;
import com.graywolf336.jail.command.Command;
import com.graywolf336.jail.command.CommandInfo;
import com.graywolf336.jail.Util;
import com.graywolf336.jail.enums.Lang;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
@CommandInfo(
maxArgs = 1,
@ -23,44 +22,44 @@ import com.graywolf336.jail.enums.Lang;
pattern = "check",
permission = "jail.command.jailcheck",
usage = "/jail check [name]"
)
)
public class JailCheckCommand implements Command {
// Checks the status of the specified prisoner
public boolean execute(JailManager jm, CommandSender sender, String... args) {
//Otherwise let's check the first argument
if(jm.isPlayerJailedByLastKnownUsername(args[1])) {
if (jm.isPlayerJailedByLastKnownUsername(args[1])) {
Prisoner p = jm.getPrisonerByLastKnownName(args[1]);
//graywolf663: Being gray's evil twin; CONSOLE (10)
//prisoner: reason; jailer (time in minutes)
sender.sendMessage(ChatColor.BLUE + " " + p.getLastKnownName() + ": " + p.getReason() + "; " + p.getJailer() + " (" + Util.getDurationBreakdown(p.getRemainingTime()) + " )");
}else {
} else {
sender.sendMessage(Lang.NOTJAILED.get(args[1]));
}
return true;
}
public List<String> provideTabCompletions(JailManager jm, CommandSender sender, String... args) throws Exception {
List<String> results = new ArrayList<String>();
for(Prisoner p : jm.getAllPrisoners().values()) {
if(args.length == 2 && StringUtil.startsWithIgnoreCase(p.getLastKnownName(), args[1].toLowerCase())) {
public List<String> provideTabCompletions(JailManager jm, CommandSender sender, String... args) {
List<String> results = new ArrayList<>();
for (Prisoner p : jm.getAllPrisoners().values()) {
if (args.length == 2 && StringUtil.startsWithIgnoreCase(p.getLastKnownName(), args[1].toLowerCase())) {
results.add(p.getLastKnownName());
}else {
} else {
results.add(p.getLastKnownName());
}
}
Collections.sort(results);
if(args.length == 2)
for(Player p : jm.getPlugin().getServer().getOnlinePlayers())
if(args[1].isEmpty() || StringUtil.startsWithIgnoreCase(p.getName(), args[1]))
if(!results.contains(p.getName()))
if (args.length == 2)
for (Player p : jm.getPlugin().getServer().getOnlinePlayers())
if (args[1].isEmpty() || StringUtil.startsWithIgnoreCase(p.getName(), args[1]))
if (!results.contains(p.getName()))
results.add(p.getName());
return results;
}
}

View File

@ -1,12 +1,5 @@
package com.graywolf336.jail.command.subcommands;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import org.bukkit.command.CommandSender;
import org.bukkit.util.StringUtil;
import com.graywolf336.jail.JailManager;
import com.graywolf336.jail.beans.ConfirmPlayer;
import com.graywolf336.jail.beans.Jail;
@ -14,6 +7,12 @@ import com.graywolf336.jail.command.Command;
import com.graywolf336.jail.command.CommandInfo;
import com.graywolf336.jail.enums.Confirmation;
import com.graywolf336.jail.enums.Lang;
import org.bukkit.command.CommandSender;
import org.bukkit.util.StringUtil;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
@CommandInfo(
maxArgs = 2,
@ -22,22 +21,24 @@ import com.graywolf336.jail.enums.Lang;
pattern = "clear|clearforce",
permission = "jail.command.jailclear",
usage = "/jail clear (-f) (jail)"
)
)
public class JailClearCommand implements Command {
public boolean execute(JailManager jm, CommandSender sender, String... args) {
boolean force = false;
//Check if we need to forcefully clear something
for(String s : args)
if(s.equalsIgnoreCase("-f") || s.equalsIgnoreCase("-force"))
for (String s : args)
if (s.equalsIgnoreCase("-f") || s.equalsIgnoreCase("-force")) {
force = true;
break;
}
if(jm.isConfirming(sender.getName())) {
if (jm.isConfirming(sender.getName())) {
sender.sendMessage(Lang.ALREADY.get());
}else if(force && sender.hasPermission("jail.command.jailclearforce")) {
} else if (force && sender.hasPermission("jail.command.jailclearforce")) {
jm.addConfirming(sender.getName(), new ConfirmPlayer(sender.getName(), args, Confirmation.CLEARFORCE));
sender.sendMessage(Lang.START.get());
}else {
} else {
jm.addConfirming(sender.getName(), new ConfirmPlayer(sender.getName(), args, Confirmation.CLEAR));
sender.sendMessage(Lang.START.get());
}
@ -45,20 +46,20 @@ public class JailClearCommand implements Command {
return true;
}
public List<String> provideTabCompletions(JailManager jm, CommandSender sender, String... args) throws Exception {
List<String> results = new ArrayList<String>();
for(Jail j : jm.getJails()) {
if((args.length == 2 && StringUtil.startsWithIgnoreCase(j.getName(), args[1]))
public List<String> provideTabCompletions(JailManager jm, CommandSender sender, String... args) {
List<String> results = new ArrayList<>();
for (Jail j : jm.getJails()) {
if ((args.length == 2 && StringUtil.startsWithIgnoreCase(j.getName(), args[1]))
|| (args.length == 3 && StringUtil.startsWithIgnoreCase(j.getName(), args[2]))) {
results.add(j.getName());
}else {
} else {
results.add(j.getName());
}
}
Collections.sort(results);
return results;
}
}

View File

@ -1,19 +1,5 @@
package com.graywolf336.jail.command.subcommands;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.LinkedList;
import java.util.List;
import org.apache.commons.lang3.ArrayUtils;
import org.bukkit.ChatColor;
import org.bukkit.OfflinePlayer;
import org.bukkit.command.CommandSender;
import org.bukkit.entity.Player;
import org.bukkit.util.StringUtil;
import com.graywolf336.jail.JailManager;
import com.graywolf336.jail.Util;
import com.graywolf336.jail.beans.Cell;
@ -28,6 +14,18 @@ import com.graywolf336.jail.events.PrePrisonerJailedEvent;
import com.graywolf336.jail.interfaces.ICell;
import com.lexicalscope.jewel.cli.ArgumentValidationException;
import com.lexicalscope.jewel.cli.CliFactory;
import org.apache.commons.lang.ArrayUtils;
import org.bukkit.ChatColor;
import org.bukkit.OfflinePlayer;
import org.bukkit.command.CommandSender;
import org.bukkit.entity.Player;
import org.bukkit.util.StringUtil;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.LinkedList;
import java.util.List;
@CommandInfo(
maxArgs = -1,
@ -36,14 +34,14 @@ import com.lexicalscope.jewel.cli.CliFactory;
pattern = "jail|j",
permission = "jail.command.jail",
usage = "/jail [name] (-t time) (-j JailName) (-c CellName) (-a AnyCell) (-m Muted) (-r A reason for jailing)"
)
)
public class JailCommand implements Command {
private static final String noJailPermission = "jail.cantbejailed";
private List<String> commands = Arrays.asList(new String[] { "p", "t", "i", "j", "c", "a", "m", "r", "f" });
private final List<String> commands = Arrays.asList("p", "t", "i", "j", "c", "a", "m", "r", "f");
/*
* Executes the command. Checks the following:
*
*
* - If there are any jails.
* - If the command can be parsed correctly.
* - If the player is already jailed.
@ -54,51 +52,51 @@ public class JailCommand implements Command {
*/
@SuppressWarnings("deprecation")
public boolean execute(JailManager jm, CommandSender sender, String... args) {
if(jm.getJails().isEmpty()) {
if (jm.getJails().isEmpty()) {
sender.sendMessage(Lang.NOJAILS.get());
return true;
}
//This is just to add the -p param so CliFactory doesn't blow up
List<String> arguments = new LinkedList<String>(Arrays.asList(args));
List<String> arguments = new LinkedList<>(Arrays.asList(args));
//Only add the "-p" if it doesn't already contain it, this way people can do `/jail -p check` in the event someone
//has a name which is one of our subcommands
if(!arguments.contains("-p")) arguments.add(0, "-p");
if (!arguments.contains("-p")) arguments.add(0, "-p");
Jailing params = null;
Jailing params;
try {
params = CliFactory.parseArguments(Jailing.class, arguments.toArray(new String[arguments.size()]));
}catch(ArgumentValidationException e) {
params = CliFactory.parseArguments(Jailing.class, arguments.toArray(new String[0]));
} catch (ArgumentValidationException e) {
sender.sendMessage(ChatColor.RED + e.getMessage());
return true;
}
//Check if they've actually given us a player to jail
if(params.getPlayer() == null) {
if (params.getPlayer() == null) {
sender.sendMessage(Lang.PROVIDEAPLAYER.get(Lang.JAILING));
return true;
}else {
} else {
jm.getPlugin().debug("We are getting ready to handle jailing: " + params.getPlayer());
}
//Check if the given player is already jailed or not
if(jm.isPlayerJailedByLastKnownUsername(params.getPlayer())) {
if (jm.isPlayerJailedByLastKnownUsername(params.getPlayer())) {
sender.sendMessage(Lang.ALREADYJAILED.get(params.getPlayer()));
return true;
}
Player p = jm.getPlugin().getServer().getPlayer(params.getPlayer());
//If the player instance is not null and the player has the permission
//'jail.cantbejailed' then don't allow this to happen
if(p != null && p.hasPermission(noJailPermission)) {
if (p != null && p.hasPermission(noJailPermission)) {
sender.sendMessage(Lang.CANTBEJAILED.get());
return true;
}
String uuid = "";
if(p == null) {
String uuid;
if (p == null) {
if (!jm.getPlugin().getConfig().getBoolean(Settings.ALLOWJAILINGOFFLINEPLAYERS.getPath())) {
sender.sendMessage(Lang.PLAYERHASNEVERPLAYEDBEFORE.get());
return true;
@ -106,34 +104,34 @@ public class JailCommand implements Command {
//TODO: Make this whole jail command non-blocking
OfflinePlayer of = jm.getPlugin().getServer().getOfflinePlayer(params.getPlayer());
if(!of.hasPlayedBefore() && !jm.getPlugin().getConfig().getBoolean(Settings.ALLOWJAILINGNEVERPLAYEDBEFOREPLAYERS.getPath()) && !params.isForce()) {
if (!of.hasPlayedBefore() && !jm.getPlugin().getConfig().getBoolean(Settings.ALLOWJAILINGNEVERPLAYEDBEFOREPLAYERS.getPath()) && !params.isForce()) {
sender.sendMessage(Lang.PLAYERHASNEVERPLAYEDBEFORE.get(params.getPlayer()));
return true;
}else {
} else {
uuid = of.getUniqueId().toString();
}
}else {
} else {
uuid = p.getUniqueId().toString();
}
//Try to parse the time, if they give us nothing in the time parameter then we get the default time
//from the config and if that isn't there then we default to thirty minutes.
Long time = 10L;
Long time;
try {
if(params.isTime()) {
if (params.isTime()) {
time = Util.getTime(params.getTime());
}else {
} else {
time = Util.getTime(jm.getPlugin().getConfig().getString(Settings.DEFAULTTIME.getPath(), "30m"));
}
}catch(Exception e) {
} catch (Exception e) {
sender.sendMessage(Lang.NUMBERFORMATINCORRECT.get());
return true;
}
//Check if they provided the infinite argument
//if so, then set the time jailed forever
if(params.isInfinite()) {
if (params.isInfinite()) {
time = -1L;
}
@ -141,65 +139,65 @@ public class JailCommand implements Command {
//from the config. If that is nearest, let's make a call to getting the nearest jail to
//the sender but otherwise if it isn't nearest then let's set it to the default jail
//which is defined in the config.
String jailName = "";
if(!params.isJail()) {
String jailName;
if (!params.isJail()) {
String dJail = jm.getPlugin().getConfig().getString(Settings.DEFAULTJAIL.getPath());
if(dJail.equalsIgnoreCase("nearest")) {
if (dJail.equalsIgnoreCase("nearest")) {
jailName = jm.getNearestJail(sender).getName();
}else {
} else {
jailName = dJail;
}
}else if(!jm.isValidJail(params.getJail())) {
} else if (!jm.isValidJail(params.getJail())) {
sender.sendMessage(Lang.NOJAIL.get(params.getJail()));
return true;
}else {
} else {
jailName = params.getJail();
}
//Get the jail instance from the name of jail in the params.
Jail j = jm.getJail(jailName);
if(!j.isEnabled()) {
if (!j.isEnabled()) {
sender.sendMessage(Lang.WORLDUNLOADED.get(j.getName()));
return true;
}
ICell c = null;
//Check if the cell is defined
if(params.isCell()) {
if (params.isCell()) {
//Check if it is a valid cell
if(!jm.getJail(jailName).isValidCell(params.getCell())) {
if (!jm.getJail(jailName).isValidCell(params.getCell())) {
//There is no cell by that name
sender.sendMessage(Lang.NOCELL.get(new String[] { params.getCell(), jailName }));
sender.sendMessage(Lang.NOCELL.get(params.getCell(), jailName));
return true;
}else if(jm.getJail(jailName).getCell(params.getCell()).hasPrisoner()) {
} else if (jm.getJail(jailName).getCell(params.getCell()).hasPrisoner()) {
//If the cell has a prisoner, don't allow jailing them to that particular cell but suggest another one
sender.sendMessage(Lang.CELLNOTEMPTY.get(params.getCell()));
Cell suggestedCell = jm.getJail(jailName).getFirstEmptyCell();
if(suggestedCell != null) {
sender.sendMessage(Lang.SUGGESTEDCELL.get(new String[] { jailName, suggestedCell.getName() }));
}else {
if (suggestedCell != null) {
sender.sendMessage(Lang.SUGGESTEDCELL.get(jailName, suggestedCell.getName()));
} else {
sender.sendMessage(Lang.NOEMPTYCELLS.get(jailName));
}
return true;
}else {
} else {
c = jm.getJail(jailName).getCell(params.getCell());
}
}
//If they want just any open cell or automatic jailing in cells is turned on
//and a cell wasn't already found, then find try to find a cell
if(params.isAnyCell() && c == null) {
if (params.isAnyCell() && c == null) {
c = jm.getJail(jailName).getFirstEmptyCell();
if(c == null) {
if (c == null) {
//If there wasn't an empty cell, then tell them so.
sender.sendMessage(Lang.NOEMPTYCELLS.get(jailName));
return true;
}
}else if(jm.getPlugin().getConfig().getBoolean(Settings.AUTOMATICCELL.getPath(), true) && j.hasCells() && c == null) {
} else if (jm.getPlugin().getConfig().getBoolean(Settings.AUTOMATICCELL.getPath(), true) && j.hasCells() && c == null) {
c = jm.getJail(jailName).getFirstEmptyCell();
if(c == null) {
if (c == null) {
//If there wasn't an empty cell, then tell them so.
sender.sendMessage(Lang.NOEMPTYCELLS.get(jailName));
return true;
@ -207,23 +205,23 @@ public class JailCommand implements Command {
}
//If the jailer gave no reason, then let's get the default reason
String reason = "";
if(params.isReason()) {
String reason;
if (params.isReason()) {
StringBuilder sb = new StringBuilder();
for(String s : params.getReason()) {
for (String s : params.getReason()) {
sb.append(s).append(' ');
}
sb.deleteCharAt(sb.length() - 1);
reason = sb.toString();
}else {
reason = Lang.DEFAULTJAILEDREASON.get();
} else {
reason = Lang.DEFAULTJAILEDREASON.get();
}
//If the config has automatic muting, then let's set them as muted
boolean muted = params.getMuted();
if(jm.getPlugin().getConfig().getBoolean(Settings.AUTOMATICMUTE.getPath())) {
if (jm.getPlugin().getConfig().getBoolean(Settings.AUTOMATICMUTE.getPath())) {
muted = true;
}
@ -234,8 +232,8 @@ public class JailCommand implements Command {
jm.getPlugin().getServer().getPluginManager().callEvent(event);
//check if the event is cancelled
if(event.isCancelled()) {
if(event.getCancelledMessage().isEmpty())
if (event.isCancelled()) {
if (event.getCancelledMessage().isEmpty())
sender.sendMessage(Lang.CANCELLEDBYANOTHERPLUGIN.get(params.getPlayer()));
else
sender.sendMessage(event.getCancelledMessage());
@ -250,11 +248,11 @@ public class JailCommand implements Command {
p = event.getPlayer();
//Player is not online
if(p == null) {
sender.sendMessage(Lang.OFFLINEJAIL.get(new String[] { pris.getLastKnownName(), String.valueOf(pris.getRemainingTimeInMinutes()) }));
}else {
if (p == null) {
sender.sendMessage(Lang.OFFLINEJAIL.get(pris.getLastKnownName(), String.valueOf(pris.getRemainingTimeInMinutes())));
} else {
//Player *is* online
sender.sendMessage(Lang.ONLINEJAIL.get(new String[] { pris.getLastKnownName(), String.valueOf(pris.getRemainingTimeInMinutes()) }));
sender.sendMessage(Lang.ONLINEJAIL.get(pris.getLastKnownName(), String.valueOf(pris.getRemainingTimeInMinutes())));
}
try {
@ -267,71 +265,72 @@ public class JailCommand implements Command {
return true;
}
public List<String> provideTabCompletions(JailManager jm, CommandSender sender, String... args) throws Exception {
public List<String> provideTabCompletions(JailManager jm, CommandSender sender, String... args) {
//by the time it gets to this command it'll have at least two arguments
String last = args[args.length - 1];
jm.getPlugin().debug("The last item is: " + last);
if(last.isEmpty() || !commands.contains(last.replace("-", ""))) {
if (last.isEmpty() || !commands.contains(last.replace("-", ""))) {
//the current part is empty. Need to look at their previous
//item and if it is a valid option, then provide them a valid tab complete option
if(args.length - 2 > -1) {
if (args.length - 2 > -1) {
String previous = args[args.length - 2];
jm.getPlugin().debug("args[args.length - 2]: " + previous);
if(previous.equalsIgnoreCase("-p")) return getPlayers(jm, last);
else if(previous.equalsIgnoreCase("-j")) return jm.getJailsByPrefix(last);
else if(previous.equalsIgnoreCase("-c")) {
if (previous.equalsIgnoreCase("-p")) return getPlayers(jm, last);
else if (previous.equalsIgnoreCase("-j")) return jm.getJailsByPrefix(last);
else if (previous.equalsIgnoreCase("-c")) {
//Since we need to give them a list of the cells in a jail
//we need to get the jail they're giving
int jailIndex = ArrayUtils.indexOf(args, "-j");
if(jailIndex != -1) {
if (jailIndex != -1) {
String jail = args[jailIndex + 1];
jm.getPlugin().debug("The jail is: " + jail);
if(jm.isValidJail(jail)) return getCells(jm, jail, last);
if (jm.isValidJail(jail)) return getCells(jm, jail, last);
}
}else if(previous.endsWith("r")) return Collections.emptyList();
else if(!commands.contains(args[args.length - 2].replace("-", ""))) return Util.getUnusedItems(commands, args, false);
}else {
return getPlayers(jm, last);
} else if (previous.endsWith("r")) return Collections.emptyList();
else if (!commands.contains(args[args.length - 2].replace("-", "")))
return Util.getUnusedItems(commands, args, false);
} else {
return getPlayers(jm, last);
}
}else if(last.equalsIgnoreCase("-")) {
} else if (last.equalsIgnoreCase("-")) {
//add some smart checking so that it only returns a list of what isn't already
//in the command :)
return Util.getUnusedItems(commands, args, false);
}else {
jm.getPlugin().debug("Getting the list of online players.");
} else {
jm.getPlugin().debug("Getting the list of online players.");
return getPlayers(jm, last);
}
jm.getPlugin().debug("Returning an empty list.");
return Collections.emptyList();
}
private List<String> getPlayers(JailManager jm, String first) {
List<String> results = new ArrayList<String>();
for(Player p : jm.getPlugin().getServer().getOnlinePlayers())
if(first.isEmpty() || StringUtil.startsWithIgnoreCase(p.getName(), first))
if(!jm.isPlayerJailed(p.getUniqueId()) && !p.hasPermission(noJailPermission)) //don't send back them if they're already jailed or can't be jailed
List<String> results = new ArrayList<>();
for (Player p : jm.getPlugin().getServer().getOnlinePlayers())
if (first.isEmpty() || StringUtil.startsWithIgnoreCase(p.getName(), first))
if (!jm.isPlayerJailed(p.getUniqueId()) && !p.hasPermission(noJailPermission)) //don't send back them if they're already jailed or can't be jailed
results.add(p.getName());
Collections.sort(results);
jm.getPlugin().debug("The list we're returning is: " + Util.getStringFromList(", ", results));
return results;
}
private List<String> getCells(JailManager jm, String jail, String cell) {
List<String> results = new ArrayList<String>();
for(Cell c : jm.getJail(jail).getCells())
if(!c.hasPrisoner() && (cell.isEmpty() || StringUtil.startsWithIgnoreCase(c.getName(), cell)))
results.add(c.getName());
List<String> results = new ArrayList<>();
for (Cell c : jm.getJail(jail).getCells())
if (!c.hasPrisoner() && (cell.isEmpty() || StringUtil.startsWithIgnoreCase(c.getName(), cell)))
results.add(c.getName());
Collections.sort(results);
return results;
}
}

View File

@ -1,14 +1,13 @@
package com.graywolf336.jail.command.subcommands;
import java.util.Collections;
import java.util.List;
import org.bukkit.command.CommandSender;
import com.graywolf336.jail.JailManager;
import com.graywolf336.jail.command.Command;
import com.graywolf336.jail.command.CommandInfo;
import com.graywolf336.jail.enums.Lang;
import org.bukkit.command.CommandSender;
import java.util.Collections;
import java.util.List;
@CommandInfo(
maxArgs = 0,
@ -17,18 +16,18 @@ import com.graywolf336.jail.enums.Lang;
pattern = "confirm|con",
permission = "",
usage = "/jail confirm"
)
public class JailConfirmCommand implements Command{
)
public class JailConfirmCommand implements Command {
public boolean execute(JailManager jm, CommandSender sender, String... args) {
//Check if the sender is actually confirming something.
if(jm.isConfirming(sender.getName())) {
if(jm.confirmingHasExpired(sender.getName())) {
if (jm.isConfirming(sender.getName())) {
if (jm.confirmingHasExpired(sender.getName())) {
//Their confirmation time frame has closed
sender.sendMessage(Lang.EXPIRED.get());
jm.removeConfirming(sender.getName());
}else {
switch(jm.getWhatIsConfirming(sender.getName())) {
} else {
switch (jm.getWhatIsConfirming(sender.getName())) {
case CLEAR:
//Copy the original arguments for easy access
String[] cArgs = jm.getOriginalArgs(sender.getName());
@ -63,7 +62,7 @@ public class JailConfirmCommand implements Command{
//delete a cell from a jail with the given arguments
String[] msgs4 = jm.deleteAllJailCells(cArgs4[1]);
//Send the messages we got back
for(String s : msgs4) {
for (String s : msgs4) {
sender.sendMessage(s);
}
@ -84,7 +83,7 @@ public class JailConfirmCommand implements Command{
break;
}
}
}else {
} else {
//They aren't confirming anything right now.
sender.sendMessage(Lang.NOTHING.get());
}
@ -92,7 +91,7 @@ public class JailConfirmCommand implements Command{
return true;
}
public List<String> provideTabCompletions(JailManager jm, CommandSender sender, String... args) throws Exception {
public List<String> provideTabCompletions(JailManager jm, CommandSender sender, String... args) {
//confirming doesn't require any tab completing
return Collections.emptyList();
}

View File

@ -1,16 +1,15 @@
package com.graywolf336.jail.command.subcommands;
import java.util.Collections;
import java.util.List;
import org.bukkit.ChatColor;
import org.bukkit.command.CommandSender;
import org.bukkit.entity.Player;
import com.graywolf336.jail.JailManager;
import com.graywolf336.jail.beans.Jail;
import com.graywolf336.jail.command.Command;
import com.graywolf336.jail.command.CommandInfo;
import org.bukkit.ChatColor;
import org.bukkit.command.CommandSender;
import org.bukkit.entity.Player;
import java.util.Collections;
import java.util.List;
@CommandInfo(
maxArgs = 2,
@ -19,7 +18,7 @@ import com.graywolf336.jail.command.CommandInfo;
pattern = "createcells|createcell|cellcreate|cellscreate|cc",
permission = "jail.command.jailcreatecells",
usage = "/jail createcell [jail] (cellname)"
)
)
public class JailCreateCellCommand implements Command {
public boolean execute(JailManager jm, CommandSender sender, String... args) {
@ -29,36 +28,36 @@ public class JailCreateCellCommand implements Command {
String cell = "";
//Only get the cell name they provide if they provide it
if(args.length >= 3) {
if (args.length >= 3) {
cell = args[2];
}
//Check if the player is currently creating something else
if(jm.isCreatingSomething(name)) {
if (jm.isCreatingSomething(name)) {
String message = jm.getStepMessage(name);
if(!message.isEmpty()) {
if (!message.isEmpty()) {
player.sendMessage(ChatColor.RED + message);
}else {
} else {
player.sendMessage(ChatColor.RED + "You're already creating something else, please finish it or cancel.");
}
}else {
} else {
//Not creating anything, so let them create some cells.
if(jm.isValidJail(jail)) {
if (jm.isValidJail(jail)) {
Jail j = jm.getJail(jail);
//If they didn't provide a cell name, let's provide one ourself.
if(cell.isEmpty()) cell = "cell_n" + (j.getCellCount() + 1);
if (cell.isEmpty()) cell = "cell_n" + (j.getCellCount() + 1);
if(j.getCell(cell) == null) {
if(jm.addCreatingCell(name, jail, cell)) {
if (j.getCell(cell) == null) {
if (jm.addCreatingCell(name, jail, cell)) {
jm.getCellCreationSteps().startStepping(player);
}else {
} else {
player.sendMessage(ChatColor.RED + "Appears you're creating a cell or something went wrong on our side.");
}
}else {
} else {
player.sendMessage(ChatColor.RED + "There's already a cell with the name '" + cell + "', please pick a new one or remove that cell.");
}
}else {
} else {
player.sendMessage(ChatColor.RED + "No such jail found by the name of '" + jail + "'.");
}
}
@ -66,10 +65,10 @@ public class JailCreateCellCommand implements Command {
return true;
}
public List<String> provideTabCompletions(JailManager jm, CommandSender sender, String... args) throws Exception {
public List<String> provideTabCompletions(JailManager jm, CommandSender sender, String... args) {
//We shouldn't provide when they want a cell name
if(args.length >= 3) return Collections.emptyList();
if (args.length >= 3) return Collections.emptyList();
return jm.getJailsByPrefix(args.length == 2 ? args[1] : "");
}
}

View File

@ -1,15 +1,14 @@
package com.graywolf336.jail.command.subcommands;
import java.util.Collections;
import java.util.List;
import org.bukkit.ChatColor;
import org.bukkit.command.CommandSender;
import org.bukkit.entity.Player;
import com.graywolf336.jail.JailManager;
import com.graywolf336.jail.command.Command;
import com.graywolf336.jail.command.CommandInfo;
import org.bukkit.ChatColor;
import org.bukkit.command.CommandSender;
import org.bukkit.entity.Player;
import java.util.Collections;
import java.util.List;
@CommandInfo(
maxArgs = 1,
@ -18,7 +17,7 @@ import com.graywolf336.jail.command.CommandInfo;
pattern = "create",
permission = "jail.command.jailcreate",
usage = "/jail create [name]"
)
)
public class JailCreateCommand implements Command {
public boolean execute(JailManager jm, CommandSender sender, String... args) {
@ -27,20 +26,20 @@ public class JailCreateCommand implements Command {
String jail = args[1];
//Check if the player is currently creating something else
if(jm.isCreatingSomething(name)) {
if (jm.isCreatingSomething(name)) {
String message = jm.getStepMessage(name);
if(!message.isEmpty()) {
if (!message.isEmpty()) {
player.sendMessage(ChatColor.RED + message);
}else {
} else {
player.sendMessage(ChatColor.RED + "You're already creating something else, please finish it or cancel.");
}
}else {
if(jm.isValidJail(jail)) {
} else {
if (jm.isValidJail(jail)) {
player.sendMessage(ChatColor.RED + "Jail by the name of '" + jail + "' already exist!");
}else {
if(jm.addCreatingJail(name, jail)) {
} else {
if (jm.addCreatingJail(name, jail)) {
jm.getJailCreationSteps().startStepping(player);
}else {
} else {
player.sendMessage(ChatColor.RED + "Seems like you're already creating a Jail or something went wrong on our side.");
}
}
@ -49,7 +48,7 @@ public class JailCreateCommand implements Command {
return true;
}
public List<String> provideTabCompletions(JailManager jm, CommandSender sender, String... args) throws Exception {
public List<String> provideTabCompletions(JailManager jm, CommandSender sender, String... args) {
//Creating a jail shouldn't provide tab completion
return Collections.emptyList();
}

View File

@ -1,12 +1,5 @@
package com.graywolf336.jail.command.subcommands;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import org.bukkit.command.CommandSender;
import org.bukkit.util.StringUtil;
import com.graywolf336.jail.JailManager;
import com.graywolf336.jail.beans.Cell;
import com.graywolf336.jail.beans.ConfirmPlayer;
@ -15,6 +8,12 @@ import com.graywolf336.jail.command.Command;
import com.graywolf336.jail.command.CommandInfo;
import com.graywolf336.jail.enums.Confirmation;
import com.graywolf336.jail.enums.Lang;
import org.bukkit.command.CommandSender;
import org.bukkit.util.StringUtil;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
@CommandInfo(
maxArgs = 2,
@ -23,12 +22,12 @@ import com.graywolf336.jail.enums.Lang;
pattern = "deletecell|dc",
permission = "jail.command.jaildeletecell",
usage = "/jail deletecell [jail] [cell]"
)
)
public class JailDeleteCellCommand implements Command {
public boolean execute(JailManager jm, CommandSender sender, String... args) throws Exception {
if(jm.isConfirming(sender.getName())) {
public boolean execute(JailManager jm, CommandSender sender, String... args) {
if (jm.isConfirming(sender.getName())) {
sender.sendMessage(Lang.ALREADY.get());
}else {
} else {
jm.addConfirming(sender.getName(), new ConfirmPlayer(sender.getName(), args, Confirmation.DELETECELL));
sender.sendMessage(Lang.START.get());
}
@ -36,10 +35,10 @@ public class JailDeleteCellCommand implements Command {
return true;
}
public List<String> provideTabCompletions(JailManager jm, CommandSender sender, String... args) throws Exception {
List<String> results = new ArrayList<String>();
switch(args.length) {
public List<String> provideTabCompletions(JailManager jm, CommandSender sender, String... args) {
List<String> results = new ArrayList<>();
switch (args.length) {
case 1:
results.addAll(jm.getJailsByPrefix(""));
break;
@ -47,18 +46,18 @@ public class JailDeleteCellCommand implements Command {
results = jm.getJailsByPrefix(args[1]);
break;
case 3:
if(jm.isValidJail(args[1])) {
if (jm.isValidJail(args[1])) {
Jail j = jm.getJail(args[1]);
for(Cell c : j.getCells())
if(args[2].isEmpty() || StringUtil.startsWithIgnoreCase(c.getName(), args[2]))
for (Cell c : j.getCells())
if (args[2].isEmpty() || StringUtil.startsWithIgnoreCase(c.getName(), args[2]))
results.add(c.getName());
}
break;
}
Collections.sort(results);
return results;
}
}

View File

@ -1,15 +1,14 @@
package com.graywolf336.jail.command.subcommands;
import java.util.List;
import org.bukkit.command.CommandSender;
import com.graywolf336.jail.JailManager;
import com.graywolf336.jail.beans.ConfirmPlayer;
import com.graywolf336.jail.command.Command;
import com.graywolf336.jail.command.CommandInfo;
import com.graywolf336.jail.enums.Confirmation;
import com.graywolf336.jail.enums.Lang;
import org.bukkit.command.CommandSender;
import java.util.List;
@CommandInfo(
maxArgs = 1,
@ -18,12 +17,12 @@ import com.graywolf336.jail.enums.Lang;
pattern = "deletecells|dcs",
permission = "jail.command.jaildeletecells",
usage = "/jail deletecells [jail]"
)
)
public class JailDeleteCellsCommand implements Command {
public boolean execute(JailManager jm, CommandSender sender, String... args) throws Exception {
if(jm.isConfirming(sender.getName())) {
public boolean execute(JailManager jm, CommandSender sender, String... args) {
if (jm.isConfirming(sender.getName())) {
sender.sendMessage(Lang.ALREADY.get());
}else {
} else {
jm.addConfirming(sender.getName(), new ConfirmPlayer(sender.getName(), args, Confirmation.DELETECELLS));
sender.sendMessage(Lang.START.get());
}
@ -31,7 +30,7 @@ public class JailDeleteCellsCommand implements Command {
return true;
}
public List<String> provideTabCompletions(JailManager jm, CommandSender sender, String... args) throws Exception {
public List<String> provideTabCompletions(JailManager jm, CommandSender sender, String... args) {
return jm.getJailsByPrefix(args.length == 2 ? args[1] : "");
}
}

View File

@ -1,15 +1,14 @@
package com.graywolf336.jail.command.subcommands;
import java.util.List;
import org.bukkit.command.CommandSender;
import com.graywolf336.jail.JailManager;
import com.graywolf336.jail.beans.ConfirmPlayer;
import com.graywolf336.jail.command.Command;
import com.graywolf336.jail.command.CommandInfo;
import com.graywolf336.jail.enums.Confirmation;
import com.graywolf336.jail.enums.Lang;
import org.bukkit.command.CommandSender;
import java.util.List;
@CommandInfo(
maxArgs = 1,
@ -18,12 +17,12 @@ import com.graywolf336.jail.enums.Lang;
pattern = "delete|d",
permission = "jail.command.jaildelete",
usage = "/jail delete [jail]"
)
)
public class JailDeleteCommand implements Command {
public boolean execute(JailManager jm, CommandSender sender, String... args) throws Exception {
if(jm.isConfirming(sender.getName())) {
public boolean execute(JailManager jm, CommandSender sender, String... args) {
if (jm.isConfirming(sender.getName())) {
sender.sendMessage(Lang.ALREADY.get());
}else {
} else {
jm.addConfirming(sender.getName(), new ConfirmPlayer(sender.getName(), args, Confirmation.DELETE));
sender.sendMessage(Lang.START.get());
}
@ -31,7 +30,7 @@ public class JailDeleteCommand implements Command {
return true;
}
public List<String> provideTabCompletions(JailManager jm, CommandSender sender, String... args) throws Exception {
public List<String> provideTabCompletions(JailManager jm, CommandSender sender, String... args) {
return jm.getJailsByPrefix(args.length == 2 ? args[1] : "");
}
}

View File

@ -1,14 +1,13 @@
package com.graywolf336.jail.command.subcommands;
import java.util.Collections;
import java.util.List;
import org.bukkit.ChatColor;
import org.bukkit.command.CommandSender;
import com.graywolf336.jail.JailManager;
import com.graywolf336.jail.command.Command;
import com.graywolf336.jail.command.CommandInfo;
import org.bukkit.ChatColor;
import org.bukkit.command.CommandSender;
import java.util.Collections;
import java.util.List;
@CommandInfo(
maxArgs = 1,
@ -17,15 +16,15 @@ import com.graywolf336.jail.command.CommandInfo;
pattern = "help|h",
permission = "jail.command.jailhelp",
usage = "/jail help [page]"
)
)
public class JailHelpCommand implements Command {
public boolean execute(JailManager jm, CommandSender sender, String... args) throws Exception {
public boolean execute(JailManager jm, CommandSender sender, String... args) {
sender.sendMessage(ChatColor.GREEN + "This command will be filled out shortly, use this link for now:");
sender.sendMessage(ChatColor.GREEN + "https://github.com/graywolf336/Jail/wiki/Commands");
return true;
}
public List<String> provideTabCompletions(JailManager jm, CommandSender sender, String... args) throws Exception {
public List<String> provideTabCompletions(JailManager jm, CommandSender sender, String... args) {
//TODO implement
return Collections.emptyList();
}

View File

@ -1,12 +1,5 @@
package com.graywolf336.jail.command.subcommands;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import org.bukkit.ChatColor;
import org.bukkit.command.CommandSender;
import com.graywolf336.jail.JailManager;
import com.graywolf336.jail.Util;
import com.graywolf336.jail.beans.Cell;
@ -14,6 +7,12 @@ import com.graywolf336.jail.beans.Jail;
import com.graywolf336.jail.command.Command;
import com.graywolf336.jail.command.CommandInfo;
import com.graywolf336.jail.enums.Lang;
import org.bukkit.ChatColor;
import org.bukkit.command.CommandSender;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
@CommandInfo(
maxArgs = 1,
@ -22,28 +21,28 @@ import com.graywolf336.jail.enums.Lang;
pattern = "listcells|lc",
permission = "jail.command.jaillistcells",
usage = "/jail listcells [jail]"
)
)
public class JailListCellsCommand implements Command {
public boolean execute(JailManager jm, CommandSender sender, String... args) {
sender.sendMessage(ChatColor.AQUA + "----------Cells----------");
if(!jm.getJails().isEmpty()) {
if(jm.getJail(args[1]) != null) {
if (!jm.getJails().isEmpty()) {
if (jm.getJail(args[1]) != null) {
Jail j = jm.getJail(args[1]);
List<String> cells = new ArrayList<String>();
for(Cell c : j.getCells()) {
List<String> cells = new ArrayList<>();
for (Cell c : j.getCells()) {
cells.add(c.getName() + (c.getPrisoner() == null ? "" : " (" + c.getPrisoner().getLastKnownName() + ")"));
}
Collections.sort(cells);
sender.sendMessage(cells.isEmpty() ? Lang.NOCELLS.get(j.getName()) : ChatColor.GREEN + Util.getStringFromList(", ", cells));
}else {
} else {
sender.sendMessage(Lang.NOJAIL.get(args[1]));
}
}else {
} else {
sender.sendMessage(Lang.NOJAILS.get());
}
@ -51,7 +50,7 @@ public class JailListCellsCommand implements Command {
return true;
}
public List<String> provideTabCompletions(JailManager jm, CommandSender sender, String... args) throws Exception {
public List<String> provideTabCompletions(JailManager jm, CommandSender sender, String... args) {
return jm.getJailsByPrefix(args.length == 2 ? args[1] : "");
}
}

View File

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

View File

@ -1,17 +1,16 @@
package com.graywolf336.jail.command.subcommands;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import org.bukkit.command.CommandSender;
import org.bukkit.entity.Player;
import org.bukkit.util.StringUtil;
import com.graywolf336.jail.JailManager;
import com.graywolf336.jail.command.Command;
import com.graywolf336.jail.command.CommandInfo;
import com.graywolf336.jail.enums.Lang;
import org.bukkit.command.CommandSender;
import org.bukkit.entity.Player;
import org.bukkit.util.StringUtil;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
@CommandInfo(
maxArgs = 1,
@ -20,21 +19,21 @@ import com.graywolf336.jail.enums.Lang;
pattern = "mute|m",
permission = "jail.command.jailmute",
usage = "/jail mute [name]"
)
)
public class JailMuteCommand implements Command {
public boolean execute(JailManager jm, CommandSender sender, String... args) throws Exception {
public boolean execute(JailManager jm, CommandSender sender, String... args) {
//Let's check if the player they're sending us is jailed
if(jm.isPlayerJailedByLastKnownUsername(args[1])) {
if (jm.isPlayerJailedByLastKnownUsername(args[1])) {
//They are, so let's toggle whether they are muted or not
boolean muted = !jm.getPrisonerByLastKnownName(args[1]).isMuted();
jm.getPrisonerByLastKnownName(args[1]).setMuted(muted);
//Send the message to the sender based upon whether they are muted or unmuted
if(muted)
if (muted)
sender.sendMessage(Lang.NOWMUTED.get(args[1]));
else
sender.sendMessage(Lang.NOWUNMUTED.get(args[1]));
}else {
} else {
//The player provided is not jailed, so let's tell the sender that
sender.sendMessage(Lang.NOTJAILED.get(args[1]));
}
@ -42,18 +41,16 @@ public class JailMuteCommand implements Command {
return true;
}
public List<String> provideTabCompletions(JailManager jm, CommandSender sender, String... args) throws Exception {
switch(args.length) {
case 2:
List<String> results = new ArrayList<String>();
for(Player p : jm.getPlugin().getServer().getOnlinePlayers())
if(StringUtil.startsWithIgnoreCase(p.getName(), args[1].toLowerCase()))
results.add(p.getName());
Collections.sort(results);
return results;
default:
return Collections.emptyList();
public List<String> provideTabCompletions(JailManager jm, CommandSender sender, String... args) {
if (args.length == 2) {
List<String> results = new ArrayList<>();
for (Player p : jm.getPlugin().getServer().getOnlinePlayers())
if (StringUtil.startsWithIgnoreCase(p.getName(), args[1].toLowerCase()))
results.add(p.getName());
Collections.sort(results);
return results;
}
return Collections.emptyList();
}
}

View File

@ -1,15 +1,5 @@
package com.graywolf336.jail.command.subcommands;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.concurrent.TimeUnit;
import org.bukkit.ChatColor;
import org.bukkit.command.CommandSender;
import org.bukkit.entity.Player;
import org.bukkit.util.StringUtil;
import com.graywolf336.jail.JailManager;
import com.graywolf336.jail.beans.Prisoner;
import com.graywolf336.jail.command.Command;
@ -17,6 +7,15 @@ import com.graywolf336.jail.command.CommandInfo;
import com.graywolf336.jail.enums.Lang;
import com.graywolf336.jail.enums.Settings;
import com.graywolf336.jail.interfaces.IJailPayManager;
import org.bukkit.ChatColor;
import org.bukkit.command.CommandSender;
import org.bukkit.entity.Player;
import org.bukkit.util.StringUtil;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.concurrent.TimeUnit;
@CommandInfo(
maxArgs = 2,
@ -25,42 +24,42 @@ import com.graywolf336.jail.interfaces.IJailPayManager;
pattern = "pay",
permission = "jail.usercmd.jailpay",
usage = "/jail pay (amount) (name)"
)
)
public class JailPayCommand implements Command {
public boolean execute(JailManager jm, CommandSender sender, String... args) throws Exception {
if(jm.getPlugin().getConfig().getBoolean(Settings.JAILPAYENABLED.getPath())) {
public boolean execute(JailManager jm, CommandSender sender, String... args) {
if (jm.getPlugin().getConfig().getBoolean(Settings.JAILPAYENABLED.getPath())) {
IJailPayManager pm = jm.getPlugin().getJailPayManager();
switch(args.length) {
switch (args.length) {
case 1:
// `/jail pay`
//send how much it costs to get out
if(jm.isPlayerJailedByLastKnownUsername(sender.getName())) {
if (jm.isPlayerJailedByLastKnownUsername(sender.getName())) {
Prisoner p = jm.getPrisonerByLastKnownName(sender.getName());
String amt = "";
String amt;
if(pm.usingItemsForPayment()) {
if (pm.usingItemsForPayment()) {
amt = String.valueOf((int) Math.ceil(pm.calculateBill(p)));
}else {
} else {
amt = String.valueOf(pm.calculateBill(p));
}
if(p.getRemainingTime() > 0) {
if(pm.isTimedEnabled()) {
sender.sendMessage(Lang.PAYCOST.get(new String[] { pm.getCostPerMinute(), pm.getCurrencyName(), amt }));
}else {
if (p.getRemainingTime() > 0) {
if (pm.isTimedEnabled()) {
sender.sendMessage(Lang.PAYCOST.get(pm.getCostPerMinute(), pm.getCurrencyName(), amt));
} else {
sender.sendMessage(Lang.PAYNOTENABLED.get());
jm.getPlugin().debug("Jail pay 'timed' paying is not enabled (config has 0 as the cost).");
}
}else {
if(pm.isInfiniteEnabled()) {
sender.sendMessage(Lang.PAYCOST.get(new String[] { amt, pm.getCurrencyName() }));
}else {
} else {
if (pm.isInfiniteEnabled()) {
sender.sendMessage(Lang.PAYCOST.get(amt, pm.getCurrencyName()));
} else {
sender.sendMessage(Lang.PAYNOTENABLED.get());
jm.getPlugin().debug("Jail pay 'infinite' paying is not enabled (config has 0 as the cost).");
}
}
}else {
} else {
sender.sendMessage(Lang.YOUARENOTJAILED.get());
}
@ -68,133 +67,133 @@ public class JailPayCommand implements Command {
case 2:
// `/jail pay <amount>`
//They are trying to pay for their self
if(jm.isPlayerJailedByLastKnownUsername(sender.getName())) {
if (jm.isPlayerJailedByLastKnownUsername(sender.getName())) {
Prisoner p = jm.getPrisonerByLastKnownName(sender.getName());
if(p.getRemainingTime() > 0) {
if(!pm.isTimedEnabled()) {
if (p.getRemainingTime() > 0) {
if (!pm.isTimedEnabled()) {
sender.sendMessage(Lang.PAYNOTENABLED.get());
return true;
}
}else {
if(!pm.isInfiniteEnabled()) {
} else {
if (!pm.isInfiniteEnabled()) {
sender.sendMessage(Lang.PAYNOTENABLED.get());
return true;
}
}
if(args[1].startsWith("-")) {
if (args[1].startsWith("-")) {
sender.sendMessage(Lang.PAYNONEGATIVEAMOUNTS.get());
}else {
double amt = 0;
} else {
double amt;
try {
amt = Double.parseDouble(args[1]);
}catch(NumberFormatException e) {
} catch (NumberFormatException e) {
sender.sendMessage(ChatColor.RED + "<amount> must be a number.");
throw e;
}
if(pm.hasEnoughToPay((Player) sender, amt)) {
if (pm.hasEnoughToPay((Player) sender, amt)) {
double bill = pm.calculateBill(p);
if(p.getRemainingTime() > 0) {
if (p.getRemainingTime() > 0) {
//timed sentence
if(amt >= bill) {
if (amt >= bill) {
pm.pay((Player) sender, bill);
sender.sendMessage(Lang.PAYPAIDRELEASED.get(String.valueOf(bill)));
jm.getPlugin().getPrisonerManager().schedulePrisonerRelease(p);
}else {
} else {
long minutes = pm.getMinutesPayingFor(amt);
pm.pay((Player) sender, amt);
long remain = p.subtractTime(TimeUnit.MILLISECONDS.convert(minutes, TimeUnit.MINUTES));
sender.sendMessage(Lang.PAYPAIDLOWEREDTIME.get(new String[] { String.valueOf(amt), String.valueOf(TimeUnit.MINUTES.convert(remain, TimeUnit.MILLISECONDS)) }));
sender.sendMessage(Lang.PAYPAIDLOWEREDTIME.get(String.valueOf(amt), String.valueOf(TimeUnit.MINUTES.convert(remain, TimeUnit.MILLISECONDS))));
}
}else {
} else {
//infinite jailing
if(amt >= bill) {
if (amt >= bill) {
pm.pay((Player) sender, bill);
sender.sendMessage(Lang.PAYPAIDRELEASED.get(String.valueOf(bill)));
jm.getPlugin().getPrisonerManager().schedulePrisonerRelease(p);
}else {
} else {
//You haven't provided enough money to get them out
sender.sendMessage(Lang.PAYNOTENOUGHMONEYPROVIDED.get());
}
}
}else {
} else {
sender.sendMessage(Lang.PAYNOTENOUGHMONEY.get());
}
}
}else {
} else {
sender.sendMessage(Lang.YOUARENOTJAILED.get());
}
break;
case 3:
// `/jail pay <amount> <person>
//they are trying to pay for someone else
if(jm.isPlayerJailedByLastKnownUsername(sender.getName())) {
if (jm.isPlayerJailedByLastKnownUsername(sender.getName())) {
//When they are jailed they can not pay for someone else
sender.sendMessage(Lang.PAYCANTPAYWHILEJAILED.get());
}else {
if(jm.isPlayerJailedByLastKnownUsername(args[2])) {
} else {
if (jm.isPlayerJailedByLastKnownUsername(args[2])) {
Prisoner p = jm.getPrisonerByLastKnownName(args[2]);
if(p.isJailedForever()) {
if(!pm.isInfiniteEnabled()) {
if (p.isJailedForever()) {
if (!pm.isInfiniteEnabled()) {
sender.sendMessage(Lang.PAYNOTENABLED.get());
return true;
}
}else {
if(!pm.isTimedEnabled()) {
} else {
if (!pm.isTimedEnabled()) {
sender.sendMessage(Lang.PAYNOTENABLED.get());
return true;
}
}
if(args[1].startsWith("-")) {
if (args[1].startsWith("-")) {
sender.sendMessage(Lang.PAYNONEGATIVEAMOUNTS.get());
}else {
double amt = 0;
} else {
double amt;
try {
amt = Double.parseDouble(args[1]);
}catch(NumberFormatException e) {
} catch (NumberFormatException e) {
sender.sendMessage(ChatColor.RED + "<amount> must be a number.");
throw e;
}
if(pm.hasEnoughToPay((Player) sender, amt)) {
if (pm.hasEnoughToPay((Player) sender, amt)) {
double bill = pm.calculateBill(p);
if(p.getRemainingTime() > 0) {
if (p.getRemainingTime() > 0) {
//timed sentence
if(amt >= bill) {
if (amt >= bill) {
pm.pay((Player) sender, bill);
sender.sendMessage(Lang.PAYPAIDRELEASEDELSE.get(new String[] { String.valueOf(bill), p.getLastKnownName() }));
sender.sendMessage(Lang.PAYPAIDRELEASEDELSE.get(String.valueOf(bill), p.getLastKnownName()));
jm.getPlugin().getPrisonerManager().schedulePrisonerRelease(p);
}else {
} else {
long minutes = pm.getMinutesPayingFor(amt);
pm.pay((Player) sender, amt);
long remain = p.subtractTime(TimeUnit.MILLISECONDS.convert(minutes, TimeUnit.MINUTES));
sender.sendMessage(Lang.PAYPAIDLOWEREDTIMEELSE.get(new String[] { String.valueOf(amt), p.getLastKnownName(), String.valueOf(TimeUnit.MINUTES.convert(remain, TimeUnit.MILLISECONDS)) }));
sender.sendMessage(Lang.PAYPAIDLOWEREDTIMEELSE.get(String.valueOf(amt), p.getLastKnownName(), String.valueOf(TimeUnit.MINUTES.convert(remain, TimeUnit.MILLISECONDS))));
}
}else {
} else {
//infinite jailing
if(amt >= bill) {
if (amt >= bill) {
pm.pay((Player) sender, bill);
sender.sendMessage(Lang.PAYPAIDRELEASEDELSE.get(new String[] { String.valueOf(bill), p.getLastKnownName() }));
sender.sendMessage(Lang.PAYPAIDRELEASEDELSE.get(String.valueOf(bill), p.getLastKnownName()));
jm.getPlugin().getPrisonerManager().schedulePrisonerRelease(p);
}else {
} else {
//You haven't provided enough money to get them out
sender.sendMessage(Lang.PAYNOTENOUGHMONEYPROVIDED.get());
}
}
}else {
} else {
sender.sendMessage(Lang.PAYNOTENOUGHMONEY.get());
}
}
}else {
} else {
//Person they're trying to pay for is not jailed
sender.sendMessage(Lang.NOTJAILED.get(args[2]));
}
@ -203,7 +202,7 @@ public class JailPayCommand implements Command {
default:
return false;
}
}else {
} else {
jm.getPlugin().debug("Jail pay not enabled.");
sender.sendMessage(Lang.PAYNOTENABLED.get());
}
@ -211,25 +210,22 @@ public class JailPayCommand implements Command {
return true;
}
public List<String> provideTabCompletions(JailManager jm, CommandSender sender, String... args) throws Exception {
if(jm.getPlugin().getConfig().getBoolean(Settings.JAILPAYENABLED.getPath())) {
switch(args.length) {
case 3:
List<String> results = new ArrayList<String>();
for(Prisoner p : jm.getAllPrisoners().values())
if(!p.isOfflinePending()) //Don't list if they're offline pending
if(p.getRemainingTime() != -1) //Don't list if they're jailed forever
if(StringUtil.startsWithIgnoreCase(p.getLastKnownName(), args[2]))
results.add(p.getLastKnownName());
Collections.sort(results);
return results;
default:
break;
public List<String> provideTabCompletions(JailManager jm, CommandSender sender, String... args) {
if (jm.getPlugin().getConfig().getBoolean(Settings.JAILPAYENABLED.getPath())) {
if (args.length == 3) {
List<String> results = new ArrayList<>();
for (Prisoner p : jm.getAllPrisoners().values())
if (!p.isOfflinePending()) //Don't list if they're offline pending
if (p.getRemainingTime() != -1) //Don't list if they're jailed forever
if (StringUtil.startsWithIgnoreCase(p.getLastKnownName(), args[2]))
results.add(p.getLastKnownName());
Collections.sort(results);
return results;
}
}
return Collections.emptyList();
}
}

View File

@ -1,14 +1,13 @@
package com.graywolf336.jail.command.subcommands;
import java.util.Collections;
import java.util.List;
import org.bukkit.command.CommandSender;
import com.graywolf336.jail.JailManager;
import com.graywolf336.jail.command.Command;
import com.graywolf336.jail.command.CommandInfo;
import com.graywolf336.jail.enums.Lang;
import org.bukkit.command.CommandSender;
import java.util.Collections;
import java.util.List;
@CommandInfo(
maxArgs = 2,
@ -17,26 +16,26 @@ import com.graywolf336.jail.enums.Lang;
pattern = "record|r",
permission = "jail.command.jailrecord",
usage = "/jail record [name] (display)"
)
)
public class JailRecordCommand implements Command {
@SuppressWarnings("deprecation")
public boolean execute(JailManager jm, CommandSender sender, String... args) {
if(args.length == 2) {
if (args.length == 2) {
// /jail record <username>
List<String> entries = jm.getPlugin().getJailIO().getRecordEntries(args[1]);
sender.sendMessage(Lang.RECORDTIMESJAILED.get(new String[] { args[1], String.valueOf(entries.size()) }));
}else if(args.length == 3) {
sender.sendMessage(Lang.RECORDTIMESJAILED.get(args[1], String.valueOf(entries.size())));
} else if (args.length == 3) {
// /jail record <username> something
List<String> entries = jm.getPlugin().getJailIO().getRecordEntries(args[1]);
//Send all the record entries
for(String s : entries) {
for (String s : entries) {
sender.sendMessage(s);
}
sender.sendMessage(Lang.RECORDTIMESJAILED.get(new String[] { args[1], String.valueOf(entries.size()) }));
}else {
sender.sendMessage(Lang.RECORDTIMESJAILED.get(args[1], String.valueOf(entries.size())));
} else {
//They didn't do the command right
//send them back to get the usage
return false;
@ -45,7 +44,7 @@ public class JailRecordCommand implements Command {
return true;
}
public List<String> provideTabCompletions(JailManager jm, CommandSender sender, String... args) throws Exception {
public List<String> provideTabCompletions(JailManager jm, CommandSender sender, String... args) {
//We won't be implementing tab complete on this for now (unless requested)
return Collections.emptyList();
}

View File

@ -1,15 +1,14 @@
package com.graywolf336.jail.command.subcommands;
import java.util.Collections;
import java.util.List;
import org.bukkit.ChatColor;
import org.bukkit.command.CommandSender;
import com.graywolf336.jail.JailManager;
import com.graywolf336.jail.command.Command;
import com.graywolf336.jail.command.CommandInfo;
import com.graywolf336.jail.enums.Lang;
import org.bukkit.ChatColor;
import org.bukkit.command.CommandSender;
import java.util.Collections;
import java.util.List;
@CommandInfo(
maxArgs = 0,
@ -18,13 +17,13 @@ import com.graywolf336.jail.enums.Lang;
pattern = "reload",
permission = "jail.command.jailreload",
usage = "/jail reload"
)
)
public class JailReloadCommand implements Command {
public boolean execute(JailManager jm, CommandSender sender, String... args) {
try {
jm.getPlugin().reloadEverything();
sender.sendMessage(Lang.PLUGINRELOADED.get());
}catch (Exception e) {
} catch (Exception e) {
e.printStackTrace();
sender.sendMessage(ChatColor.RED + "Failed to reload due to (see the console): " + e.getMessage());
}
@ -32,7 +31,7 @@ public class JailReloadCommand implements Command {
return true;
}
public List<String> provideTabCompletions(JailManager jm, CommandSender sender, String... args) throws Exception {
public List<String> provideTabCompletions(JailManager jm, CommandSender sender, String... args) {
//Reloading the plugin doesn't require tab completions
return Collections.emptyList();
}

View File

@ -1,14 +1,5 @@
package com.graywolf336.jail.command.subcommands;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map.Entry;
import org.bukkit.command.CommandSender;
import org.bukkit.util.StringUtil;
import com.graywolf336.jail.JailManager;
import com.graywolf336.jail.Util;
import com.graywolf336.jail.beans.Cell;
@ -16,6 +7,14 @@ import com.graywolf336.jail.beans.Jail;
import com.graywolf336.jail.command.Command;
import com.graywolf336.jail.command.CommandInfo;
import com.graywolf336.jail.enums.Lang;
import org.bukkit.command.CommandSender;
import org.bukkit.util.StringUtil;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map.Entry;
@CommandInfo(
maxArgs = -1,
@ -24,48 +23,48 @@ import com.graywolf336.jail.enums.Lang;
pattern = "signs",
permission = "jail.command.jailsigns",
usage = "/jail signs [clean|refresh|update|verify] [jail] (cell)..."
)
)
public class JailSignsCommand implements Command {
private static final String[] options = new String[] { "clean", "refresh", "update", "verify" };
private static final String[] options = new String[]{"clean", "refresh", "update", "verify"};
public boolean execute(JailManager jm, CommandSender sender, String... args) throws Exception {
if(!jm.isValidJail(args[2])) {
public boolean execute(JailManager jm, CommandSender sender, String... args) {
if (!jm.isValidJail(args[2])) {
sender.sendMessage(" " + Lang.NOJAIL.get(args[1]));
return true;
}
Jail j = jm.getJail(args[2]);
HashMap<String, List<String>> items = new HashMap<String, List<String>>();
HashMap<String, List<String>> items = new HashMap<>();
if(args[1].equalsIgnoreCase("clean")) {
if (args[1].equalsIgnoreCase("clean")) {
//if they type clean, we can remove all signs which are no longer signs
//then provide them a list of signs which got cleaned up
for(Cell c : j.getCells()) {
if(Util.isStringInsideArray(c.getName(), args) || args.length == 3) {
if(c.hasSigns()) {
for (Cell c : j.getCells()) {
if (Util.isStringInsideArray(c.getName(), args) || args.length == 3) {
if (c.hasSigns()) {
List<String> cleaned = c.cleanSigns();
if(!cleaned.isEmpty()) {
if (!cleaned.isEmpty()) {
items.put(c.getName(), cleaned);
}
}
}
}
if(items.isEmpty()) {
if (items.isEmpty()) {
sender.sendMessage(Lang.NOINVALIDSIGNS.get());
}else {
} else {
sender.sendMessage(Lang.CLEANEDSIGNS.get());
for(Entry<String, List<String>> e : items.entrySet()) {
for (Entry<String, List<String>> e : items.entrySet()) {
sender.sendMessage(" " + e.getKey());
for(String s : e.getValue())
for (String s : e.getValue())
sender.sendMessage(" Sign: " + s);
}
}
return true;
}else if(args[1].equalsIgnoreCase("refresh") || args[1].equalsIgnoreCase("update")) {
} else if (args[1].equalsIgnoreCase("refresh") || args[1].equalsIgnoreCase("update")) {
//if they type refresh, we will go through all the signs and update them to
//display the correct message on the sign whether empty or time
@ -73,8 +72,8 @@ public class JailSignsCommand implements Command {
int updated = 0;
int removed = 0;
for(Cell c : j.getCells()) {
if(Util.isStringInsideArray(c.getName(), args) || args.length == 3) {
for (Cell c : j.getCells()) {
if (Util.isStringInsideArray(c.getName(), args) || args.length == 3) {
HashMap<String, List<String>> results = c.updateSigns();
updated += results.get("updated").size();
removed += results.get("removed").size();
@ -82,53 +81,53 @@ public class JailSignsCommand implements Command {
}
}
sender.sendMessage(Lang.SIGNSREFRESHED.get(new String[] { String.valueOf(updated), String.valueOf(removed), String.valueOf(cells) }));
sender.sendMessage(Lang.SIGNSREFRESHED.get(String.valueOf(updated), String.valueOf(removed), String.valueOf(cells)));
return true;
}else if(args[1].equalsIgnoreCase("verify")) {
} else if (args[1].equalsIgnoreCase("verify")) {
//if they type verify, we will go through all the signs and then provide them
//as a list of cells which have signs that aren't actually signs and provide
//the location where the signs are
for(Cell c : j.getCells()) {
if(Util.isStringInsideArray(c.getName(), args) || args.length == 3) {
for (Cell c : j.getCells()) {
if (Util.isStringInsideArray(c.getName(), args) || args.length == 3) {
List<String> invalids = c.getInvalidSigns();
if(!invalids.isEmpty()) {
if (!invalids.isEmpty()) {
items.put(c.getName(), invalids);
}
}
}
if(items.isEmpty()) {
if (items.isEmpty()) {
sender.sendMessage(Lang.NOINVALIDSIGNS.get());
}else {
} else {
sender.sendMessage(Lang.INVALIDSIGNS.get());
for(Entry<String, List<String>> e : items.entrySet()) {
for (Entry<String, List<String>> e : items.entrySet()) {
sender.sendMessage(" " + e.getKey());
for(String s : e.getValue())
for (String s : e.getValue())
sender.sendMessage(" " + Lang.SIGN.get() + ": " + s);
}
}
return true;
}else
} else
return false;
}
public List<String> provideTabCompletions(JailManager jm, CommandSender sender, String... args) throws Exception {
List<String> results = new ArrayList<String>();
public List<String> provideTabCompletions(JailManager jm, CommandSender sender, String... args) {
List<String> results = new ArrayList<>();
switch(args.length) {
switch (args.length) {
case 2:
for(String s : options)
if(args[1].isEmpty() || StringUtil.startsWithIgnoreCase(s, args[1]))
for (String s : options)
if (args[1].isEmpty() || StringUtil.startsWithIgnoreCase(s, args[1]))
results.add(s);
break;
case 3:
results.addAll(jm.getJailsByPrefix(args[2]));
break;
default:
if(jm.isValidJail(args[2]))
for(Cell c : jm.getJail(args[2]).getCells())
if(!Util.isStringInsideArray(c.getName(), args))
if (jm.isValidJail(args[2]))
for (Cell c : jm.getJail(args[2]).getCells())
if (!Util.isStringInsideArray(c.getName(), args))
results.add(c.getName());
break;
}

View File

@ -1,17 +1,16 @@
package com.graywolf336.jail.command.subcommands;
import java.util.Collections;
import java.util.List;
import org.bukkit.command.CommandSender;
import org.bukkit.entity.Player;
import com.graywolf336.jail.JailManager;
import com.graywolf336.jail.Util;
import com.graywolf336.jail.beans.Prisoner;
import com.graywolf336.jail.command.Command;
import com.graywolf336.jail.command.CommandInfo;
import com.graywolf336.jail.enums.Lang;
import org.bukkit.command.CommandSender;
import org.bukkit.entity.Player;
import java.util.Collections;
import java.util.List;
@CommandInfo(
maxArgs = 0,
@ -20,17 +19,17 @@ import com.graywolf336.jail.enums.Lang;
pattern = "status|s",
permission = "jail.usercmd.jailstatus",
usage = "/jail status"
)
public class JailStatusCommand implements Command{
)
public class JailStatusCommand implements Command {
public boolean execute(JailManager jm, CommandSender sender, String... args) {
Player pl = (Player) sender;
if(jm.isPlayerJailed(pl.getUniqueId())) {
if (jm.isPlayerJailed(pl.getUniqueId())) {
Prisoner p = jm.getPrisoner(pl.getUniqueId());
//They are jailed, so let's tell them some information
sender.sendMessage(Lang.STATUS.get(new String[] { p.getReason(), p.getJailer(), String.valueOf(p.getRemainingTimeInMinutes()), Util.getDurationBreakdown(p.getRemainingTime()) }));
}else {
sender.sendMessage(Lang.STATUS.get(p.getReason(), p.getJailer(), String.valueOf(p.getRemainingTimeInMinutes()), Util.getDurationBreakdown(p.getRemainingTime())));
} else {
//the sender of the command is not jailed, tell them that
sender.sendMessage(Lang.YOUARENOTJAILED.get());
}
@ -38,7 +37,7 @@ public class JailStatusCommand implements Command{
return true;
}
public List<String> provideTabCompletions(JailManager jm, CommandSender sender, String... args) throws Exception {
public List<String> provideTabCompletions(JailManager jm, CommandSender sender, String... args) {
//Checking your jail status doesn't require tab completion
return Collections.emptyList();
}

View File

@ -1,16 +1,15 @@
package com.graywolf336.jail.command.subcommands;
import java.util.Collections;
import java.util.List;
import org.bukkit.command.CommandSender;
import org.bukkit.entity.Player;
import com.graywolf336.jail.JailManager;
import com.graywolf336.jail.command.Command;
import com.graywolf336.jail.command.CommandInfo;
import com.graywolf336.jail.enums.Lang;
import com.graywolf336.jail.enums.Settings;
import org.bukkit.command.CommandSender;
import org.bukkit.entity.Player;
import java.util.Collections;
import java.util.List;
@CommandInfo(
maxArgs = 0,
@ -19,25 +18,25 @@ import com.graywolf336.jail.enums.Settings;
pattern = "stick",
permission = "jail.usercmd.jailstick",
usage = "/jail stick"
)
)
public class JailStickCommand implements Command {
public boolean execute(JailManager jm, CommandSender sender, String... args) throws Exception {
if(jm.getPlugin().getConfig().getBoolean(Settings.JAILSTICKENABLED.getPath())) {
public boolean execute(JailManager jm, CommandSender sender, String... args) {
if (jm.getPlugin().getConfig().getBoolean(Settings.JAILSTICKENABLED.getPath())) {
boolean using = jm.getPlugin().getJailStickManager().toggleUsingStick(((Player) sender).getUniqueId());
if(using) {
if (using) {
sender.sendMessage(Lang.JAILSTICKENABLED.get());
}else {
} else {
sender.sendMessage(Lang.JAILSTICKDISABLED.get());
}
}else {
} else {
sender.sendMessage(Lang.JAILSTICKUSAGEDISABLED.get());
}
return true;
}
public List<String> provideTabCompletions(JailManager jm, CommandSender sender, String... args) throws Exception {
public List<String> provideTabCompletions(JailManager jm, CommandSender sender, String... args) {
//Nothing to tab complete on jail stick
return Collections.emptyList();
}

View File

@ -1,14 +1,13 @@
package com.graywolf336.jail.command.subcommands;
import java.util.Collections;
import java.util.List;
import org.bukkit.ChatColor;
import org.bukkit.command.CommandSender;
import com.graywolf336.jail.JailManager;
import com.graywolf336.jail.command.Command;
import com.graywolf336.jail.command.CommandInfo;
import org.bukkit.ChatColor;
import org.bukkit.command.CommandSender;
import java.util.Collections;
import java.util.List;
@CommandInfo(
maxArgs = 0,
@ -17,31 +16,31 @@ import com.graywolf336.jail.command.CommandInfo;
pattern = "stop",
permission = "jail.command.jailstop",
usage = "/jail stop"
)
)
public class JailStopCommand implements Command {
public boolean execute(JailManager jm, CommandSender sender, String... args) {
boolean nothing = true;
if(jm.isCreatingACell(sender.getName())) {
if (jm.isCreatingACell(sender.getName())) {
jm.removeCellCreationPlayer(sender.getName());
sender.sendMessage(ChatColor.RED + "You have stopped creating cells.");
nothing = false;
}
if(jm.isCreatingAJail(sender.getName())) {
if (jm.isCreatingAJail(sender.getName())) {
jm.removeJailCreationPlayer(sender.getName());
sender.sendMessage(ChatColor.RED + "You have stopped creating a jail.");
nothing = false;
}
if(nothing) {
if (nothing) {
sender.sendMessage(ChatColor.RED + "You've stopped creating....nothing.");
}
return true;
}
public List<String> provideTabCompletions(JailManager jm, CommandSender sender, String... args) throws Exception {
public List<String> provideTabCompletions(JailManager jm, CommandSender sender, String... args) {
//no tab completion required for stop command
return Collections.emptyList();
}

View File

@ -1,18 +1,17 @@
package com.graywolf336.jail.command.subcommands;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import org.bukkit.command.CommandSender;
import org.bukkit.entity.Player;
import org.bukkit.util.StringUtil;
import com.graywolf336.jail.JailManager;
import com.graywolf336.jail.beans.Jail;
import com.graywolf336.jail.command.Command;
import com.graywolf336.jail.command.CommandInfo;
import com.graywolf336.jail.enums.Lang;
import org.bukkit.command.CommandSender;
import org.bukkit.entity.Player;
import org.bukkit.util.StringUtil;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
@CommandInfo(
maxArgs = 2,
@ -21,35 +20,34 @@ import com.graywolf336.jail.enums.Lang;
pattern = "teleportin|telein",
permission = "jail.command.jailtelein",
usage = "/jail telein [jail] (name)"
)
)
public class JailTeleInCommand implements Command {
@SuppressWarnings("deprecation")
public boolean execute(JailManager jm, CommandSender sender, String... args) throws Exception {
public boolean execute(JailManager jm, CommandSender sender, String... args) {
Jail j = jm.getJail(args[1]);
//The jail doesn't exist
if(j == null) {
if (j == null) {
sender.sendMessage(Lang.NOJAIL.get(args[1]));
}else {
} else {
//The jail does exist
//now let's check the size of the command
//if it has two args then someone is sending someone else in
//otherwise it is just the sender going in
if(args.length == 3) {
if (args.length == 3) {
Player p = jm.getPlugin().getServer().getPlayer(args[2]);
//If the player they're trying to send is offline, don't do anything
if(p == null) {
if (p == null) {
sender.sendMessage(Lang.PLAYERNOTONLINE.get(args[2]));
}else {
} else {
p.teleport(j.getTeleportIn());
sender.sendMessage(Lang.TELEIN.get(new String[] { args[2], args[1] }));
sender.sendMessage(Lang.TELEIN.get(args[2], args[1]));
}
}else {
if(sender instanceof Player) {
} else {
if (sender instanceof Player) {
((Player) sender).teleport(j.getTeleportIn());
sender.sendMessage(Lang.TELEIN.get(new String[] { sender.getName(), args[1] }));
}else {
sender.sendMessage(Lang.TELEIN.get(sender.getName(), args[1]));
} else {
sender.sendMessage(Lang.PLAYERCONTEXTREQUIRED.get());
}
}
@ -58,19 +56,19 @@ public class JailTeleInCommand implements Command {
return true;
}
public List<String> provideTabCompletions(JailManager jm, CommandSender sender, String... args) throws Exception {
switch(args.length) {
public List<String> provideTabCompletions(JailManager jm, CommandSender sender, String... args) {
switch (args.length) {
case 2:
return jm.getJailsByPrefix(args[1]);
case 3:
List<String> results = new ArrayList<String>();
for(Player p : jm.getPlugin().getServer().getOnlinePlayers())
if(args[2].isEmpty() || StringUtil.startsWithIgnoreCase(p.getName(), args[2]))
List<String> results = new ArrayList<>();
for (Player p : jm.getPlugin().getServer().getOnlinePlayers())
if (args[2].isEmpty() || StringUtil.startsWithIgnoreCase(p.getName(), args[2]))
results.add(p.getName());
Collections.sort(results);
return results;
default:
return Collections.emptyList();

View File

@ -1,18 +1,17 @@
package com.graywolf336.jail.command.subcommands;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import org.bukkit.command.CommandSender;
import org.bukkit.entity.Player;
import org.bukkit.util.StringUtil;
import com.graywolf336.jail.JailManager;
import com.graywolf336.jail.beans.Jail;
import com.graywolf336.jail.command.Command;
import com.graywolf336.jail.command.CommandInfo;
import com.graywolf336.jail.enums.Lang;
import org.bukkit.command.CommandSender;
import org.bukkit.entity.Player;
import org.bukkit.util.StringUtil;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
@CommandInfo(
maxArgs = 2,
@ -21,35 +20,34 @@ import com.graywolf336.jail.enums.Lang;
pattern = "teleportout|teleout",
permission = "jail.command.jailteleout",
usage = "/jail teleout [jail] (name)"
)
)
public class JailTeleOutCommand implements Command {
@SuppressWarnings("deprecation")
public boolean execute(JailManager jm, CommandSender sender, String... args) throws Exception {
public boolean execute(JailManager jm, CommandSender sender, String... args) {
Jail j = jm.getJail(args[1]);
//The jail doesn't exist
if(j == null) {
if (j == null) {
sender.sendMessage(Lang.NOJAIL.get(args[1]));
}else {
} else {
//The jail does exist
//now let's check the size of the command
//if it has two args then someone is sending someone else in
//otherwise it is just the sender going in
if(args.length == 3) {
if (args.length == 3) {
Player p = jm.getPlugin().getServer().getPlayer(args[2]);
//If the player they're trying to send is offline, don't do anything
if(p == null) {
if (p == null) {
sender.sendMessage(Lang.PLAYERNOTONLINE.get(args[2]));
}else {
} else {
p.teleport(j.getTeleportFree());
sender.sendMessage(Lang.TELEOUT.get(new String[] { args[2], args[1] }));
sender.sendMessage(Lang.TELEOUT.get(args[2], args[1]));
}
}else {
if(sender instanceof Player) {
} else {
if (sender instanceof Player) {
((Player) sender).teleport(j.getTeleportFree());
sender.sendMessage(Lang.TELEOUT.get(new String[] { sender.getName(), args[1] }));
}else {
sender.sendMessage(Lang.TELEOUT.get(sender.getName(), args[1]));
} else {
sender.sendMessage(Lang.PLAYERCONTEXTREQUIRED.get());
}
}
@ -58,19 +56,19 @@ public class JailTeleOutCommand implements Command {
return true;
}
public List<String> provideTabCompletions(JailManager jm, CommandSender sender, String... args) throws Exception {
switch(args.length) {
public List<String> provideTabCompletions(JailManager jm, CommandSender sender, String... args) {
switch (args.length) {
case 2:
return jm.getJailsByPrefix(args[1]);
case 3:
List<String> results = new ArrayList<String>();
for(Player p : jm.getPlugin().getServer().getOnlinePlayers())
if(args[2].isEmpty() || StringUtil.startsWithIgnoreCase(p.getName(), args[2]))
List<String> results = new ArrayList<>();
for (Player p : jm.getPlugin().getServer().getOnlinePlayers())
if (args[2].isEmpty() || StringUtil.startsWithIgnoreCase(p.getName(), args[2]))
results.add(p.getName());
Collections.sort(results);
return results;
default:
return Collections.emptyList();

View File

@ -1,18 +1,17 @@
package com.graywolf336.jail.command.subcommands;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import org.bukkit.command.CommandSender;
import org.bukkit.util.StringUtil;
import com.graywolf336.jail.JailManager;
import com.graywolf336.jail.Util;
import com.graywolf336.jail.beans.Prisoner;
import com.graywolf336.jail.command.Command;
import com.graywolf336.jail.command.CommandInfo;
import com.graywolf336.jail.enums.Lang;
import org.bukkit.command.CommandSender;
import org.bukkit.util.StringUtil;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
@CommandInfo(
maxArgs = 3,
@ -21,65 +20,65 @@ import com.graywolf336.jail.enums.Lang;
pattern = "time|t",
permission = "jail.command.jailtime",
usage = "/jail time [add|remove|set|show] [name] <time>"
)
)
public class JailTimeCommand implements Command {
private static final String[] options = new String[] { "add", "remove", "set", "show" };
private static final String[] options = new String[]{"add", "remove", "set", "show"};
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]);
switch(args.length) {
switch (args.length) {
case 3:
if(args[1].equalsIgnoreCase("show")) {
sender.sendMessage(Lang.PRISONERSTIME.get(new String[] { p.getLastKnownName(), String.valueOf(p.getRemainingTimeInMinutes()) }));
}else {
if (args[1].equalsIgnoreCase("show")) {
sender.sendMessage(Lang.PRISONERSTIME.get(p.getLastKnownName(), String.valueOf(p.getRemainingTimeInMinutes())));
} else {
return false;
}
break;
case 4:
if(args[1].equalsIgnoreCase("add")) {
if (args[1].equalsIgnoreCase("add")) {
p.addTime(Util.getTime(args[3]));
}else if(args[1].equalsIgnoreCase("remove")) {
} else if (args[1].equalsIgnoreCase("remove")) {
p.subtractTime(Util.getTime(args[3]));
}else if(args[1].equalsIgnoreCase("set")) {
} else if (args[1].equalsIgnoreCase("set")) {
p.setRemainingTime(Util.getTime(args[3]));
}else {
} else {
return false;
}
sender.sendMessage(Lang.PRISONERSTIME.get(new String[] { p.getLastKnownName(), String.valueOf(p.getRemainingTimeInMinutes()) }));
sender.sendMessage(Lang.PRISONERSTIME.get(p.getLastKnownName(), String.valueOf(p.getRemainingTimeInMinutes())));
break;
default:
return false;
}
}else {
} else {
sender.sendMessage(Lang.NOTJAILED.get(args[2]));
}
return true;
}
public List<String> provideTabCompletions(JailManager jm, CommandSender sender, String... args) throws Exception {
List<String> results = new ArrayList<String>();
switch(args.length) {
public List<String> provideTabCompletions(JailManager jm, CommandSender sender, String... args) {
List<String> results = new ArrayList<>();
switch (args.length) {
case 2:
for(String s : options)
if(args[1].isEmpty() || StringUtil.startsWithIgnoreCase(s, args[1]))
for (String s : options)
if (args[1].isEmpty() || StringUtil.startsWithIgnoreCase(s, args[1]))
results.add(s);
break;
case 3:
for(Prisoner p : jm.getAllPrisoners().values())
if(StringUtil.startsWithIgnoreCase(p.getLastKnownName(), args[2]))
for (Prisoner p : jm.getAllPrisoners().values())
if (StringUtil.startsWithIgnoreCase(p.getLastKnownName(), args[2]))
results.add(p.getLastKnownName());
break;
default:
break;
}
Collections.sort(results);
return results;
}
}

View File

@ -1,19 +1,18 @@
package com.graywolf336.jail.command.subcommands;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashSet;
import java.util.List;
import org.bukkit.command.CommandSender;
import org.bukkit.util.StringUtil;
import com.graywolf336.jail.JailManager;
import com.graywolf336.jail.beans.Jail;
import com.graywolf336.jail.beans.Prisoner;
import com.graywolf336.jail.command.Command;
import com.graywolf336.jail.command.CommandInfo;
import com.graywolf336.jail.enums.Lang;
import org.bukkit.command.CommandSender;
import org.bukkit.util.StringUtil;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashSet;
import java.util.List;
@CommandInfo(
maxArgs = 2,
@ -22,10 +21,10 @@ import com.graywolf336.jail.enums.Lang;
pattern = "transferall|transall|ta",
permission = "jail.command.jailtransferall",
usage = "/jail transferall [current] [target]"
)
)
public class JailTransferAllCommand implements Command {
public boolean execute(JailManager jm, CommandSender sender, String... args) throws Exception {
if(jm.getJails().isEmpty()) {
public boolean execute(JailManager jm, CommandSender sender, String... args) {
if (jm.getJails().isEmpty()) {
sender.sendMessage(Lang.NOJAILS.get());
return true;
}
@ -33,10 +32,10 @@ public class JailTransferAllCommand implements Command {
jm.getPlugin().debug("Starting to transfer everyone from '" + args[1] + "' into '" + args[2] + "'.");
//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]));
return true;
}else if(!jm.isValidJail(args[2])) {
} else if (!jm.isValidJail(args[2])) {
//Check if the targetjail is a valid jail as well
sender.sendMessage(Lang.NOJAIL.get(args[2]));
return true;
@ -45,32 +44,32 @@ public class JailTransferAllCommand implements Command {
jm.getPlugin().debug("Sending the transferring off, jail checks all came clean.");
Jail old = jm.getJail(args[1]);
HashSet<Prisoner> oldPrisoners = new HashSet<Prisoner>(old.getAllPrisoners().values());
HashSet<Prisoner> oldPrisoners = new HashSet<>(old.getAllPrisoners().values());
//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);
}
//Send the messages to the sender when completed
sender.sendMessage(Lang.TRANSFERALLCOMPLETE.get(new String[] { old.getName(), args[2] }));
sender.sendMessage(Lang.TRANSFERALLCOMPLETE.get(old.getName(), args[2]));
return true;
}
public List<String> provideTabCompletions(JailManager jm, CommandSender sender, String... args) throws Exception {
switch(args.length) {
public List<String> provideTabCompletions(JailManager jm, CommandSender sender, String... args) {
switch (args.length) {
case 2:
return jm.getJailsByPrefix(args[1]);
case 3:
List<String> results = new ArrayList<String>();
for(Jail j : jm.getJails())
if(!j.getName().equalsIgnoreCase(args[1]) && (args[2].isEmpty() || StringUtil.startsWithIgnoreCase(j.getName(), args[2])))
List<String> results = new ArrayList<>();
for (Jail j : jm.getJails())
if (!j.getName().equalsIgnoreCase(args[1]) && (args[2].isEmpty() || StringUtil.startsWithIgnoreCase(j.getName(), args[2])))
results.add(j.getName());
Collections.sort(results);
return results;
default:
return Collections.emptyList();

View File

@ -1,17 +1,5 @@
package com.graywolf336.jail.command.subcommands;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.LinkedList;
import java.util.List;
import org.apache.commons.lang3.ArrayUtils;
import org.bukkit.ChatColor;
import org.bukkit.command.CommandSender;
import org.bukkit.entity.Player;
import org.bukkit.util.StringUtil;
import com.graywolf336.jail.JailManager;
import com.graywolf336.jail.Util;
import com.graywolf336.jail.beans.Cell;
@ -24,6 +12,17 @@ import com.graywolf336.jail.enums.Lang;
import com.graywolf336.jail.events.PrePrisonerTransferredEvent;
import com.lexicalscope.jewel.cli.ArgumentValidationException;
import com.lexicalscope.jewel.cli.CliFactory;
import org.apache.commons.lang.ArrayUtils;
import org.bukkit.ChatColor;
import org.bukkit.command.CommandSender;
import org.bukkit.entity.Player;
import org.bukkit.util.StringUtil;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.LinkedList;
import java.util.List;
@CommandInfo(
maxArgs = 6,
@ -32,36 +31,36 @@ import com.lexicalscope.jewel.cli.CliFactory;
pattern = "transfer|trans",
permission = "jail.command.jailtransfer",
usage = "/jail transfer [-p player] (-j jail) (-c cell)"
)
)
public class JailTransferCommand implements Command {
private List<String> commands = Arrays.asList(new String[] { "p", "j", "c" });
public boolean execute(JailManager jm, CommandSender sender, String... args) throws Exception {
if(jm.getJails().isEmpty()) {
private final List<String> commands = Arrays.asList("p", "j", "c");
public boolean execute(JailManager jm, CommandSender sender, String... args) {
if (jm.getJails().isEmpty()) {
sender.sendMessage(Lang.NOJAILS.get());
return true;
}
//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<>(Arrays.asList(args));
//remove the first argument of "transfer"
arguments.remove(0);
//Parse the command
Transfer params = null;
Transfer params;
try {
params = CliFactory.parseArguments(Transfer.class, arguments.toArray(new String[arguments.size()]));
}catch(ArgumentValidationException e) {
params = CliFactory.parseArguments(Transfer.class, arguments.toArray(new String[0]));
} catch (ArgumentValidationException e) {
sender.sendMessage(ChatColor.RED + e.getMessage());
return true;
}
//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));
return true;
}else if(!jm.isPlayerJailedByLastKnownUsername(params.getPlayer())) {
} else if (!jm.isPlayerJailedByLastKnownUsername(params.getPlayer())) {
sender.sendMessage(Lang.NOTJAILED.get(params.getPlayer()));
return true;
}
@ -69,10 +68,10 @@ public class JailTransferCommand implements Command {
jm.getPlugin().debug("Checking everything before we transfer: " + params.getPlayer());
//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));
return true;
}else if(!jm.isValidJail(params.getJail())) {
} else if (!jm.isValidJail(params.getJail())) {
//Check if the jail they did provided is not a valid jail
sender.sendMessage(Lang.NOJAIL.get(params.getJail()));
return true;
@ -84,22 +83,22 @@ public class JailTransferCommand implements Command {
Cell targetCell = null;
//Check if they provided a cell and if so does it exist
if(params.getCell() != null) {
if(target.getCell(params.getCell()) == null) {
sender.sendMessage(Lang.NOCELL.get(new String[] { params.getCell(), params.getJail() }));
if (params.getCell() != null) {
if (target.getCell(params.getCell()) == null) {
sender.sendMessage(Lang.NOCELL.get(params.getCell(), params.getJail()));
return true;
}else {
} else {
//Store the cell for easy of access and also check if it already is full
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
sender.sendMessage(Lang.CELLNOTEMPTY.get(params.getCell()));
//But suggest the first empty cell we find
Cell suggestedCell = jm.getJail(params.getCell()).getFirstEmptyCell();
if(suggestedCell != null) {
sender.sendMessage(Lang.SUGGESTEDCELL.get(new String[] { params.getCell(), suggestedCell.getName() }));
}else {
if (suggestedCell != null) {
sender.sendMessage(Lang.SUGGESTEDCELL.get(params.getCell(), suggestedCell.getName()));
} else {
sender.sendMessage(Lang.NOEMPTYCELLS.get(params.getCell()));
}
@ -117,11 +116,11 @@ public class JailTransferCommand implements Command {
target, targetCell, p, jm.getPlugin().getServer().getPlayer(p.getUUID()), sender.getName());
jm.getPlugin().getServer().getPluginManager().callEvent(event);
if(event.isCancelled()) {
if(event.getCancelledMessage().isEmpty()) {
if (event.isCancelled()) {
if (event.getCancelledMessage().isEmpty()) {
//The plugin didn't provide a cancel message/reason so send the default one
sender.sendMessage(Lang.TRANSFERCANCELLEDBYANOTHERPLUGIN.get(params.getPlayer()));
}else {
} else {
sender.sendMessage(event.getCancelledMessage());
}
@ -134,71 +133,72 @@ public class JailTransferCommand implements Command {
target, targetCell, p);
//Send the messages to the sender, if no cell then say that but if cell send that as well
if(targetCell == null) {
sender.sendMessage(Lang.TRANSFERCOMPLETENOCELL.get(new String[] { params.getPlayer(), target.getName() }));
}else {
sender.sendMessage(Lang.TRANSFERCOMPLETECELL.get(new String[] { params.getPlayer(), target.getName(), targetCell.getName() }));
if (targetCell == null) {
sender.sendMessage(Lang.TRANSFERCOMPLETENOCELL.get(params.getPlayer(), target.getName()));
} else {
sender.sendMessage(Lang.TRANSFERCOMPLETECELL.get(params.getPlayer(), target.getName(), targetCell.getName()));
}
return true;
}
public List<String> provideTabCompletions(JailManager jm, CommandSender sender, String... args) throws Exception {
public List<String> provideTabCompletions(JailManager jm, CommandSender sender, String... args) {
//by the time it gets to this command it'll have at least two arguments
String last = args[args.length - 1];
if(last.isEmpty() || !commands.contains(last.replace("-", ""))) {
if (last.isEmpty() || !commands.contains(last.replace("-", ""))) {
//the current part is empty. Need to look at their previous
//item and if it is a valid option, then provide them a valid tab complete option
if(args.length - 2 > -1) {
if (args.length - 2 > -1) {
String previous = args[args.length - 2];
jm.getPlugin().debug("args[args.length - 2]: " + previous);
if(previous.equalsIgnoreCase("-p")) return getPlayers(jm, last);
else if(previous.equalsIgnoreCase("-j")) return jm.getJailsByPrefix(last);
else if(previous.equalsIgnoreCase("-c")) {
if (previous.equalsIgnoreCase("-p")) return getPlayers(jm, last);
else if (previous.equalsIgnoreCase("-j")) return jm.getJailsByPrefix(last);
else if (previous.equalsIgnoreCase("-c")) {
//Since we need to give them a list of the cells in a jail
//we need to get the jail they're giving
int jailIndex = ArrayUtils.indexOf(args, "-j");
if(jailIndex != -1) {
if (jailIndex != -1) {
String jail = args[jailIndex + 1];
jm.getPlugin().debug("The jail is: " + jail);
if(jm.isValidJail(jail)) return getCells(jm, jail, last);
if (jm.isValidJail(jail)) return getCells(jm, jail, last);
}
}else if(!commands.contains(args[args.length - 2].replace("-", ""))) return Util.getUnusedItems(commands, args, true);
} else if (!commands.contains(args[args.length - 2].replace("-", "")))
return Util.getUnusedItems(commands, args, true);
}
}else if(last.equalsIgnoreCase("-")) {
} else if (last.equalsIgnoreCase("-")) {
//add some smart checking so that it only returns a list of what isn't already
//in the command :)
return Util.getUnusedItems(commands, args, true);
}else {
} else {
return getPlayers(jm, last);
}
return Collections.emptyList();
}
private List<String> getPlayers(JailManager jm, String first) {
List<String> results = new ArrayList<String>();
for(Player p : jm.getPlugin().getServer().getOnlinePlayers())
if(first.isEmpty() || StringUtil.startsWithIgnoreCase(p.getName(), first))
List<String> results = new ArrayList<>();
for (Player p : jm.getPlugin().getServer().getOnlinePlayers())
if (first.isEmpty() || StringUtil.startsWithIgnoreCase(p.getName(), first))
results.add(p.getName());
Collections.sort(results);
return results;
}
private List<String> getCells(JailManager jm, String jail, String cell) {
List<String> results = new ArrayList<String>();
for(Cell c : jm.getJail(jail).getCells())
if(!c.hasPrisoner() && (cell.isEmpty() || StringUtil.startsWithIgnoreCase(c.getName(), cell)))
results.add(c.getName());
List<String> results = new ArrayList<>();
for (Cell c : jm.getJail(jail).getCells())
if (!c.hasPrisoner() && (cell.isEmpty() || StringUtil.startsWithIgnoreCase(c.getName(), cell)))
results.add(c.getName());
Collections.sort(results);
return results;
}
}

View File

@ -1,13 +1,12 @@
package com.graywolf336.jail.command.subcommands;
import java.util.Collections;
import java.util.List;
import org.bukkit.command.CommandSender;
import com.graywolf336.jail.JailManager;
import com.graywolf336.jail.command.Command;
import com.graywolf336.jail.command.CommandInfo;
import org.bukkit.command.CommandSender;
import java.util.Collections;
import java.util.List;
@CommandInfo(
maxArgs = 0,
@ -16,7 +15,7 @@ import com.graywolf336.jail.command.CommandInfo;
pattern = "version|ver",
permission = "jail.command.jailversion",
usage = "/jail version"
)
)
public class JailVersionCommand implements Command {
public boolean execute(JailManager jm, CommandSender sender, String... args) {
@ -26,7 +25,7 @@ public class JailVersionCommand implements Command {
return true;
}
public List<String> provideTabCompletions(JailManager jm, CommandSender sender, String... args) throws Exception {
public List<String> provideTabCompletions(JailManager jm, CommandSender sender, String... args) {
//no tab completion required for version command
return Collections.emptyList();
}

View File

@ -1,13 +1,5 @@
package com.graywolf336.jail.command.subcommands;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import org.bukkit.command.CommandSender;
import org.bukkit.entity.Player;
import org.bukkit.util.StringUtil;
import com.graywolf336.jail.JailManager;
import com.graywolf336.jail.JailVoteManager;
import com.graywolf336.jail.beans.JailVote;
@ -15,6 +7,13 @@ import com.graywolf336.jail.command.Command;
import com.graywolf336.jail.command.CommandInfo;
import com.graywolf336.jail.enums.Lang;
import com.graywolf336.jail.enums.Settings;
import org.bukkit.command.CommandSender;
import org.bukkit.entity.Player;
import org.bukkit.util.StringUtil;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
@CommandInfo(
maxArgs = 2,
@ -23,112 +22,111 @@ import com.graywolf336.jail.enums.Settings;
pattern = "vote|v",
permission = "jail.usercmd.jailvote",
usage = "/jail vote [player] (yes|no)"
)
)
public class JailVoteCommand implements Command {
private static final String[] options = new String[] { "yes", "no" };
@SuppressWarnings("deprecation")
private static final String[] options = new String[]{"yes", "no"};
public boolean execute(JailManager jm, CommandSender sender, String... args) {
if(jm.getPlugin().getConfig().getBoolean(Settings.JAILVOTEENABLED.getPath()) && jm.getPlugin().getJailVoteManager() != null && !jm.getJails().isEmpty()) {
if (jm.getPlugin().getConfig().getBoolean(Settings.JAILVOTEENABLED.getPath()) && jm.getPlugin().getJailVoteManager() != null && !jm.getJails().isEmpty()) {
Player p = (Player) sender;
JailVoteManager jvm = jm.getPlugin().getJailVoteManager();
switch(args.length) {
switch (args.length) {
case 2:
if(jvm.isVotedFor(args[1])) {
if(jvm.hasVotedAlready(args[1], p.getUniqueId())) {
if (jvm.isVotedFor(args[1])) {
if (jvm.hasVotedAlready(args[1], p.getUniqueId())) {
sender.sendMessage(Lang.VOTEALREADYVOTEDFOR.get(args[1]));
}else {
if(jvm.addVote(args[1], p.getUniqueId(), true)) {
} else {
if (jvm.addVote(args[1], p.getUniqueId(), true)) {
sender.sendMessage(Lang.VOTEYESSUCCESS.get(args[1]));
}else {
} else {
sender.sendMessage(Lang.VOTEUNSUCCESSFUL.get());
}
}
}else if(sender.hasPermission("jail.vote.start")) {
Player voteAgainst = jm.getPlugin().getServer().getPlayer(args[1]);
if(voteAgainst == null) {
} else if (sender.hasPermission("jail.vote.start")) {
Player voteAgainst = jm.getPlugin().getServer().getPlayer(args[1]);
if (voteAgainst == null) {
sender.sendMessage(Lang.PLAYERNOTONLINE.get());
}else {
if(voteAgainst.hasPermission("jail.cantbejailed")) {
} else {
if (voteAgainst.hasPermission("jail.cantbejailed")) {
sender.sendMessage(Lang.CANTBEJAILED.get());
}else {
} else {
jvm.addVote(new JailVote(voteAgainst.getName()));
jvm.addVote(voteAgainst.getName(), p.getUniqueId(), true);
jm.getPlugin().getServer().broadcastMessage(Lang.VOTEBROADCASTHEADER.get());
jm.getPlugin().getServer().broadcastMessage(Lang.VOTEBROADCASTLINE1.get(new String[] { sender.getName(), args[1] }));
jm.getPlugin().getServer().broadcastMessage(Lang.VOTEBROADCASTLINE1.get(sender.getName(), args[1]));
jm.getPlugin().getServer().broadcastMessage(Lang.VOTEBROADCASTLINE2.get(voteAgainst.getName()));
jm.getPlugin().getServer().broadcastMessage(Lang.VOTEBROADCASTLINE3.get(voteAgainst.getName()));
jm.getPlugin().getServer().broadcastMessage(Lang.VOTEBROADCASTLINE4.get(jvm.getTimerLengthDescription()));
jm.getPlugin().getServer().broadcastMessage(Lang.VOTEBROADCASTFOOTER.get());
jvm.scheduleCalculating(args[1]);
}
}
}else {
} else {
jm.getPlugin().debug(sender.getName() + " tried to start a vote to jail someone but didn't have permission, jail.vote.start");
sender.sendMessage(Lang.VOTENOPERMISSIONTOSTART.get(args[1]));
}
break;
case 3:
String name = args[1];
if(jvm.isVotedFor(name)) {
if(jvm.hasVotedAlready(args[1], p.getUniqueId())) {
if (jvm.isVotedFor(name)) {
if (jvm.hasVotedAlready(args[1], p.getUniqueId())) {
sender.sendMessage(Lang.VOTEALREADYVOTEDFOR.get(args[1]));
}else {
if(args[2].equalsIgnoreCase("yes")) {
} else {
if (args[2].equalsIgnoreCase("yes")) {
jvm.addVote(args[1], p.getUniqueId(), true);
sender.sendMessage(Lang.VOTEYESSUCCESS.get(args[1]));
}else {
} else {
jvm.addVote(args[1], p.getUniqueId(), false);
sender.sendMessage(Lang.VOTENOSUCCESS.get(args[1]));
}
}
}else {
} else {
sender.sendMessage(Lang.VOTENOVOTEFORTHATPLAYER.get(name));
}
break;
default:
return false;
}
}else {
} else {
sender.sendMessage(Lang.VOTENOTENABLED.get());
if(jm.getPlugin().getJailVoteManager() == null) {
if (jm.getPlugin().getJailVoteManager() == null) {
jm.getPlugin().getLogger().severe("Jail Vote Manager didn't load correctly, it is null.");
}else if(jm.getJails().isEmpty()) {
} else if (jm.getJails().isEmpty()) {
jm.getPlugin().getLogger().severe("There are no jails, Jail Vote needs a Jail to work.");
}
}
return true;
}
public List<String> provideTabCompletions(JailManager jm, CommandSender sender, String... args) throws Exception {
if(jm.getPlugin().getConfig().getBoolean(Settings.JAILVOTEENABLED.getPath()) && jm.getPlugin().getJailVoteManager() != null && !jm.getJails().isEmpty()) {
List<String> results = new ArrayList<String>();
switch(args.length) {
public List<String> provideTabCompletions(JailManager jm, CommandSender sender, String... args) {
if (jm.getPlugin().getConfig().getBoolean(Settings.JAILVOTEENABLED.getPath()) && jm.getPlugin().getJailVoteManager() != null && !jm.getJails().isEmpty()) {
List<String> results = new ArrayList<>();
switch (args.length) {
case 2:
for(Player p : jm.getPlugin().getServer().getOnlinePlayers())
if(args[1].isEmpty() || StringUtil.startsWithIgnoreCase(p.getName(), args[1]))
for (Player p : jm.getPlugin().getServer().getOnlinePlayers())
if (args[1].isEmpty() || StringUtil.startsWithIgnoreCase(p.getName(), args[1]))
results.add(p.getName());
break;
case 3:
for(String s : options)
if(args[2].isEmpty() || StringUtil.startsWithIgnoreCase(s, args[2]))
for (String s : options)
if (args[2].isEmpty() || StringUtil.startsWithIgnoreCase(s, args[2]))
results.add(s);
break;
default:
break;
}
Collections.sort(results);
return results;
}else {
} else {
return Collections.emptyList();
}
}

View File

@ -1,14 +1,24 @@
package com.graywolf336.jail.enums;
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,
/** 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,
/** When they are deleting a cell from a jail. */
/**
* When they are deleting a cell from a jail.
*/
DELETECELL,
/** When they are deleting all a jail's cells. */
/**
* When they are deleting all a jail's cells.
*/
DELETECELLS,
/** When they are deleting a jail. */
DELETE;
/**
* When they are deleting a jail.
*/
DELETE
}

View File

@ -1,22 +1,40 @@
package com.graywolf336.jail.enums;
public enum JailVoteResult {
/** The result when the PrePrisonerJailedEvent is cancelled. */
/**
* The result when the PrePrisonerJailedEvent is cancelled.
*/
EVENTCANCELLED,
/** The result when the jailing results in an exception for some reason. */
/**
* The result when the jailing results in an exception for some reason.
*/
JAILEDEXCEPTION,
/** The result when the jail which is picked is not enabled. */
/**
* The result when the jail which is picked is not enabled.
*/
JAILNOTENABLED,
/** The result when the player who the vote is for is no longer online. */
/**
* The result when the player who the vote is for is no longer online.
*/
NOTONLINE,
/** The result when there aren't enough yes votes as configured. */
/**
* The result when there aren't enough yes votes as configured.
*/
NOTENOUGHYESVOTES,
/** The result when there are no jails. */
/**
* The result when there are no jails.
*/
NOJAIL,
/** The result when there are more no votes than yes votes. */
/**
* The result when there are more no votes than yes votes.
*/
NO,
/** The result when the votes are tied, resulting in no jailing. */
/**
* The result when the votes are tied, resulting in no jailing.
*/
TIED,
/** The result when there are enough yes votes over no votes for the vote to be successful. */
/**
* The result when there are enough yes votes over no votes for the vote to be successful.
*/
YES
}

View File

@ -5,266 +5,514 @@ import org.bukkit.configuration.file.YamlConfiguration;
public enum Lang {
// actions section
/** Section for when they break a block. */
/**
* Section for when they break a block.
*/
BLOCKBREAKING("actions"),
/** Section for when they place a block. */
/**
* Section for when they place a block.
*/
BLOCKPLACING("actions"),
/** Section for when they try to do a command that isn't whitelisted. */
/**
* Section for when they try to do a command that isn't whitelisted.
*/
COMMAND("actions"),
/** Section for when a player tramples a crop and protection is enabled. */
/**
* Section for when a player tramples a crop and protection is enabled.
*/
CROPTRAMPLING("actions"),
/** Section for when a player interacts with a block that is blacklisted. */
/**
* Section for when a player interacts with a block that is blacklisted.
*/
INTERACTIONBLOCKS("actions"),
/** Section for when a player interacts with an item that is blacklisted. */
/**
* Section for when a player interacts with an item that is blacklisted.
*/
INTERACTIONITEMS("actions"),
/** Section for when a player moves outside of the jail. */
/**
* Section for when a player moves outside of the jail.
*/
MOVING("actions"),
// Jailing section
/** The message displayed when players are kicked for being afk. */
/**
* The message displayed when players are kicked for being afk.
*/
AFKKICKMESSAGE("jailing"),
/** The message sent when jailing someone that is already jailed. */
/**
* The message sent when jailing someone that is already jailed.
*/
ALREADYJAILED("jailing"),
/** The message sent when we broadcast/log the message for time below -1. */
/**
* The message sent when we broadcast/log the message for time below -1.
*/
BROADCASTMESSAGEFOREVER("jailing"),
/** The message sent when we broadcast/log the message for any time above -1. */
/**
* The message sent when we broadcast/log the message for any time above -1.
*/
BROADCASTMESSAGEFORMINUTES("jailing"),
/** The message sent to the broadcast/log the unjailing of someone. */
/**
* The message sent to the broadcast/log the unjailing of someone.
*/
BROADCASTUNJAILING("jailing"),
/** The message sent to the sender when trying to jail someone and a plugin cancels it but doesn't leave a message why. */
/**
* The message sent to the sender when trying to jail someone and a plugin cancels it but doesn't leave a message why.
*/
CANCELLEDBYANOTHERPLUGIN("jailing"),
/** The message sent when trying to jail someone who can't be jailed by permission. */
/**
* The message sent when trying to jail someone who can't be jailed by permission.
*/
CANTBEJAILED("jailing"),
/** The message sent to the sender when they are trying to jail into a cell which is not empty. */
/**
* The message sent to the sender when they are trying to jail into a cell which is not empty.
*/
CELLNOTEMPTY("jailing"),
/** The jailer set whenever a jailer is not provided. */
/**
* The jailer set whenever a jailer is not provided.
*/
DEFAULTJAILER("jailing"),
/** The message sent when someone is jailed without a reason. */
/**
* The message sent when someone is jailed without a reason.
*/
DEFAULTJAILEDREASON("jailing"),
/** The message sent when someone is unjailed yet they never came online and so they were forcefully unjailed. */
/**
* The message sent when someone is unjailed yet they never came online and so they were forcefully unjailed.
*/
FORCEUNJAILED("jailing"),
/** The message sent when players are jailed without a reason. */
/**
* The message sent when players are jailed without a reason.
*/
JAILED("jailing"),
/** The message sent when players are jailed with a reason. */
/**
* The message sent when players are jailed with a reason.
*/
JAILEDWITHREASON("jailing"),
/** The message sent when players are jailed and they try to talk. */
/**
* The message sent when players are jailed and they try to talk.
*/
MUTED("jailing"),
/** The message sent when the sender tries to jail someone in a cell and there aren't any cells to suggest. */
/**
* The message sent when the sender tries to jail someone in a cell and there aren't any cells to suggest.
*/
NOEMPTYCELLS("jailing"),
/** The message sent to the sender when they list all the prisoners in a jail which has no prisoners. */
/**
* The message sent to the sender when they list all the prisoners in a jail which has no prisoners.
*/
NOPRISONERS("jailing"),
/** The message sent when a player is not jailed and the sender is trying to see/do something about it. */
/**
* The message sent when a player is not jailed and the sender is trying to see/do something about it.
*/
NOTJAILED("jailing"),
/** The message sent to the sender when they mute a prisoner. */
/**
* The message sent to the sender when they mute a prisoner.
*/
NOWMUTED("jailing"),
/** The message sent to the sender when they unmute a prisoner. */
/**
* The message sent to the sender when they unmute a prisoner.
*/
NOWUNMUTED("jailing"),
/** The message sent to the jailer when they jail someone offline. */
/**
* The message sent to the jailer when they jail someone offline.
*/
OFFLINEJAIL("jailing"),
/** The message sent to the jailer when they jail someone who is online. */
/**
* The message sent to the jailer when they jail someone who is online.
*/
ONLINEJAIL("jailing"),
/** The message sent to the jailer when they jail someone who has never played before. */
/**
* The message sent to the jailer when they jail someone who has never played before.
*/
PLAYERHASNEVERPLAYEDBEFORE("jailing"),
/** The message sent when finding out how much time a prisoner has. */
/**
* The message sent when finding out how much time a prisoner has.
*/
PRISONERSTIME("jailing"),
/** The message sent to the prisoner when they try to do something but it is protected. */
/**
* The message sent to the prisoner when they try to do something but it is protected.
*/
PROTECTIONMESSAGE("jailing"),
/** The message sent to the prisoner when they try to do something and it is protected, but no penalty. */
/**
* The message sent to the prisoner when they try to do something and it is protected, but no penalty.
*/
PROTECTIONMESSAGENOPENALTY("jailing"),
/** The message sent to the sender when they need to provide a player. */
/**
* The message sent to the sender when they need to provide a player.
*/
PROVIDEAPLAYER("jailing"),
/** The message sent to the sender when they need to provide a jail. */
/**
* The message sent to the sender when they need to provide a jail.
*/
PROVIDEAJAIL("jailing"),
/** The message sent to someone trying to jail someone else with a jail stick that requires health below a certain amount. */
/**
* The message sent to someone trying to jail someone else with a jail stick that requires health below a certain amount.
*/
RESISTEDARRESTJAILER("jailing"),
/** The message sent to the person someone else is trying to jail that requires their health below a certain amount. */
/**
* The message sent to the person someone else is trying to jail that requires their health below a certain amount.
*/
RESISTEDARRESTPLAYER("jailing"),
/** The message sent when to a prisoner about their status in jail. */
/**
* The message sent when to a prisoner about their status in jail.
*/
STATUS("jailing"),
/** The message sent to the sender of a command when suggesting a cell. */
/**
* The message sent to the sender of a command when suggesting a cell.
*/
SUGGESTEDCELL("jailing"),
/** The message sent to the sender when they teleport someone to a jail's teleport in location. */
/**
* The message sent to the sender when they teleport someone to a jail's teleport in location.
*/
TELEIN("jailing"),
/** The message sent to the sender when they teleport someone to a jail's teleport out location. */
/**
* The message sent to the sender when they teleport someone to a jail's teleport out location.
*/
TELEOUT("jailing"),
/** The message sent to the sender when they transfer all a jail's prisoners to another jail. */
/**
* The message sent to the sender when they transfer all a jail's prisoners to another jail.
*/
TRANSFERALLCOMPLETE("jailing"),
/** The message sent when another plugin cancels the transferring but doesn't provide a reason why. */
/**
* The message sent when another plugin cancels the transferring but doesn't provide a reason why.
*/
TRANSFERCANCELLEDBYANOTHERPLUGIN("jailing"),
/** The message sent to the sender when they transfer someone to a jail and a cell. */
/**
* The message sent to the sender when they transfer someone to a jail and a cell.
*/
TRANSFERCOMPLETECELL("jailing"),
/** The message sent to the sender when they transfer someone to a jail. */
/**
* The message sent to the sender when they transfer someone to a jail.
*/
TRANSFERCOMPLETENOCELL("jailing"),
/** The message sent to the player when they get transferred to a new jail. */
/**
* The message sent to the player when they get transferred to a new jail.
*/
TRANSFERRED("jailing"),
/** The message sent when players are released from jail. */
/**
* The message sent when players are released from jail.
*/
UNJAILED("jailing"),
/** The message sent to the person who released a prisoner from jail. */
/**
* The message sent to the person who released a prisoner from jail.
*/
UNJAILSUCCESS("jailing"),
/** The message sent when you jailing offline players is not allowed. */
/**
* The message sent when you jailing offline players is not allowed.
*/
UNALLOWEDTOJAILOFFLINE("jailing"),
/** The message went when an offline player is unjailed. */
/**
* The message went when an offline player is unjailed.
*/
WILLBEUNJAILED("jailing"),
/** The message sent when trying to jail a player in an unloaded world. */
/**
* The message sent when trying to jail a player in an unloaded world.
*/
WORLDUNLOADED("jailing"),
/** The message sent when a player joins and is jailed in a world that is unloaded. */
/**
* The message sent when a player joins and is jailed in a world that is unloaded.
*/
WORLDUNLOADEDKICK("jailing"),
/** The message sent to the sender when they check their jail status and they aren't jailed. */
/**
* The message sent to the sender when they check their jail status and they aren't jailed.
*/
YOUARENOTJAILED("jailing"),
// Handcuffing section
/** The message sent to the sender when trying to handcuff someone who can't be. */
/**
* The message sent to the sender when trying to handcuff someone who can't be.
*/
CANTBEHANDCUFFED("handcuffing"),
/** The message sent to the sender whenever they try to handcuff someone who is in jail. */
/**
* The message sent to the sender whenever they try to handcuff someone who is in jail.
*/
CURRENTLYJAILEDHANDCUFF("handcuffing", "currentlyjailed"),
/** The message sent to the sender when the player doesn't have any handcuffs. */
/**
* The message sent to the sender when the player doesn't have any handcuffs.
*/
NOTHANDCUFFED("handcuffing"),
/** The message sent to the handcuff on a successful handcuffing. */
/**
* The message sent to the handcuff on a successful handcuffing.
*/
HANDCUFFSON("handcuffing"),
/** The message sent when players are handcuffed. */
/**
* The message sent when players are handcuffed.
*/
HANDCUFFED("handcuffing"),
/** The message sent to the player who has release handcuffs. */
/**
* The message sent to the player who has release handcuffs.
*/
HANDCUFFSRELEASED("handcuffing"),
/** The message sent when the player has his/her handcuffs removed. */
/**
* The message sent when the player has his/her handcuffs removed.
*/
UNHANDCUFFED("handcuffing"),
// General section, used by different parts
/** Part message of any messages which require 'all the jails' or such. */
/**
* Part message of any messages which require 'all the jails' or such.
*/
ALLJAILS("general"),
/** The one line on signs when the cell is empty. */
/**
* The one line on signs when the cell is empty.
*/
CELLEMPTYSIGN("general"),
/** The message sent to the sender whenever they try to remove a cell but was unsuccessful due to a prisoner. */
/**
* The message sent to the sender whenever they try to remove a cell but was unsuccessful due to a prisoner.
*/
CELLREMOVALUNSUCCESSFUL("general"),
/** The message sent whenever a cell is successfully removed. */
/**
* The message sent whenever a cell is successfully removed.
*/
CELLREMOVED("general"),
/** The message sent when cleaning our cell signs. */
/**
* The message sent when cleaning our cell signs.
*/
CLEANEDSIGNS("general"),
/** The message sent when seeing what signs are invalid. */
/**
* The message sent when seeing what signs are invalid.
*/
INVALIDSIGNS("general"),
/** The line on a cell's sign when the prisoner is jailed forever. */
/**
* The line on a cell's sign when the prisoner is jailed forever.
*/
JAILEDFOREVERSIGN("general"),
/** The simple word jailing to be put in other parts. */
/**
* The simple word jailing to be put in other parts.
*/
JAILING("general"),
/** The message sent to the sender when they try to remove a jail but there are still prisoners in there. */
/**
* The message sent to the sender when they try to remove a jail but there are still prisoners in there.
*/
JAILREMOVALUNSUCCESSFUL("general"),
/** The message sent whenever a jail is successfully removed. */
/**
* The message sent whenever a jail is successfully removed.
*/
JAILREMOVED("general"),
/** The message sent whenever a player toggles using jail stick to disabled. */
/**
* The message sent whenever a player toggles using jail stick to disabled.
*/
JAILSTICKDISABLED("general"),
/** The message sent whenever a player toggles using jail stick to enabled. */
/**
* The message sent whenever a player toggles using jail stick to enabled.
*/
JAILSTICKENABLED("general"),
/** The message sent whenever a player tries to toggle using jail stick but the config has it disabled. */
/**
* The message sent whenever a player tries to toggle using jail stick but the config has it disabled.
*/
JAILSTICKUSAGEDISABLED("general"),
/** Message sent when doing something that requires a cell but the given name of a cell doesn't exist. */
/**
* Message sent when doing something that requires a cell but the given name of a cell doesn't exist.
*/
NOCELL("general"),
/** Message sent when needing a cell or something and there are no cells. */
/**
* Message sent when needing a cell or something and there are no cells.
*/
NOCELLS("general"),
/** Message sent when no invalid signs were found. */
/**
* Message sent when no invalid signs were found.
*/
NOINVALIDSIGNS("general"),
/** The message sent whenever the sender does something which the jail does not found. */
/**
* The message sent whenever the sender does something which the jail does not found.
*/
NOJAIL("general"),
/** The message sent whenever the sender does something and there are no jails. */
/**
* The message sent whenever the sender does something and there are no jails.
*/
NOJAILS("general"),
/** The message sent whenever the sender/player doesn't have permission. */
/**
* The message sent whenever the sender/player doesn't have permission.
*/
NOPERMISSION("general"),
/** The message sent whenever the sender/player supplies a number format that is incorrect. */
/**
* The message sent whenever the sender/player supplies a number format that is incorrect.
*/
NUMBERFORMATINCORRECT("general"),
/** The message sent whenever something is done that needs a player but doesn't have it. */
/**
* The message sent whenever something is done that needs a player but doesn't have it.
*/
PLAYERCONTEXTREQUIRED("general"),
/** The message sent whenever an online player is required but not found. */
/**
* The message sent whenever an online player is required but not found.
*/
PLAYERNOTONLINE("general"),
/** The message sent to the sender when the plugin data has been reloaded. */
/**
* The message sent to the sender when the plugin data has been reloaded.
*/
PLUGINRELOADED("general"),
/** The message sent to the sender of a command when the plugin didn't start correct. */
/**
* The message sent to the sender of a command when the plugin didn't start correct.
*/
PLUGINNOTLOADED("general"),
/** The message sent whenever the prisoners are cleared from jail(s). */
/**
* The message sent whenever the prisoners are cleared from jail(s).
*/
PRISONERSCLEARED("general"),
/** The format we should use when entering a record into flatfile or showing it. */
/**
* The format we should use when entering a record into flatfile or showing it.
*/
RECORDENTRY("general"),
/** The message format sent saying how many times a user has been jailed. */
/**
* The message format sent saying how many times a user has been jailed.
*/
RECORDTIMESJAILED("general"),
/** The simple word: sign. */
/**
* The simple word: sign.
*/
SIGN("general"),
/** The message sent when the signs are refreshed. */
/**
* The message sent when the signs are refreshed.
*/
SIGNSREFRESHED("general"),
/** The format of the time entry we should use for the record entries. */
/**
* The format of the time entry we should use for the record entries.
*/
TIMEFORMAT("general"),
/** The simple word transferring to be put in other parts. */
/**
* The simple word transferring to be put in other parts.
*/
TRANSFERRING("general"),
/** The message sent whenever someone does a command we don't know. */
/**
* The message sent whenever someone does a command we don't know.
*/
UNKNOWNCOMMAND("general"),
// Jail pay
/** The message sent when the jail pay portion is not enabled. */
/**
* The message sent when the jail pay portion is not enabled.
*/
PAYNOTENABLED("jailpay", "notenabled"),
/** The message sent when finding out how much it costs. */
/**
* The message sent when finding out how much it costs.
*/
PAYCOST("jailpay", "cost"),
/** The message sent when finding out how much it costs and they are jailed forever. */
/**
* The message sent when finding out how much it costs and they are jailed forever.
*/
PAYCOSTINFINITE("jailpay", "costinfinite"),
/** The message sent when someone tries to pay a negative amount. */
/**
* The message sent when someone tries to pay a negative amount.
*/
PAYNONEGATIVEAMOUNTS("jailpay", "nonegativeamounts"),
/** The message sent when someone is jailed and tries to pay for someone else. */
/**
* The message sent when someone is jailed and tries to pay for someone else.
*/
PAYCANTPAYWHILEJAILED("jailpay", "cantpayforotherswhilejailed"),
/** The message sent whenever someone tries to pay an amount they don't have. */
/**
* The message sent whenever someone tries to pay an amount they don't have.
*/
PAYNOTENOUGHMONEY("jailpay", "notenoughmoney"),
/** The message sent when they try to pay an amount but it isn't enough for the jailing sentence. */
/**
* The message sent when they try to pay an amount but it isn't enough for the jailing sentence.
*/
PAYNOTENOUGHMONEYPROVIDED("jailpay", "notenoughmoneyprovided"),
/** The message sent when they pay and get released. */
/**
* The message sent when they pay and get released.
*/
PAYPAIDRELEASED("jailpay", "paidreleased"),
/** The message sent when they pay for someone else and release them. */
/**
* The message sent when they pay for someone else and release them.
*/
PAYPAIDRELEASEDELSE("jailpay", "paidreleasedelse"),
/** The message sent when they pay and lower their time. */
/**
* The message sent when they pay and lower their time.
*/
PAYPAIDLOWEREDTIME("jailpay", "paidloweredtime"),
/** The message sent when they pay and lower someone else's time. */
/**
* The message sent when they pay and lower someone else's time.
*/
PAYPAIDLOWEREDTIMEELSE("jailpay", "paidloweredtimeelse"),
// Jail vote
/** The header sent when broadcasting a new jail vote. */
/**
* The header sent when broadcasting a new jail vote.
*/
VOTEBROADCASTHEADER("jailvote.broadcast", "header"),
/** The footer sent when broadcasting a new jail vote. */
/**
* The footer sent when broadcasting a new jail vote.
*/
VOTEBROADCASTFOOTER("jailvote.broadcast", "footer"),
/** Line1 of the broadcast message sent when a new jail vote is happening. */
/**
* Line1 of the broadcast message sent when a new jail vote is happening.
*/
VOTEBROADCASTLINE1("jailvote.broadcast", "line1"),
/** Line2 of the broadcast message sent when a new jail vote is happening. */
/**
* Line2 of the broadcast message sent when a new jail vote is happening.
*/
VOTEBROADCASTLINE2("jailvote.broadcast", "line2"),
/** Line3 of the broadcast message sent when a new jail vote is happening. */
/**
* Line3 of the broadcast message sent when a new jail vote is happening.
*/
VOTEBROADCASTLINE3("jailvote.broadcast", "line3"),
/** Line4 of the broadcast message sent when a new jail vote is happening. */
/**
* Line4 of the broadcast message sent when a new jail vote is happening.
*/
VOTEBROADCASTLINE4("jailvote.broadcast", "line4"),
/** The message sent when someone tries to vote for a player when a vote isn't running. */
/**
* The message sent when someone tries to vote for a player when a vote isn't running.
*/
VOTENOVOTEFORTHATPLAYER("jailvote", "novotegoingforthatplayer"),
/** The message sent to a player who tries to start a vote to jail someone and doesn't have permission. */
/**
* The message sent to a player who tries to start a vote to jail someone and doesn't have permission.
*/
VOTENOPERMISSIONTOSTART("jailvote", "nopermissiontostartvote"),
/** The message sent when jail vote is not enabled. */
/**
* The message sent when jail vote is not enabled.
*/
VOTENOTENABLED("jailvote", "notenabled"),
/** The message sent whenever someone's vote is not successful. */
/**
* The message sent whenever someone's vote is not successful.
*/
VOTEUNSUCCESSFUL("jailvote", "voteunsuccessful"),
/** The message sent whenever a player successfully votes no. */
/**
* The message sent whenever a player successfully votes no.
*/
VOTENOSUCCESS("jailvote", "votenosuccessful"),
/** The message sent whenever a player successfully votes yes. */
/**
* The message sent whenever a player successfully votes yes.
*/
VOTEYESSUCCESS("jailvote", "voteyessuccessful"),
/** The message broadcasted whenever a vote is tied. */
/**
* The message broadcasted whenever a vote is tied.
*/
VOTESTIED("jailvote", "votestied"),
/** The message broadcasted whenever there are more no votes. */
/**
* The message broadcasted whenever there are more no votes.
*/
VOTESSAIDNO("jailvote", "morenovotes"),
/** The message broadcasted whenever there aren't the minimum yes votes. */
/**
* The message broadcasted whenever there aren't the minimum yes votes.
*/
VOTESNOTENOUGHYES("jailvote", "notenoughyes"),
/** The message broadcasted whenever the player the vote is for is no longer online. */
/**
* The message broadcasted whenever the player the vote is for is no longer online.
*/
VOTEPLAYERNOLONGERONLINE("jailvote", "playernolongeronline"),
/** The message sent when a player tries to vote again for someone. */
/**
* The message sent when a player tries to vote again for someone.
*/
VOTEALREADYVOTEDFOR("jailvote", "alreadyvotedfor"),
// Confirming action messages.
/** The message sent when the sender is already confirming something. */
/**
* The message sent when the sender is already confirming something.
*/
ALREADY("confirm"),
/** The message sent when their confirmation has expired. */
/**
* The message sent when their confirmation has expired.
*/
EXPIRED("confirm"),
/** The message sent to the sender when they tried to confirm something but don't have anything to confirm. */
/**
* The message sent to the sender when they tried to confirm something but don't have anything to confirm.
*/
NOTHING("confirm"),
/** The message sent to the sender when they type something and need to confirm it. */
/**
* The message sent to the sender when they type something and need to confirm it.
*/
START("confirm");
private String section, name, path;
private final String section;
private final String name;
private final String path;
private static YamlConfiguration lang;
Lang(String section) {
@ -282,24 +530,27 @@ public enum Lang {
/**
* Sets the {@link YamlConfiguration} instance to use.
*
* @param file
* of the language to use.
* @param file of the language to use.
*/
public static void setFile(YamlConfiguration file) {
lang = file;
}
/** Gets the {@link YamlConfiguration} instance. */
/**
* Gets the {@link YamlConfiguration} instance.
*/
public static YamlConfiguration getFile() {
return lang;
}
/** Writes any new language settings to the language file in storage. */
/**
* Writes any new language settings to the language file in storage.
*/
public static boolean writeNewLanguage(YamlConfiguration newLang) {
boolean anything = false;
for(Lang l : values()) {
if(!lang.contains(l.path)) {
for (Lang l : values()) {
if (!lang.contains(l.path)) {
lang.set(l.path, newLang.getString(l.path));
anything = true;
}
@ -308,23 +559,26 @@ public enum Lang {
return anything;
}
/** Returns the message in the language, no variables are replaced. */
/**
* Returns the message in the language, no variables are replaced.
*/
public String get() {
return get(new String[] {});
return get(new String[]{});
}
/** Returns the message in the language, no variables are replaced. */
/**
* Returns the message in the language, no variables are replaced.
*/
public String get(Lang langString) {
return get(new String[] { langString.get() });
return get(langString.get());
}
/**
* Returns the message in the language, with the provided variables being replaced.
*
* @param variables
* All the variables to replace, in order from 0 to however many.
* @param variables All the variables to replace, in order from 0 to however many.
* @return The message as a colorful message or an empty message if that
* isn't defined in the language file.
* isn't defined in the language file.
*/
public String get(String... variables) {
String message = lang.getString(path);

View File

@ -43,13 +43,13 @@ public enum Settings {
JAILEDSTOREINVENTORY("jailing.jail.inventory.store"),
JAILPAYENABLED("jailpay.enabled"),
JAILPAYITEM("jailpay.item"),
JAILPAYPRICEPERMINUTE ("jailpay.pricePerMinute"),
JAILPAYPRICEINFINITE ("jailpay.priceInfinite"),
JAILVOTEENABLED ("jailvote.enabled"),
JAILVOTETIMER ("jailvote.voteTimer"),
JAILMINYESVOTES ("jailvote.minimumYes"),
JAILVOTEREASON ("jailvote.reason"),
JAILVOTETIME ("jailvote.time"),
JAILPAYPRICEPERMINUTE("jailpay.pricePerMinute"),
JAILPAYPRICEINFINITE("jailpay.priceInfinite"),
JAILVOTEENABLED("jailvote.enabled"),
JAILVOTETIMER("jailvote.voteTimer"),
JAILMINYESVOTES("jailvote.minimumYes"),
JAILVOTEREASON("jailvote.reason"),
JAILVOTETIME("jailvote.time"),
LANGUAGE("system.language"),
LOGJAILINGTOCONSOLE("jailing.jail.log.console"),
LOGJAILINGTOPROFILE("jailing.jail.log.profile"),
@ -73,14 +73,15 @@ public enum Settings {
UPDATETIME("system.updates.time"),
USEBUKKITTIMER("system.useBukkitTimer");
private String path;
private final String path;
private Settings(String path) {
Settings(String path) {
this.path = path;
}
/**
* Gets the path this setting is in config.
*
* @return The path where this setting resides in the config.
*/
public String getPath() {

View File

@ -1,35 +1,34 @@
package com.graywolf336.jail.events;
import com.graywolf336.jail.JailMain;
import org.bukkit.event.Event;
import org.bukkit.event.HandlerList;
import com.graywolf336.jail.JailMain;
/**
* Event thrown after the plugin is reloaded, internal usage only.
*
*
* <p>
* <p>
*
* This event is called right after the plugin and mostly everything has reloaded.
* We listen to this event for updating various items in classes which are only
* listeners so we don't store instances of them elsewhere.
*
*
* @author graywolf336
* @since 3.0.0
* @version 1.0.0
* @since 3.0.0
*/
public class JailPluginReloadedEvent extends Event {
private static final HandlerList handlers = new HandlerList();
private JailMain plugin;
private final JailMain plugin;
public JailPluginReloadedEvent(JailMain main) {
this.plugin = main;
}
public JailMain getPlugin() {
return this.plugin;
}
public static HandlerList getHandlerList() {
return handlers;
}

View File

@ -1,36 +1,35 @@
package com.graywolf336.jail.events;
import org.bukkit.event.Event;
import org.bukkit.event.HandlerList;
import com.graywolf336.jail.beans.Jail;
import com.graywolf336.jail.beans.Prisoner;
import com.graywolf336.jail.interfaces.ICell;
import org.bukkit.event.Event;
import org.bukkit.event.HandlerList;
/**
* Event thrown when a prisoner is offline put will be put into jail next time they come online.
*
*
* <p>
* <p>
*
* This event is called before everything for the jailing takes place, as the player is offline.
* This event is called for informative purposes, see {@link PrePrisonerJailedEvent}
* for the event called before they teleported in and all that fancy stuff.
*
*
* @author graywolf336
* @since 3.0.0
* @version 1.0.0
* @since 3.0.0
*/
public class OfflinePrisonerJailedEvent extends Event {
private static final HandlerList handlers = new HandlerList();
private Jail jail;
private ICell cell;
private Prisoner prisoner;
private final Jail jail;
private final ICell cell;
private final Prisoner prisoner;
/**
* Creates a new {@link OfflinePrisonerJailedEvent prisoner jailed event} for the given prisoner.
*
* @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 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 prisoner The prisoner data.
*/
public OfflinePrisonerJailedEvent(Jail jail, ICell cell, Prisoner prisoner) {
@ -39,32 +38,44 @@ public class OfflinePrisonerJailedEvent extends Event {
this.prisoner = prisoner;
}
/** Gets the {@link Jail} this prisoner is being sent to. */
/**
* Gets the {@link Jail} this prisoner is being sent to.
*/
public Jail getJail() {
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 ICell getCell() {
return this.cell;
}
/** Checks if there was a cell involved. */
/**
* Checks if there was a cell involved.
*/
public boolean hasCell() {
return this.cell != null;
}
/** Gets the {@link Prisoner} data for this prisoner. */
/**
* Gets the {@link Prisoner} data for this prisoner.
*/
public Prisoner getPrisoner() {
return this.prisoner;
}
/** Gets the jailer who jailed this prisoner. */
/**
* Gets the jailer who jailed this prisoner.
*/
public String getJailer() {
return this.prisoner.getJailer();
}
/** Gets the reason the prisoner was jailed. */
/**
* Gets the reason the prisoner was jailed.
*/
public String getReason() {
return this.prisoner.getReason();
}

View File

@ -1,46 +1,45 @@
package com.graywolf336.jail.events;
import org.bukkit.entity.Player;
import org.bukkit.event.Cancellable;
import org.bukkit.event.Event;
import org.bukkit.event.HandlerList;
import com.graywolf336.jail.beans.Cell;
import com.graywolf336.jail.beans.Jail;
import com.graywolf336.jail.beans.Prisoner;
import com.graywolf336.jail.beans.Stick;
import com.graywolf336.jail.interfaces.ICell;
import org.bukkit.entity.Player;
import org.bukkit.event.Cancellable;
import org.bukkit.event.Event;
import org.bukkit.event.HandlerList;
/**
* Event thrown before we a player is jailed by someone hitting them with a {@link Stick jail stick}.
*
*
* <p>
* <p>
*
* This event is called right before we actually jail a player, and is cancellable.
*
*
* @author graywolf336
* @since 3.0.0
* @version 1.0.0
* @since 3.0.0
*/
public class PrePrisonerJailedByJailStickEvent extends Event implements Cancellable {
private static final HandlerList handlers = new HandlerList();
private boolean cancelled = false;
private Jail jail;
private final Jail jail;
private ICell cell;
private Prisoner prisoner;
private Player player;
private final Prisoner prisoner;
private final Player player;
private String jailer, cancelMsg;
private Stick stick;
private final Stick stick;
/**
* 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 cell The cell we're going to be sending the prisoner to, can be null.
*
* @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 prisoner The prisoner data.
* @param player The player being jailed.
* @param jailer The name of what jailed this prisoner.
* @param stick The {@link Stick jail stick} used.
* @param player The player being jailed.
* @param jailer The name of what jailed this prisoner.
* @param stick The {@link Stick jail stick} used.
*/
public PrePrisonerJailedByJailStickEvent(Jail jail, ICell cell, Prisoner prisoner, Player player, String jailer, Stick stick) {
this.jail = jail;
@ -52,71 +51,95 @@ public class PrePrisonerJailedByJailStickEvent extends Event implements Cancella
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() {
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 ICell getCell() {
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) {
this.cell = cell;
}
/** Checks if there is a cell involved. */
/**
* Checks if there is a cell involved.
*/
public boolean hasCell() {
return this.cell != null;
return this.cell != null;
}
/** Gets the {@link Prisoner} data for this prisoner. */
/**
* Gets the {@link Prisoner} data for this prisoner.
*/
public Prisoner getPrisoner() {
return this.prisoner;
}
/** Gets the instance of the player being jailed. */
/**
* Gets the instance of the player being jailed.
*/
public Player getPlayer() {
return this.player;
}
/** Gets the jailer who jailed this prisoner. */
/**
* Gets the jailer who jailed this prisoner.
*/
public String getJailer() {
return this.jailer;
}
/**
* Sets who jailed this prisoner.
*
*
* @param jailer The name to put who is the jailer for this prisoner.
*/
public void setJailer(String jailer) {
this.jailer = jailer;
}
/** Gets the jail stick used. */
/**
* Gets the jail stick used.
*/
public Stick getJailStick() {
return this.stick;
}
/** Checks whether this event is cancelled or not. */
/**
* Checks whether this event is cancelled or not.
*/
public boolean isCancelled() {
return this.cancelled;
}
/** Sets whether this event should be cancelled. */
/**
* Sets whether this event should be cancelled.
*/
public void setCancelled(boolean cancel) {
this.cancelled = cancel;
}
/** Returns the cancelled message. */
/**
* Returns the cancelled message.
*/
public String getCancelledMessage() {
return this.cancelMsg;
}
/** Sets the cancelled message. */
/**
* Sets the cancelled message.
*/
public void setCancelledMessage(String msg) {
this.cancelMsg = msg;
}

View File

@ -1,45 +1,44 @@
package com.graywolf336.jail.events;
import org.bukkit.entity.Player;
import org.bukkit.event.Cancellable;
import org.bukkit.event.Event;
import org.bukkit.event.HandlerList;
import com.graywolf336.jail.beans.Cell;
import com.graywolf336.jail.beans.Jail;
import com.graywolf336.jail.beans.Prisoner;
import com.graywolf336.jail.interfaces.ICell;
import org.bukkit.entity.Player;
import org.bukkit.event.Cancellable;
import org.bukkit.event.Event;
import org.bukkit.event.HandlerList;
/**
* Event thrown before we are jailing a player, both offline and online players.
*
*
* <p>
* <p>
*
* This event is called right before we actually jail a player, and is cancellable, whether the player is offline or online, getPlayer() will always return null if isOnline() return false.
*
*
* @author graywolf336
* @since 3.0.0
* @version 1.0.0
* @since 3.0.0
*/
public class PrePrisonerJailedEvent extends Event implements Cancellable {
private static final HandlerList handlers = new HandlerList();
private boolean cancelled = false;
private boolean online;
private Jail jail;
private final boolean online;
private final Jail jail;
private ICell cell;
private Prisoner prisoner;
private Player player;
private final Prisoner prisoner;
private final Player player;
private String jailer, cancelMsg;
/**
* 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 c The cell we're going to be sending the prisoner to, can be null.
*
* @param jail The jail the prisoner will be jailed at.
* @param c The cell we're going to be sending the prisoner to, can be null.
* @param prisoner The prisoner data.
* @param player The player being jailed.
* @param online Whether the player is online or not.
* @param jailer The name of what jailed this prisoner.
* @param player The player being jailed.
* @param online Whether the player is online or not.
* @param jailer The name of what jailed this prisoner.
*/
public PrePrisonerJailedEvent(Jail jail, ICell c, Prisoner prisoner, Player player, boolean online, String jailer) {
this.jail = jail;
@ -51,85 +50,111 @@ public class PrePrisonerJailedEvent extends Event implements Cancellable {
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() {
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 ICell getCell() {
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) {
this.cell = cell;
}
/** Checks if there is a cell involved. */
/**
* Checks if there is a cell involved.
*/
public boolean hasCell() {
return this.cell != null;
return this.cell != null;
}
/** Gets the {@link Prisoner} data for this prisoner. */
/**
* Gets the {@link Prisoner} data for this prisoner.
*/
public Prisoner getPrisoner() {
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() {
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() {
return this.online;
}
/** Gets the jailer who jailed this prisoner. */
/**
* Gets the jailer who jailed this prisoner.
*/
public String getJailer() {
return this.jailer;
}
/**
* Sets who jailed this prisoner.
*
*
* @param jailer The name to put who is the jailer for this prisoner.
*/
public void setJailer(String jailer) {
this.jailer = jailer;
}
/** Gets the reason the player was jailed for. */
/**
* Gets the reason the player was jailed for.
*/
public String getReason() {
return this.prisoner.getReason();
}
/**
* Sets the reason the prisoner was jailed for.
*
*
* @param reason the prisoner was jailed for.
*/
public void setReason(String reason) {
this.prisoner.setReason(reason);
}
/** Checks whether this event is cancelled or not. */
/**
* Checks whether this event is cancelled or not.
*/
public boolean isCancelled() {
return this.cancelled;
}
/** Sets whether this event should be cancelled. */
/**
* Sets whether this event should be cancelled.
*/
public void setCancelled(boolean cancel) {
this.cancelled = cancel;
}
/** Returns the cancelled message. */
/**
* Returns the cancelled message.
*/
public String getCancelledMessage() {
return this.cancelMsg;
}
/** Sets the cancelled message. */
/**
* Sets the cancelled message.
*/
public void setCancelledMessage(String msg) {
this.cancelMsg = msg;
}

View File

@ -1,40 +1,39 @@
package com.graywolf336.jail.events;
import org.bukkit.entity.Player;
import org.bukkit.event.Event;
import org.bukkit.event.HandlerList;
import com.graywolf336.jail.beans.Jail;
import com.graywolf336.jail.beans.Prisoner;
import com.graywolf336.jail.interfaces.ICell;
import org.bukkit.entity.Player;
import org.bukkit.event.Event;
import org.bukkit.event.HandlerList;
/**
* Event thrown after a prisoner is released.
*
*
* <p>
* <p>
*
* This event is called before everything for the releasing takes place.
* This event is called for informative purposes, see {@link PrisonerReleasedEvent}
* for the event called after they get teleported out and all that fancy stuff.
*
*
* @author graywolf336
* @since 3.0.0
* @version 1.0.0
* @since 3.0.0
*/
public class PrePrisonerReleasedEvent extends Event {
private static final HandlerList handlers = new HandlerList();
private Jail jail;
private ICell cell;
private Prisoner prisoner;
private Player player;
private final Jail jail;
private final ICell cell;
private final Prisoner prisoner;
private final Player 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 cell The cell we're going to be sending the prisoner to, can be null.
*
* @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 prisoner The prisoner data.
* @param player The player being jailed.
* @param player The player being jailed.
*/
public PrePrisonerReleasedEvent(Jail jail, ICell cell, Prisoner prisoner, Player player) {
this.jail = jail;
@ -43,27 +42,37 @@ public class PrePrisonerReleasedEvent extends Event {
this.player = player;
}
/** Gets the {@link Jail} this prisoner is coming from. */
/**
* Gets the {@link Jail} this prisoner is coming from.
*/
public Jail getJail() {
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 ICell getCell() {
return this.cell;
}
/** Checks if there is a cell involved. */
/**
* Checks if there is a cell involved.
*/
public boolean hasCell() {
return this.cell != null;
return this.cell != null;
}
/** Gets the {@link Prisoner} data for this prisoner. */
/**
* Gets the {@link Prisoner} data for this prisoner.
*/
public Prisoner getPrisoner() {
return this.prisoner;
}
/** Gets the instance of the player being released. */
/**
* Gets the instance of the player being released.
*/
public Player getPlayer() {
return this.player;
}

View File

@ -1,44 +1,45 @@
package com.graywolf336.jail.events;
import com.graywolf336.jail.beans.Cell;
import com.graywolf336.jail.beans.Jail;
import com.graywolf336.jail.beans.Prisoner;
import org.bukkit.entity.Player;
import org.bukkit.event.Cancellable;
import org.bukkit.event.Event;
import org.bukkit.event.HandlerList;
import com.graywolf336.jail.beans.Cell;
import com.graywolf336.jail.beans.Jail;
import com.graywolf336.jail.beans.Prisoner;
/**
* Event thrown before we transfer a prisoner, both offline and online prisoner.
*
*
* <p>
* <p>
*
* This event is called right before we actually transfer a prisoner, and is cancellable, whether the prisoner is offline or online, getPlayer() will always return null if isOnline() return false.
*
*
* @author graywolf336
* @since 3.0.0
* @version 1.0.1
* @since 3.0.0
*/
public class PrePrisonerTransferredEvent extends Event implements Cancellable {
private static final HandlerList handlers = new HandlerList();
private boolean cancelled = false;
private Jail originalJail, targetJail;
private Cell originalCell, targetCell;
private Prisoner prisoner;
private Player player;
private final Jail originalJail;
private Jail targetJail;
private final Cell originalCell;
private Cell targetCell;
private final Prisoner prisoner;
private final Player player;
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.
*
*
* @param originalJail The jail the prisoner is coming from.
* @param originalCell The cell the prisoner is coming from, can be null.
* @param targetJail The jail the prisoner is going to.
* @param targetCell The cell the prisoner is going to, can be null.
* @param prisoner The prisoner data.
* @param player The player being jailed.
* @param transferor The name of what is transferring this prisoner.
* @param targetJail The jail the prisoner is going to.
* @param targetCell The cell the prisoner is going to, can be null.
* @param prisoner The prisoner data.
* @param player The player being jailed.
* @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) {
this.originalJail = originalJail;
@ -51,52 +52,63 @@ public class PrePrisonerTransferredEvent extends Event implements Cancellable {
this.cancelMsg = "";
}
/** Gets the {@link Jail} this prisoner is coming from. */
/**
* Gets the {@link Jail} this prisoner is coming from.
*/
public Jail getOriginalJail() {
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() {
return this.originalCell;
}
/** Checks if there is an original cell involved. */
/**
* Checks if there is an original cell involved.
*/
public boolean hasOriginalCell() {
return this.originalCell != null;
return this.originalCell != null;
}
/** Gets the {@link Jail} this prisoner is being transferred to. */
/**
* Gets the {@link Jail} this prisoner is being transferred to.
*/
public Jail getTargetJail() {
return this.targetJail;
}
/**
* 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.
*/
public void setTargetJail(Jail 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.
* <p>
* Will return null if the cell is not in the targetJail.
*/
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;
}
/** Checks if there is a target cell involved. */
/**
* Checks if there is a target cell involved.
*/
public boolean hasTargetCell() {
return this.getTargetCell() != null;
return this.getTargetCell() != null;
}
/**
* 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.
*/
public void setTargetCell(Cell cell) {
@ -105,7 +117,7 @@ public class PrePrisonerTransferredEvent extends Event implements Cancellable {
/**
* Gets the {@link Prisoner} data for this prisoner.
*
*
* @return the {@link Prisoner} instance
*/
public Prisoner getPrisoner() {
@ -114,7 +126,7 @@ public class PrePrisonerTransferredEvent extends Event implements Cancellable {
/**
* Gets the instance of the player being transferred <strong>but will return null if they're not online</strong>.
*
*
* @return the {@link Player} instance
*/
public Player getPlayer() {
@ -123,7 +135,7 @@ public class PrePrisonerTransferredEvent extends Event implements Cancellable {
/**
* Gets whether the prisoner being transferred is online or not.
*
*
* @return Whether the player is online or not
*/
public boolean isPlayerOnline() {
@ -132,7 +144,7 @@ public class PrePrisonerTransferredEvent extends Event implements Cancellable {
/**
* Gets the name of what is transferring this prisoner.
*
*
* @return name of the person who started the transfer
*/
public String getTransferor() {
@ -141,29 +153,37 @@ public class PrePrisonerTransferredEvent extends Event implements Cancellable {
/**
* Sets the prisoner whom the data should say jailed this prisoner.
*
*
* @param transferor The name to put who is the jailer for this prisoner.
*/
public void setTransferor(String transferor) {
this.transferor = transferor;
}
/** Checks whether this event is cancelled or not. */
/**
* Checks whether this event is cancelled or not.
*/
public boolean isCancelled() {
return this.cancelled;
}
/** Sets whether this event should be cancelled. */
/**
* Sets whether this event should be cancelled.
*/
public void setCancelled(boolean cancel) {
this.cancelled = cancel;
}
/** Returns the cancelled message. */
/**
* Returns the cancelled message.
*/
public String getCancelledMessage() {
return this.cancelMsg;
}
/** Sets the cancelled message. */
/**
* Sets the cancelled message.
*/
public void setCancelledMessage(String msg) {
this.cancelMsg = msg;
}

View File

@ -1,37 +1,36 @@
package com.graywolf336.jail.events;
import com.graywolf336.jail.beans.Cell;
import com.graywolf336.jail.beans.Jail;
import com.graywolf336.jail.beans.Prisoner;
import org.bukkit.entity.Player;
import org.bukkit.event.Event;
import org.bukkit.event.HandlerList;
import org.bukkit.event.entity.PlayerDeathEvent;
import com.graywolf336.jail.beans.Cell;
import com.graywolf336.jail.beans.Jail;
import com.graywolf336.jail.beans.Prisoner;
/**
* Event thrown when a prisoner dies.
*
*
* @author graywolf336
* @since 3.0.0
* @version 1.0.0
* @since 3.0.0
*/
public class PrisonerDeathEvent extends Event {
private static final HandlerList handlers = new HandlerList();
private PlayerDeathEvent event;
private Jail jail;
private Cell cell;
private Prisoner prisoner;
private Player player;
private final PlayerDeathEvent event;
private final Jail jail;
private final Cell cell;
private final Prisoner prisoner;
private final Player player;
/**
* Creates a new {@link PrisonerDeathEvent prisoner death event} for the given player.
*
* @param event The {@link PlayerDeathEvent} which triggered this event.
* @param jail The jail the prisoner is in.
* @param cell The cell the prisoner is in, can be null.
*
* @param event The {@link PlayerDeathEvent} which triggered this event.
* @param jail The jail the prisoner is in.
* @param cell The cell the prisoner is in, can be null.
* @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) {
this.event = event;
@ -41,32 +40,44 @@ public class PrisonerDeathEvent extends Event {
this.player = player;
}
/** Gets the {@link PlayerDeathEvent} which triggered this PrisonerDeathEvent. */
/**
* Gets the {@link PlayerDeathEvent} which triggered this PrisonerDeathEvent.
*/
public PlayerDeathEvent getPlayerDeathEvent() {
return this.event;
}
/** Gets the {@link Jail} this prisoner is in. */
/**
* Gets the {@link Jail} this prisoner is in.
*/
public Jail getJail() {
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() {
return this.cell;
}
/** Checks if there is a cell involved. */
/**
* Checks if there is a cell involved.
*/
public boolean hasCell() {
return this.cell != null;
return this.cell != null;
}
/** Gets the {@link Prisoner}'s data. */
/**
* Gets the {@link Prisoner}'s data.
*/
public Prisoner getPrisoner() {
return this.prisoner;
}
/** Gets the instance of the player who died. */
/**
* Gets the instance of the player who died.
*/
public Player getPlayer() {
return this.player;
}

View File

@ -1,40 +1,39 @@
package com.graywolf336.jail.events;
import org.bukkit.entity.Player;
import org.bukkit.event.Event;
import org.bukkit.event.HandlerList;
import com.graywolf336.jail.beans.Cell;
import com.graywolf336.jail.beans.Jail;
import com.graywolf336.jail.beans.Prisoner;
import org.bukkit.entity.Player;
import org.bukkit.event.Event;
import org.bukkit.event.HandlerList;
/**
* Event thrown after a prisoner is put into jail.
*
*
* <p>
* <p>
*
* This event is called after everything for the jailing takes place.
* This event is called for informative purposes, see {@link PrePrisonerJailedEvent}
* for the event called before they teleported in and all that fancy stuff.
*
*
* @author graywolf336
* @since 3.0.0
* @version 1.0.0
* @since 3.0.0
*/
public class PrisonerJailedEvent extends Event {
private static final HandlerList handlers = new HandlerList();
private Jail jail;
private Cell cell;
private Prisoner prisoner;
private Player player;
private final Jail jail;
private final Cell cell;
private final Prisoner prisoner;
private final Player player;
/**
* Creates a new {@link PrisonerJailedEvent prisoner jailed event} for the given player.
*
* @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 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 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) {
this.jail = jail;
@ -43,37 +42,51 @@ public class PrisonerJailedEvent extends Event {
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() {
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() {
return this.cell;
}
/** Checks if there was a cell involved. */
/**
* Checks if there was a cell involved.
*/
public boolean hasCell() {
return this.cell != null;
return this.cell != null;
}
/** Gets the {@link Prisoner} data for this prisoner. */
/**
* Gets the {@link Prisoner} data for this prisoner.
*/
public Prisoner getPrisoner() {
return this.prisoner;
}
/** Gets the instance of the player being jailed. */
/**
* Gets the instance of the player being jailed.
*/
public Player getPlayer() {
return this.player;
}
/** Gets the jailer who jailed this prisoner. */
/**
* Gets the jailer who jailed this prisoner.
*/
public String getJailer() {
return this.prisoner.getJailer();
}
/** Gets the reason the prisoner was jailed. */
/**
* Gets the reason the prisoner was jailed.
*/
public String getReason() {
return this.prisoner.getReason();
}

View File

@ -1,40 +1,39 @@
package com.graywolf336.jail.events;
import org.bukkit.entity.Player;
import org.bukkit.event.Event;
import org.bukkit.event.HandlerList;
import com.graywolf336.jail.beans.Cell;
import com.graywolf336.jail.beans.Jail;
import com.graywolf336.jail.beans.Prisoner;
import org.bukkit.entity.Player;
import org.bukkit.event.Event;
import org.bukkit.event.HandlerList;
/**
* Event thrown after a prisoner is released.
*
*
* <p>
* <p>
*
* This event is called after everything for the releasing takes place.
* This event is called for informative purposes, see {@link PrePrisonerReleasedEvent}
* for the event called before they teleported out and all that fancy stuff.
*
*
* @author graywolf336
* @since 3.0.0
* @version 1.0.0
* @since 3.0.0
*/
public class PrisonerReleasedEvent extends Event {
private static final HandlerList handlers = new HandlerList();
private Jail jail;
private Cell cell;
private Prisoner prisoner;
private Player player;
private final Jail jail;
private final Cell cell;
private final Prisoner prisoner;
private final Player player;
/**
* Creates a new {@link PrisonerReleasedEvent prisoner released event} for the given player.
*
* @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 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 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) {
this.jail = jail;
@ -43,27 +42,37 @@ public class PrisonerReleasedEvent extends Event {
this.player = player;
}
/** Gets the {@link Jail} this prisoner is coming from. */
/**
* Gets the {@link Jail} this prisoner is coming from.
*/
public Jail getJail() {
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() {
return this.cell;
}
/** Checks if there was a cell involved. */
/**
* Checks if there was a cell involved.
*/
public boolean hasCell() {
return this.cell != null;
return this.cell != null;
}
/** Gets the {@link Prisoner} data for this prisoner. */
/**
* Gets the {@link Prisoner} data for this prisoner.
*/
public Prisoner getPrisoner() {
return this.prisoner;
}
/** Gets the instance of the player being released. */
/**
* Gets the instance of the player being released.
*/
public Player getPlayer() {
return this.player;
}

View File

@ -1,39 +1,39 @@
package com.graywolf336.jail.events;
import com.graywolf336.jail.beans.Cell;
import com.graywolf336.jail.beans.Jail;
import com.graywolf336.jail.beans.Prisoner;
import org.bukkit.entity.Player;
import org.bukkit.event.Cancellable;
import org.bukkit.event.Event;
import org.bukkit.event.HandlerList;
import com.graywolf336.jail.beans.Cell;
import com.graywolf336.jail.beans.Jail;
import com.graywolf336.jail.beans.Prisoner;
/**
* Event thrown when a prisoner's time changes.
*
*
* @author graywolf336
* @since 3.0.0
* @version 1.0.0
* @since 3.0.0
*/
public class PrisonerTimeChangeEvent extends Event implements Cancellable {
private static final HandlerList handlers = new HandlerList();
private boolean cancelled = false;
private Jail jail;
private Cell cell;
private Prisoner prisoner;
private Player player;
private long before, after;
private final Jail jail;
private final Cell cell;
private final Prisoner prisoner;
private final Player player;
private final long before;
private long after;
/**
* Creates a new {@link PrisonerTimeChangeEvent prisoner time change event} for the given prisoner.
*
* @param jail The jail the prisoner is in.
* @param cell The cell the prisoner is in, can be null.
*
* @param jail The jail the prisoner is in.
* @param cell The cell the prisoner is in, can be null.
* @param prisoner The prisoner's data.
* @param player The player being jailed.
* @param before the time before it changed
* @param after the time after it changed
* @param player The player being jailed.
* @param before the time before it changed
* @param after the time after it changed
*/
public PrisonerTimeChangeEvent(Jail jail, Cell cell, Prisoner prisoner, Player player, long before, long after) {
this.jail = jail;
@ -44,67 +44,87 @@ public class PrisonerTimeChangeEvent extends Event implements Cancellable {
this.after = after;
}
/** Gets the {@link Jail} this prisoner is in. */
/**
* Gets the {@link Jail} this prisoner is in.
*/
public Jail getJail() {
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() {
return this.cell;
}
/** Checks if there is a cell involved. */
/**
* Checks if there is a cell involved.
*/
public boolean hasCell() {
return this.cell != null;
return this.cell != null;
}
/** Gets the {@link Prisoner}'s data. */
/**
* Gets the {@link Prisoner}'s data.
*/
public Prisoner getPrisoner() {
return this.prisoner;
}
/** Gets the instance of the player who died. */
/**
* Gets the instance of the player who died.
*/
public Player getPlayer() {
return this.player;
}
/** Gets the time the prisoner had before it changed. */
/**
* Gets the time the prisoner had before it changed.
*/
public long getTimeBeforeChange() {
return this.before;
return this.before;
}
/** Gets the time the prisoner will have after the change. */
/**
* Gets the time the prisoner will have after the change.
*/
public long getTimeAfterChange() {
return this.after;
return this.after;
}
/** Sets the time the prisoner will have after the change. */
/**
* Sets the time the prisoner will have after the change.
*/
public void setTimeAfterChange(long newtime) {
this.after = Math.max(0, newtime);
this.after = Math.max(0, newtime);
}
/**
* Gets the difference the change is making.
*
* <p />
*
* <p>
* <p/>
* <p>
* The change can be positive or negative. If it is positive then the
* time after is smaller than it was before. If it is negative then the
* time after is larger than it was before.
*
*
* @return The difference between the two time changes.
*/
public long getTimeDifference() {
return this.before - this.after;
return this.before - this.after;
}
/** Checks whether this event is cancelled or not. */
/**
* Checks whether this event is cancelled or not.
*/
public boolean isCancelled() {
return this.cancelled;
}
/** Sets whether this event should be cancelled. */
/**
* Sets whether this event should be cancelled.
*/
public void setCancelled(boolean cancel) {
this.cancelled = cancel;
}

View File

@ -1,40 +1,41 @@
package com.graywolf336.jail.events;
import org.bukkit.entity.Player;
import org.bukkit.event.Event;
import org.bukkit.event.HandlerList;
import com.graywolf336.jail.beans.Cell;
import com.graywolf336.jail.beans.Jail;
import com.graywolf336.jail.beans.Prisoner;
import org.bukkit.entity.Player;
import org.bukkit.event.Event;
import org.bukkit.event.HandlerList;
/**
* Event thrown after we transfer a prisoner, both an offline and an online prisoner.
*
*
* <p>
* <p>
*
* This event is called after we transfer the prisoner whether the prisoner is offline or online, getPlayer() will always return null if isOnline() return false.
*
*
* @author graywolf336
* @since 3.0.0
* @version 1.0.0
* @since 3.0.0
*/
public class PrisonerTransferredEvent extends Event {
private static final HandlerList handlers = new HandlerList();
private Jail originalJail, targetJail;
private Cell originalCell, targetCell;
private Prisoner prisoner;
private Player player;
private final Jail originalJail;
private final Jail targetJail;
private final Cell originalCell;
private final Cell targetCell;
private final Prisoner prisoner;
private final Player player;
/**
* 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 originalCell The cell the prisoner is coming from, can be null.
* @param targetJail The jail the prisoner went to.
* @param targetCell The cell the prisoner went to, can be null.
* @param prisoner The prisoner data.
* @param player The player being jailed.
* @param targetJail The jail the prisoner went to.
* @param targetCell The cell the prisoner went to, can be null.
* @param prisoner The prisoner data.
* @param player The player being jailed.
*/
public PrisonerTransferredEvent(Jail originalJail, Cell originalCell, Jail targetJail, Cell targetCell, Prisoner prisoner, Player player) {
this.originalJail = originalJail;
@ -45,51 +46,68 @@ public class PrisonerTransferredEvent extends Event {
this.player = player;
}
/** Gets the {@link Jail} this prisoner is coming from. */
/**
* Gets the {@link Jail} this prisoner is coming from.
*/
public Jail getOriginalJail() {
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() {
return this.originalCell;
}
/** Checks if there was an original cell involved. */
/**
* Checks if there was an original cell involved.
*/
public boolean hasOriginalCell() {
return this.originalCell != null;
return this.originalCell != null;
}
/** Gets the {@link Jail} this prisoner is being transferred to. */
/**
* Gets the {@link Jail} this prisoner is being transferred to.
*/
public Jail getTargetJail() {
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.
* <p>
* Will return null if the cell is not in the targetJail.
*/
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;
}
/** Checks if there was a target cell involved. */
/**
* Checks if there was a target cell involved.
*/
public boolean hasTargetCell() {
return this.getTargetCell() != null;
return this.getTargetCell() != null;
}
/** Gets the {@link Prisoner} data for this prisoner. */
/**
* Gets the {@link Prisoner} data for this prisoner.
*/
public Prisoner getPrisoner() {
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() {
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() {
return player == null;
}

View File

@ -1,19 +1,17 @@
package com.graywolf336.jail.exceptions;
/**
*
* The exception thrown trying to unjail via a thread that is NOT the primary thread.
*
*
* @author graywolf336
* @since 3.0.0
* @version 1.0.0
* @since 3.0.0
*/
public class AsyncUnJailingNotSupportedException extends Exception {
private static final long serialVersionUID = -1540695375715404835L;
/**
* Creation of an exception from unjailing via a thread that is not the primary one.
*
*/
public AsyncUnJailingNotSupportedException() {
super("Unjailing via a thread that is NOT the primary thread is not supported.");

View File

@ -1,19 +1,18 @@
package com.graywolf336.jail.exceptions;
/**
*
* The exception thrown when a cell is required but wasn't provided.
*
*
* @author graywolf336
* @since 3.0.0
* @version 1.0.0
* @since 3.0.0
*/
public class CellRequiredException extends Exception {
private static final long serialVersionUID = 6496748770371151376L;
/**
* Creation of a new cell is required exception.
*
*
* @param action where the jail is required.
*/
public CellRequiredException(String action) {

View File

@ -1,19 +1,18 @@
package com.graywolf336.jail.exceptions;
/**
*
* The exception thrown when a jail is required but wasn't provided.
*
*
* @author graywolf336
* @since 3.0.0
* @version 1.0.0
* @since 3.0.0
*/
public class JailRequiredException extends Exception {
private static final long serialVersionUID = 1046287197309037470L;
/**
* Creation of a new jail is required exception.
*
*
* @param action where the jail is required.
*/
public JailRequiredException(String action) {

View File

@ -1,27 +1,25 @@
package com.graywolf336.jail.exceptions;
/**
*
* The exception thrown when a prisoner is already jailed.
*
*
* @author graywolf336
* @since 3.0.0
* @version 1.0.0
* @since 3.0.0
*/
public class PrisonerAlreadyJailedException extends Exception {
private static final long serialVersionUID = -5830449694077279409L;
/**
* Creation of a prisoner is already jailed exception.
*
*/
public PrisonerAlreadyJailedException() {
super("A prisoner (no name or uuid provided) is already jailed and can not be jailed twice.");
}
/**
* Creation of a prisoner is already jailed exception.
*
*
* @param prisonerName the prisoner's name
* @param prisonerUUID the uuid of the prisoner
*/

View File

@ -1,19 +1,18 @@
package com.graywolf336.jail.exceptions;
/**
*
* The exception thrown when a prisoner's data is required but wasn't provided.
*
*
* @author graywolf336
* @since 3.0.0
* @version 1.0.0
* @since 3.0.0
*/
public class PrisonerRequiredException extends Exception {
private static final long serialVersionUID = 5289068334047189357L;
/**
* Creation of a new jail is required exception.
*
*
* @param action where the jail is required.
*/
public PrisonerRequiredException(String action) {

View File

@ -1,158 +1,159 @@
package com.graywolf336.jail.interfaces;
import com.graywolf336.jail.beans.Prisoner;
import com.graywolf336.jail.beans.SimpleLocation;
import org.bukkit.Location;
import org.bukkit.block.Chest;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import org.bukkit.Location;
import org.bukkit.block.Chest;
import com.graywolf336.jail.beans.Prisoner;
import com.graywolf336.jail.beans.SimpleLocation;
public interface ICell {
/**
* Gets the id of the cell in the database, <strong>internal usage only</strong>
*
*
* @return database's id, don't use for external reasons
*/
public int getDatabaseID();
int getDatabaseID();
/**
* Gets the name of the cell.
*
*
* @return Cell's name
*/
public String getName();
String getName();
/**
* Sets the prisoner in this cell.
*
*
* @param prisoner the {@link Prisoner} to set
*/
public void setPrisoner(Prisoner prisoner);
void setPrisoner(Prisoner prisoner);
/**
* Gets the prisoner being held in this cell.
*
*
* @return the {@link Prisoner} instance in this cell, null if no prisoner
*/
public Prisoner getPrisoner();
Prisoner getPrisoner();
/** Nullifies the prisoner data. */
public void removePrisoner();
/**
* Nullifies the prisoner data.
*/
void removePrisoner();
/**
* Returns true if there is currently a prisoner in this cell.
*
*
* @return Whether there is a prisoner or not
*/
public boolean hasPrisoner();
boolean hasPrisoner();
/**
* Adds all the given signs to the cell.
*
*
* @param signs all of the signs to add
*/
public void addAllSigns(HashSet<SimpleLocation> signs);
void addAllSigns(HashSet<SimpleLocation> signs);
/**
* Adds a sign to the cell.
*
*
* @param sign the {@link SimpleLocation} of the sign to add
*/
public void addSign(SimpleLocation sign);
void addSign(SimpleLocation sign);
/**
* Returns all the signs for this cell.
*
*
* @return All the signs used by this cell
*/
public HashSet<SimpleLocation> getSigns();
HashSet<SimpleLocation> getSigns();
/**
* Checks if there are any signs for this cell.
*
*
* @return Whether this cell has signs or not.
*/
public boolean hasSigns();
boolean hasSigns();
/**
* Returns the entire list of signs in a string.
*
*
* @return the serialized string of sign locations
*/
public String getSignString();
String getSignString();
/**
* Gets a list of all the signs which are invalid (not signs anymore).
*
* @return Returns a list of all the invalid signs
*
* @return Returns a list of all the invalid signs
*/
public List<String> getInvalidSigns();
List<String> getInvalidSigns();
/**
* Removes all the signs which are no longer sign blocks.
*
*
* @return The signs cleaned up
*/
public List<String> cleanSigns();
List<String> cleanSigns();
/**
* Updates all the signs this cell has.
*
* @return collection of changes. The <strong>"removed"</strong> entry has all the signs which were removed. The <strong>"updated"</strong> entry has all the signs which got updated.
*/
public HashMap<String, List<String>> updateSigns();
HashMap<String, List<String>> updateSigns();
/**
* Sets the location of where the prisoner will be teleported at when jailed here.
*
*
* @param location the {@link SimpleLocation} of the teleport
*/
public void setTeleport(SimpleLocation location);
void setTeleport(SimpleLocation location);
/**
* Gets the teleport location where the prisoner will be teleported at when jailed here.
*
*
* @return the teleport in {@link Location location}
*/
public Location getTeleport();
Location getTeleport();
/**
* Sets the location of the chest.
*
*
* @param simpleLocation the {@link SimpleLocation} of the chest
*/
public void setChestLocation(SimpleLocation simpleLocation);
void setChestLocation(SimpleLocation simpleLocation);
/**
* Gets the location of the chest, returns null if no chest is stored at this cell.
*
* @return The location of the chest, null if none.
*/
public Location getChestLocation();
Location getChestLocation();
/**
* Gets the chest for this cell, returns null if there is no chest or the location we have is not a chest.
*
* @return The chest and its state.
*/
public Chest getChest();
Chest getChest();
/**
* Checks if the chest location doesn't equal null and if it is a double chest.
*
* @return true if there is a chest, false if there isn't.
*/
public boolean hasChest();
boolean hasChest();
/**
* Checks to see if this cell uses a chest or not.
*
*
* @return Whether there is a location for chest stored.
*/
public boolean useChest();
boolean useChest();
/**
* Sets whether this cell has been changed or not.
@ -160,12 +161,12 @@ public interface ICell {
* @param changed true if we've changed it, mostly use if you want to force an update
* @return the resulting change, whether it is changed or not
*/
public boolean setChanged(boolean changed);
boolean setChanged(boolean changed);
/**
* Gets whether the Cell has changed from the last save or not.
*
*
* @return Whether the cell has changed or not since last save
*/
public boolean hasChanged();
boolean hasChanged();
}

View File

@ -1,93 +1,91 @@
package com.graywolf336.jail.interfaces;
import com.graywolf336.jail.beans.Prisoner;
import net.milkbowl.vault.economy.Economy;
import org.bukkit.Material;
import org.bukkit.entity.Player;
import com.graywolf336.jail.beans.Prisoner;
public interface IJailPayManager {
/**
* Checks if paying for infinite is enabled.
*
* @return Whether infinite paying is enabled.
*/
public boolean isInfiniteEnabled();
/**
* Checks if paying for infinite is enabled.
*
* @return Whether infinite paying is enabled.
*/
boolean isInfiniteEnabled();
/**
* Checks if paying for timed is enabled.
*
*
* @return Whether time paying is enabled.
*/
public boolean isTimedEnabled();
boolean isTimedEnabled();
/**
* Gets how much it cost per minute in string format.
*
*
* @return How much it costs per minute
*/
public String getCostPerMinute();
String getCostPerMinute();
/**
* Calculates how much players have to pay to get completely free.
*
*
* @param prisoner data of who we're calculating
* @return The economy cost the prisoner will need to pay to get completely free.
*/
public double calculateBill(Prisoner prisoner);
double calculateBill(Prisoner prisoner);
/**
* Gets how many minutes someone is paying for (rounds to the lowest number).
*
*
* @param amount amount of money
* @return the amount of time they're paying for
*/
public long getMinutesPayingFor(double amount);
long getMinutesPayingFor(double amount);
/**
* Returns if we are using items for payment instead of economy.
*
*
* @return Whether paying using items is enabled
*/
public boolean usingItemsForPayment();
boolean usingItemsForPayment();
/**
* Gets the {@link Material} it costs for jail pay, will be air if using economy.
*
*
* @return The item type it costs, air if using virtual economy.
*/
public Material getItemItCost();
Material getItemItCost();
/**
* Checks if the player has enough money/items to pay what they have said they want to.
*
*
* @param player The player who is doing the paying.
* @param amount The amount to check they if they have.
* @return true if they have enough, false if not.
*/
public boolean hasEnoughToPay(Player player, double amount);
boolean hasEnoughToPay(Player player, double amount);
/**
* Pays the required fees from the given player, removing items or money from economy.
*
*
* @param player The player who is paying.
* @param amount The amount of items or money to withdraw from the player.
*/
public void pay(Player player, double amount);
void pay(Player player, double amount);
/**
* Gets the name of the item in nice capitals.
*
*
* @return The currency name in nice capital letters.
*/
public String getCurrencyName();
String getCurrencyName();
/**
* Returns the economy provider to do transaction with.
*
*
* @return the {@link Economy} instance
*/
public Economy getEconomy();
Economy getEconomy();
}

View File

@ -1,67 +1,67 @@
package com.graywolf336.jail.interfaces;
import com.graywolf336.jail.beans.Stick;
import org.bukkit.Material;
import java.util.UUID;
import org.bukkit.Material;
import com.graywolf336.jail.beans.Stick;
/**
* Interface for the jail stick manager.
*
*
* @author graywolf336
* @version 1.0.0
* @since 3.0.0
*
*/
public interface IJailStickManager {
/**
/**
* Gets the {@link Stick jail stick} by the provided {@link Material}, can be null.
*
*
* @param mat of the stick to get
* @return The {@link Stick jail stick}
*/
public Stick getStick(Material mat);
Stick getStick(Material mat);
/**
* Checks if the provided Material is a valid {@link Stick jail stick}
*
*
* @param mat the {@link Material} to check
* @return whether the provided material is a valid stick
*/
public boolean isValidStick(Material mat);
boolean isValidStick(Material mat);
/**
* Adds a player to be using a jail stick, with the uuid of the player.
*
*
* @param id of the player to add
*/
public void addUsingStick(UUID id);
void addUsingStick(UUID id);
/**
* Removes a player from using a jail stick, with the uuid of the player.
*
*
* @param id of the player to remove using a jail stick
*/
public void removeUsingStick(UUID id);
void removeUsingStick(UUID id);
/**
* Returns whether or not the player is using a jail stick.
*
*
* @param id of the player to check if using one
* @return true if the player is using a jail stick, false if not
*/
public boolean isUsingJailStick(UUID id);
boolean isUsingJailStick(UUID id);
/**
* Toggles whether the player is using a jail stick, returning the true if enabled false if disabled.
*
*
* @param id of the player to toggle using a stick
* @return true if we enabled it, false if we disabled it.
*/
public boolean toggleUsingStick(UUID id);
/** Removes all the users currently using the sticks. */
public void removeAllStickUsers();
boolean toggleUsingStick(UUID id);
/**
* Removes all the users currently using the sticks.
*/
void removeAllStickUsers();
}

View File

@ -1,12 +1,5 @@
package com.graywolf336.jail.listeners;
import org.bukkit.event.EventHandler;
import org.bukkit.event.EventPriority;
import org.bukkit.event.Listener;
import org.bukkit.event.player.PlayerJoinEvent;
import org.bukkit.event.player.PlayerKickEvent;
import org.bukkit.event.player.PlayerQuitEvent;
import com.graywolf336.jail.JailMain;
import com.graywolf336.jail.beans.CachePrisoner;
import com.graywolf336.jail.beans.Jail;
@ -15,23 +8,28 @@ import com.graywolf336.jail.events.PrePrisonerReleasedEvent;
import com.graywolf336.jail.events.PrePrisonerTransferredEvent;
import com.graywolf336.jail.events.PrisonerJailedEvent;
import com.graywolf336.jail.events.PrisonerTransferredEvent;
import org.bukkit.event.EventHandler;
import org.bukkit.event.EventPriority;
import org.bukkit.event.Listener;
import org.bukkit.event.player.PlayerJoinEvent;
import org.bukkit.event.player.PlayerKickEvent;
import org.bukkit.event.player.PlayerQuitEvent;
/**
* The listen for all events which need to add/remove to the prisoner cache.
*
*
* <p>
* <p>
*
* These listeners add and remove prisoner cache objects to the cache,
* this way we gain performance for servers which have a high amount
* of prisoners jailed. (500+)
*
* @author graywolf336
* @since 3.0.0
* @version 1.0.0
*
* @author graywolf336
* @version 1.0.0
* @since 3.0.0
*/
public class CacheListener implements Listener {
private JailMain pl;
private final JailMain pl;
public CacheListener(JailMain plugin) {
this.pl = plugin;
@ -39,7 +37,7 @@ public class CacheListener implements Listener {
@EventHandler(priority = EventPriority.LOWEST)
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());
Prisoner p = j.getPrisoner(event.getPlayer().getUniqueId());
@ -49,14 +47,14 @@ public class CacheListener implements Listener {
@EventHandler(priority = EventPriority.LOWEST)
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());
}
}
@EventHandler(priority = EventPriority.LOWEST)
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());
}
}
@ -68,15 +66,15 @@ public class CacheListener implements Listener {
@EventHandler(priority = EventPriority.LOWEST)
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());
}
}
@EventHandler(priority = EventPriority.LOWEST)
public void beforeTransferringListener(PrePrisonerTransferredEvent event) {
if(event.isPlayerOnline()) {
if(pl.getJailManager().inCache(event.getPlayer().getUniqueId())) {
if (event.isPlayerOnline()) {
if (pl.getJailManager().inCache(event.getPlayer().getUniqueId())) {
pl.getJailManager().removeCacheObject(event.getPlayer().getUniqueId());
}
}

View File

@ -1,11 +1,5 @@
package com.graywolf336.jail.listeners;
import java.util.List;
import org.bukkit.event.EventHandler;
import org.bukkit.event.EventPriority;
import org.bukkit.event.Listener;
import com.graywolf336.jail.JailMain;
import com.graywolf336.jail.Util;
import com.graywolf336.jail.enums.Settings;
@ -15,23 +9,28 @@ import com.graywolf336.jail.events.PrisonerJailedEvent;
import com.graywolf336.jail.events.PrisonerReleasedEvent;
import com.graywolf336.jail.events.PrisonerTimeChangeEvent;
import com.graywolf336.jail.events.PrisonerTransferredEvent;
import org.bukkit.event.EventHandler;
import org.bukkit.event.EventPriority;
import org.bukkit.event.Listener;
import java.util.List;
public class CellSignListener implements Listener {
private String lineOne = "", lineTwo = "", lineThree = "", lineFour = "";
private JailMain pl;
private final JailMain pl;
public CellSignListener(JailMain plugin) {
pl = plugin;
List<String> lines = pl.getConfig().getStringList(Settings.CELLSIGNLINES.getPath());
if(lines.size() >= 1) lineOne = lines.get(0);
if(lines.size() >= 2) lineTwo = lines.get(1);
if(lines.size() >= 3) lineThree = lines.get(2);
if(lines.size() >= 4) lineFour = lines.get(3);
if (lines.size() >= 1) lineOne = lines.get(0);
if (lines.size() >= 2) lineTwo = lines.get(1);
if (lines.size() >= 3) lineThree = lines.get(2);
if (lines.size() >= 4) lineFour = lines.get(3);
try {
Util.updateSignLinesCache(new String[] { lineOne, lineTwo, lineThree, lineFour });
}catch(Exception e) {
Util.updateSignLinesCache(new String[]{lineOne, lineTwo, lineThree, lineFour});
} catch (Exception e) {
//this should never happen
pl.debug("Error on Cell Sign Listener constructor:" + e.getMessage());
}
@ -39,15 +38,13 @@ public class CellSignListener implements Listener {
@EventHandler(ignoreCancelled = true, priority = EventPriority.MONITOR)
public void changeTheCellSigns(final PrisonerTimeChangeEvent event) {
pl.getServer().getScheduler().scheduleSyncDelayedTask(pl, new Runnable() {
public void run() {
if (event.hasCell() && event.getCell().hasSigns()) {
event.getCell().updateSigns();
}
pl.getServer().getScheduler().scheduleSyncDelayedTask(pl, () -> {
if (event.hasCell() && event.getCell().hasSigns()) {
event.getCell().updateSigns();
}
});
}
@EventHandler(priority = EventPriority.MONITOR)
public void changeSignsOnOfflineJailing(OfflinePrisonerJailedEvent event) {
if (event.hasCell() && event.getCell().hasSigns()) {
@ -90,11 +87,11 @@ public class CellSignListener implements Listener {
lineThree = "";
lineFour = "";
if(lines.size() >= 1) lineOne = lines.get(0);
if(lines.size() >= 2) lineTwo = lines.get(1);
if(lines.size() >= 3) lineThree = lines.get(2);
if(lines.size() >= 4) lineFour = lines.get(3);
if (lines.size() >= 1) lineOne = lines.get(0);
if (lines.size() >= 2) lineTwo = lines.get(1);
if (lines.size() >= 3) lineThree = lines.get(2);
if (lines.size() >= 4) lineFour = lines.get(3);
Util.updateSignLinesCache(new String[] { lineOne, lineTwo, lineThree, lineFour });
Util.updateSignLinesCache(new String[]{lineOne, lineTwo, lineThree, lineFour});
}
}

View File

@ -1,31 +1,30 @@
package com.graywolf336.jail.listeners;
import com.graywolf336.jail.JailMain;
import com.graywolf336.jail.enums.Settings;
import org.bukkit.block.Block;
import org.bukkit.event.EventHandler;
import org.bukkit.event.Listener;
import org.bukkit.event.entity.EntityChangeBlockEvent;
import org.bukkit.event.entity.EntityExplodeEvent;
import com.graywolf336.jail.JailMain;
import com.graywolf336.jail.enums.Settings;
public class EntityListener implements Listener {
private JailMain pl;
private final JailMain pl;
public EntityListener(JailMain plugin) {
this.pl = plugin;
}
@EventHandler(ignoreCancelled=true)
@EventHandler(ignoreCancelled = true)
public void onEntityExplode(EntityExplodeEvent event) {
//Only do the checking if plugin has it enabled
//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
for(Block b : event.blockList()) {
for (Block b : event.blockList()) {
//Check the current block and if it is inside a jail,
//then let's do something else
if(pl.getJailManager().isLocationAJail(b.getLocation())) {
if (pl.getJailManager().isLocationAJail(b.getLocation())) {
//Clear the blocklist, this way the explosion effect still happens
event.blockList().clear();
return;
@ -34,12 +33,12 @@ public class EntityListener implements Listener {
}
}
@EventHandler(ignoreCancelled=true)
@EventHandler(ignoreCancelled = true)
public void protectFromEndermen(EntityChangeBlockEvent event) {
//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
if(pl.getJailManager().isLocationAJail(event.getBlock().getLocation())) {
if (pl.getJailManager().isLocationAJail(event.getBlock().getLocation())) {
//Let's cancel the event so it doesn't happen
event.setCancelled(true);
}

View File

@ -1,7 +1,6 @@
package com.graywolf336.jail.listeners;
import java.util.HashMap;
import com.graywolf336.jail.JailMain;
import org.bukkit.ChatColor;
import org.bukkit.Location;
import org.bukkit.event.EventHandler;
@ -13,20 +12,20 @@ import org.bukkit.event.player.PlayerCommandPreprocessEvent;
import org.bukkit.event.player.PlayerMoveEvent;
import org.bukkit.event.player.PlayerTeleportEvent;
import com.graywolf336.jail.JailMain;
import java.util.HashMap;
public class HandCuffListener implements Listener {
private JailMain pl;
private HashMap<String, Location> tos;
private final JailMain pl;
private final HashMap<String, Location> tos;
public HandCuffListener(JailMain plugin) {
this.pl = plugin;
this.tos = new HashMap<String, Location>();
this.tos = new HashMap<>();
}
@EventHandler(ignoreCancelled=true)
@EventHandler(ignoreCancelled = true)
public void onPlayerMove(PlayerMoveEvent event) {
if(event.isCancelled()) return;
if (false) return;
if (pl.getHandCuffManager().isHandCuffed(event.getPlayer().getUniqueId())) {
Location to = pl.getHandCuffManager().getLocation(event.getPlayer().getUniqueId());
@ -36,16 +35,16 @@ public class HandCuffListener implements Listener {
tos.put(event.getPlayer().getName(), 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!");
pl.getHandCuffManager().updateNextTime(event.getPlayer().getUniqueId());
}
}
}
@EventHandler(ignoreCancelled=true)
@EventHandler(ignoreCancelled = true)
public void onPlayerTeleport(PlayerTeleportEvent event) {
if(event.isCancelled()) return;
if (false) return;
if (pl.getHandCuffManager().isHandCuffed(event.getPlayer().getUniqueId()) && event.getTo() != tos.get(event.getPlayer().getName())) {
Location to = pl.getHandCuffManager().getLocation(event.getPlayer().getUniqueId());
@ -55,26 +54,26 @@ public class HandCuffListener implements Listener {
tos.put(event.getPlayer().getName(), 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!");
pl.getHandCuffManager().updateNextTime(event.getPlayer().getUniqueId());
}
}
}
@EventHandler(ignoreCancelled=true)
@EventHandler(ignoreCancelled = true)
public void playerChat(AsyncPlayerChatEvent event) {
if(event.isCancelled()) return;
if (false) return;
if (pl.getHandCuffManager().isHandCuffed(event.getPlayer().getUniqueId()) && !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!");
}
}
@EventHandler(ignoreCancelled=true)
@EventHandler(ignoreCancelled = true)
public void blockBreak(BlockBreakEvent event) {
if(event.isCancelled()) return;
if (false) return;
if (pl.getHandCuffManager().isHandCuffed(event.getPlayer().getUniqueId())) {
event.setCancelled(true);
@ -82,9 +81,9 @@ public class HandCuffListener implements Listener {
}
}
@EventHandler(ignoreCancelled=true)
@EventHandler(ignoreCancelled = true)
public void blockPlace(BlockPlaceEvent event) {
if(event.isCancelled()) return;
if (false) return;
if (pl.getHandCuffManager().isHandCuffed(event.getPlayer().getUniqueId())) {
event.setCancelled(true);
@ -92,12 +91,12 @@ public class HandCuffListener implements Listener {
}
}
@EventHandler(ignoreCancelled=true)
@EventHandler(ignoreCancelled = true)
public void preCommands(PlayerCommandPreprocessEvent event) {
if(event.isCancelled()) return;
if (false) return;
if (pl.getHandCuffManager().isHandCuffed(event.getPlayer().getUniqueId()) && !event.getPlayer().hasPermission("jail.command.handcuff") && (!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!");
}
}

View File

@ -1,35 +1,34 @@
package com.graywolf336.jail.listeners;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Date;
import org.bukkit.Color;
import org.bukkit.Material;
import org.bukkit.event.EventHandler;
import org.bukkit.event.Listener;
import org.bukkit.inventory.ItemStack;
import org.bukkit.inventory.meta.LeatherArmorMeta;
import com.graywolf336.jail.JailMain;
import com.graywolf336.jail.enums.Lang;
import com.graywolf336.jail.enums.Settings;
import com.graywolf336.jail.events.PrePrisonerJailedByJailStickEvent;
import com.graywolf336.jail.events.PrePrisonerJailedEvent;
import com.graywolf336.jail.events.PrisonerJailedEvent;
import org.bukkit.Color;
import org.bukkit.Material;
import org.bukkit.event.EventHandler;
import org.bukkit.event.Listener;
import org.bukkit.inventory.ItemStack;
import org.bukkit.inventory.meta.LeatherArmorMeta;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Date;
public class JailingListener implements Listener {
private JailMain pl;
private DateFormat dateFormat;
private final JailMain pl;
private final DateFormat dateFormat;
public JailingListener(JailMain plugin) {
this.pl = plugin;
this.dateFormat = new SimpleDateFormat(Lang.TIMEFORMAT.get());
}
@EventHandler(ignoreCancelled=true)
@EventHandler(ignoreCancelled = true)
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(),
event.getPrisoner().getLastKnownName(),
event.getPrisoner().getJailer(), dateFormat.format(new Date()),
@ -37,9 +36,9 @@ public class JailingListener implements Listener {
}
}
@EventHandler(ignoreCancelled=true)
@EventHandler(ignoreCancelled = true)
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(),
event.getPrisoner().getLastKnownName(),
event.getPrisoner().getJailer(), dateFormat.format(new Date()),
@ -49,77 +48,75 @@ public class JailingListener implements Listener {
@EventHandler
public void setInmatesClothing(final PrisonerJailedEvent event) {
if(pl.getConfig().getBoolean(Settings.CLOTHINGENABLED.getPath())) {
pl.getServer().getScheduler().runTaskLater(pl, new Runnable() {
public void run() {
String[] helmet = pl.getConfig().getString(Settings.CLOTHINGHELMET.getPath()).toUpperCase().split("~");
switch(helmet.length) {
case 1:
event.getPlayer().getInventory().setHelmet(new ItemStack(Material.valueOf(helmet[0])));
break;
case 2:
ItemStack item = new ItemStack(Material.valueOf(helmet[0]));
LeatherArmorMeta meta = (LeatherArmorMeta) item.getItemMeta();
String[] colors = helmet[1].split(",");
meta.setColor(Color.fromBGR(Integer.parseInt(colors[2]), Integer.parseInt(colors[1]), Integer.parseInt(colors[0])));
item.setItemMeta(meta);
event.getPlayer().getInventory().setHelmet(item);
break;
default:
break;
}
if (pl.getConfig().getBoolean(Settings.CLOTHINGENABLED.getPath())) {
pl.getServer().getScheduler().runTaskLater(pl, () -> {
String[] helmet = pl.getConfig().getString(Settings.CLOTHINGHELMET.getPath()).toUpperCase().split("~");
switch (helmet.length) {
case 1:
event.getPlayer().getInventory().setHelmet(new ItemStack(Material.valueOf(helmet[0])));
break;
case 2:
ItemStack item = new ItemStack(Material.valueOf(helmet[0]));
LeatherArmorMeta meta = (LeatherArmorMeta) item.getItemMeta();
String[] colors = helmet[1].split(",");
meta.setColor(Color.fromBGR(Integer.parseInt(colors[2]), Integer.parseInt(colors[1]), Integer.parseInt(colors[0])));
item.setItemMeta(meta);
event.getPlayer().getInventory().setHelmet(item);
break;
default:
break;
}
String[] chest = pl.getConfig().getString(Settings.CLOTHINGCHEST.getPath()).toUpperCase().split("~");
switch(chest.length) {
case 1:
event.getPlayer().getInventory().setChestplate(new ItemStack(Material.valueOf(chest[0])));
break;
case 2:
ItemStack item = new ItemStack(Material.valueOf(chest[0]));
LeatherArmorMeta meta = (LeatherArmorMeta) item.getItemMeta();
String[] colors = chest[1].split(",");
meta.setColor(Color.fromBGR(Integer.parseInt(colors[2]), Integer.parseInt(colors[1]), Integer.parseInt(colors[0])));
item.setItemMeta(meta);
event.getPlayer().getInventory().setChestplate(item);
break;
default:
break;
}
String[] chest = pl.getConfig().getString(Settings.CLOTHINGCHEST.getPath()).toUpperCase().split("~");
switch (chest.length) {
case 1:
event.getPlayer().getInventory().setChestplate(new ItemStack(Material.valueOf(chest[0])));
break;
case 2:
ItemStack item = new ItemStack(Material.valueOf(chest[0]));
LeatherArmorMeta meta = (LeatherArmorMeta) item.getItemMeta();
String[] colors = chest[1].split(",");
meta.setColor(Color.fromBGR(Integer.parseInt(colors[2]), Integer.parseInt(colors[1]), Integer.parseInt(colors[0])));
item.setItemMeta(meta);
event.getPlayer().getInventory().setChestplate(item);
break;
default:
break;
}
String[] legs = pl.getConfig().getString(Settings.CLOTHINGLEGS.getPath()).toUpperCase().split("~");
switch(legs.length) {
case 1:
event.getPlayer().getInventory().setLeggings(new ItemStack(Material.valueOf(legs[0])));
break;
case 2:
ItemStack item = new ItemStack(Material.valueOf(legs[0]));
LeatherArmorMeta meta = (LeatherArmorMeta) item.getItemMeta();
String[] colors = legs[1].split(",");
meta.setColor(Color.fromBGR(Integer.parseInt(colors[2]), Integer.parseInt(colors[1]), Integer.parseInt(colors[0])));
item.setItemMeta(meta);
event.getPlayer().getInventory().setLeggings(item);
break;
default:
break;
}
String[] legs = pl.getConfig().getString(Settings.CLOTHINGLEGS.getPath()).toUpperCase().split("~");
switch (legs.length) {
case 1:
event.getPlayer().getInventory().setLeggings(new ItemStack(Material.valueOf(legs[0])));
break;
case 2:
ItemStack item = new ItemStack(Material.valueOf(legs[0]));
LeatherArmorMeta meta = (LeatherArmorMeta) item.getItemMeta();
String[] colors = legs[1].split(",");
meta.setColor(Color.fromBGR(Integer.parseInt(colors[2]), Integer.parseInt(colors[1]), Integer.parseInt(colors[0])));
item.setItemMeta(meta);
event.getPlayer().getInventory().setLeggings(item);
break;
default:
break;
}
String[] boots = pl.getConfig().getString(Settings.CLOTHINGBOOTS.getPath()).toUpperCase().split("~");
switch(boots.length) {
case 1:
event.getPlayer().getInventory().setBoots(new ItemStack(Material.valueOf(boots[0])));
break;
case 2:
ItemStack item = new ItemStack(Material.valueOf(boots[0]));
LeatherArmorMeta meta = (LeatherArmorMeta) item.getItemMeta();
String[] colors = boots[1].split(",");
meta.setColor(Color.fromBGR(Integer.parseInt(colors[2]), Integer.parseInt(colors[1]), Integer.parseInt(colors[0])));
item.setItemMeta(meta);
event.getPlayer().getInventory().setBoots(item);
break;
default:
break;
}
};
String[] boots = pl.getConfig().getString(Settings.CLOTHINGBOOTS.getPath()).toUpperCase().split("~");
switch (boots.length) {
case 1:
event.getPlayer().getInventory().setBoots(new ItemStack(Material.valueOf(boots[0])));
break;
case 2:
ItemStack item = new ItemStack(Material.valueOf(boots[0]));
LeatherArmorMeta meta = (LeatherArmorMeta) item.getItemMeta();
String[] colors = boots[1].split(",");
meta.setColor(Color.fromBGR(Integer.parseInt(colors[2]), Integer.parseInt(colors[1]), Integer.parseInt(colors[0])));
item.setItemMeta(meta);
event.getPlayer().getInventory().setBoots(item);
break;
default:
break;
}
}, 20);
}
}

View File

@ -1,12 +1,5 @@
package com.graywolf336.jail.listeners;
import java.util.concurrent.TimeUnit;
import org.bukkit.event.EventHandler;
import org.bukkit.event.Listener;
import org.bukkit.event.player.PlayerMoveEvent;
import org.bukkit.event.player.PlayerTeleportEvent;
import com.graywolf336.jail.JailMain;
import com.graywolf336.jail.Util;
import com.graywolf336.jail.beans.CachePrisoner;
@ -14,35 +7,41 @@ import com.graywolf336.jail.beans.Jail;
import com.graywolf336.jail.beans.Prisoner;
import com.graywolf336.jail.enums.Lang;
import com.graywolf336.jail.enums.Settings;
import org.bukkit.event.EventHandler;
import org.bukkit.event.Listener;
import org.bukkit.event.player.PlayerMoveEvent;
import org.bukkit.event.player.PlayerTeleportEvent;
import java.util.concurrent.TimeUnit;
public class MoveProtectionListener implements Listener {
private JailMain pl;
private final JailMain pl;
public MoveProtectionListener(JailMain plugin) {
this.pl = plugin;
}
@EventHandler(ignoreCancelled=true)
@EventHandler(ignoreCancelled = true)
public void moveProtection(PlayerMoveEvent event) {
//If they haven't moved on the X or Z axis, then we shouldn't try to handle their moving
//this was suggested as Pull Request 63. Going to test it some, but the hope is that
//we don't handle move events so much and thus improve performance.
if(event.getFrom().getBlockX() == event.getTo().getBlockX() && event.getFrom().getBlockZ() == event.getTo().getBlockZ()) {
if (event.getFrom().getBlockX() == event.getTo().getBlockX() && event.getFrom().getBlockZ() == event.getTo().getBlockZ()) {
return;
}
//If we have the move protection enabled, then let's do 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
if(pl.getJailManager().inCache(event.getPlayer().getUniqueId())) {
if (pl.getJailManager().inCache(event.getPlayer().getUniqueId())) {
CachePrisoner cp = pl.getJailManager().getCacheObject(event.getPlayer().getUniqueId());
Jail j = cp.getJail();
Prisoner p = cp.getPrisoner();
//If the player is being teleported, let's ignore it
if(p.isTeleporting()) {
if (p.isTeleporting()) {
return;
}
@ -57,27 +56,27 @@ public class MoveProtectionListener implements Listener {
long add = Util.getTime(pl.getConfig().getString(Settings.MOVEPENALTY.getPath()));
p.addTime(add);
String msg = "";
if(add == 0L) {
String msg;
if (add == 0L) {
//Generate the protection message, provide the method with one argument
//which is the thing we are protecting against
msg = Lang.PROTECTIONMESSAGENOPENALTY.get(Lang.MOVING);
}else {
} else {
//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
msg = Lang.PROTECTIONMESSAGE.get(new String[] { String.valueOf(TimeUnit.MINUTES.convert(add, TimeUnit.MILLISECONDS)), Lang.MOVING.get() });
msg = Lang.PROTECTIONMESSAGE.get(String.valueOf(TimeUnit.MINUTES.convert(add, TimeUnit.MILLISECONDS)), Lang.MOVING.get());
}
//Send the message
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.");
}
//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());
}else {
} else {
//Otherwise let's teleport them to the in location of the jail
event.setTo(j.getTeleportIn());
}
@ -86,7 +85,7 @@ public class MoveProtectionListener implements Listener {
}
}
@EventHandler(ignoreCancelled=true)
@EventHandler(ignoreCancelled = true)
public void onPlayerTeleport(PlayerTeleportEvent event) {
PlayerMoveEvent move = new PlayerMoveEvent(event.getPlayer(), event.getFrom(), event.getTo());
moveProtection(move);

View File

@ -1,10 +1,18 @@
package com.graywolf336.jail.listeners;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Set;
import java.util.UUID;
import com.graywolf336.jail.JailMain;
import com.graywolf336.jail.JailManager;
import com.graywolf336.jail.Util;
import com.graywolf336.jail.beans.AnyCell;
import com.graywolf336.jail.beans.Cell;
import com.graywolf336.jail.beans.Jail;
import com.graywolf336.jail.beans.Prisoner;
import com.graywolf336.jail.beans.Stick;
import com.graywolf336.jail.enums.Lang;
import com.graywolf336.jail.enums.Settings;
import com.graywolf336.jail.events.PrePrisonerJailedByJailStickEvent;
import com.graywolf336.jail.events.PrisonerDeathEvent;
import com.graywolf336.jail.interfaces.ICell;
import org.bukkit.ChatColor;
import org.bukkit.Location;
import org.bukkit.entity.Player;
@ -22,55 +30,46 @@ import org.bukkit.event.player.PlayerKickEvent;
import org.bukkit.event.player.PlayerQuitEvent;
import org.bukkit.event.player.PlayerRespawnEvent;
import com.graywolf336.jail.JailMain;
import com.graywolf336.jail.JailManager;
import com.graywolf336.jail.Util;
import com.graywolf336.jail.beans.AnyCell;
import com.graywolf336.jail.beans.Cell;
import com.graywolf336.jail.beans.Jail;
import com.graywolf336.jail.beans.Prisoner;
import com.graywolf336.jail.beans.Stick;
import com.graywolf336.jail.enums.Lang;
import com.graywolf336.jail.enums.Settings;
import com.graywolf336.jail.events.PrePrisonerJailedByJailStickEvent;
import com.graywolf336.jail.events.PrisonerDeathEvent;
import com.graywolf336.jail.interfaces.ICell;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Set;
import java.util.UUID;
public class PlayerListener implements Listener {
private JailMain pl;
private HashMap<UUID, Long> clicks;
private final JailMain pl;
private final HashMap<UUID, Long> clicks;
public PlayerListener(JailMain plugin) {
this.pl = plugin;
this.clicks = new HashMap<UUID, Long>();
this.clicks = new HashMap<>();
}
@EventHandler(ignoreCancelled=true)
@EventHandler(ignoreCancelled = true)
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();
Location loc = event.getClickedBlock() == null ? p.getLocation() : event.getClickedBlock().getLocation();
JailManager jm = pl.getJailManager();
if(p.getInventory().getItemInMainHand().isSimilar(Util.getWand())) {
if(jm.isCreatingSomething(p.getName())) {
if (p.getInventory().getItemInMainHand().isSimilar(Util.getWand())) {
if (jm.isCreatingSomething(p.getName())) {
long current = System.currentTimeMillis();
if(clicks.containsKey(p.getUniqueId())) {
if(current - clicks.get(p.getUniqueId()) > 500) {
if (clicks.containsKey(p.getUniqueId())) {
if (current - clicks.get(p.getUniqueId()) > 500) {
clicks.put(p.getUniqueId(), current);
}else {
} else {
pl.debug("Prevented a double click for " + p.getName() + "!");
return;
}
}else {
} else {
clicks.put(p.getUniqueId(), current);
}
if(jm.isCreatingAJail(p.getName())) {
if (jm.isCreatingAJail(p.getName())) {
pl.debug("Stepping into creating a jail.");
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.");
jm.getCellCreationSteps().step(jm, p, jm.getCellCreationPlayer(p.getName()), loc);
}
@ -79,10 +78,10 @@ public class PlayerListener implements Listener {
}
}
@EventHandler(ignoreCancelled=true, priority = EventPriority.LOW)
@EventHandler(ignoreCancelled = true, priority = EventPriority.LOW)
public void chatting(AsyncPlayerChatEvent event) {
if(pl.getJailManager().isPlayerJailed(event.getPlayer().getUniqueId())) {
if(pl.getJailManager().getPrisoner(event.getPlayer().getUniqueId()).isMuted()) {
if (pl.getJailManager().isPlayerJailed(event.getPlayer().getUniqueId())) {
if (pl.getJailManager().getPrisoner(event.getPlayer().getUniqueId()).isMuted()) {
event.setCancelled(true);
event.getPlayer().sendMessage(Lang.MUTED.get());
}
@ -90,28 +89,30 @@ public class PlayerListener implements Listener {
//If the config has receive messages set to false, let's remove all the prisoners
//from getting the chat messages.
if(!pl.getConfig().getBoolean(Settings.RECIEVEMESSAGES.getPath())) {
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());
if (!pl.getConfig().getBoolean(Settings.RECIEVEMESSAGES.getPath())) {
if (pl.inDebug())
pl.getLogger().info("Debug - There are " + event.getRecipients().size() + " players getting the message before.");
Set<Player> rec = new HashSet<>(event.getRecipients());
for(Jail j : pl.getJailManager().getJails())
for(Prisoner p : j.getAllPrisoners().values())
for (Jail j : pl.getJailManager().getJails())
for (Prisoner p : j.getAllPrisoners().values())
rec.remove(pl.getServer().getPlayer(p.getUUID()));
event.getRecipients().clear();
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)
public void checkForOfflineJailStuff(PlayerJoinEvent event) {
//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
Jail j = pl.getJailManager().getJailPlayerIsIn(event.getPlayer().getUniqueId());
if(!j.isEnabled()) {
if (!j.isEnabled()) {
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.");
return;
@ -122,24 +123,23 @@ public class PlayerListener implements Listener {
p.setLastKnownName(event.getPlayer().getName());
//Check if they're offline pending, as if this is true then they were jailed offline
if(p.isOfflinePending()) {
if(p.getRemainingTime() == 0L) {
if (p.isOfflinePending()) {
if (p.getRemainingTime() == 0L) {
//If their remaining time is 0, let's unjail them
pl.getPrisonerManager().schedulePrisonerRelease(p);
}else if(p.isToBeTransferred()) {
} else if (p.isToBeTransferred()) {
Cell c = j.getCellPrisonerIsIn(event.getPlayer().getUniqueId());
//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);
event.getPlayer().teleport(j.getTeleportIn());
p.setTeleporting(false);
}else {
} else {
//If they are in a cell, teleport them into that cell
p.setTeleporting(true);
event.getPlayer().teleport(c.getTeleport());
p.setTeleporting(false);
}
p.setTeleporting(false);
p.setToBeTransferred(false);
} else {
@ -149,12 +149,12 @@ public class PlayerListener implements Listener {
}
//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);
}
//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);
}
}
@ -162,8 +162,8 @@ public class PlayerListener implements Listener {
@EventHandler
public void notifyUpdate(PlayerJoinEvent event) {
if(pl.getConfig().getBoolean(Settings.UPDATENOTIFICATIONS.getPath())) {
if(event.getPlayer().isOp() && pl.getUpdate().isAvailable()) {
if (pl.getConfig().getBoolean(Settings.UPDATENOTIFICATIONS.getPath())) {
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 + pl.getUpdate().getFileUrl());
}
@ -172,36 +172,36 @@ public class PlayerListener implements Listener {
@EventHandler
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
if(pl.getConfig().getBoolean(Settings.SCOREBOARDENABLED.getPath())) {
if (pl.getConfig().getBoolean(Settings.SCOREBOARDENABLED.getPath())) {
pl.getScoreBoardManager().removeScoreBoard(event.getPlayer());
}
}
}
@EventHandler(ignoreCancelled=true)
@EventHandler(ignoreCancelled = true)
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
if(pl.getConfig().getBoolean(Settings.SCOREBOARDENABLED.getPath())) {
if (pl.getConfig().getBoolean(Settings.SCOREBOARDENABLED.getPath())) {
pl.getScoreBoardManager().removeScoreBoard(event.getPlayer());
}
}
clicks.remove(event.getPlayer().getUniqueId());
}
@EventHandler(priority = EventPriority.LOW)
public void foodControl(FoodLevelChangeEvent event) {
if(pl.getConfig().getBoolean(Settings.FOODCONTROL.getPath())) {
if(pl.getJailManager().isPlayerJailed(event.getEntity().getUniqueId())) {
if (pl.getConfig().getBoolean(Settings.FOODCONTROL.getPath())) {
if (pl.getJailManager().isPlayerJailed(event.getEntity().getUniqueId())) {
int min = pl.getConfig().getInt(Settings.FOODCONTROLMIN.getPath());
int max = pl.getConfig().getInt(Settings.FOODCONTROLMAX.getPath());
if (event.getFoodLevel() < min) {
if (event.getFoodLevel() < min) {
event.setFoodLevel(min);
}else {
} else {
event.setFoodLevel(max);
}
}
@ -210,7 +210,7 @@ public class PlayerListener implements Listener {
@EventHandler
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());
PrisonerDeathEvent prisonerEvent = new PrisonerDeathEvent(event, j, j.getCellPrisonerIsIn(event.getEntity().getUniqueId()), j.getPrisoner(event.getEntity().getUniqueId()), event.getEntity());
@ -220,59 +220,60 @@ public class PlayerListener implements Listener {
@EventHandler(priority = EventPriority.HIGHEST)
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());
if(j.isJailedInACell(event.getPlayer().getUniqueId())) {
if (j.isJailedInACell(event.getPlayer().getUniqueId())) {
event.setRespawnLocation(j.getCellPrisonerIsIn(event.getPlayer().getUniqueId()).getTeleport());
}else {
} else {
event.setRespawnLocation(j.getTeleportIn());
}
}
}
@EventHandler(priority = EventPriority.LOWEST, ignoreCancelled=true)
@EventHandler(priority = EventPriority.LOWEST, ignoreCancelled = true)
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,
//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 player = (Player) event.getEntity();
//They aren't using the jail stick, they need to toggle themselves
if(!pl.getJailStickManager().isUsingJailStick(attacker.getUniqueId())) return;
if (!pl.getJailStickManager().isUsingJailStick(attacker.getUniqueId())) return;
//They don't have a valid jail stick type
if(!pl.getJailStickManager().isValidStick(attacker.getInventory().getItemInMainHand().getType())) return;
if (!pl.getJailStickManager().isValidStick(attacker.getInventory().getItemInMainHand().getType())) return;
//They don't have permission for that type of jail stick
if(!attacker.hasPermission("jail.usejailstick." + attacker.getInventory().getItemInMainHand().getType().toString().toLowerCase())) return;
if (!attacker.hasPermission("jail.usejailstick." + attacker.getInventory().getItemInMainHand().getType().toString().toLowerCase()))
return;
//The player they hit is already jailed.
if(pl.getJailManager().isPlayerJailed(player.getUniqueId())) {
attacker.sendMessage(Lang.ALREADYJAILED.get(player.getName()));
return;
if (pl.getJailManager().isPlayerJailed(player.getUniqueId())) {
attacker.sendMessage(Lang.ALREADYJAILED.get(player.getName()));
return;
}
//The player can't be jailed due to permissions.
if(player.hasPermission("jail.cantbejailed")) {
if (player.hasPermission("jail.cantbejailed")) {
attacker.sendMessage(Lang.CANTBEJAILED.get());
return;
}
//Get the stick the attacker (police) is using
Stick s = pl.getJailStickManager().getStick(attacker.getInventory().getItemInMainHand().getType());
//Check if the player can resist arrest via health with this stick
pl.debug("Jail stick health resist check: " + "(" + s.getHealth() + "," + player.getHealth() + ") - " + (s.getHealth() <= player.getHealth() && s.getHealth() != -1));
if(s.getHealth() < player.getHealth() && s.getHealth() != -1) {
attacker.sendMessage(Lang.RESISTEDARRESTJAILER.get(player.getName()));
if (s.getHealth() < player.getHealth() && s.getHealth() != -1) {
attacker.sendMessage(Lang.RESISTEDARRESTJAILER.get(player.getName()));
player.sendMessage(Lang.RESISTEDARRESTPLAYER.get(attacker.getName()));
return;
return;
}
//The player can be jailed.
Prisoner p = new Prisoner(player.getUniqueId().toString(), player.getName(),
pl.getConfig().getBoolean(Settings.AUTOMATICMUTE.getPath()),
@ -283,12 +284,12 @@ public class PlayerListener implements Listener {
pl.getServer().getPluginManager().callEvent(jEvent);
if(jEvent.isCancelled()) {
if(jEvent.getCancelledMessage().isEmpty())
if (jEvent.isCancelled()) {
if (jEvent.getCancelledMessage().isEmpty())
attacker.sendMessage(Lang.CANCELLEDBYANOTHERPLUGIN.get(player.getName()));
else
attacker.sendMessage(jEvent.getCancelledMessage());
}else {
} else {
//recall data from the event
Jail j = jEvent.getJail();
ICell c = jEvent.getCell();
@ -296,11 +297,11 @@ public class PlayerListener implements Listener {
player = jEvent.getPlayer();
//Player is not online
if(player == null) {
attacker.sendMessage(Lang.OFFLINEJAIL.get(new String[] { p.getLastKnownName(), String.valueOf(p.getRemainingTimeInMinutes()) }));
}else {
if (player == null) {
attacker.sendMessage(Lang.OFFLINEJAIL.get(p.getLastKnownName(), String.valueOf(p.getRemainingTimeInMinutes())));
} else {
//Player *is* online
attacker.sendMessage(Lang.ONLINEJAIL.get(new String[] { p.getLastKnownName(), String.valueOf(p.getRemainingTimeInMinutes()) }));
attacker.sendMessage(Lang.ONLINEJAIL.get(p.getLastKnownName(), String.valueOf(p.getRemainingTimeInMinutes())));
}
try {

View File

@ -1,7 +1,9 @@
package com.graywolf336.jail.listeners;
import java.util.concurrent.TimeUnit;
import com.graywolf336.jail.JailMain;
import com.graywolf336.jail.Util;
import com.graywolf336.jail.enums.Lang;
import com.graywolf336.jail.enums.Settings;
import org.bukkit.Material;
import org.bukkit.event.EventHandler;
import org.bukkit.event.EventPriority;
@ -12,27 +14,24 @@ import org.bukkit.event.block.BlockPlaceEvent;
import org.bukkit.event.player.PlayerCommandPreprocessEvent;
import org.bukkit.event.player.PlayerInteractEvent;
import com.graywolf336.jail.JailMain;
import com.graywolf336.jail.Util;
import com.graywolf336.jail.enums.Lang;
import com.graywolf336.jail.enums.Settings;
import java.util.concurrent.TimeUnit;
public class ProtectionListener implements Listener {
private JailMain pl;
private final JailMain pl;
public ProtectionListener(JailMain plugin) {
this.pl = plugin;
}
@EventHandler(ignoreCancelled=true, priority = EventPriority.LOW)
@EventHandler(ignoreCancelled = true, priority = EventPriority.LOW)
public void protectionBlockBreaking(BlockBreakEvent event) {
//Before we check if the player is jailed, let's save a
//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
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
if(!Util.isStringInsideList(event.getBlock().getType().toString().toLowerCase(),
if (!Util.isStringInsideList(event.getBlock().getType().toString().toLowerCase(),
pl.getConfig().getStringList(Settings.BLOCKBREAKWHITELIST.getPath()))) {
//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
@ -41,50 +40,50 @@ public class ProtectionListener implements Listener {
long add = Util.getTime(pl.getConfig().getString(Settings.BLOCKBREAKPENALTY.getPath()));
pl.getJailManager().getPrisoner(event.getPlayer().getUniqueId()).addTime(add);
String msg = "";
if(add == 0L) {
String msg;
if (add == 0L) {
//Generate the protection message, provide the method with one argument
//which is the thing we are protecting against
msg = Lang.PROTECTIONMESSAGENOPENALTY.get(Lang.BLOCKBREAKING.get());
}else {
} else {
//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
msg = Lang.PROTECTIONMESSAGE.get(new String[] { String.valueOf(TimeUnit.MINUTES.convert(add, TimeUnit.MILLISECONDS)), Lang.BLOCKBREAKING.get() });
msg = Lang.PROTECTIONMESSAGE.get(String.valueOf(TimeUnit.MINUTES.convert(add, TimeUnit.MILLISECONDS)), Lang.BLOCKBREAKING.get());
}
//Send the message
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.");
}
//Stop the event from happening, as the block wasn't in the whitelist
event.setCancelled(true);
}
}else {
//The player is not jailed but they're trying to break blocks inside of the Jail
} else {
//The player is not jailed but they're trying to break blocks inside of the Jail
//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,
//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
if(!event.getPlayer().hasPermission("jail.modifyjail")) {
if (!event.getPlayer().hasPermission("jail.modifyjail")) {
event.setCancelled(true);
}
}
}
}
@EventHandler(ignoreCancelled=true, priority = EventPriority.LOW)
@EventHandler(ignoreCancelled = true, priority = EventPriority.LOW)
public void protectionBlockPlacing(BlockPlaceEvent event) {
//Before we check if the player is jailed, let's save a
//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
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
if(!Util.isStringInsideList(event.getBlock().getType().toString().toLowerCase(),
if (!Util.isStringInsideList(event.getBlock().getType().toString().toLowerCase(),
pl.getConfig().getStringList(Settings.BLOCKPLACEWHITELIST.getPath()))) {
//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
@ -93,75 +92,75 @@ public class ProtectionListener implements Listener {
long add = Util.getTime(pl.getConfig().getString(Settings.BLOCKPLACEPENALTY.getPath()));
pl.getJailManager().getPrisoner(event.getPlayer().getUniqueId()).addTime(add);
String msg = "";
if(add == 0L) {
String msg;
if (add == 0L) {
//Generate the protection message, provide the method with one argument
//which is the thing we are protecting against
msg = Lang.PROTECTIONMESSAGENOPENALTY.get(Lang.BLOCKPLACING);
}else {
} else {
//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
msg = Lang.PROTECTIONMESSAGE.get(new String[] { String.valueOf(TimeUnit.MINUTES.convert(add, TimeUnit.MILLISECONDS)), Lang.BLOCKPLACING.get() });
msg = Lang.PROTECTIONMESSAGE.get(String.valueOf(TimeUnit.MINUTES.convert(add, TimeUnit.MILLISECONDS)), Lang.BLOCKPLACING.get());
}
//Send the message
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.");
}
//Stop the event from happening, as the block wasn't in the whitelist
event.setCancelled(true);
}
}else {
//The player is not jailed but they're trying to place blocks inside of the Jail
} else {
//The player is not jailed but they're trying to place blocks inside of the Jail
//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,
//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
if(!event.getPlayer().hasPermission("jail.modifyjail")) {
if (!event.getPlayer().hasPermission("jail.modifyjail")) {
event.setCancelled(true);
}
}
}
}
@EventHandler(ignoreCancelled=true, priority = EventPriority.LOW)
@EventHandler(ignoreCancelled = true, priority = EventPriority.LOW)
public void commandProtection(PlayerCommandPreprocessEvent event) {
//Before we check if the player is jailed, let's save a
//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
//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;
for(String whited : pl.getConfig().getStringList(Settings.COMMANDWHITELIST.getPath()))
if(event.getMessage().toLowerCase().startsWith(whited.toLowerCase()))
for (String whited : pl.getConfig().getStringList(Settings.COMMANDWHITELIST.getPath()))
if (event.getMessage().toLowerCase().startsWith(whited.toLowerCase()))
match = true;
//If no match found in the whitelist, then let's block this command.
if(!match) {
if (!match) {
try {
long add = Util.getTime(pl.getConfig().getString(Settings.COMMANDPENALTY.getPath()));
pl.getJailManager().getPrisoner(event.getPlayer().getUniqueId()).addTime(add);
String msg = "";
if(add == 0L) {
String msg;
if (add == 0L) {
//Generate the protection message, provide the method with one argument
//which is the thing we are protecting against
msg = Lang.PROTECTIONMESSAGENOPENALTY.get(Lang.COMMAND);
}else {
} else {
//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
msg = Lang.PROTECTIONMESSAGE.get(new String[] { String.valueOf(TimeUnit.MINUTES.convert(add, TimeUnit.MILLISECONDS)), Lang.COMMAND.get() });
msg = Lang.PROTECTIONMESSAGE.get(String.valueOf(TimeUnit.MINUTES.convert(add, TimeUnit.MILLISECONDS)), Lang.COMMAND.get());
}
//Send the message
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.");
}
@ -172,17 +171,17 @@ public class ProtectionListener implements Listener {
}
}
@EventHandler(ignoreCancelled=true, priority = EventPriority.LOW)
@EventHandler(ignoreCancelled = true, priority = EventPriority.LOW)
public void chestProtection(PlayerInteractEvent event) {
//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
//If they are in a cell and are opening a chest, then we check
//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.
if(pl.getJailManager().getJailPlayerIsIn(event.getPlayer().getUniqueId()).isJailedInACell(event.getPlayer().getUniqueId())) {
if(pl.getConfig().getBoolean(Settings.PRISONEROPENCHEST.getPath())) {
if (pl.getJailManager().getJailPlayerIsIn(event.getPlayer().getUniqueId()).isJailedInACell(event.getPlayer().getUniqueId())) {
if (pl.getConfig().getBoolean(Settings.PRISONEROPENCHEST.getPath())) {
//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 bpos2 = event.getClickedBlock().getLocation().add(+1, 0, 0).getBlock().getType();
@ -194,55 +193,53 @@ public class ProtectionListener implements Listener {
boolean pos3 = bpos3 == Material.CHEST || bpos3 == 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!
if(pl.inDebug()) event.getPlayer().sendMessage("[Jail Debug]: You're opening up a double chest.");
}else {
if (pl.inDebug())
event.getPlayer().sendMessage("[Jail Debug]: You're opening up a double chest.");
} else {
//it is not a double chest, so we won't be allowing it.
event.setCancelled(true);
return;
}
}else {
} else {
//the config has opening chests disabled
event.setCancelled(true);
return;
}
}else {
} else {
//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.
event.setCancelled(true);
return;
}
}
}
}
@EventHandler(ignoreCancelled=true, priority = EventPriority.LOWEST)
@EventHandler(ignoreCancelled = true, priority = EventPriority.LOWEST)
public void cropTramplingProtection(PlayerInteractEvent event) {
//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
if(pl.getConfig().getBoolean(Settings.CROPTRAMPLINGPROTECTION.getPath())) {
if(event.getAction() == Action.PHYSICAL && event.getClickedBlock().getType() == Material.FARMLAND) {
if(pl.getJailManager().getJailFromLocation(event.getClickedBlock().getLocation()) != null) {
if (pl.getConfig().getBoolean(Settings.CROPTRAMPLINGPROTECTION.getPath())) {
if (event.getAction() == Action.PHYSICAL && event.getClickedBlock().getType() == Material.FARMLAND) {
if (pl.getJailManager().getJailFromLocation(event.getClickedBlock().getLocation()) != null) {
try {
long add = Util.getTime(pl.getConfig().getString(Settings.CROPTRAMPLINGPENALTY.getPath()));
pl.getJailManager().getPrisoner(event.getPlayer().getUniqueId()).addTime(add);
String msg = "";
if(add == 0L) {
String msg;
if (add == 0L) {
//Generate the protection message, provide the method with one argument
//which is the thing we are protecting against
msg = Lang.PROTECTIONMESSAGENOPENALTY.get(Lang.CROPTRAMPLING);
}else {
} else {
//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
msg = Lang.PROTECTIONMESSAGE.get(new String[] { String.valueOf(TimeUnit.MINUTES.convert(add, TimeUnit.MILLISECONDS)), Lang.CROPTRAMPLING.get() });
msg = Lang.PROTECTIONMESSAGE.get(String.valueOf(TimeUnit.MINUTES.convert(add, TimeUnit.MILLISECONDS)), Lang.CROPTRAMPLING.get());
}
//Send the message
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.");
}
@ -253,66 +250,66 @@ public class ProtectionListener implements Listener {
}
}
@EventHandler(ignoreCancelled=true)
@EventHandler(ignoreCancelled = true)
public void interactionProtection(PlayerInteractEvent event) {
//As the old version didn't do anything with Physical interactions, we won't either
if (event.getAction() != Action.PHYSICAL) {
//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
if (event.getClickedBlock() != null) {
//Get the interaction blacklist, check if the current block is in there
//if it is, then let's take action
if(Util.isStringInsideList(event.getClickedBlock().getType().toString().toLowerCase(),
if (Util.isStringInsideList(event.getClickedBlock().getType().toString().toLowerCase(),
pl.getConfig().getStringList(Settings.PREVENTINTERACTIONBLOCKS.getPath()))) {
try {
long add = Util.getTime(pl.getConfig().getString(Settings.PREVENTINTERACTIONBLOCKSPENALTY.getPath()));
pl.getJailManager().getPrisoner(event.getPlayer().getUniqueId()).addTime(add);
String msg = "";
if(add == 0L) {
String msg;
if (add == 0L) {
//Generate the protection message, provide the method with one argument
//which is the thing we are protecting against
msg = Lang.PROTECTIONMESSAGENOPENALTY.get(Lang.INTERACTIONBLOCKS);
}else {
} else {
//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
msg = Lang.PROTECTIONMESSAGE.get(new String[] { String.valueOf(TimeUnit.MINUTES.convert(add, TimeUnit.MILLISECONDS)), Lang.INTERACTIONBLOCKS.get() });
msg = Lang.PROTECTIONMESSAGE.get(String.valueOf(TimeUnit.MINUTES.convert(add, TimeUnit.MILLISECONDS)), Lang.INTERACTIONBLOCKS.get());
}
//Send the message
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.");
}
event.setCancelled(true);
}
}else if (event.getPlayer().getInventory().getItemInMainHand() != null) {
} else if (event.getPlayer().getInventory().getItemInMainHand() != null) {
//Otherwise let's check if they have something in hand
//Get the interaction blacklist, check if the current item is in there
//if it is, then let's take action
if(Util.isStringInsideList(event.getClickedBlock().getType().toString().toLowerCase(),
if (Util.isStringInsideList(event.getClickedBlock().getType().toString().toLowerCase(),
pl.getConfig().getStringList(Settings.PREVENTINTERACTIONITEMS.getPath()))) {
try {
long add = Util.getTime(pl.getConfig().getString(Settings.PREVENTINTERACTIONITEMSPENALTY.getPath()));
pl.getJailManager().getPrisoner(event.getPlayer().getUniqueId()).addTime(add);
String msg = "";
if(add == 0L) {
String msg;
if (add == 0L) {
//Generate the protection message, provide the method with one argument
//which is the thing we are protecting against
msg = Lang.PROTECTIONMESSAGENOPENALTY.get(Lang.INTERACTIONITEMS);
}else {
} else {
//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
msg = Lang.PROTECTIONMESSAGE.get(new String[] { String.valueOf(TimeUnit.MINUTES.convert(add, TimeUnit.MILLISECONDS)), Lang.INTERACTIONITEMS.get() });
msg = Lang.PROTECTIONMESSAGE.get(String.valueOf(TimeUnit.MINUTES.convert(add, TimeUnit.MILLISECONDS)), Lang.INTERACTIONITEMS.get());
}
//Send the message
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.");
}

View File

@ -1,30 +1,29 @@
package com.graywolf336.jail.listeners;
import com.graywolf336.jail.JailMain;
import com.graywolf336.jail.beans.Jail;
import org.bukkit.event.EventHandler;
import org.bukkit.event.EventPriority;
import org.bukkit.event.Listener;
import org.bukkit.event.world.WorldLoadEvent;
import org.bukkit.event.world.WorldUnloadEvent;
import com.graywolf336.jail.JailMain;
import com.graywolf336.jail.beans.Jail;
public class WorldListener implements Listener {
private JailMain pl;
private final JailMain pl;
public WorldListener(JailMain plugin) {
this.pl = plugin;
}
@EventHandler(ignoreCancelled=true, priority = EventPriority.LOW)
@EventHandler(ignoreCancelled = true, priority = EventPriority.LOW)
public void worldLoaded(WorldLoadEvent event) {
for(Jail j : pl.getJailManager().getJails())
if(j.getWorldName().equalsIgnoreCase(event.getWorld().getName())) j.setEnabled(true);
for (Jail j : pl.getJailManager().getJails())
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) {
for(Jail j : pl.getJailManager().getJails())
if(j.getWorldName().equalsIgnoreCase(event.getWorld().getName())) j.setEnabled(false);
for (Jail j : pl.getJailManager().getJails())
if (j.getWorldName().equalsIgnoreCase(event.getWorld().getName())) j.setEnabled(false);
}
}

View File

@ -1,15 +1,5 @@
package com.graywolf336.jail.steps;
import org.bukkit.ChatColor;
import org.bukkit.Location;
import org.bukkit.Material;
import org.bukkit.block.Block;
import org.bukkit.block.Chest;
import org.bukkit.block.Sign;
import org.bukkit.entity.Player;
import org.bukkit.inventory.ItemStack;
import org.bukkit.util.Vector;
import com.graywolf336.jail.JailManager;
import com.graywolf336.jail.Util;
import com.graywolf336.jail.beans.Cell;
@ -17,44 +7,56 @@ import com.graywolf336.jail.beans.CreationPlayer;
import com.graywolf336.jail.beans.Jail;
import com.graywolf336.jail.beans.SimpleLocation;
import com.graywolf336.jail.enums.Lang;
import org.bukkit.ChatColor;
import org.bukkit.Location;
import org.bukkit.Material;
import org.bukkit.Tag;
import org.bukkit.block.Block;
import org.bukkit.block.Chest;
import org.bukkit.block.Sign;
import org.bukkit.entity.Player;
import org.bukkit.inventory.ItemStack;
import org.bukkit.util.Vector;
/**
* Class for stepping a player through the Cell creation process, instance is stored in {@link JailManager}.
*
*
* @author graywolf336
* @since 3.0.0
* @version 1.0.1
* @since 3.0.0
*/
public class CellCreationSteps {
/** Sends the Cell Creation message for starting out. */
public void startStepping(Player player){
/**
* Sends the Cell Creation message for starting out.
*/
public void startStepping(Player player) {
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 clay brick to set it.");
player.sendMessage(ChatColor.AQUA + "----------------------------------------");
ItemStack wand = Util.getWand();
if(player.getInventory().contains(wand)) {
if (player.getInventory().contains(wand)) {
int i = player.getInventory().first(wand);
if(i != -1) {
if (i != -1) {
player.getInventory().setItem(i, player.getInventory().getItemInMainHand());
player.getInventory().setItemInMainHand(wand);
}
}else {
} else {
player.getInventory().addItem(wand);
}
}
/**
* 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 player The player who is doing the creating.
* @param cp The {@link CreationPlayer} instance
*
* @param jm The {@link JailManager} instance.
* @param player The player who is doing the creating.
* @param cp The {@link CreationPlayer} instance
* @param location The location, null if none, being set.
*/
public void step(JailManager jm, Player player, CreationPlayer cp, Location location) {
jm.getPlugin().debug("Stepping into step #" + cp.getStep());
switch(cp.getStep()) {
switch (cp.getStep()) {
case 1:
firstStep(jm, cp, player);
break;
@ -71,29 +73,33 @@ public class CellCreationSteps {
}
}
/** 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) {
Vector v1 = jm.getJail(cp.getJailName()).getMinPoint().toVector().clone();
Vector v2 = jm.getJail(cp.getJailName()).getMaxPoint().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.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 + "----------------------------------------");
cp.setTeleportIn(player.getLocation());
cp.nextStep();
}else {
} else {
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 + "----------------------------------------");
}
}
/** 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) {
if (block.getType() == Material.SIGN || block.getType() == Material.WALL_SIGN) {
if (Tag.SIGNS.isTagged(block.getType()) || Tag.WALL_SIGNS.isTagged(block.getType())) {
cp.addSign(new SimpleLocation(block.getLocation()));
//Set the sign's first text
@ -105,7 +111,7 @@ public class CellCreationSteps {
sign.update();
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.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 + "----------------------------------------");
@ -113,21 +119,23 @@ public class CellCreationSteps {
}
}
/** 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) {
if (block.getType() == Material.CHEST || block.getType() == Material.TRAPPED_CHEST) {
if(((Chest) block.getState()).getInventory().getSize() >= 40) {
if (((Chest) block.getState()).getInventory().getSize() >= 40) {
cp.setChestLocation(new SimpleLocation(block.getLocation()));
player.sendMessage(ChatColor.AQUA + "---------- Jail Cell Creation ----------");
player.sendMessage(ChatColor.GREEN + "Chest selected.");
player.sendMessage(ChatColor.AQUA + "----------------------------------------");
}else {
} else {
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 + "----------------------------------------");
return;
}
}else {
} else {
player.sendMessage(ChatColor.AQUA + "---------- Jail Cell Creation ----------");
player.sendMessage(ChatColor.RED + "No chest selected.");
player.sendMessage(ChatColor.AQUA + "----------------------------------------");
@ -143,7 +151,7 @@ public class CellCreationSteps {
c.addAllSigns(cp.getSigns());
c.setTeleport(cp.getTeleportInSL());
if(cp.getChestLocation() != null)
if (cp.getChestLocation() != null)
c.setChestLocation(cp.getChestLocation());
j.addCell(c, true);

View File

@ -1,54 +1,55 @@
package com.graywolf336.jail.steps;
import com.graywolf336.jail.JailManager;
import com.graywolf336.jail.Util;
import com.graywolf336.jail.beans.CreationPlayer;
import com.graywolf336.jail.beans.Jail;
import org.bukkit.ChatColor;
import org.bukkit.Location;
import org.bukkit.entity.Player;
import org.bukkit.inventory.ItemStack;
import org.bukkit.util.Vector;
import com.graywolf336.jail.JailManager;
import com.graywolf336.jail.Util;
import com.graywolf336.jail.beans.CreationPlayer;
import com.graywolf336.jail.beans.Jail;
/**
* Class for stepping a player through the Jail creation process, instance is stored in {@link JailManager}.
*
*
* @author graywolf336
* @since 3.0.0
* @version 1.1.1
* @since 3.0.0
*/
public class JailCreationSteps {
/** Sends the Jail Creation message for starting out. */
/**
* Sends the Jail Creation message for starting out.
*/
public void startStepping(Player player) {
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 clay brick. DO NOT FORGET TO MARK THE FLOOR AND CEILING TOO!");
player.sendMessage(ChatColor.AQUA + "--------------------------------------");
ItemStack wand = Util.getWand();
if(player.getInventory().contains(wand)) {
if (player.getInventory().contains(wand)) {
int i = player.getInventory().first(wand);
if(i != -1) {
if (i != -1) {
player.getInventory().setItem(i, player.getInventory().getItemInMainHand());
player.getInventory().setItemInMainHand(wand);
}
}else {
} else {
player.getInventory().addItem(wand);
}
}
/**
* 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 player The player who is doing the creating.
* @param cp The {@link CreationPlayer} instance
*
* @param jm The {@link JailManager} instance.
* @param player The player who is doing the creating.
* @param cp The {@link CreationPlayer} instance
* @param location The location, null if none, being set.
*/
public void step(JailManager jm, Player player, CreationPlayer cp, Location location) {
jm.getPlugin().debug("Stepping into step #" + cp.getStep());
switch(cp.getStep()) {
switch (cp.getStep()) {
case 1:
firstStep(cp, player, location);
break;
@ -68,7 +69,9 @@ public class JailCreationSteps {
}
}
/** 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) {
p.sendMessage(ChatColor.AQUA + "---------- Jail Zone Creation----------");
p.sendMessage(ChatColor.GREEN + "First point selected. Now select the second point.");
@ -78,7 +81,9 @@ public class JailCreationSteps {
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) {
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.");
@ -88,7 +93,9 @@ public class JailCreationSteps {
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) {
int[] p1 = cp.getCornerOne();
@ -97,7 +104,7 @@ public class JailCreationSteps {
Vector v2 = new Vector(p2[0], p2[1], p2[2]);
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.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 + "----------------------------------------");
@ -118,11 +125,11 @@ public class JailCreationSteps {
Vector v2 = new Vector(p2[0], p2[1], p2[2]);
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 + "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 + "----------------------------------------");
}else {
} else {
cp.setTeleportFree(p.getLocation());
finalStep(jm, cp, p);
@ -139,7 +146,7 @@ public class JailCreationSteps {
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());
}

View File

@ -6,7 +6,7 @@ authors: [graywolf336]
website: dev.bukkit.org/server-mods/jail/
softdepend: [WorldEdit, Vault, Multiverse-Core]
load: POSTWORLD
api-version: 1.13
api-version: 1.17
commands:
jail:
@ -153,8 +153,6 @@ permissions:
default: op
jail.command.jailversion:
default: op
jail.usercmd.jailvote:
default: op
jail.vote.start:
default: op
jail.see.broadcast:

View File

@ -1,90 +0,0 @@
package test.java.com.graywolf336.jail;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertTrue;
import static org.mockito.Matchers.any;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.when;
import java.util.Random;
import java.util.UUID;
import org.bukkit.Location;
import org.bukkit.entity.Player;
import org.bukkit.event.player.PlayerMoveEvent;
import org.bukkit.plugin.PluginDescriptionFile;
import org.junit.AfterClass;
import org.junit.BeforeClass;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.powermock.core.classloader.annotations.PrepareForTest;
import org.powermock.modules.junit4.PowerMockRunner;
import test.java.com.graywolf336.jail.util.TestInstanceCreator;
import com.carrotsearch.junitbenchmarks.AbstractBenchmark;
import com.carrotsearch.junitbenchmarks.BenchmarkOptions;
import com.graywolf336.jail.JailMain;
import com.graywolf336.jail.beans.CachePrisoner;
import com.graywolf336.jail.beans.Prisoner;
@RunWith(PowerMockRunner.class)
@PrepareForTest({ JailMain.class, PluginDescriptionFile.class })
public class BenchmarkTest extends AbstractBenchmark {
private static TestInstanceCreator creator;
private static JailMain main;
private static UUID use;
private static Random r;
@BeforeClass
public static void setUp() throws Exception {
creator = new TestInstanceCreator();
assertNotNull("The instance creator is null.", creator);
assertTrue(creator.setup());
main = creator.getMain();
assertNotNull("The JailMain class is null.", main);
assertTrue("The adding of a jail failed.", creator.addJail("testingJail"));
assertFalse("There are no jails.", main.getJailManager().getJails().isEmpty());
for(int i = 0; i < 1000; i++) {
if(i == 555)
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));
}
//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)));
r = new Random();
}
@AfterClass
public static void tearDown() throws Exception {
creator.tearDown();
main = null;
}
@BenchmarkOptions(benchmarkRounds = 1000, warmupRounds = 0)
@Test
public void testPrisonerSizeAndJailed() {
assertEquals("Prisoners not jailed?", 1000, main.getJailManager().getAllPrisoners().size());
assertTrue("Prisoner 555 is not jailed", main.getJailManager().isPlayerJailed(use));
}
@SuppressWarnings("deprecation")
@BenchmarkOptions(benchmarkRounds = 5000, warmupRounds = 0)
@Test
public void testPlayerMoveEvent() {
Player p = mock(Player.class);
when(p.getUniqueId()).thenReturn(use);
when(p.getName()).thenReturn("mockPlayer555");
when(p.teleport(any(Location.class))).thenReturn(true);
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());
PlayerMoveEvent e = new PlayerMoveEvent(p, from, to);
main.getPlayerMoveListener().moveProtection(e);
}
}

View File

@ -1,99 +0,0 @@
package test.java.com.graywolf336.jail;
import static org.hamcrest.CoreMatchers.is;
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.assertThat;
import static org.junit.Assert.assertTrue;
import java.util.UUID;
import org.bukkit.Location;
import org.bukkit.plugin.PluginDescriptionFile;
import org.junit.AfterClass;
import org.junit.BeforeClass;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.powermock.core.classloader.annotations.PrepareForTest;
import org.powermock.modules.junit4.PowerMockRunner;
import test.java.com.graywolf336.jail.util.TestInstanceCreator;
import com.graywolf336.jail.JailMain;
import com.graywolf336.jail.JailsAPI;
@RunWith(PowerMockRunner.class)
@PrepareForTest({ JailMain.class, PluginDescriptionFile.class })
public class TestJailAPI {
private static TestInstanceCreator creator;
private static JailMain main;
@BeforeClass
public static void setUp() throws Exception {
creator = new TestInstanceCreator();
assertNotNull("The instance creator is null.", creator);
assertTrue(creator.setup());
main = creator.getMain();
assertNotNull("The JailMain class is null.", main);
assertTrue("The adding of a jail failed.", creator.addJail("TestJailAPI"));
}
@AfterClass
public static void tearDown() throws Exception {
creator.tearDown();
main = null;
}
@Test
public void testManagersAreThere() {
assertNotNull(main.getHandCuffManager());
assertNotNull(main.getJailManager());
assertNotNull(main.getPrisonerManager());
assertNotNull(main.getJailVoteManager());
}
@Test
public void verifyManagersAreTheSame() {
assertThat("The HandCuff Manager references are different.", JailsAPI.getHandCuffManager(), is(main.getHandCuffManager()));
assertThat("The Jail Manager references are different.", JailsAPI.getJailManager(), is(main.getJailManager()));
assertThat("The Prisoner Manager references are different.", JailsAPI.getPrisonerManager(), is(main.getPrisonerManager()));
assertThat("The Jail Stick Manager references are different.", JailsAPI.getJailStickManager(), is(main.getJailStickManager()));
assertThat("The Jail Vote Manager references are different.", JailsAPI.getJailVoteManager(), is(main.getJailVoteManager()));
}
@Test
public void testHandCuffManagerAPI() {
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"));
assertFalse("The test id of someone is already handcuffed.", JailsAPI.getHandCuffManager().isHandCuffed(id));
JailsAPI.getHandCuffManager().addHandCuffs(id, loc);
assertTrue(JailsAPI.getHandCuffManager().isHandCuffed(id));
assertThat(JailsAPI.getHandCuffManager().getLocation(id), is(loc));
JailsAPI.getHandCuffManager().removeHandCuffs(id);
assertFalse(JailsAPI.getHandCuffManager().isHandCuffed(id));
assertNull(JailsAPI.getHandCuffManager().getLocation(id));
}
@Test
public void testJailManagerAPI() {
assertThat("The Jail Manager reference to the plugin is different.", JailsAPI.getJailManager().getPlugin(), is(main));
assertNotNull("The getJails method returned a null value.", JailsAPI.getJailManager().getJails());
assertEquals("There isn't a Jail in the returned Jails.", 1, JailsAPI.getJailManager().getJails().size());
assertThat("Jail Names aren't equal..", new String[] { "TestJailAPI" }, is(JailsAPI.getJailManager().getJailNames()));
assertTrue("The adding of a new jail, furtherTesting, wasn't successful.", creator.addJail("furtherTesting"));
assertTrue("The added jail, furtherTesting, doesn't exist.", JailsAPI.getJailManager().isValidJail("furtherTesting"));
JailsAPI.getJailManager().removeJail("furtherTesting");
assertFalse("The jail furtherTesting wasn't successfully removed.", JailsAPI.getJailManager().isValidJail("furtherTesting"));
assertNull("The jail furtherTesting is not null.", JailsAPI.getJailManager().getJail("furtherTesting"));
assertNotNull("The jail TestJailAPI is null.", JailsAPI.getJailManager().getJail("TestJailAPI"));
assertNotNull("An empty string returned a null value even though there is one jail.", JailsAPI.getJailManager().getJail(""));
assertNotNull("The first jail is null from the console sender.", JailsAPI.getJailManager().getNearestJail(creator.getCommandSender()));
assertNotNull("The nearest jail from the player sender is null.", JailsAPI.getJailManager().getNearestJail(creator.getPlayerCommandSender()));
assertNotNull("The cells object returned is null.", JailsAPI.getJailManager().getAllCells());
assertTrue("There are some cells even though there shouldn't be.", JailsAPI.getJailManager().getAllCells().isEmpty());
}
}

Some files were not shown because too many files have changed in this diff Show More