Add .gitattributes

This commit is contained in:
graywolf336 2014-06-12 10:44:13 -05:00
parent a77e0cc472
commit d535b758d4
75 changed files with 10347 additions and 10309 deletions

38
.gitattributes vendored Normal file
View File

@ -0,0 +1,38 @@
# Handle line endings automatically for files detected as text
# and leave all files detected as binary untouched.
* text=auto
#
# The above will handle all files NOT found below
#
# These files are text and should be normalized (Convert crlf => lf)
*.css text
*.df text
*.htm text
*.html text
*.java text
*.js text
*.json text
*.jsp text
*.jspf text
*.properties text
*.sh text
*.sql text
*.svg text
*.tld text
*.txt text
*.xml text
# These files are binary and should be left untouched
# (binary is a macro for -text -diff)
*.class binary
*.dll binary
*.ear binary
*.gif binary
*.ico binary
*.jar binary
*.jpg binary
*.jpeg binary
*.png binary
*.so binary
*.war binary

86
.gitignore vendored
View File

@ -1,46 +1,46 @@
# Compiled source # # Compiled source #
################### ###################
*.com *.com
*.class *.class
*.dll *.dll
*.exe *.exe
*.o *.o
*.so *.so
# Packages # # Packages #
############ ############
# it's better to unpack these files and commit the raw source # it's better to unpack these files and commit the raw source
# git has its own built in compression methods # git has its own built in compression methods
*.7z *.7z
*.dmg *.dmg
*.gz *.gz
*.iso *.iso
*.jar *.jar
*.rar *.rar
*.tar *.tar
*.zip *.zip
# Logs and databases # # Logs and databases #
###################### ######################
*.log *.log
*.sql *.sql
*.sqlite *.sqlite
# OS generated files # # OS generated files #
###################### ######################
.DS_Store* .DS_Store*
ehthumbs.db ehthumbs.db
Icon? Icon?
Thumbs.db Thumbs.db
# folders # # folders #
########### ###########
bin/ bin/
target/ target/
.settings/ .settings/
.classpath .classpath
.project .project
config.yml config.yml
src/com/matejdro/ src/com/matejdro/
/dependency-reduced-pom.xml /dependency-reduced-pom.xml
/global.yml /global.yml

130
README.md
View File

@ -1,66 +1,66 @@
[Jail 3.0](http://ci.graywolf336.com/job/Jail/) [Jail 3.0](http://ci.graywolf336.com/job/Jail/)
==== ====
This plugins adds Jail to your Minecraft server. Admins can define several jails and then jail/unjail people or jail them on time basis. Plugin also offers wide variety of protections, so players won't escape out of your jail. This plugins adds Jail to your Minecraft server. Admins can define several jails and then jail/unjail people or jail them on time basis. Plugin also offers wide variety of protections, so players won't escape out of your jail.
**All mysql queries and actions are done sync, meaning if the connection to the mysql server is slow/down this will probably end up blocking the server. There are plans to change this, as we don't want to slow down anyone's servers.** **All mysql queries and actions are done sync, meaning if the connection to the mysql server is slow/down this will probably end up blocking the server. There are plans to change this, as we don't want to slow down anyone's servers.**
[![Build Status](http://ci.graywolf336.com/job/Jail/badge/icon)](http://ci.graywolf336.com/job/Jail/) [![Build Status](http://ci.graywolf336.com/job/Jail/badge/icon)](http://ci.graywolf336.com/job/Jail/)
Beta 2 Changes Beta 2 Changes
=== ===
*Changes since Beta 1* *Changes since Beta 1*
* Using UUID as the only means of knowing if someone is jailed or not, last known username is stored for commands * Using UUID as the only means of knowing if someone is jailed or not, last known username is stored for commands
* Jailings via jail sticks are now recorded, [#20](https://github.com/graywolf336/Jail/issues/20) * Jailings via jail sticks are now recorded, [#20](https://github.com/graywolf336/Jail/issues/20)
* Fix the default Jail Stick not being loaded correctly, [#21](https://github.com/graywolf336/Jail/issues/21) * Fix the default Jail Stick not being loaded correctly, [#21](https://github.com/graywolf336/Jail/issues/21)
* Implement Scoreboards, with title and time configurable. ([#15](https://github.com/graywolf336/Jail/issues/15)) * Implement Scoreboards, with title and time configurable. ([#15](https://github.com/graywolf336/Jail/issues/15))
* Implemented Jail Pay [#11](https://github.com/graywolf336/Jail/issues/11) * Implemented Jail Pay [#11](https://github.com/graywolf336/Jail/issues/11)
* Convert old data and config values, only some are done and if you don't want the old data delete your `global.yml` * Convert old data and config values, only some are done and if you don't want the old data delete your `global.yml`
* Add config option to disallow the usage of Jail Sticks * Add config option to disallow the usage of Jail Sticks
* Added `/jail time` for easy access to adding/subtracting time - [Bukkit Dev Ticket #432](http://dev.bukkit.org/bukkit-plugins/jail/tickets/432/) * Added `/jail time` for easy access to adding/subtracting time - [Bukkit Dev Ticket #432](http://dev.bukkit.org/bukkit-plugins/jail/tickets/432/)
* Added `/togglejaildebug` for easily toggling the debugging state, enable if you have a problem and want to send me information * Added `/togglejaildebug` for easily toggling the debugging state, enable if you have a problem and want to send me information
* *
Beta 1 Changes Beta 1 Changes
=== ===
*Changes since alpha* *Changes since alpha*
* MySQL storage is now a valid option for storage ([#18](https://github.com/graywolf336/Jail/issues/18)) * MySQL storage is now a valid option for storage ([#18](https://github.com/graywolf336/Jail/issues/18))
* MySQL data validation, basically if a cell or prisoner reference a jail which no longer exists they are removed * MySQL data validation, basically if a cell or prisoner reference a jail which no longer exists they are removed
* Fix a bug with not being able to unjail someone forcefully if they were in a cell ([#17](https://github.com/graywolf336/Jail/issues/17)) * Fix a bug with not being able to unjail someone forcefully if they were in a cell ([#17](https://github.com/graywolf336/Jail/issues/17))
* Add the record keeping system ([#12](https://github.com/graywolf336/Jail/issues/12)) * Add the record keeping system ([#12](https://github.com/graywolf336/Jail/issues/12))
* Added Jail Sticks, format of them has slightly changed ([#16](https://github.com/graywolf336/Jail/issues/16)) * Added Jail Sticks, format of them has slightly changed ([#16](https://github.com/graywolf336/Jail/issues/16))
Changes Changes
=== ===
*With this being version 3 of this plugin, a couple things have changed but the core concept is still the exact same. Here are some drastic changes:* *With this being version 3 of this plugin, a couple things have changed but the core concept is still the exact same. Here are some drastic changes:*
* Time can now be entered different formats, 3hours or 15mins or 4days * Time can now be entered different formats, 3hours or 15mins or 4days
* New language system * New language system
* New config system (per jail configs are going to make a come back) * New config system (per jail configs are going to make a come back)
* Items in the config use item names now, **not** the ids * Items in the config use item names now, **not** the ids
* All commands are prevented by default, now there is **only** a whitelist * All commands are prevented by default, now there is **only** a whitelist
* All interactions are prevented by default, add to the whitelist what you want * All interactions are prevented by default, add to the whitelist what you want
* If store inventory is not enabled, inventories are deleted upon jailing * If store inventory is not enabled, inventories are deleted upon jailing
* Sign text has a new format, old format will not be converted * Sign text has a new format, old format will not be converted
* Max reason length has been removed, might be added back in if needed * Max reason length has been removed, might be added back in if needed
ToDo ToDo
=== ===
* Jail pay * Jail pay
* Jail set * Jail set
* Jail vote * Jail vote
* Jailing for swearing * Jailing for swearing
* Guards (PlayerMoveProtectionAction - when they try to move do we teleport them back, let the guards get them, or nothing) * Guards (PlayerMoveProtectionAction - when they try to move do we teleport them back, let the guards get them, or nothing)
* Storing permissions * Storing permissions
* Update Notifications * Update Notifications
* Pages on jail list * Pages on jail list
Notice Notice
=== ===
* If you ran an alpha or beta, please delete the en.yml so that you get the additional messages added since your version (will update in the future) * If you ran an alpha or beta, please delete the en.yml so that you get the additional messages added since your version (will update in the future)
* Old messages (language) will not be converted * Old messages (language) will not be converted
* MaximumAFKTime setting will not convert over, the format isn't clear and the old version didn't provide a way to get values with decimal places * MaximumAFKTime setting will not convert over, the format isn't clear and the old version didn't provide a way to get values with decimal places
* EnableLogging has been removed, we are always going to be logging (unless major request to control this) * EnableLogging has been removed, we are always going to be logging (unless major request to control this)
* Prisoner's old inventory strings in the database are lost, we can not convert those * Prisoner's old inventory strings in the database are lost, we can not convert those
* Prisoner's Previous Position is not converted. * Prisoner's Previous Position is not converted.
[Jail 3.0 JavaDoc](http://ci.graywolf336.com/job/Jail/javadoc) [Jail 3.0 JavaDoc](http://ci.graywolf336.com/job/Jail/javadoc)
==== ====

436
pom.xml
View File

@ -1,219 +1,219 @@
<?xml version="1.0" encoding="UTF-8"?> <?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" <project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"> xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion> <modelVersion>4.0.0</modelVersion>
<groupId>com.graywolf336</groupId> <groupId>com.graywolf336</groupId>
<artifactId>Jail</artifactId> <artifactId>Jail</artifactId>
<version>3.0.0-SNAPSHOT</version> <version>3.0.0-SNAPSHOT</version>
<name>Jail</name> <name>Jail</name>
<description>Ban too harsh? Mute too weak? Kicking not enough? Jail them! </description> <description>Ban too harsh? Mute too weak? Kicking not enough? Jail them! </description>
<url>http://dev.bukkit.org/bukkit-plugins/jail/</url> <url>http://dev.bukkit.org/bukkit-plugins/jail/</url>
<ciManagement> <ciManagement>
<url>http://ci.graywolf336.com/job/Jail/</url> <url>http://ci.graywolf336.com/job/Jail/</url>
<system>jenkins</system> <system>jenkins</system>
</ciManagement> </ciManagement>
<issueManagement> <issueManagement>
<url>http://dev.bukkit.org/bukkit-plugins/jail/tickets/</url> <url>http://dev.bukkit.org/bukkit-plugins/jail/tickets/</url>
<system>Dev Bukkit</system> <system>Dev Bukkit</system>
</issueManagement> </issueManagement>
<scm> <scm>
<url>https://github.com/graywolf336/Jail</url> <url>https://github.com/graywolf336/Jail</url>
<connection>scm:git:git://github.com/graywolf336/Jail.git</connection> <connection>scm:git:git://github.com/graywolf336/Jail.git</connection>
<developerConnection>scm:git:git:@github.com/graywolf336/Jail.git</developerConnection> <developerConnection>scm:git:git:@github.com/graywolf336/Jail.git</developerConnection>
</scm> </scm>
<repositories> <repositories>
<repository> <repository>
<id>vault-repo</id> <id>vault-repo</id>
<url>http://nexus.theyeticave.net/content/repositories/pub_releases</url> <url>http://nexus.theyeticave.net/content/repositories/pub_releases</url>
</repository> </repository>
<repository> <repository>
<id>bukkit-repo</id> <id>bukkit-repo</id>
<url>http://repo.bukkit.org/content/groups/public</url> <url>http://repo.bukkit.org/content/groups/public</url>
</repository> </repository>
<repository> <repository>
<id>sk89q-repo</id> <id>sk89q-repo</id>
<url>http://maven.sk89q.com/repo/</url> <url>http://maven.sk89q.com/repo/</url>
</repository> </repository>
</repositories> </repositories>
<dependencies> <dependencies>
<dependency> <dependency>
<groupId>org.bukkit</groupId> <groupId>org.bukkit</groupId>
<artifactId>bukkit</artifactId> <artifactId>bukkit</artifactId>
<version>1.7.9-R0.1-SNAPSHOT</version> <version>1.7.9-R0.1-SNAPSHOT</version>
<type>jar</type> <type>jar</type>
</dependency> </dependency>
<dependency> <dependency>
<groupId>org.bukkit</groupId> <groupId>org.bukkit</groupId>
<artifactId>craftbukkit</artifactId> <artifactId>craftbukkit</artifactId>
<version>1.7.9-R0.1-SNAPSHOT</version> <version>1.7.9-R0.1-SNAPSHOT</version>
<type>jar</type> <type>jar</type>
</dependency> </dependency>
<dependency> <dependency>
<groupId>com.sk89q</groupId> <groupId>com.sk89q</groupId>
<artifactId>worldedit</artifactId> <artifactId>worldedit</artifactId>
<version>5.5.7-SNAPSHOT</version> <version>5.5.7-SNAPSHOT</version>
</dependency> </dependency>
<dependency> <dependency>
<groupId>net.milkbowl.vault</groupId> <groupId>net.milkbowl.vault</groupId>
<artifactId>Vault</artifactId> <artifactId>Vault</artifactId>
<version>1.2.27-SNAPSHOT</version> <version>1.2.27-SNAPSHOT</version>
<type>jar</type> <type>jar</type>
</dependency> </dependency>
<dependency> <dependency>
<groupId>com.lexicalscope.jewelcli</groupId> <groupId>com.lexicalscope.jewelcli</groupId>
<artifactId>jewelcli</artifactId> <artifactId>jewelcli</artifactId>
<version>0.8.9</version> <version>0.8.9</version>
</dependency> </dependency>
<!-- Start of Test Dependencies --> <!-- Start of Test Dependencies -->
<dependency> <dependency>
<groupId>junit</groupId> <groupId>junit</groupId>
<artifactId>junit</artifactId> <artifactId>junit</artifactId>
<version>4.11</version> <version>4.11</version>
</dependency> </dependency>
<dependency> <dependency>
<groupId>org.powermock</groupId> <groupId>org.powermock</groupId>
<artifactId>powermock-module-junit4</artifactId> <artifactId>powermock-module-junit4</artifactId>
<version>1.5.5</version> <version>1.5.5</version>
<scope>test</scope> <scope>test</scope>
</dependency> </dependency>
<dependency> <dependency>
<groupId>org.powermock</groupId> <groupId>org.powermock</groupId>
<artifactId>powermock-api-easymock</artifactId> <artifactId>powermock-api-easymock</artifactId>
<version>1.5.5</version> <version>1.5.5</version>
<scope>test</scope> <scope>test</scope>
</dependency> </dependency>
<dependency> <dependency>
<groupId>org.powermock</groupId> <groupId>org.powermock</groupId>
<artifactId>powermock-api-mockito</artifactId> <artifactId>powermock-api-mockito</artifactId>
<version>1.5.5</version> <version>1.5.5</version>
<scope>test</scope> <scope>test</scope>
</dependency> </dependency>
<dependency> <dependency>
<groupId>org.easymock</groupId> <groupId>org.easymock</groupId>
<artifactId>easymock</artifactId> <artifactId>easymock</artifactId>
<version>3.2</version> <version>3.2</version>
<scope>test</scope> <scope>test</scope>
</dependency> </dependency>
<dependency> <dependency>
<groupId>com.carrotsearch</groupId> <groupId>com.carrotsearch</groupId>
<artifactId>junit-benchmarks</artifactId> <artifactId>junit-benchmarks</artifactId>
<version>0.7.2</version> <version>0.7.2</version>
<scope>test</scope> <scope>test</scope>
</dependency> </dependency>
<!-- End of Test Dependencies --> <!-- End of Test Dependencies -->
</dependencies> </dependencies>
<build> <build>
<directory>target</directory> <directory>target</directory>
<outputDirectory>target/classes</outputDirectory> <outputDirectory>target/classes</outputDirectory>
<!-- <sourceDirectory>${basedir}/src</sourceDirectory> --> <!-- <sourceDirectory>${basedir}/src</sourceDirectory> -->
<defaultGoal>clean install test</defaultGoal> <defaultGoal>clean install test</defaultGoal>
<resources> <resources>
<resource> <resource>
<targetPath>.</targetPath> <targetPath>.</targetPath>
<filtering>true</filtering> <filtering>true</filtering>
<directory>${basedir}/src/main/resources/</directory> <directory>${basedir}/src/main/resources/</directory>
<includes> <includes>
<include>*.yml</include> <include>*.yml</include>
</includes> </includes>
</resource> </resource>
</resources> </resources>
<testResources> <testResources>
<testResource> <testResource>
<directory>${basedir}/src/main/resources</directory> <directory>${basedir}/src/main/resources</directory>
</testResource> </testResource>
</testResources> </testResources>
<!-- Plugins --> <!-- Plugins -->
<plugins> <plugins>
<!-- Compile plugin --> <!-- Compile plugin -->
<plugin> <plugin>
<groupId>org.apache.maven.plugins</groupId> <groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId> <artifactId>maven-compiler-plugin</artifactId>
<version>2.3.2</version> <version>2.3.2</version>
<configuration> <configuration>
<source>1.6</source> <source>1.6</source>
<target>1.6</target> <target>1.6</target>
</configuration> </configuration>
</plugin> </plugin>
<!-- Jar Plugin --> <!-- Jar Plugin -->
<plugin> <plugin>
<groupId>org.apache.maven.plugins</groupId> <groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-jar-plugin</artifactId> <artifactId>maven-jar-plugin</artifactId>
<version>2.3.1</version> <version>2.3.1</version>
<configuration> <configuration>
<archive> <archive>
<manifestEntries /> <manifestEntries />
</archive> </archive>
</configuration> </configuration>
</plugin> </plugin>
<plugin> <plugin>
<groupId>org.apache.maven.plugins</groupId> <groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-shade-plugin</artifactId> <artifactId>maven-shade-plugin</artifactId>
<version>2.2</version> <version>2.2</version>
<executions> <executions>
<execution> <execution>
<phase>package</phase> <phase>package</phase>
<goals> <goals>
<goal>shade</goal> <goal>shade</goal>
</goals> </goals>
<configuration> <configuration>
<artifactSet> <artifactSet>
<includes> <includes>
<include>com.lexicalscope.jewelcli:jewelcli</include> <include>com.lexicalscope.jewelcli:jewelcli</include>
</includes> </includes>
</artifactSet> </artifactSet>
</configuration> </configuration>
</execution> </execution>
</executions> </executions>
</plugin> </plugin>
<plugin> <plugin>
<groupId>org.apache.maven.plugins</groupId> <groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-surefire-plugin</artifactId> <artifactId>maven-surefire-plugin</artifactId>
<version>2.11</version> <version>2.11</version>
<configuration> <configuration>
<parallel>methods</parallel> <parallel>methods</parallel>
<threadCount>10</threadCount> <threadCount>10</threadCount>
<excludes> <excludes>
<exclude>**/TestCommandSender.java</exclude> <exclude>**/TestCommandSender.java</exclude>
<exclude>**/TestInstanceCreator.java</exclude> <exclude>**/TestInstanceCreator.java</exclude>
</excludes> </excludes>
</configuration> </configuration>
<dependencies> <dependencies>
<dependency> <dependency>
<groupId>org.apache.maven.surefire</groupId> <groupId>org.apache.maven.surefire</groupId>
<artifactId>surefire-junit47</artifactId> <artifactId>surefire-junit47</artifactId>
<version>2.11</version> <version>2.11</version>
</dependency> </dependency>
</dependencies> </dependencies>
</plugin> </plugin>
</plugins> </plugins>
</build> </build>
<distributionManagement> <distributionManagement>
<repository> <repository>
<id>repo-release</id> <id>repo-release</id>
<name>repo.graywolf336.com Releases</name> <name>repo.graywolf336.com Releases</name>
<url>http://repo.graywolf336.com/content/repositories/releases/</url> <url>http://repo.graywolf336.com/content/repositories/releases/</url>
</repository> </repository>
<snapshotRepository> <snapshotRepository>
<id>repo-snapshot</id> <id>repo-snapshot</id>
<name>repo.graywolf336.com Snapshots</name> <name>repo.graywolf336.com Snapshots</name>
<url>http://repo.graywolf336.com/content/repositories/snapshots/</url> <url>http://repo.graywolf336.com/content/repositories/snapshots/</url>
</snapshotRepository> </snapshotRepository>
</distributionManagement> </distributionManagement>
</project> </project>

View File

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

File diff suppressed because it is too large Load Diff

View File

@ -1,271 +1,271 @@
package com.graywolf336.jail; package com.graywolf336.jail;
import org.bukkit.command.Command; import org.bukkit.command.Command;
import org.bukkit.command.CommandSender; import org.bukkit.command.CommandSender;
import org.bukkit.plugin.PluginManager; import org.bukkit.plugin.PluginManager;
import org.bukkit.plugin.java.JavaPlugin; import org.bukkit.plugin.java.JavaPlugin;
import com.graywolf336.jail.beans.Jail; import com.graywolf336.jail.beans.Jail;
import com.graywolf336.jail.beans.Prisoner; import com.graywolf336.jail.beans.Prisoner;
import com.graywolf336.jail.command.CommandHandler; import com.graywolf336.jail.command.CommandHandler;
import com.graywolf336.jail.command.JailHandler; import com.graywolf336.jail.command.JailHandler;
import com.graywolf336.jail.enums.Settings; import com.graywolf336.jail.enums.Settings;
import com.graywolf336.jail.legacy.LegacyManager; import com.graywolf336.jail.legacy.LegacyManager;
import com.graywolf336.jail.listeners.BlockListener; import com.graywolf336.jail.listeners.BlockListener;
import com.graywolf336.jail.listeners.CacheListener; import com.graywolf336.jail.listeners.CacheListener;
import com.graywolf336.jail.listeners.EntityListener; import com.graywolf336.jail.listeners.EntityListener;
import com.graywolf336.jail.listeners.HandCuffListener; import com.graywolf336.jail.listeners.HandCuffListener;
import com.graywolf336.jail.listeners.JailingListener; import com.graywolf336.jail.listeners.JailingListener;
import com.graywolf336.jail.listeners.MoveProtectionListener; import com.graywolf336.jail.listeners.MoveProtectionListener;
import com.graywolf336.jail.listeners.PlayerListener; import com.graywolf336.jail.listeners.PlayerListener;
import com.graywolf336.jail.listeners.ProtectionListener; import com.graywolf336.jail.listeners.ProtectionListener;
/** /**
* The main class for this Jail plugin, holds instances of vital classes. * The main class for this Jail plugin, holds instances of vital classes.
* *
* @author graywolf336 * @author graywolf336
* @since 1.x.x * @since 1.x.x
* @version 3.0.0 * @version 3.0.0
*/ */
public class JailMain extends JavaPlugin { public class JailMain extends JavaPlugin {
private CommandHandler cmdHand; private CommandHandler cmdHand;
private HandCuffManager hcm; private HandCuffManager hcm;
private JailHandler jh; private JailHandler jh;
private JailIO io; private JailIO io;
private JailManager jm; private JailManager jm;
private JailPayManager jpm; private JailPayManager jpm;
private JailStickManager jsm; private JailStickManager jsm;
private JailTimer jt; private JailTimer jt;
private PrisonerManager pm; private PrisonerManager pm;
private ScoreBoardManager sbm; private ScoreBoardManager sbm;
private MoveProtectionListener mpl; private MoveProtectionListener mpl;
private boolean debug = false; private boolean debug = false;
public void onEnable() { public void onEnable() {
loadConfig(); loadConfig();
debug = getConfig().getBoolean(Settings.DEBUG.getPath()); debug = getConfig().getBoolean(Settings.DEBUG.getPath());
if(debug) getLogger().info("Debugging enabled."); if(debug) getLogger().info("Debugging enabled.");
hcm = new HandCuffManager(); hcm = new HandCuffManager();
jm = new JailManager(this); jm = new JailManager(this);
//Try to load the old stuff before we load anything, esp the storage stuff //Try to load the old stuff before we load anything, esp the storage stuff
LegacyManager lm = new LegacyManager(this); LegacyManager lm = new LegacyManager(this);
if(lm.doWeNeedToConvert()) { if(lm.doWeNeedToConvert()) {
lm.convertOldData(); lm.convertOldData();
if(!lm.wasAnythingConverted()) getLogger().severe("We was unable to convert some, or all, of the old data."); if(!lm.wasAnythingConverted()) getLogger().severe("We was unable to convert some, or all, of the old data.");
} }
io = new JailIO(this); io = new JailIO(this);
io.loadLanguage(); io.loadLanguage();
//If the prepareStorage returns false, we need to disable the plugin //If the prepareStorage returns false, we need to disable the plugin
if(!io.prepareStorage(true)) { if(!io.prepareStorage(true)) {
this.getLogger().severe("An error occured while preparing the connection to the storage, please see the error above for more information."); this.getLogger().severe("An error occured while preparing the connection to the storage, please see the error above for more information.");
this.getServer().getPluginManager().disablePlugin(this); this.getServer().getPluginManager().disablePlugin(this);
return; return;
} }
io.loadJails(); io.loadJails();
//If we converted something, let's save EVERYTHING including the cells //If we converted something, let's save EVERYTHING including the cells
if(lm.wasAnythingConverted()) { if(lm.wasAnythingConverted()) {
io.saveEverything(); io.saveEverything();
} }
cmdHand = new CommandHandler(this); cmdHand = new CommandHandler(this);
jh = new JailHandler(this); jh = new JailHandler(this);
pm = new PrisonerManager(this); pm = new PrisonerManager(this);
jsm = new JailStickManager(this); jsm = new JailStickManager(this);
PluginManager plm = this.getServer().getPluginManager(); PluginManager plm = this.getServer().getPluginManager();
plm.registerEvents(new BlockListener(this), this); plm.registerEvents(new BlockListener(this), this);
plm.registerEvents(new CacheListener(this), this); plm.registerEvents(new CacheListener(this), this);
plm.registerEvents(new EntityListener(this), this); plm.registerEvents(new EntityListener(this), this);
plm.registerEvents(new HandCuffListener(this), this); plm.registerEvents(new HandCuffListener(this), this);
plm.registerEvents(new JailingListener(this), this); plm.registerEvents(new JailingListener(this), this);
plm.registerEvents(new PlayerListener(this), this); plm.registerEvents(new PlayerListener(this), this);
plm.registerEvents(new ProtectionListener(this), this); plm.registerEvents(new ProtectionListener(this), this);
//Only register the move protection listener if this is enabled in the //Only register the move protection listener if this is enabled in the
//config when we first start the plugin. The reason for this change is //config when we first start the plugin. The reason for this change is
//that the move event is called a ton of times per single move and so //that the move event is called a ton of times per single move and so
//not registering this event listener will hopefully safe some performance. //not registering this event listener will hopefully safe some performance.
//But doing this also forces people to restart their server if they to //But doing this also forces people to restart their server if they to
//enable it after disabling it. //enable it after disabling it.
if(getConfig().getBoolean(Settings.MOVEPROTECTION.getPath())) { if(getConfig().getBoolean(Settings.MOVEPROTECTION.getPath())) {
this.mpl = new MoveProtectionListener(this); this.mpl = new MoveProtectionListener(this);
plm.registerEvents(this.mpl, this); plm.registerEvents(this.mpl, this);
} }
jt = new JailTimer(this); jt = new JailTimer(this);
reloadJailPayManager(); reloadJailPayManager();
sbm = new ScoreBoardManager(this); sbm = new ScoreBoardManager(this);
getLogger().info("Completed enablement."); getLogger().info("Completed enablement.");
} }
public void onDisable() { public void onDisable() {
if(jm != null) if(jm != null)
for(Jail j : jm.getJails()) for(Jail j : jm.getJails())
io.saveJail(j); io.saveJail(j);
if(jt != null) if(jt != null)
if(jt.getTimer() != null) if(jt.getTimer() != null)
jt.getTimer().stop(); jt.getTimer().stop();
if(io != null) if(io != null)
io.closeConnection(); io.closeConnection();
jt = null; jt = null;
sbm = null; sbm = null;
jpm = null; jpm = null;
cmdHand = null; cmdHand = null;
pm = null; pm = null;
jm = null; jm = null;
jsm = null; jsm = null;
io = null; io = null;
hcm = null; hcm = null;
} }
private void loadConfig() { private void loadConfig() {
//Only create the default config if it doesn't exist //Only create the default config if it doesn't exist
saveDefaultConfig(); saveDefaultConfig();
//Append new key-value pairs to the config //Append new key-value pairs to the config
getConfig().options().copyDefaults(true); getConfig().options().copyDefaults(true);
// Set the header and save // Set the header and save
getConfig().options().header(getHeader()); getConfig().options().header(getHeader());
saveConfig(); saveConfig();
} }
private String getHeader() { private String getHeader() {
String sep = System.getProperty("line.separator"); String sep = System.getProperty("line.separator");
return "###################" + sep return "###################" + sep
+ "Jail v" + this.getDescription().getVersion() + " config file" + sep + "Jail v" + this.getDescription().getVersion() + " config file" + sep
+ "Note: You -must- use spaces instead of tabs!" + sep + + "Note: You -must- use spaces instead of tabs!" + sep +
"###################"; "###################";
} }
/* Majority of the new command system was heavily influenced by the MobArena. /* Majority of the new command system was heavily influenced by the MobArena.
* Thank you garbagemule for the great system you have in place there. * Thank you garbagemule for the great system you have in place there.
* *
* Send the command off to the CommandHandler class, that way this main class doesn't get clogged up. * Send the command off to the CommandHandler class, that way this main class doesn't get clogged up.
*/ */
public boolean onCommand(CommandSender sender, Command command, String commandLabel, String[] args) { public boolean onCommand(CommandSender sender, Command command, String commandLabel, String[] args) {
if(commandLabel.equalsIgnoreCase("jail") || commandLabel.equalsIgnoreCase("j")) { if(commandLabel.equalsIgnoreCase("jail") || commandLabel.equalsIgnoreCase("j")) {
jh.parseCommand(jm, sender, args); jh.parseCommand(jm, sender, args);
}else { }else {
cmdHand.handleCommand(jm, sender, command.getName().toLowerCase(), args); cmdHand.handleCommand(jm, sender, command.getName().toLowerCase(), args);
} }
return true;//Always return true here, that way we can handle the help and command usage ourself. return true;//Always return true here, that way we can handle the help and command usage ourself.
} }
/** Reloads the scoreboard manager class, useful when something is changed int he config about it. */ /** Reloads the scoreboard manager class, useful when something is changed int he config about it. */
public void reloadScoreBoardManager() { public void reloadScoreBoardManager() {
this.sbm.removeAllScoreboards(); this.sbm.removeAllScoreboards();
this.sbm = null; this.sbm = null;
this.sbm = new ScoreBoardManager(this); this.sbm = new ScoreBoardManager(this);
if(getConfig().getBoolean(Settings.SCOREBOARDENABLED.getPath())) { if(getConfig().getBoolean(Settings.SCOREBOARDENABLED.getPath())) {
for(Jail j : jm.getJails()) { for(Jail j : jm.getJails()) {
for(Prisoner p : j.getAllPrisoners().values()) { for(Prisoner p : j.getAllPrisoners().values()) {
if(getServer().getPlayer(p.getUUID()) != null) { if(getServer().getPlayer(p.getUUID()) != null) {
this.sbm.addScoreBoard(getServer().getPlayer(p.getUUID()), p); this.sbm.addScoreBoard(getServer().getPlayer(p.getUUID()), p);
} }
} }
} }
} }
} }
/** Reloads the Jail Sticks, so the new ones can be loaded from the config. */ /** Reloads the Jail Sticks, so the new ones can be loaded from the config. */
public void reloadJailSticks() { public void reloadJailSticks() {
this.jsm.removeAllStickUsers(); this.jsm.removeAllStickUsers();
this.jsm = null; this.jsm = null;
this.jsm = new JailStickManager(this); this.jsm = new JailStickManager(this);
} }
/** /**
* Reloads the {@link JailPayManager}. * Reloads the {@link JailPayManager}.
* *
* @throws Exception If we couldn't successfully create a new Jail Pay Manager instance. * @throws Exception If we couldn't successfully create a new Jail Pay Manager instance.
*/ */
public void reloadJailPayManager() { public void reloadJailPayManager() {
this.jpm = null; this.jpm = null;
if(getConfig().getBoolean(Settings.JAILPAYENABLED.getPath())) { if(getConfig().getBoolean(Settings.JAILPAYENABLED.getPath())) {
if(getServer().getPluginManager().isPluginEnabled("Vault")) { if(getServer().getPluginManager().isPluginEnabled("Vault")) {
this.jpm = new JailPayManager(this); this.jpm = new JailPayManager(this);
}else { }else {
getConfig().set(Settings.JAILPAYENABLED.getPath(), false); getConfig().set(Settings.JAILPAYENABLED.getPath(), false);
getLogger().severe("Jail Pay couldn't find an economy, disabling Jail Pay."); getLogger().severe("Jail Pay couldn't find an economy, disabling Jail Pay.");
} }
} }
} }
/** Gets the {@link HandCuffManager} instance. */ /** Gets the {@link HandCuffManager} instance. */
public HandCuffManager getHandCuffManager() { public HandCuffManager getHandCuffManager() {
return this.hcm; return this.hcm;
} }
/** Gets the {@link JailIO} instance. */ /** Gets the {@link JailIO} instance. */
public JailIO getJailIO() { public JailIO getJailIO() {
return this.io; return this.io;
} }
/** Gets the {@link JailManager} instance. */ /** Gets the {@link JailManager} instance. */
public JailManager getJailManager() { public JailManager getJailManager() {
return this.jm; return this.jm;
} }
/** Gets the {@link JailPayManager} instance. */ /** Gets the {@link JailPayManager} instance. */
public JailPayManager getJailPayManager() { public JailPayManager getJailPayManager() {
return this.jpm; return this.jpm;
} }
/** Gets the {@link PrisonerManager} instance. */ /** Gets the {@link PrisonerManager} instance. */
public PrisonerManager getPrisonerManager() { public PrisonerManager getPrisonerManager() {
return this.pm; return this.pm;
} }
/** Gets the {@link JailStickManager} instance. */ /** Gets the {@link JailStickManager} instance. */
public JailStickManager getJailStickManager() { public JailStickManager getJailStickManager() {
return this.jsm; return this.jsm;
} }
/** Gets the {@link ScoreBoardManager} instance. */ /** Gets the {@link ScoreBoardManager} instance. */
public ScoreBoardManager getScoreBoardManager() { public ScoreBoardManager getScoreBoardManager() {
return this.sbm; return this.sbm;
} }
/** Sets whether the plugin is in debugging or not. */ /** Sets whether the plugin is in debugging or not. */
public boolean setDebugging(boolean debug) { public boolean setDebugging(boolean debug) {
this.debug = debug; this.debug = debug;
//Save whether we are debugging when we disable the plugin //Save whether we are debugging when we disable the plugin
getConfig().set(Settings.DEBUG.getPath(), this.debug); getConfig().set(Settings.DEBUG.getPath(), this.debug);
saveConfig(); saveConfig();
return this.debug; return this.debug;
} }
/** Returns if the plugin is in debug state or not. */ /** Returns if the plugin is in debug state or not. */
public boolean inDebug() { public boolean inDebug() {
return this.debug; return this.debug;
} }
/** Logs a debugging message to the console if debugging is enabled. */ /** Logs a debugging message to the console if debugging is enabled. */
public void debug(String message) { public void debug(String message) {
if(inDebug()) getLogger().info("[Debug]: " + message); if(inDebug()) getLogger().info("[Debug]: " + message);
} }
public MoveProtectionListener getPlayerMoveListener() { public MoveProtectionListener getPlayerMoveListener() {
return this.mpl; return this.mpl;
} }
} }

View File

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

View File

@ -1,173 +1,173 @@
package com.graywolf336.jail; package com.graywolf336.jail;
import java.util.ArrayList; import java.util.ArrayList;
import java.util.HashMap; import java.util.HashMap;
import org.bukkit.Material; import org.bukkit.Material;
import org.bukkit.configuration.file.FileConfiguration; import org.bukkit.configuration.file.FileConfiguration;
import org.bukkit.entity.Player; import org.bukkit.entity.Player;
import com.graywolf336.jail.beans.Stick; import com.graywolf336.jail.beans.Stick;
import com.graywolf336.jail.enums.Settings; import com.graywolf336.jail.enums.Settings;
/** /**
* Manages the jail stick users. * Manages the jail stick users.
* *
* @author graywolf336 * @author graywolf336
* @version 1.0.2 * @version 1.0.2
* @since 3.0.0 * @since 3.0.0
* *
*/ */
public class JailStickManager { public class JailStickManager {
private ArrayList<String> stickers; private ArrayList<String> stickers;
private HashMap<Material, Stick> sticks; private HashMap<Material, Stick> sticks;
public JailStickManager(JailMain plugin) { public JailStickManager(JailMain plugin) {
this.stickers = new ArrayList<String>(); this.stickers = new ArrayList<String>();
this.sticks = new HashMap<Material, Stick>(); this.sticks = new HashMap<Material, Stick>();
this.loadJailSticks(plugin); this.loadJailSticks(plugin);
} }
private void loadJailSticks(JailMain pl) { private void loadJailSticks(JailMain pl) {
FileConfiguration config = pl.getConfig(); FileConfiguration config = pl.getConfig();
//item name,time,jail name,reason //item name,time,jail name,reason
for(String s : config.getStringList(Settings.JAILSTICKSTICKS.getPath())) { for(String s : config.getStringList(Settings.JAILSTICKSTICKS.getPath())) {
pl.debug(s); pl.debug(s);
String[] a = s.split(","); String[] a = s.split(",");
//Check if the jail given, if any, exists //Check if the jail given, if any, exists
if(!a[2].isEmpty()) { if(!a[2].isEmpty()) {
if(!pl.getJailManager().isValidJail(a[2])) { if(!pl.getJailManager().isValidJail(a[2])) {
pl.getLogger().severe(s); pl.getLogger().severe(s);
pl.getLogger().severe("The above jail stick configuration is invalid and references a jail that doesn't exist."); pl.getLogger().severe("The above jail stick configuration is invalid and references a jail that doesn't exist.");
continue; continue;
} }
} }
Material m = Material.getMaterial(a[0].toUpperCase()); Material m = Material.getMaterial(a[0].toUpperCase());
if(this.sticks.containsKey(m)) { if(this.sticks.containsKey(m)) {
pl.getLogger().severe(s); pl.getLogger().severe(s);
pl.getLogger().severe("You can not use the same item for two different Jail Sticks. This already exists as a Jail Stick: " + a[0]); pl.getLogger().severe("You can not use the same item for two different Jail Sticks. This already exists as a Jail Stick: " + a[0]);
continue; continue;
} }
try { try {
this.sticks.put(m, new Stick(a[2], a[3], Long.valueOf(a[1]))); this.sticks.put(m, new Stick(a[2], a[3], Long.valueOf(a[1])));
}catch (Exception e) { }catch (Exception e) {
e.printStackTrace(); e.printStackTrace();
pl.getLogger().severe(s); pl.getLogger().severe(s);
pl.getLogger().severe("Unable to create a new stick for " + a[0] + ", see the exception above for details."); pl.getLogger().severe("Unable to create a new stick for " + a[0] + ", see the exception above for details.");
continue; continue;
} }
} }
int c = sticks.size(); int c = sticks.size();
pl.getLogger().info("Loaded " + c + " jail stick" + (c == 1 ? "" : "s") + "."); pl.getLogger().info("Loaded " + c + " jail stick" + (c == 1 ? "" : "s") + ".");
} }
/** /**
* Gets the {@link Stick jail stick} by the provided {@link Material}, can be null. * Gets the {@link Stick jail stick} by the provided {@link Material}, can be null.
* *
* @param mat of the stick to get * @param mat of the stick to get
* @return The {@link Stick jail stick} * @return The {@link Stick jail stick}
*/ */
public Stick getStick(Material mat) { public Stick getStick(Material mat) {
return this.sticks.get(mat); return this.sticks.get(mat);
} }
/** Checks if the provided Material is a valid {@link Stick jail stick}. */ /** Checks if the provided Material is a valid {@link Stick jail stick}. */
public boolean isValidStick(Material mat) { public boolean isValidStick(Material mat) {
return this.sticks.containsKey(mat); return this.sticks.containsKey(mat);
} }
/** /**
* Adds a player to be using a jail stick, with the player instance. * Adds a player to be using a jail stick, with the player instance.
* *
* @param player to add * @param player to add
*/ */
public void addUsingStick(Player player) { public void addUsingStick(Player player) {
this.stickers.add(player.getName()); this.stickers.add(player.getName());
} }
/** /**
* Adds a player to be using a jail stick, with their username. * Adds a player to be using a jail stick, with their username.
* *
* @param name of the player to add * @param name of the player to add
*/ */
public void addUsingStick(String name) { public void addUsingStick(String name) {
this.stickers.add(name); this.stickers.add(name);
} }
/** /**
* Removes a player from using a jail stick, with the player instance. * Removes a player from using a jail stick, with the player instance.
* *
* @param player to remove using a jail stick * @param player to remove using a jail stick
*/ */
public void removeUsingStick(Player player) { public void removeUsingStick(Player player) {
this.stickers.remove(player.getName()); this.stickers.remove(player.getName());
} }
/** /**
* Removes a player from using a jail stick, with their username. * Removes a player from using a jail stick, with their username.
* *
* @param name of the player to remove using a jail stick * @param name of the player to remove using a jail stick
*/ */
public void removeUsingStick(String name) { public void removeUsingStick(String name) {
this.stickers.remove(name); this.stickers.remove(name);
} }
/** /**
* Returns whether or not the player is using a jail stick. * Returns whether or not the player is using a jail stick.
* *
* @param player to check if using one * @param player to check if using one
* @return true if the player is using a jail stick, false if not * @return true if the player is using a jail stick, false if not
*/ */
public boolean isUsingJailStick(Player player) { public boolean isUsingJailStick(Player player) {
return this.stickers.contains(player.getName()); return this.stickers.contains(player.getName());
} }
/** /**
* Returns whether or not the player is using a jail stick. * Returns whether or not the player is using a jail stick.
* *
* @param name of the player to check if using one * @param name of the player to check if using one
* @return true if the player is using a jail stick, false if not * @return true if the player is using a jail stick, false if not
*/ */
public boolean isUsingJailStick(String name) { public boolean isUsingJailStick(String name) {
return this.stickers.contains(name); return this.stickers.contains(name);
} }
/** /**
* Toggles whether the player is using a jail stick, returning the true if enabled false if disabled. * Toggles whether the player is using a jail stick, returning the true if enabled false if disabled.
* *
* @param player to toggle using a stick * @param player to toggle using a stick
* @return true if we enabled it, false if we disabled it. * @return true if we enabled it, false if we disabled it.
*/ */
public boolean toggleUsingStick(Player player) { public boolean toggleUsingStick(Player player) {
return this.toggleUsingStick(player.getName()); return this.toggleUsingStick(player.getName());
} }
/** /**
* Toggles whether the player is using a jail stick, returning the true if enabled false if disabled. * Toggles whether the player is using a jail stick, returning the true if enabled false if disabled.
* *
* @param name of the person to toggle * @param name of the person to toggle
* @return true if we enabled it, false if we disabled it. * @return true if we enabled it, false if we disabled it.
*/ */
public boolean toggleUsingStick(String name) { public boolean toggleUsingStick(String name) {
if(this.stickers.contains(name)) { if(this.stickers.contains(name)) {
this.stickers.remove(name); this.stickers.remove(name);
return false; return false;
}else { }else {
this.stickers.add(name); this.stickers.add(name);
return true; return true;
} }
} }
/** Removes all the users currently using the sticks. */ /** Removes all the users currently using the sticks. */
public void removeAllStickUsers() { public void removeAllStickUsers() {
for(String s: stickers) { for(String s: stickers) {
this.removeUsingStick(s); this.removeUsingStick(s);
} }
} }
} }

View File

@ -1,112 +1,112 @@
package com.graywolf336.jail; package com.graywolf336.jail;
import java.awt.event.ActionEvent; import java.awt.event.ActionEvent;
import java.awt.event.ActionListener; import java.awt.event.ActionListener;
import javax.swing.Timer; import javax.swing.Timer;
import org.bukkit.entity.Player; import org.bukkit.entity.Player;
import com.graywolf336.jail.beans.Jail; import com.graywolf336.jail.beans.Jail;
import com.graywolf336.jail.beans.Prisoner; import com.graywolf336.jail.beans.Prisoner;
import com.graywolf336.jail.enums.LangString; import com.graywolf336.jail.enums.LangString;
import com.graywolf336.jail.enums.Settings; import com.graywolf336.jail.enums.Settings;
/** /**
* Contains all the logic for counting down the time of the prisoners time. * Contains all the logic for counting down the time of the prisoners time.
* *
* @author graywolf336 * @author graywolf336
* @since 2.x.x * @since 2.x.x
* @version 3.0.0 * @version 3.0.0
* *
*/ */
public class JailTimer { public class JailTimer {
private JailMain pl; private JailMain pl;
private Timer timer; private Timer timer;
private Long lastTime; private Long lastTime;
public JailTimer(JailMain plugin) { public JailTimer(JailMain plugin) {
this.pl = plugin; this.pl = plugin;
this.lastTime = System.currentTimeMillis(); this.lastTime = System.currentTimeMillis();
if(pl.getConfig().getBoolean(Settings.USEBUKKITTIMER.getPath())) { if(pl.getConfig().getBoolean(Settings.USEBUKKITTIMER.getPath())) {
pl.getLogger().info("Using the Bukkit Scheduler."); pl.getLogger().info("Using the Bukkit Scheduler.");
pl.getServer().getScheduler().scheduleSyncRepeatingTask(pl, new TimeEvent(), 20, 20); pl.getServer().getScheduler().scheduleSyncRepeatingTask(pl, new TimeEvent(), 20, 20);
}else { }else {
pl.getLogger().info("Using the Java Timer."); pl.getLogger().info("Using the Java Timer.");
timer = new Timer(1000, new ActionListener () { timer = new Timer(1000, new ActionListener () {
public void actionPerformed (ActionEvent event) { public void actionPerformed (ActionEvent event) {
pl.getServer().getScheduler().scheduleSyncDelayedTask(pl, new TimeEvent()); pl.getServer().getScheduler().scheduleSyncDelayedTask(pl, new TimeEvent());
}; };
}); });
timer.start(); timer.start();
} }
} }
/** Returns the instance of this timer. */ /** Returns the instance of this timer. */
public Timer getTimer() { public Timer getTimer() {
return this.timer; return this.timer;
} }
class TimeEvent implements Runnable { class TimeEvent implements Runnable {
public void run() { public void run() {
long timePassed; long timePassed;
//Let's check if more than 10 seconds has passed since the //Let's check if more than 10 seconds has passed since the
//last time we checked //last time we checked
if (System.currentTimeMillis() - lastTime >= 10000) { if (System.currentTimeMillis() - lastTime >= 10000) {
//set the time passed to the current time minus the last time we checked //set the time passed to the current time minus the last time we checked
timePassed = System.currentTimeMillis() - lastTime; timePassed = System.currentTimeMillis() - lastTime;
lastTime = System.currentTimeMillis(); lastTime = System.currentTimeMillis();
}else { }else {
//Less than 10 seconds has past when we last ran this //Less than 10 seconds has past when we last ran this
//so let's wait till the next round before we do this //so let's wait till the next round before we do this
return; return;
} }
for(Jail j : pl.getJailManager().getJails()) { for(Jail j : pl.getJailManager().getJails()) {
for(Prisoner p : j.getAllPrisoners().values()) { for(Prisoner p : j.getAllPrisoners().values()) {
//only execute this code if the prisoner's time is more than 0 milliseconds //only execute this code if the prisoner's time is more than 0 milliseconds
if(p.getRemainingTime() > 0) { if(p.getRemainingTime() > 0) {
Player player = pl.getServer().getPlayer(p.getUUID()); Player player = pl.getServer().getPlayer(p.getUUID());
//Check if the player is offline //Check if the player is offline
if(player == null) { if(player == null) {
//if they are offline AND the config has counting down the time //if they are offline AND the config has counting down the time
//while the prisoner is offline, then let's do it //while the prisoner is offline, then let's do it
if(pl.getConfig().getBoolean(Settings.COUNTDOWNTIMEOFFLINE.getPath())) { if(pl.getConfig().getBoolean(Settings.COUNTDOWNTIMEOFFLINE.getPath())) {
//Set their remaining time but if it is less than zero, set it to zero //Set their remaining time but if it is less than zero, set it to zero
p.setRemainingTime(Math.max(0, p.getRemainingTime() - timePassed)); p.setRemainingTime(Math.max(0, p.getRemainingTime() - timePassed));
if(p.getRemainingTime() == 0) pl.getPrisonerManager().releasePrisoner(player, p); if(p.getRemainingTime() == 0) pl.getPrisonerManager().releasePrisoner(player, p);
} }
}else { }else {
//The prisoner isn't offline, so let's count down //The prisoner isn't offline, so let's count down
//Set their remaining time but if it is less than zero, set it to zero //Set their remaining time but if it is less than zero, set it to zero
p.setRemainingTime(Math.max(0, p.getRemainingTime() - timePassed)); p.setRemainingTime(Math.max(0, p.getRemainingTime() - timePassed));
if(p.getRemainingTime() == 0) pl.getPrisonerManager().releasePrisoner(player, p); if(p.getRemainingTime() == 0) pl.getPrisonerManager().releasePrisoner(player, p);
//Now, let's set and check their afk time //Now, let's set and check their afk time
//add the time passed to their current afk time //add the time passed to their current afk time
try { try {
long afk = Util.getTime(pl.getConfig().getString(Settings.MAXAFKTIME.getPath())); long afk = Util.getTime(pl.getConfig().getString(Settings.MAXAFKTIME.getPath()));
if(afk > 0) { if(afk > 0) {
p.setAFKTime(p.getAFKTime() + timePassed); p.setAFKTime(p.getAFKTime() + timePassed);
if(p.getAFKTime() > afk) { if(p.getAFKTime() > afk) {
p.setAFKTime(0); p.setAFKTime(0);
player.kickPlayer(pl.getJailIO().getLanguageString(LangString.AFKKICKMESSAGE)); player.kickPlayer(pl.getJailIO().getLanguageString(LangString.AFKKICKMESSAGE));
} }
} }
} catch (Exception e) { } catch (Exception e) {
pl.getLogger().severe("Error while processing the max afk time: " + e.getMessage()); pl.getLogger().severe("Error while processing the max afk time: " + e.getMessage());
} }
} }
} }
} }
//Save all the prisoners and jails after we're done //Save all the prisoners and jails after we're done
pl.getJailIO().saveJail(j); pl.getJailIO().saveJail(j);
} }
} }
} }
} }

File diff suppressed because it is too large Load Diff

View File

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

View File

@ -1,334 +1,334 @@
package com.graywolf336.jail; package com.graywolf336.jail;
import java.io.ByteArrayInputStream; import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream; import java.io.ByteArrayOutputStream;
import java.io.IOException; import java.io.IOException;
import java.util.LinkedList; import java.util.LinkedList;
import java.util.List; import java.util.List;
import java.util.concurrent.TimeUnit; import java.util.concurrent.TimeUnit;
import java.util.regex.Matcher; import java.util.regex.Matcher;
import java.util.regex.Pattern; import java.util.regex.Pattern;
import org.bukkit.Bukkit; import org.bukkit.Bukkit;
import org.bukkit.ChatColor; import org.bukkit.ChatColor;
import org.bukkit.Material; import org.bukkit.Material;
import org.bukkit.entity.Player; import org.bukkit.entity.Player;
import org.bukkit.inventory.Inventory; import org.bukkit.inventory.Inventory;
import org.bukkit.inventory.ItemStack; import org.bukkit.inventory.ItemStack;
import org.bukkit.inventory.PlayerInventory; import org.bukkit.inventory.PlayerInventory;
import org.bukkit.inventory.meta.ItemMeta; import org.bukkit.inventory.meta.ItemMeta;
import org.bukkit.util.Vector; import org.bukkit.util.Vector;
import org.bukkit.util.io.BukkitObjectInputStream; import org.bukkit.util.io.BukkitObjectInputStream;
import org.bukkit.util.io.BukkitObjectOutputStream; import org.bukkit.util.io.BukkitObjectOutputStream;
import org.yaml.snakeyaml.external.biz.base64Coder.Base64Coder; import org.yaml.snakeyaml.external.biz.base64Coder.Base64Coder;
import com.graywolf336.jail.beans.Prisoner; import com.graywolf336.jail.beans.Prisoner;
/** /**
* Provides a variety of methods, static, that are used throughout the plugin. * Provides a variety of methods, static, that are used throughout the plugin.
* *
* @author graywolf336 * @author graywolf336
* @since 2.x.x * @since 2.x.x
* @version 3.0.0 * @version 3.0.0
*/ */
public class Util { public class Util {
private final static Pattern DURATION_PATTERN = Pattern.compile("^(\\d+)\\s*(m(?:inute)?s?|h(?:ours?)?|d(?:ays?)?|s(?:econd)?s?)?$", Pattern.CASE_INSENSITIVE); private final static Pattern DURATION_PATTERN = Pattern.compile("^(\\d+)\\s*(m(?:inute)?s?|h(?:ours?)?|d(?:ays?)?|s(?:econd)?s?)?$", Pattern.CASE_INSENSITIVE);
/** /**
* Checks if the first {@link Vector} is inside this region. * Checks if the first {@link Vector} is inside this region.
* *
* @param point The point to check * @param point The point to check
* @param first point of the region * @param first point of the region
* @param second second point of the region * @param second second point of the region
* @return True if all the coords of the first vector are in the entire region. * @return True if all the coords of the first vector are in the entire region.
*/ */
public static boolean isInsideAB(Vector point, Vector first, Vector second) { public static boolean isInsideAB(Vector point, Vector first, Vector second) {
boolean x = isInside(point.getBlockX(), first.getBlockX(), second.getBlockX()); boolean x = isInside(point.getBlockX(), first.getBlockX(), second.getBlockX());
boolean y = isInside(point.getBlockY(), first.getBlockY(), second.getBlockY()); boolean y = isInside(point.getBlockY(), first.getBlockY(), second.getBlockY());
boolean z = isInside(point.getBlockZ(), first.getBlockZ(), second.getBlockZ()); boolean z = isInside(point.getBlockZ(), first.getBlockZ(), second.getBlockZ());
return x && y && z; return x && y && z;
} }
/** /**
* Checks if two numbers are inside a point, or something. * Checks if two numbers are inside a point, or something.
* *
* <p /> * <p />
* *
* @param loc The location. * @param loc The location.
* @param first The first point * @param first The first point
* @param second The second point * @param second The second point
* @return true if they are inside, false if not. * @return true if they are inside, false if not.
*/ */
private static boolean isInside(int loc, int first, int second) { private static boolean isInside(int loc, int first, int second) {
int point1 = 0; int point1 = 0;
int point2 = 0; int point2 = 0;
if (first < second) { if (first < second) {
point1 = first; point1 = first;
point2 = second; point2 = second;
} else { } else {
point2 = first; point2 = first;
point1 = second; point1 = second;
} }
return (point1 <= loc) && (loc <= point2); return (point1 <= loc) && (loc <= point2);
} }
/** /**
* Checks if the given string is inside the list, ignoring the casing. * Checks if the given string is inside the list, ignoring the casing.
* *
* <p /> * <p />
* *
* @param list of strings to check * @param list of strings to check
* @param value to check * @param value to check
* @return true if the list contains the provided value, false if it doesn't * @return true if the list contains the provided value, false if it doesn't
*/ */
public static boolean isStringInsideList(List<String> list, String value) { public static boolean isStringInsideList(List<String> list, String value) {
boolean r = false; boolean r = false;
for(String s : list) for(String s : list)
if(s.equalsIgnoreCase(value)) if(s.equalsIgnoreCase(value))
return true; return true;
return r; return r;
} }
/** Returns a colorful message from the color codes. */ /** Returns a colorful message from the color codes. */
public static String getColorfulMessage(String message) { public static String getColorfulMessage(String message) {
return message.replaceAll("(?i)&([0-9abcdefklmnor])", "\u00A7$1"); return message.replaceAll("(?i)&([0-9abcdefklmnor])", "\u00A7$1");
} }
/** Returns the wand used throughout the different creation steps. */ /** Returns the wand used throughout the different creation steps. */
public static ItemStack getWand() { public static ItemStack getWand() {
ItemStack wand = new ItemStack(Material.WOOD_SWORD); ItemStack wand = new ItemStack(Material.WOOD_SWORD);
ItemMeta meta = wand.getItemMeta(); ItemMeta meta = wand.getItemMeta();
meta.setDisplayName(ChatColor.AQUA + "Jail Wand"); meta.setDisplayName(ChatColor.AQUA + "Jail Wand");
LinkedList<String> lore = new LinkedList<String>(); LinkedList<String> lore = new LinkedList<String>();
lore.add(ChatColor.BLUE + "The wand for creating"); lore.add(ChatColor.BLUE + "The wand for creating");
lore.add(ChatColor.BLUE + "a jail or cell."); lore.add(ChatColor.BLUE + "a jail or cell.");
meta.setLore(lore); meta.setLore(lore);
wand.setItemMeta(meta); wand.setItemMeta(meta);
return wand; return wand;
} }
/** /**
* Converts a string like '20minutes' into the appropriate amount of milliseconds. * Converts a string like '20minutes' into the appropriate amount of milliseconds.
* *
* @param time The string to convert. * @param time The string to convert.
* @return The time in milliseconds that is converted. * @return The time in milliseconds that is converted.
* @throws Exception if there are no matches * @throws Exception if there are no matches
*/ */
public static Long getTime(String time) throws Exception { public static Long getTime(String time) throws Exception {
if(time.equalsIgnoreCase("-1")) return -1L; if(time.equalsIgnoreCase("-1")) return -1L;
Long t = 10L; Long t = 10L;
Matcher match = DURATION_PATTERN.matcher(time); Matcher match = DURATION_PATTERN.matcher(time);
if (match.matches()) { if (match.matches()) {
String units = match.group(2); String units = match.group(2);
if ("seconds".equals(units) || "second".equals(units) || "s".equals(units)) if ("seconds".equals(units) || "second".equals(units) || "s".equals(units))
t = TimeUnit.MILLISECONDS.convert(Long.valueOf(match.group(1)), TimeUnit.SECONDS); t = TimeUnit.MILLISECONDS.convert(Long.valueOf(match.group(1)), TimeUnit.SECONDS);
else if ("minutes".equals(units) || "minute".equals(units) || "mins".equals(units) || "min".equals(units) || "m".equals(units)) else if ("minutes".equals(units) || "minute".equals(units) || "mins".equals(units) || "min".equals(units) || "m".equals(units))
t = TimeUnit.MILLISECONDS.convert(Long.valueOf(match.group(1)), TimeUnit.MINUTES); t = TimeUnit.MILLISECONDS.convert(Long.valueOf(match.group(1)), TimeUnit.MINUTES);
else if ("hours".equals(units) || "hour".equals(units) || "h".equals(units)) else if ("hours".equals(units) || "hour".equals(units) || "h".equals(units))
t = TimeUnit.MILLISECONDS.convert(Long.valueOf(match.group(1)), TimeUnit.HOURS); t = TimeUnit.MILLISECONDS.convert(Long.valueOf(match.group(1)), TimeUnit.HOURS);
else if ("days".equals(units) || "day".equals(units) || "d".equals(units)) else if ("days".equals(units) || "day".equals(units) || "d".equals(units))
t = TimeUnit.MILLISECONDS.convert(Long.valueOf(match.group(1)), TimeUnit.DAYS); t = TimeUnit.MILLISECONDS.convert(Long.valueOf(match.group(1)), TimeUnit.DAYS);
else { else {
try { try {
t = TimeUnit.MILLISECONDS.convert(Long.parseLong(time), TimeUnit.MINUTES); t = TimeUnit.MILLISECONDS.convert(Long.parseLong(time), TimeUnit.MINUTES);
}catch(NumberFormatException e) { }catch(NumberFormatException e) {
throw new Exception("Invalid format."); throw new Exception("Invalid format.");
} }
} }
}else { }else {
throw new Exception("Invalid format."); throw new Exception("Invalid format.");
} }
return Long.valueOf(t); return Long.valueOf(t);
} }
/** /**
* Converts the player inventory to a String array of Base64 strings. First string is the content and second string is the armor. * Converts the player inventory to a String array of Base64 strings. First string is the content and second string is the armor.
* *
* @param playerInventory to turn into an array of strings. * @param playerInventory to turn into an array of strings.
* @return Array of strings: [ main content, armor content ] * @return Array of strings: [ main content, armor content ]
* @throws IllegalStateException * @throws IllegalStateException
*/ */
public static String[] playerInventoryToBase64(PlayerInventory playerInventory) throws IllegalStateException { public static String[] playerInventoryToBase64(PlayerInventory playerInventory) throws IllegalStateException {
//get the main content part, this doesn't return the armor //get the main content part, this doesn't return the armor
String content = toBase64(playerInventory); String content = toBase64(playerInventory);
String armor = itemStackArrayToBase64(playerInventory.getArmorContents()); String armor = itemStackArrayToBase64(playerInventory.getArmorContents());
return new String[] { content, armor }; return new String[] { content, armor };
} }
/** /**
* *
* A method to serialize an {@link ItemStack} array to Base64 String. * A method to serialize an {@link ItemStack} array to Base64 String.
* *
* <p /> * <p />
* *
* Based off of {@link #toBase64(Inventory)}. * Based off of {@link #toBase64(Inventory)}.
* *
* @param items to turn into a Base64 String. * @param items to turn into a Base64 String.
* @return Base64 string of the items. * @return Base64 string of the items.
* @throws IllegalStateException * @throws IllegalStateException
*/ */
public static String itemStackArrayToBase64(ItemStack[] items) throws IllegalStateException { public static String itemStackArrayToBase64(ItemStack[] items) throws IllegalStateException {
try { try {
ByteArrayOutputStream outputStream = new ByteArrayOutputStream(); ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
BukkitObjectOutputStream dataOutput = new BukkitObjectOutputStream(outputStream); BukkitObjectOutputStream dataOutput = new BukkitObjectOutputStream(outputStream);
// Write the size of the inventory // Write the size of the inventory
dataOutput.writeInt(items.length); dataOutput.writeInt(items.length);
// Save every element in the list // Save every element in the list
for (int i = 0; i < items.length; i++) { for (int i = 0; i < items.length; i++) {
dataOutput.writeObject(items[i]); dataOutput.writeObject(items[i]);
} }
// Serialize that array // Serialize that array
dataOutput.close(); dataOutput.close();
return Base64Coder.encodeLines(outputStream.toByteArray()); return Base64Coder.encodeLines(outputStream.toByteArray());
} catch (Exception e) { } catch (Exception e) {
throw new IllegalStateException("Unable to save item stacks.", e); throw new IllegalStateException("Unable to save item stacks.", e);
} }
} }
/** /**
* A method to serialize an inventory to Base64 string. * A method to serialize an inventory to Base64 string.
* *
* <p /> * <p />
* *
* Special thanks to Comphenix in the Bukkit forums or also known * Special thanks to Comphenix in the Bukkit forums or also known
* as aadnk on GitHub. * as aadnk on GitHub.
* *
* <a href="https://gist.github.com/aadnk/8138186">Original Source</a> * <a href="https://gist.github.com/aadnk/8138186">Original Source</a>
* *
* @param inventory to serialize * @param inventory to serialize
* @return Base64 string of the provided inventory * @return Base64 string of the provided inventory
* @throws IllegalStateException * @throws IllegalStateException
*/ */
public static String toBase64(Inventory inventory) throws IllegalStateException { public static String toBase64(Inventory inventory) throws IllegalStateException {
try { try {
ByteArrayOutputStream outputStream = new ByteArrayOutputStream(); ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
BukkitObjectOutputStream dataOutput = new BukkitObjectOutputStream(outputStream); BukkitObjectOutputStream dataOutput = new BukkitObjectOutputStream(outputStream);
// Write the size of the inventory // Write the size of the inventory
dataOutput.writeInt(inventory.getSize()); dataOutput.writeInt(inventory.getSize());
// Save every element in the list // Save every element in the list
for (int i = 0; i < inventory.getSize(); i++) { for (int i = 0; i < inventory.getSize(); i++) {
dataOutput.writeObject(inventory.getItem(i)); dataOutput.writeObject(inventory.getItem(i));
} }
// Serialize that array // Serialize that array
dataOutput.close(); dataOutput.close();
return Base64Coder.encodeLines(outputStream.toByteArray()); return Base64Coder.encodeLines(outputStream.toByteArray());
} catch (Exception e) { } catch (Exception e) {
throw new IllegalStateException("Unable to save item stacks.", e); throw new IllegalStateException("Unable to save item stacks.", e);
} }
} }
/** /**
* *
* A method to get an {@link Inventory} from an encoded, Base64, string. * 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 * Special thanks to Comphenix in the Bukkit forums or also known
* as aadnk on GitHub. * as aadnk on GitHub.
* *
* <a href="https://gist.github.com/aadnk/8138186">Original Source</a> * <a href="https://gist.github.com/aadnk/8138186">Original Source</a>
* *
* @param data Base64 string of data containing an inventory. * @param data Base64 string of data containing an inventory.
* @return Inventory created from the Base64 string. * @return Inventory created from the Base64 string.
* @throws IOException * @throws IOException
*/ */
public static Inventory fromBase64(String data) throws IOException { public static Inventory fromBase64(String data) throws IOException {
if(data.isEmpty()) Bukkit.getServer().createInventory(null, 0); if(data.isEmpty()) Bukkit.getServer().createInventory(null, 0);
try { try {
ByteArrayInputStream inputStream = new ByteArrayInputStream(Base64Coder.decodeLines(data)); ByteArrayInputStream inputStream = new ByteArrayInputStream(Base64Coder.decodeLines(data));
BukkitObjectInputStream dataInput = new BukkitObjectInputStream(inputStream); BukkitObjectInputStream dataInput = new BukkitObjectInputStream(inputStream);
Inventory inventory = Bukkit.getServer().createInventory(null, dataInput.readInt()); Inventory inventory = Bukkit.getServer().createInventory(null, dataInput.readInt());
// Read the serialized inventory // Read the serialized inventory
for (int i = 0; i < inventory.getSize(); i++) { for (int i = 0; i < inventory.getSize(); i++) {
inventory.setItem(i, (ItemStack) dataInput.readObject()); inventory.setItem(i, (ItemStack) dataInput.readObject());
} }
dataInput.close(); dataInput.close();
return inventory; return inventory;
} catch (ClassNotFoundException e) { } catch (ClassNotFoundException e) {
throw new IOException("Unable to decode class type.", e); throw new IOException("Unable to decode class type.", e);
} }
} }
/** /**
* Gets an array of ItemStacks from Base64 string. * Gets an array of ItemStacks from Base64 string.
* *
* <p /> * <p />
* *
* Base off of {@link #fromBase64(String)}. * Base off of {@link #fromBase64(String)}.
* *
* @param data Base64 string to convert to ItemStack array. * @param data Base64 string to convert to ItemStack array.
* @return ItemStack array created from the Base64 string. * @return ItemStack array created from the Base64 string.
* @throws IOException * @throws IOException
*/ */
public static ItemStack[] itemStackArrayFromBase64(String data) throws IOException { public static ItemStack[] itemStackArrayFromBase64(String data) throws IOException {
if(data.isEmpty()) return new ItemStack[] {}; if(data.isEmpty()) return new ItemStack[] {};
try { try {
ByteArrayInputStream inputStream = new ByteArrayInputStream(Base64Coder.decodeLines(data)); ByteArrayInputStream inputStream = new ByteArrayInputStream(Base64Coder.decodeLines(data));
BukkitObjectInputStream dataInput = new BukkitObjectInputStream(inputStream); BukkitObjectInputStream dataInput = new BukkitObjectInputStream(inputStream);
ItemStack[] items = new ItemStack[dataInput.readInt()]; ItemStack[] items = new ItemStack[dataInput.readInt()];
// Read the serialized inventory // Read the serialized inventory
for (int i = 0; i < items.length; i++) { for (int i = 0; i < items.length; i++) {
items[i] = (ItemStack) dataInput.readObject(); items[i] = (ItemStack) dataInput.readObject();
} }
dataInput.close(); dataInput.close();
return items; return items;
} catch (ClassNotFoundException e) { } catch (ClassNotFoundException e) {
throw new IOException("Unable to decode class type.", e); throw new IOException("Unable to decode class type.", e);
} }
} }
public static void restoreInventory(Player player, Prisoner prisoner) { public static void restoreInventory(Player player, Prisoner prisoner) {
try { try {
Inventory content = Util.fromBase64(prisoner.getInventory()); Inventory content = Util.fromBase64(prisoner.getInventory());
ItemStack[] armor = Util.itemStackArrayFromBase64(prisoner.getArmor()); ItemStack[] armor = Util.itemStackArrayFromBase64(prisoner.getArmor());
for(ItemStack item : armor) { for(ItemStack item : armor) {
if(item == null) if(item == null)
continue; continue;
else if(item.getType().toString().toLowerCase().contains("helmet")) else if(item.getType().toString().toLowerCase().contains("helmet"))
player.getInventory().setHelmet(item); player.getInventory().setHelmet(item);
else if(item.getType().toString().toLowerCase().contains("chestplate")) else if(item.getType().toString().toLowerCase().contains("chestplate"))
player.getInventory().setChestplate(item); player.getInventory().setChestplate(item);
else if(item.getType().toString().toLowerCase().contains("leg")) else if(item.getType().toString().toLowerCase().contains("leg"))
player.getInventory().setLeggings(item); player.getInventory().setLeggings(item);
else if(item.getType().toString().toLowerCase().contains("boots")) else if(item.getType().toString().toLowerCase().contains("boots"))
player.getInventory().setBoots(item); player.getInventory().setBoots(item);
else if (player.getInventory().firstEmpty() == -1) else if (player.getInventory().firstEmpty() == -1)
player.getWorld().dropItem(player.getLocation(), item); player.getWorld().dropItem(player.getLocation(), item);
else else
player.getInventory().addItem(item); player.getInventory().addItem(item);
} }
for(ItemStack item : content.getContents()) { for(ItemStack item : content.getContents()) {
if(item == null) continue; if(item == null) continue;
else if(player.getInventory().firstEmpty() == -1) else if(player.getInventory().firstEmpty() == -1)
player.getWorld().dropItem(player.getLocation(), item); player.getWorld().dropItem(player.getLocation(), item);
else else
player.getInventory().addItem(item); player.getInventory().addItem(item);
} }
} catch (IOException e) { } catch (IOException e) {
e.printStackTrace(); e.printStackTrace();
Bukkit.getLogger().severe("Unable to restore " + player.getName() + "'s inventory."); Bukkit.getLogger().severe("Unable to restore " + player.getName() + "'s inventory.");
} }
} }
} }

View File

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

View File

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

View File

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

View File

@ -1,254 +1,254 @@
package com.graywolf336.jail.beans; package com.graywolf336.jail.beans;
import java.util.UUID; import java.util.UUID;
import java.util.concurrent.TimeUnit; import java.util.concurrent.TimeUnit;
import org.bukkit.Bukkit; import org.bukkit.Bukkit;
import org.bukkit.GameMode; import org.bukkit.GameMode;
import org.bukkit.Location; import org.bukkit.Location;
/** /**
* Represents a Prisoner, player who is jailed, and contains all the information about him/her. * Represents a Prisoner, player who is jailed, and contains all the information about him/her.
* *
* @author graywolf336 * @author graywolf336
* @since 2.x.x * @since 2.x.x
* @version 3.0.1 * @version 3.0.1
*/ */
public class Prisoner { public class Prisoner {
private String uuid, name, jailer, reason, inventory, armor; private String uuid, name, jailer, reason, inventory, armor;
private boolean muted, offlinePending, teleporting, toBeTransferred; private boolean muted, offlinePending, teleporting, toBeTransferred;
private long time, afk; private long time, afk;
private Location previousPosition; private Location previousPosition;
private GameMode previousGameMode; private GameMode previousGameMode;
/** /**
* Creates a new prisoner with a name and whether they are muted or not. * Creates a new prisoner with a name and whether they are muted or not.
* *
* @param uuid The uuid of the prisoner * @param uuid The uuid of the prisoner
* @param name The name of the prisoner * @param name The name of the prisoner
* @param muted Whether the prisoner is muted or not * @param muted Whether the prisoner is muted or not
* @param time The amount of remaining time the prisoner has * @param time The amount of remaining time the prisoner has
* @param jailer The name of the person who jailed this prisoner * @param jailer The name of the person who jailed this prisoner
* @param reason The reason why this prisoner is in jail * @param reason The reason why this prisoner is in jail
*/ */
public Prisoner(String uuid, String name, boolean muted, long time, String jailer, String reason) { public Prisoner(String uuid, String name, boolean muted, long time, String jailer, String reason) {
this.uuid = uuid; this.uuid = uuid;
this.name = name; this.name = name;
this.muted = muted; this.muted = muted;
this.time = time; this.time = time;
this.jailer = jailer; this.jailer = jailer;
this.reason = reason; this.reason = reason;
this.offlinePending = false; this.offlinePending = false;
this.teleporting = false; this.teleporting = false;
this.toBeTransferred = false; this.toBeTransferred = false;
this.previousPosition = null; this.previousPosition = null;
this.previousGameMode = GameMode.SURVIVAL; this.previousGameMode = GameMode.SURVIVAL;
this.inventory = ""; this.inventory = "";
this.armor = ""; this.armor = "";
this.afk = 0; this.afk = 0;
} }
/** Returns the UUID of the prisoner. */ /** Returns the UUID of the prisoner. */
public UUID getUUID() { public UUID getUUID() {
return UUID.fromString(this.uuid); return UUID.fromString(this.uuid);
} }
/** Gets the name of this prisoner. */ /** Gets the name of this prisoner. */
public String getLastKnownName() { public String getLastKnownName() {
return this.name; return this.name;
} }
/** Sets the name of this prisoner. */ /** Sets the name of this prisoner. */
public String setLastKnownName(String username) { public String setLastKnownName(String username) {
this.name = username; this.name = username;
return this.name; return this.name;
} }
/** Gets the reason this player was jailed for. */ /** Gets the reason this player was jailed for. */
public String getReason() { public String getReason() {
return this.reason; return this.reason;
} }
/** Sets the reason this player was jailed for. */ /** Sets the reason this player was jailed for. */
public void setReason(String reason) { public void setReason(String reason) {
this.reason = reason; this.reason = reason;
} }
/** Gets the person who jailed this prisoner. */ /** Gets the person who jailed this prisoner. */
public String getJailer() { public String getJailer() {
return this.jailer; return this.jailer;
} }
/** Sets the person who jailed this prisoner. */ /** Sets the person who jailed this prisoner. */
public void setJailer(String jailer) { public void setJailer(String jailer) {
this.jailer = jailer; this.jailer = jailer;
} }
/** Gets whether the prisoner is muted or not. */ /** Gets whether the prisoner is muted or not. */
public boolean isMuted() { public boolean isMuted() {
return this.muted; return this.muted;
} }
/** Sets whether the prisoner is muted or not. */ /** Sets whether the prisoner is muted or not. */
public void setMuted(boolean muted) { public void setMuted(boolean muted) {
this.muted = muted; this.muted = muted;
} }
/** Gets the remaining time the prisoner has. */ /** Gets the remaining time the prisoner has. */
public long getRemainingTime() { public long getRemainingTime() {
return this.time; return this.time;
} }
/** Gets the remaining time the prisoner has in minutes. */ /** Gets the remaining time the prisoner has in minutes. */
public long getRemainingTimeInMinutes() { public long getRemainingTimeInMinutes() {
return TimeUnit.MINUTES.convert(time, TimeUnit.MILLISECONDS); return TimeUnit.MINUTES.convert(time, TimeUnit.MILLISECONDS);
} }
/** Gets the remaining time the prison has in minutes except only in int format. */ /** Gets the remaining time the prison has in minutes except only in int format. */
public int getRemainingTimeInMinutesInt() { public int getRemainingTimeInMinutesInt() {
return (int) this.getRemainingTimeInMinutes(); return (int) this.getRemainingTimeInMinutes();
} }
/** /**
* Sets the remaining time the prisoner has left. * Sets the remaining time the prisoner has left.
* *
* @param time The amount of time left, in milliseconds. * @param time The amount of time left, in milliseconds.
*/ */
public void setRemainingTime(long time) { public void setRemainingTime(long time) {
this.time = time; this.time = time;
} }
/** /**
* Adds the given time to the remaining time the prisoner has left. * Adds the given time to the remaining time the prisoner has left.
* *
* @param time to add to the prisoner's remaining time. * @param time to add to the prisoner's remaining time.
* @return the new remaining time the prisoner has * @return the new remaining time the prisoner has
*/ */
public long addTime(long time) { public long addTime(long time) {
this.time += time; this.time += time;
return this.time; return this.time;
} }
/** /**
* Subtracts the given time from the remaining time the prisoner has left. * Subtracts the given time from the remaining time the prisoner has left.
* *
* @param time to subtract from the prisoner's remaining time. * @param time to subtract from the prisoner's remaining time.
* @return the new remaining time the prisoner has * @return the new remaining time the prisoner has
*/ */
public long subtractTime(long time) { public long subtractTime(long time) {
this.time -= time; this.time -= time;
return this.time; return this.time;
} }
/** Gets whether the player is offline or not. */ /** Gets whether the player is offline or not. */
public boolean isOfflinePending() { public boolean isOfflinePending() {
return this.offlinePending; return this.offlinePending;
} }
/** Sets whether the player is offline or not. */ /** Sets whether the player is offline or not. */
public void setOfflinePending(boolean offline) { public void setOfflinePending(boolean offline) {
this.offlinePending = offline; this.offlinePending = offline;
} }
/** Gets whether the player is being teleported or not. */ /** Gets whether the player is being teleported or not. */
public boolean isTeleporting() { public boolean isTeleporting() {
return this.teleporting; return this.teleporting;
} }
/** Sets whether the player is being teleported or not. */ /** Sets whether the player is being teleported or not. */
public void setTeleporting(boolean teleport) { public void setTeleporting(boolean teleport) {
this.teleporting = teleport; this.teleporting = teleport;
} }
/** Gets whether the prisoner is going to be transferred or not, mainly for teleporting on join purposes. */ /** Gets whether the prisoner is going to be transferred or not, mainly for teleporting on join purposes. */
public boolean isToBeTransferred() { public boolean isToBeTransferred() {
return this.toBeTransferred; return this.toBeTransferred;
} }
/** Sets whether the prisoner is going to be transferred or not, mainly for teleporting on join purposes. */ /** Sets whether the prisoner is going to be transferred or not, mainly for teleporting on join purposes. */
public void setToBeTransferred(boolean transferred) { public void setToBeTransferred(boolean transferred) {
this.toBeTransferred = transferred; this.toBeTransferred = transferred;
} }
/** Gets the previous location of this player, can be null. */ /** Gets the previous location of this player, can be null. */
public Location getPreviousLocation() { public Location getPreviousLocation() {
return this.previousPosition; return this.previousPosition;
} }
/** Gets the previous location of this player, separated by a comma. */ /** Gets the previous location of this player, separated by a comma. */
public String getPreviousLocationString() { public String getPreviousLocationString() {
if(previousPosition == null) return ""; if(previousPosition == null) return "";
else return previousPosition.getWorld().getName() + "," + else return previousPosition.getWorld().getName() + "," +
previousPosition.getX() + "," + previousPosition.getX() + "," +
previousPosition.getY() + "," + previousPosition.getY() + "," +
previousPosition.getZ() + "," + previousPosition.getZ() + "," +
previousPosition.getYaw() + "," + previousPosition.getYaw() + "," +
previousPosition.getPitch(); previousPosition.getPitch();
} }
/** Sets the previous location of this player. */ /** Sets the previous location of this player. */
public void setPreviousPosition(Location location) { public void setPreviousPosition(Location location) {
this.previousPosition = location; this.previousPosition = location;
} }
/** Sets the previous location of this player from a comma separated string. */ /** Sets the previous location of this player from a comma separated string. */
public void setPreviousPosition(String location) { public void setPreviousPosition(String location) {
if(location == null) return; if(location == null) return;
if(location.isEmpty()) return; if(location.isEmpty()) return;
String[] s = location.split(","); String[] s = location.split(",");
this.previousPosition = new Location(Bukkit.getWorld(s[0]), this.previousPosition = new Location(Bukkit.getWorld(s[0]),
Double.valueOf(s[1]), Double.valueOf(s[1]),
Double.valueOf(s[2]), Double.valueOf(s[2]),
Double.valueOf(s[3]), Double.valueOf(s[3]),
Float.valueOf(s[4]), Float.valueOf(s[4]),
Float.valueOf(s[5])); Float.valueOf(s[5]));
} }
/** Gets the previous gamemode of this player. */ /** Gets the previous gamemode of this player. */
public GameMode getPreviousGameMode() { public GameMode getPreviousGameMode() {
return this.previousGameMode; return this.previousGameMode;
} }
/** Sets the previous gamemode of this player. */ /** Sets the previous gamemode of this player. */
public void setPreviousGameMode(GameMode previous) { public void setPreviousGameMode(GameMode previous) {
this.previousGameMode = previous; this.previousGameMode = previous;
} }
/** Sets the previous gamemode of this player based upon the provided string. */ /** Sets the previous gamemode of this player based upon the provided string. */
public void setPreviousGameMode(String previous) { public void setPreviousGameMode(String previous) {
if(previous == null) return; if(previous == null) return;
else if(previous.isEmpty()) return; else if(previous.isEmpty()) return;
else this.previousGameMode = GameMode.valueOf(previous); else this.previousGameMode = GameMode.valueOf(previous);
} }
/** Gets the inventory string for this player, it is encoded in Base64 string. */ /** Gets the inventory string for this player, it is encoded in Base64 string. */
public String getInventory() { public String getInventory() {
return this.inventory; return this.inventory;
} }
/** Sets the inventory Base64 string. */ /** Sets the inventory Base64 string. */
public void setInventory(String inventory) { public void setInventory(String inventory) {
this.inventory = inventory; this.inventory = inventory;
} }
/** Gets the armor content, encoded in Base64 string. */ /** Gets the armor content, encoded in Base64 string. */
public String getArmor() { public String getArmor() {
return this.armor; return this.armor;
} }
/** Sets the armor inventory Base64 string. */ /** Sets the armor inventory Base64 string. */
public void setArmor(String armor) { public void setArmor(String armor) {
this.armor = armor; this.armor = armor;
} }
/** Gets the time, in milliseconds, this prisoner has been afk. */ /** Gets the time, in milliseconds, this prisoner has been afk. */
public long getAFKTime() { public long getAFKTime() {
return this.afk; return this.afk;
} }
/** Sets the time, in milliseconds, this prisoner has been afk. */ /** Sets the time, in milliseconds, this prisoner has been afk. */
public void setAFKTime(long time) { public void setAFKTime(long time) {
this.afk = time; this.afk = time;
} }
} }

View File

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

View File

@ -1,37 +1,37 @@
package com.graywolf336.jail.beans; package com.graywolf336.jail.beans;
/** /**
* Represents a Jail Stick, contains all the information. * Represents a Jail Stick, contains all the information.
* *
* @author graywolf336 * @author graywolf336
* @version 1.0.1 * @version 1.0.1
* @since 3.0.0 * @since 3.0.0
* *
*/ */
public class Stick { public class Stick {
private String jail, reason; private String jail, reason;
private long time; private long time;
public Stick(String jail, String reason, long time) { public Stick(String jail, String reason, long time) {
this.jail = jail; this.jail = jail;
this.reason = reason; this.reason = reason;
this.time = time; this.time = time;
} }
public String getJail() { public String getJail() {
return this.jail; return this.jail;
} }
public String getReason() { public String getReason() {
return this.reason; return this.reason;
} }
public long getTime() { public long getTime() {
return this.time; return this.time;
} }
@Override @Override
public String toString() { public String toString() {
return time + "," + jail + "," + reason; return time + "," + jail + "," + reason;
} }
} }

View File

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

View File

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

View File

@ -1,41 +1,41 @@
package com.graywolf336.jail.command.commands; package com.graywolf336.jail.command.commands;
import org.bukkit.command.CommandSender; import org.bukkit.command.CommandSender;
import org.bukkit.entity.Player; import org.bukkit.entity.Player;
import com.graywolf336.jail.JailManager; import com.graywolf336.jail.JailManager;
import com.graywolf336.jail.command.Command; import com.graywolf336.jail.command.Command;
import com.graywolf336.jail.command.CommandInfo; import com.graywolf336.jail.command.CommandInfo;
import com.graywolf336.jail.enums.LangString; import com.graywolf336.jail.enums.LangString;
@CommandInfo( @CommandInfo(
maxArgs = 1, maxArgs = 1,
minimumArgs = 1, minimumArgs = 1,
needsPlayer = false, needsPlayer = false,
pattern = "handcuff|hc", pattern = "handcuff|hc",
permission = "jail.command.handcuff", permission = "jail.command.handcuff",
usage = "/handcuff [player]" usage = "/handcuff [player]"
) )
public class HandCuffCommand implements Command { public class HandCuffCommand implements Command {
public boolean execute(JailManager jm, CommandSender sender, String... args) { public boolean execute(JailManager jm, CommandSender sender, String... args) {
Player player = jm.getPlugin().getServer().getPlayer(args[0]); Player player = jm.getPlugin().getServer().getPlayer(args[0]);
if(player == null) { if(player == null) {
sender.sendMessage(jm.getPlugin().getJailIO().getLanguageString(LangString.PLAYERNOTONLINE)); sender.sendMessage(jm.getPlugin().getJailIO().getLanguageString(LangString.PLAYERNOTONLINE));
}else if(player.hasPermission("jail.cantbehandcuffed")) { }else if(player.hasPermission("jail.cantbehandcuffed")) {
sender.sendMessage(jm.getPlugin().getJailIO().getLanguageString(LangString.CANTBEHANDCUFFED, new String[] { player.getName() })); sender.sendMessage(jm.getPlugin().getJailIO().getLanguageString(LangString.CANTBEHANDCUFFED, new String[] { player.getName() }));
}else if(jm.isPlayerJailed(player.getUniqueId())) { }else if(jm.isPlayerJailed(player.getUniqueId())) {
sender.sendMessage(jm.getPlugin().getJailIO().getLanguageString(LangString.CURRENTLYJAILEDHANDCUFF, new String[] { player.getName() })); sender.sendMessage(jm.getPlugin().getJailIO().getLanguageString(LangString.CURRENTLYJAILEDHANDCUFF, new String[] { player.getName() }));
}else if(jm.getPlugin().getHandCuffManager().isHandCuffed(player.getUniqueId())) { }else if(jm.getPlugin().getHandCuffManager().isHandCuffed(player.getUniqueId())) {
sender.sendMessage(jm.getPlugin().getJailIO().getLanguageString(LangString.HANDCUFFSRELEASED, new String[] { player.getName() })); sender.sendMessage(jm.getPlugin().getJailIO().getLanguageString(LangString.HANDCUFFSRELEASED, new String[] { player.getName() }));
jm.getPlugin().getHandCuffManager().removeHandCuffs(player.getUniqueId()); jm.getPlugin().getHandCuffManager().removeHandCuffs(player.getUniqueId());
player.sendMessage(jm.getPlugin().getJailIO().getLanguageString(LangString.UNHANDCUFFED)); player.sendMessage(jm.getPlugin().getJailIO().getLanguageString(LangString.UNHANDCUFFED));
}else { }else {
jm.getPlugin().getHandCuffManager().addHandCuffs(player.getUniqueId(), player.getLocation()); jm.getPlugin().getHandCuffManager().addHandCuffs(player.getUniqueId(), player.getLocation());
sender.sendMessage(jm.getPlugin().getJailIO().getLanguageString(LangString.HANDCUFFSON, new String[] { player.getName() })); sender.sendMessage(jm.getPlugin().getJailIO().getLanguageString(LangString.HANDCUFFSON, new String[] { player.getName() }));
player.sendMessage(jm.getPlugin().getJailIO().getLanguageString(LangString.HANDCUFFED)); player.sendMessage(jm.getPlugin().getJailIO().getLanguageString(LangString.HANDCUFFED));
} }
return true; return true;
} }
} }

View File

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

View File

@ -1,35 +1,35 @@
package com.graywolf336.jail.command.commands; package com.graywolf336.jail.command.commands;
import org.bukkit.command.CommandSender; import org.bukkit.command.CommandSender;
import org.bukkit.entity.Player; import org.bukkit.entity.Player;
import com.graywolf336.jail.JailManager; import com.graywolf336.jail.JailManager;
import com.graywolf336.jail.command.Command; import com.graywolf336.jail.command.Command;
import com.graywolf336.jail.command.CommandInfo; import com.graywolf336.jail.command.CommandInfo;
import com.graywolf336.jail.enums.LangString; import com.graywolf336.jail.enums.LangString;
@CommandInfo( @CommandInfo(
maxArgs = 1, maxArgs = 1,
minimumArgs = 1, minimumArgs = 1,
needsPlayer = false, needsPlayer = false,
pattern = "unhandcuff|uhc", pattern = "unhandcuff|uhc",
permission = "jail.command.handcuff", permission = "jail.command.handcuff",
usage = "/unhandcuff [player]" usage = "/unhandcuff [player]"
) )
public class UnHandCuffCommand implements Command { public class UnHandCuffCommand implements Command {
public boolean execute(JailManager jm, CommandSender sender, String... args) { public boolean execute(JailManager jm, CommandSender sender, String... args) {
Player player = jm.getPlugin().getServer().getPlayerExact(args[0]); Player player = jm.getPlugin().getServer().getPlayerExact(args[0]);
if(player == null) { if(player == null) {
sender.sendMessage(jm.getPlugin().getJailIO().getLanguageString(LangString.PLAYERNOTONLINE)); sender.sendMessage(jm.getPlugin().getJailIO().getLanguageString(LangString.PLAYERNOTONLINE));
}else if(jm.getPlugin().getHandCuffManager().isHandCuffed(player.getUniqueId())) { }else if(jm.getPlugin().getHandCuffManager().isHandCuffed(player.getUniqueId())) {
sender.sendMessage(jm.getPlugin().getJailIO().getLanguageString(LangString.HANDCUFFSRELEASED, new String[] { player.getName() })); sender.sendMessage(jm.getPlugin().getJailIO().getLanguageString(LangString.HANDCUFFSRELEASED, new String[] { player.getName() }));
jm.getPlugin().getHandCuffManager().removeHandCuffs(player.getUniqueId()); jm.getPlugin().getHandCuffManager().removeHandCuffs(player.getUniqueId());
player.sendMessage(jm.getPlugin().getJailIO().getLanguageString(LangString.UNHANDCUFFED)); player.sendMessage(jm.getPlugin().getJailIO().getLanguageString(LangString.UNHANDCUFFED));
}else { }else {
sender.sendMessage(jm.getPlugin().getJailIO().getLanguageString(LangString.NOTHANDCUFFED, new String[] { player.getName() })); sender.sendMessage(jm.getPlugin().getJailIO().getLanguageString(LangString.NOTHANDCUFFED, new String[] { player.getName() }));
} }
return true; return true;
} }
} }

View File

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

View File

@ -1,38 +1,38 @@
package com.graywolf336.jail.command.commands; package com.graywolf336.jail.command.commands;
import org.bukkit.ChatColor; import org.bukkit.ChatColor;
import org.bukkit.command.CommandSender; import org.bukkit.command.CommandSender;
import com.graywolf336.jail.JailManager; import com.graywolf336.jail.JailManager;
import com.graywolf336.jail.command.Command; import com.graywolf336.jail.command.Command;
import com.graywolf336.jail.command.CommandInfo; import com.graywolf336.jail.command.CommandInfo;
import com.graywolf336.jail.enums.LangString; import com.graywolf336.jail.enums.LangString;
import com.graywolf336.jail.enums.Settings; import com.graywolf336.jail.enums.Settings;
@CommandInfo( @CommandInfo(
maxArgs = 1, maxArgs = 1,
minimumArgs = 1, minimumArgs = 1,
needsPlayer = false, needsPlayer = false,
pattern = "unjailforce|ujf", pattern = "unjailforce|ujf",
permission = "jail.command.unjailforce", permission = "jail.command.unjailforce",
usage = "/unjailforce [player]" usage = "/unjailforce [player]"
) )
public class UnJailForceCommand implements Command { public class UnJailForceCommand implements Command {
public boolean execute(JailManager jm, CommandSender sender, String... args) { public boolean execute(JailManager jm, CommandSender sender, String... args) {
//Check if the player is jailed //Check if the player is jailed
if(jm.isPlayerJailedByLastKnownUsername(args[0])) { if(jm.isPlayerJailedByLastKnownUsername(args[0])) {
jm.getPlugin().getPrisonerManager().forceRelease(jm.getPrisonerByLastKnownName(args[0])); jm.getPlugin().getPrisonerManager().forceRelease(jm.getPrisonerByLastKnownName(args[0]));
sender.sendMessage(jm.getPlugin().getJailIO().getLanguageString(LangString.FORCEUNJAILED, args[0])); sender.sendMessage(jm.getPlugin().getJailIO().getLanguageString(LangString.FORCEUNJAILED, args[0]));
if(jm.getPlugin().getConfig().getBoolean(Settings.LOGJAILINGTOCONSOLE.getPath())) { if(jm.getPlugin().getConfig().getBoolean(Settings.LOGJAILINGTOCONSOLE.getPath())) {
jm.getPlugin().getLogger().info(ChatColor.stripColor(jm.getPlugin().getJailIO().getLanguageString(LangString.BROADCASTUNJAILING, new String[] { args[0], sender.getName() }))); jm.getPlugin().getLogger().info(ChatColor.stripColor(jm.getPlugin().getJailIO().getLanguageString(LangString.BROADCASTUNJAILING, new String[] { args[0], sender.getName() })));
} }
}else { }else {
//The player is not currently jailed //The player is not currently jailed
sender.sendMessage(jm.getPlugin().getJailIO().getLanguageString(LangString.NOTJAILED, args[0])); sender.sendMessage(jm.getPlugin().getJailIO().getLanguageString(LangString.NOTJAILED, args[0]));
} }
return true; return true;
} }
} }

View File

@ -1,32 +1,32 @@
package com.graywolf336.jail.command.commands.jewels; package com.graywolf336.jail.command.commands.jewels;
import java.util.List; import java.util.List;
import com.lexicalscope.jewel.cli.Option; import com.lexicalscope.jewel.cli.Option;
public interface Jailing { public interface Jailing {
@Option(longName={"player", "pl"}, shortName="p", description = "the player's name") @Option(longName={"player", "pl"}, shortName="p", description = "the player's name")
public String getPlayer(); public String getPlayer();
@Option(longName={"time", "length"}, shortName="t", description = "the amount of time") @Option(longName={"time", "length"}, shortName="t", description = "the amount of time")
public String getTime(); public String getTime();
@Option(longName={"jail", "prison"}, shortName="j", description = "the jail") @Option(longName={"jail", "prison"}, shortName="j", description = "the jail")
public String getJail(); public String getJail();
@Option(longName={"cell"}, shortName="c", description = "the cell") @Option(longName={"cell"}, shortName="c", description = "the cell")
public String getCell(); public String getCell();
@Option(longName={"muted", "canttalk"}, shortName="m", description = "whether the prisoner is muted or not") @Option(longName={"muted", "canttalk"}, shortName="m", description = "whether the prisoner is muted or not")
public boolean getMuted(); public boolean getMuted();
@Option(longName={"reason"}, shortName="r", description = "the reason this player is being jailed") @Option(longName={"reason"}, shortName="r", description = "the reason this player is being jailed")
public List<String> getReason(); public List<String> getReason();
public boolean isTime(); public boolean isTime();
public boolean isJail(); public boolean isJail();
public boolean isCell(); public boolean isCell();
public boolean isMuted(); public boolean isMuted();
public boolean isReason(); public boolean isReason();
} }

View File

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

View File

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

View File

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

View File

@ -1,31 +1,31 @@
package com.graywolf336.jail.command.subcommands; package com.graywolf336.jail.command.subcommands;
import org.bukkit.command.CommandSender; import org.bukkit.command.CommandSender;
import com.graywolf336.jail.JailManager; import com.graywolf336.jail.JailManager;
import com.graywolf336.jail.beans.ConfirmPlayer; import com.graywolf336.jail.beans.ConfirmPlayer;
import com.graywolf336.jail.command.Command; import com.graywolf336.jail.command.Command;
import com.graywolf336.jail.command.CommandInfo; import com.graywolf336.jail.command.CommandInfo;
import com.graywolf336.jail.enums.Confirmation; import com.graywolf336.jail.enums.Confirmation;
import com.graywolf336.jail.enums.LangString; import com.graywolf336.jail.enums.LangString;
@CommandInfo( @CommandInfo(
maxArgs = 2, maxArgs = 2,
minimumArgs = 2, minimumArgs = 2,
needsPlayer = false, needsPlayer = false,
pattern = "deletecell|dc", pattern = "deletecell|dc",
permission = "jail.command.jaildeletecell", permission = "jail.command.jaildeletecell",
usage = "/jail deletecell <jail> <cell>" usage = "/jail deletecell <jail> <cell>"
) )
public class JailDeleteCellCommand implements Command { public class JailDeleteCellCommand implements Command {
public boolean execute(JailManager jm, CommandSender sender, String... args) throws Exception { public boolean execute(JailManager jm, CommandSender sender, String... args) throws Exception {
if(jm.isConfirming(sender.getName())) { if(jm.isConfirming(sender.getName())) {
sender.sendMessage(jm.getPlugin().getJailIO().getLanguageString(LangString.ALREADY)); sender.sendMessage(jm.getPlugin().getJailIO().getLanguageString(LangString.ALREADY));
}else { }else {
jm.addConfirming(sender.getName(), new ConfirmPlayer(sender.getName(), args, Confirmation.DELETECELL)); jm.addConfirming(sender.getName(), new ConfirmPlayer(sender.getName(), args, Confirmation.DELETECELL));
sender.sendMessage(jm.getPlugin().getJailIO().getLanguageString(LangString.START)); sender.sendMessage(jm.getPlugin().getJailIO().getLanguageString(LangString.START));
} }
return true; return true;
} }
} }

View File

@ -1,31 +1,31 @@
package com.graywolf336.jail.command.subcommands; package com.graywolf336.jail.command.subcommands;
import org.bukkit.command.CommandSender; import org.bukkit.command.CommandSender;
import com.graywolf336.jail.JailManager; import com.graywolf336.jail.JailManager;
import com.graywolf336.jail.beans.ConfirmPlayer; import com.graywolf336.jail.beans.ConfirmPlayer;
import com.graywolf336.jail.command.Command; import com.graywolf336.jail.command.Command;
import com.graywolf336.jail.command.CommandInfo; import com.graywolf336.jail.command.CommandInfo;
import com.graywolf336.jail.enums.Confirmation; import com.graywolf336.jail.enums.Confirmation;
import com.graywolf336.jail.enums.LangString; import com.graywolf336.jail.enums.LangString;
@CommandInfo( @CommandInfo(
maxArgs = 1, maxArgs = 1,
minimumArgs = 1, minimumArgs = 1,
needsPlayer = false, needsPlayer = false,
pattern = "deletecells|dcs", pattern = "deletecells|dcs",
permission = "jail.command.jaildeletecell", permission = "jail.command.jaildeletecell",
usage = "/jail deletecells <jail>" usage = "/jail deletecells <jail>"
) )
public class JailDeleteCellsCommand implements Command { public class JailDeleteCellsCommand implements Command {
public boolean execute(JailManager jm, CommandSender sender, String... args) throws Exception { public boolean execute(JailManager jm, CommandSender sender, String... args) throws Exception {
if(jm.isConfirming(sender.getName())) { if(jm.isConfirming(sender.getName())) {
sender.sendMessage(jm.getPlugin().getJailIO().getLanguageString(LangString.ALREADY)); sender.sendMessage(jm.getPlugin().getJailIO().getLanguageString(LangString.ALREADY));
}else { }else {
jm.addConfirming(sender.getName(), new ConfirmPlayer(sender.getName(), args, Confirmation.DELETECELLS)); jm.addConfirming(sender.getName(), new ConfirmPlayer(sender.getName(), args, Confirmation.DELETECELLS));
sender.sendMessage(jm.getPlugin().getJailIO().getLanguageString(LangString.START)); sender.sendMessage(jm.getPlugin().getJailIO().getLanguageString(LangString.START));
} }
return true; return true;
} }
} }

View File

@ -1,31 +1,31 @@
package com.graywolf336.jail.command.subcommands; package com.graywolf336.jail.command.subcommands;
import org.bukkit.command.CommandSender; import org.bukkit.command.CommandSender;
import com.graywolf336.jail.JailManager; import com.graywolf336.jail.JailManager;
import com.graywolf336.jail.beans.ConfirmPlayer; import com.graywolf336.jail.beans.ConfirmPlayer;
import com.graywolf336.jail.command.Command; import com.graywolf336.jail.command.Command;
import com.graywolf336.jail.command.CommandInfo; import com.graywolf336.jail.command.CommandInfo;
import com.graywolf336.jail.enums.Confirmation; import com.graywolf336.jail.enums.Confirmation;
import com.graywolf336.jail.enums.LangString; import com.graywolf336.jail.enums.LangString;
@CommandInfo( @CommandInfo(
maxArgs = 1, maxArgs = 1,
minimumArgs = 1, minimumArgs = 1,
needsPlayer = false, needsPlayer = false,
pattern = "delete|d", pattern = "delete|d",
permission = "jail.command.jaildelete", permission = "jail.command.jaildelete",
usage = "/jail delete <jail>" usage = "/jail delete <jail>"
) )
public class JailDeleteCommand implements Command { public class JailDeleteCommand implements Command {
public boolean execute(JailManager jm, CommandSender sender, String... args) throws Exception { public boolean execute(JailManager jm, CommandSender sender, String... args) throws Exception {
if(jm.isConfirming(sender.getName())) { if(jm.isConfirming(sender.getName())) {
sender.sendMessage(jm.getPlugin().getJailIO().getLanguageString(LangString.ALREADY)); sender.sendMessage(jm.getPlugin().getJailIO().getLanguageString(LangString.ALREADY));
}else { }else {
jm.addConfirming(sender.getName(), new ConfirmPlayer(sender.getName(), args, Confirmation.DELETE)); jm.addConfirming(sender.getName(), new ConfirmPlayer(sender.getName(), args, Confirmation.DELETE));
sender.sendMessage(jm.getPlugin().getJailIO().getLanguageString(LangString.START)); sender.sendMessage(jm.getPlugin().getJailIO().getLanguageString(LangString.START));
} }
return true; return true;
} }
} }

View File

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

View File

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

View File

@ -1,38 +1,38 @@
package com.graywolf336.jail.command.subcommands; package com.graywolf336.jail.command.subcommands;
import org.bukkit.command.CommandSender; import org.bukkit.command.CommandSender;
import com.graywolf336.jail.JailManager; import com.graywolf336.jail.JailManager;
import com.graywolf336.jail.command.Command; import com.graywolf336.jail.command.Command;
import com.graywolf336.jail.command.CommandInfo; import com.graywolf336.jail.command.CommandInfo;
import com.graywolf336.jail.enums.LangString; import com.graywolf336.jail.enums.LangString;
@CommandInfo( @CommandInfo(
maxArgs = 1, maxArgs = 1,
minimumArgs = 1, minimumArgs = 1,
needsPlayer = false, needsPlayer = false,
pattern = "mute|m", pattern = "mute|m",
permission = "jail.command.jailmute", permission = "jail.command.jailmute",
usage = "/jail mute <player>" usage = "/jail mute <player>"
) )
public class JailMuteCommand implements Command { public class JailMuteCommand implements Command {
public boolean execute(JailManager jm, CommandSender sender, String... args) throws Exception { public boolean execute(JailManager jm, CommandSender sender, String... args) throws Exception {
//Let's check if the player they're sending us is jailed //Let's check if the player they're sending us is jailed
if(jm.isPlayerJailedByLastKnownUsername(args[1])) { if(jm.isPlayerJailedByLastKnownUsername(args[1])) {
//They are, so let's toggle whether they are muted or not //They are, so let's toggle whether they are muted or not
boolean muted = !jm.getPrisonerByLastKnownName(args[1]).isMuted(); boolean muted = !jm.getPrisonerByLastKnownName(args[1]).isMuted();
jm.getPrisonerByLastKnownName(args[1]).setMuted(muted); jm.getPrisonerByLastKnownName(args[1]).setMuted(muted);
//Send the message to the sender based upon whether they are muted or unmuted //Send the message to the sender based upon whether they are muted or unmuted
if(muted) if(muted)
sender.sendMessage(jm.getPlugin().getJailIO().getLanguageString(LangString.NOWMUTED, args[1])); sender.sendMessage(jm.getPlugin().getJailIO().getLanguageString(LangString.NOWMUTED, args[1]));
else else
sender.sendMessage(jm.getPlugin().getJailIO().getLanguageString(LangString.NOWUNMUTED, args[1])); sender.sendMessage(jm.getPlugin().getJailIO().getLanguageString(LangString.NOWUNMUTED, args[1]));
}else { }else {
//The player provided is not jailed, so let's tell the sender that //The player provided is not jailed, so let's tell the sender that
sender.sendMessage(jm.getPlugin().getJailIO().getLanguageString(LangString.NOTJAILED, args[1])); sender.sendMessage(jm.getPlugin().getJailIO().getLanguageString(LangString.NOTJAILED, args[1]));
} }
return true; return true;
} }
} }

View File

@ -1,229 +1,229 @@
package com.graywolf336.jail.command.subcommands; package com.graywolf336.jail.command.subcommands;
import java.util.concurrent.TimeUnit; import java.util.concurrent.TimeUnit;
import org.bukkit.ChatColor; import org.bukkit.ChatColor;
import org.bukkit.command.CommandSender; import org.bukkit.command.CommandSender;
import org.bukkit.entity.Player; import org.bukkit.entity.Player;
import com.graywolf336.jail.JailManager; import com.graywolf336.jail.JailManager;
import com.graywolf336.jail.JailPayManager; import com.graywolf336.jail.JailPayManager;
import com.graywolf336.jail.beans.Prisoner; import com.graywolf336.jail.beans.Prisoner;
import com.graywolf336.jail.command.Command; import com.graywolf336.jail.command.Command;
import com.graywolf336.jail.command.CommandInfo; import com.graywolf336.jail.command.CommandInfo;
import com.graywolf336.jail.enums.LangString; import com.graywolf336.jail.enums.LangString;
import com.graywolf336.jail.enums.Settings; import com.graywolf336.jail.enums.Settings;
@CommandInfo( @CommandInfo(
maxArgs = 2, maxArgs = 2,
minimumArgs = 0, minimumArgs = 0,
needsPlayer = true, needsPlayer = true,
pattern = "pay", pattern = "pay",
permission = "jail.usercmd.jailpay", permission = "jail.usercmd.jailpay",
usage = "/jail pay <amount> <player>" usage = "/jail pay <amount> <player>"
) )
public class JailPayCommand implements Command { public class JailPayCommand implements Command {
public boolean execute(JailManager jm, CommandSender sender, String... args) throws Exception { public boolean execute(JailManager jm, CommandSender sender, String... args) throws Exception {
if(jm.getPlugin().getConfig().getBoolean(Settings.JAILPAYENABLED.getPath())) { if(jm.getPlugin().getConfig().getBoolean(Settings.JAILPAYENABLED.getPath())) {
JailPayManager pm = jm.getPlugin().getJailPayManager(); JailPayManager pm = jm.getPlugin().getJailPayManager();
switch(args.length) { switch(args.length) {
case 1: case 1:
// `/jail pay` // `/jail pay`
//send how much it costs to get out //send how much it costs to get out
if(jm.isPlayerJailedByLastKnownUsername(sender.getName())) { if(jm.isPlayerJailedByLastKnownUsername(sender.getName())) {
Prisoner p = jm.getPrisonerByLastKnownName(sender.getName()); Prisoner p = jm.getPrisonerByLastKnownName(sender.getName());
String amt = ""; String amt = "";
if(pm.usingItemsForPayment()) { if(pm.usingItemsForPayment()) {
amt = String.valueOf((int) Math.ceil(pm.calculateBill(p))); amt = String.valueOf((int) Math.ceil(pm.calculateBill(p)));
}else { }else {
amt = String.valueOf(pm.calculateBill(p)); amt = String.valueOf(pm.calculateBill(p));
} }
if(p.getRemainingTime() > 0) { if(p.getRemainingTime() > 0) {
if(pm.isTimedEnabled()) { if(pm.isTimedEnabled()) {
sender.sendMessage(jm.getPlugin().getJailIO().getLanguageString(LangString.PAYCOST, new String[] { pm.getCostPerMinute(), pm.getCurrencyName(), amt })); sender.sendMessage(jm.getPlugin().getJailIO().getLanguageString(LangString.PAYCOST, new String[] { pm.getCostPerMinute(), pm.getCurrencyName(), amt }));
}else { }else {
sender.sendMessage(jm.getPlugin().getJailIO().getLanguageString(LangString.PAYNOTENABLED)); sender.sendMessage(jm.getPlugin().getJailIO().getLanguageString(LangString.PAYNOTENABLED));
jm.getPlugin().debug("Jail pay 'timed' paying is not enabled (config has 0 as the cost)."); jm.getPlugin().debug("Jail pay 'timed' paying is not enabled (config has 0 as the cost).");
} }
}else { }else {
if(pm.isInfiniteEnabled()) { if(pm.isInfiniteEnabled()) {
sender.sendMessage(jm.getPlugin().getJailIO().getLanguageString(LangString.PAYCOST, new String[] { amt, pm.getCurrencyName() })); sender.sendMessage(jm.getPlugin().getJailIO().getLanguageString(LangString.PAYCOST, new String[] { amt, pm.getCurrencyName() }));
}else { }else {
sender.sendMessage(jm.getPlugin().getJailIO().getLanguageString(LangString.PAYNOTENABLED)); sender.sendMessage(jm.getPlugin().getJailIO().getLanguageString(LangString.PAYNOTENABLED));
jm.getPlugin().debug("Jail pay 'infinite' paying is not enabled (config has 0 as the cost)."); jm.getPlugin().debug("Jail pay 'infinite' paying is not enabled (config has 0 as the cost).");
} }
} }
}else { }else {
sender.sendMessage(jm.getPlugin().getJailIO().getLanguageString(LangString.YOUARENOTJAILED)); sender.sendMessage(jm.getPlugin().getJailIO().getLanguageString(LangString.YOUARENOTJAILED));
} }
break; break;
case 2: case 2:
// `/jail pay <amount>` // `/jail pay <amount>`
//They are trying to pay for their self //They are trying to pay for their self
if(jm.isPlayerJailedByLastKnownUsername(sender.getName())) { if(jm.isPlayerJailedByLastKnownUsername(sender.getName())) {
Prisoner p = jm.getPrisonerByLastKnownName(sender.getName()); Prisoner p = jm.getPrisonerByLastKnownName(sender.getName());
if(p.getRemainingTime() > 0) { if(p.getRemainingTime() > 0) {
if(!pm.isTimedEnabled()) { if(!pm.isTimedEnabled()) {
sender.sendMessage(jm.getPlugin().getJailIO().getLanguageString(LangString.PAYNOTENABLED)); sender.sendMessage(jm.getPlugin().getJailIO().getLanguageString(LangString.PAYNOTENABLED));
return true; return true;
} }
}else { }else {
if(!pm.isInfiniteEnabled()) { if(!pm.isInfiniteEnabled()) {
sender.sendMessage(jm.getPlugin().getJailIO().getLanguageString(LangString.PAYNOTENABLED)); sender.sendMessage(jm.getPlugin().getJailIO().getLanguageString(LangString.PAYNOTENABLED));
return true; return true;
} }
} }
if(args[1].startsWith("-")) { if(args[1].startsWith("-")) {
sender.sendMessage(jm.getPlugin().getJailIO().getLanguageString(LangString.PAYNONEGATIVEAMOUNTS)); sender.sendMessage(jm.getPlugin().getJailIO().getLanguageString(LangString.PAYNONEGATIVEAMOUNTS));
}else { }else {
double amt = 0; double amt = 0;
try { try {
amt = Double.parseDouble(args[1]); amt = Double.parseDouble(args[1]);
}catch(NumberFormatException e) { }catch(NumberFormatException e) {
sender.sendMessage(ChatColor.RED + "<amount> must be a number."); sender.sendMessage(ChatColor.RED + "<amount> must be a number.");
throw e; throw e;
} }
if(pm.hasEnoughToPay((Player) sender, amt)) { if(pm.hasEnoughToPay((Player) sender, amt)) {
double bill = pm.calculateBill(p); double bill = pm.calculateBill(p);
if(p.getRemainingTime() > 0) { if(p.getRemainingTime() > 0) {
//timed sentence //timed sentence
if(amt >= bill) { if(amt >= bill) {
pm.pay((Player) sender, bill); pm.pay((Player) sender, bill);
sender.sendMessage(jm.getPlugin().getJailIO().getLanguageString(LangString.PAYPAIDRELEASED, String.valueOf(bill))); sender.sendMessage(jm.getPlugin().getJailIO().getLanguageString(LangString.PAYPAIDRELEASED, String.valueOf(bill)));
jm.getPlugin().getPrisonerManager().releasePrisoner((Player) sender, p); jm.getPlugin().getPrisonerManager().releasePrisoner((Player) sender, p);
}else { }else {
long minutes = pm.getMinutesPayingFor(amt); long minutes = pm.getMinutesPayingFor(amt);
pm.pay((Player) sender, amt); pm.pay((Player) sender, amt);
long remain = p.subtractTime(TimeUnit.MILLISECONDS.convert(minutes, TimeUnit.MINUTES)); long remain = p.subtractTime(TimeUnit.MILLISECONDS.convert(minutes, TimeUnit.MINUTES));
sender.sendMessage(jm.getPlugin().getJailIO().getLanguageString(LangString.PAYPAIDLOWEREDTIME, sender.sendMessage(jm.getPlugin().getJailIO().getLanguageString(LangString.PAYPAIDLOWEREDTIME,
new String[] { String.valueOf(amt), String.valueOf(TimeUnit.MINUTES.convert(remain, TimeUnit.MILLISECONDS)) })); new String[] { String.valueOf(amt), String.valueOf(TimeUnit.MINUTES.convert(remain, TimeUnit.MILLISECONDS)) }));
} }
}else { }else {
//infinite jailing //infinite jailing
if(amt >= bill) { if(amt >= bill) {
pm.pay((Player) sender, bill); pm.pay((Player) sender, bill);
sender.sendMessage(jm.getPlugin().getJailIO().getLanguageString(LangString.PAYPAIDRELEASED, String.valueOf(bill))); sender.sendMessage(jm.getPlugin().getJailIO().getLanguageString(LangString.PAYPAIDRELEASED, String.valueOf(bill)));
jm.getPlugin().getPrisonerManager().releasePrisoner((Player) sender, p); jm.getPlugin().getPrisonerManager().releasePrisoner((Player) sender, p);
}else { }else {
//You haven't provided enough money to get them out //You haven't provided enough money to get them out
sender.sendMessage(jm.getPlugin().getJailIO().getLanguageString(LangString.PAYNOTENOUGHMONEYPROVIDED)); sender.sendMessage(jm.getPlugin().getJailIO().getLanguageString(LangString.PAYNOTENOUGHMONEYPROVIDED));
} }
} }
}else { }else {
sender.sendMessage(jm.getPlugin().getJailIO().getLanguageString(LangString.PAYNOTENOUGHMONEY)); sender.sendMessage(jm.getPlugin().getJailIO().getLanguageString(LangString.PAYNOTENOUGHMONEY));
} }
} }
}else { }else {
sender.sendMessage(jm.getPlugin().getJailIO().getLanguageString(LangString.YOUARENOTJAILED)); sender.sendMessage(jm.getPlugin().getJailIO().getLanguageString(LangString.YOUARENOTJAILED));
} }
break; break;
case 3: case 3:
// `/jail pay <amount> <person> // `/jail pay <amount> <person>
//they are trying to pay for someone else //they are trying to pay for someone else
if(jm.isPlayerJailedByLastKnownUsername(sender.getName())) { if(jm.isPlayerJailedByLastKnownUsername(sender.getName())) {
//When they are jailed they can not pay for someone else //When they are jailed they can not pay for someone else
sender.sendMessage(jm.getPlugin().getJailIO().getLanguageString(LangString.PAYCANTPAYWHILEJAILED)); sender.sendMessage(jm.getPlugin().getJailIO().getLanguageString(LangString.PAYCANTPAYWHILEJAILED));
}else { }else {
if(jm.isPlayerJailedByLastKnownUsername(args[2])) { if(jm.isPlayerJailedByLastKnownUsername(args[2])) {
Prisoner p = jm.getPrisonerByLastKnownName(args[2]); Prisoner p = jm.getPrisonerByLastKnownName(args[2]);
if(p.getRemainingTime() > 0) { if(p.getRemainingTime() > 0) {
if(!pm.isTimedEnabled()) { if(!pm.isTimedEnabled()) {
sender.sendMessage(jm.getPlugin().getJailIO().getLanguageString(LangString.PAYNOTENABLED)); sender.sendMessage(jm.getPlugin().getJailIO().getLanguageString(LangString.PAYNOTENABLED));
return true; return true;
} }
}else { }else {
if(!pm.isInfiniteEnabled()) { if(!pm.isInfiniteEnabled()) {
sender.sendMessage(jm.getPlugin().getJailIO().getLanguageString(LangString.PAYNOTENABLED)); sender.sendMessage(jm.getPlugin().getJailIO().getLanguageString(LangString.PAYNOTENABLED));
return true; return true;
} }
} }
if(args[1].startsWith("-")) { if(args[1].startsWith("-")) {
sender.sendMessage(jm.getPlugin().getJailIO().getLanguageString(LangString.PAYNONEGATIVEAMOUNTS)); sender.sendMessage(jm.getPlugin().getJailIO().getLanguageString(LangString.PAYNONEGATIVEAMOUNTS));
}else { }else {
double amt = 0; double amt = 0;
try { try {
amt = Double.parseDouble(args[1]); amt = Double.parseDouble(args[1]);
}catch(NumberFormatException e) { }catch(NumberFormatException e) {
sender.sendMessage(ChatColor.RED + "<amount> must be a number."); sender.sendMessage(ChatColor.RED + "<amount> must be a number.");
throw e; throw e;
} }
if(pm.hasEnoughToPay((Player) sender, amt)) { if(pm.hasEnoughToPay((Player) sender, amt)) {
double bill = pm.calculateBill(p); double bill = pm.calculateBill(p);
if(p.getRemainingTime() > 0) { if(p.getRemainingTime() > 0) {
//timed sentence //timed sentence
if(amt >= bill) { if(amt >= bill) {
pm.pay((Player) sender, bill); pm.pay((Player) sender, bill);
sender.sendMessage(jm.getPlugin().getJailIO().getLanguageString(LangString.PAYPAIDRELEASEDELSE, new String[] { String.valueOf(bill), p.getLastKnownName() })); sender.sendMessage(jm.getPlugin().getJailIO().getLanguageString(LangString.PAYPAIDRELEASEDELSE, new String[] { String.valueOf(bill), p.getLastKnownName() }));
jm.getPlugin().getPrisonerManager().releasePrisoner(jm.getPlugin().getServer().getPlayer(p.getUUID()), p); jm.getPlugin().getPrisonerManager().releasePrisoner(jm.getPlugin().getServer().getPlayer(p.getUUID()), p);
}else { }else {
long minutes = pm.getMinutesPayingFor(amt); long minutes = pm.getMinutesPayingFor(amt);
pm.pay((Player) sender, amt); pm.pay((Player) sender, amt);
long remain = p.subtractTime(TimeUnit.MILLISECONDS.convert(minutes, TimeUnit.MINUTES)); long remain = p.subtractTime(TimeUnit.MILLISECONDS.convert(minutes, TimeUnit.MINUTES));
sender.sendMessage(jm.getPlugin().getJailIO().getLanguageString(LangString.PAYPAIDLOWEREDTIMEELSE, sender.sendMessage(jm.getPlugin().getJailIO().getLanguageString(LangString.PAYPAIDLOWEREDTIMEELSE,
new String[] { String.valueOf(amt), p.getLastKnownName(), String.valueOf(TimeUnit.MINUTES.convert(remain, TimeUnit.MILLISECONDS)) })); new String[] { String.valueOf(amt), p.getLastKnownName(), String.valueOf(TimeUnit.MINUTES.convert(remain, TimeUnit.MILLISECONDS)) }));
} }
}else { }else {
//infinite jailing //infinite jailing
if(amt >= bill) { if(amt >= bill) {
pm.pay((Player) sender, bill); pm.pay((Player) sender, bill);
sender.sendMessage(jm.getPlugin().getJailIO().getLanguageString(LangString.PAYPAIDRELEASEDELSE, new String[] { String.valueOf(bill), p.getLastKnownName() })); sender.sendMessage(jm.getPlugin().getJailIO().getLanguageString(LangString.PAYPAIDRELEASEDELSE, new String[] { String.valueOf(bill), p.getLastKnownName() }));
jm.getPlugin().getPrisonerManager().releasePrisoner(jm.getPlugin().getServer().getPlayer(p.getUUID()), p); jm.getPlugin().getPrisonerManager().releasePrisoner(jm.getPlugin().getServer().getPlayer(p.getUUID()), p);
}else { }else {
//You haven't provided enough money to get them out //You haven't provided enough money to get them out
sender.sendMessage(jm.getPlugin().getJailIO().getLanguageString(LangString.PAYNOTENOUGHMONEYPROVIDED)); sender.sendMessage(jm.getPlugin().getJailIO().getLanguageString(LangString.PAYNOTENOUGHMONEYPROVIDED));
} }
} }
}else { }else {
sender.sendMessage(jm.getPlugin().getJailIO().getLanguageString(LangString.PAYNOTENOUGHMONEY)); sender.sendMessage(jm.getPlugin().getJailIO().getLanguageString(LangString.PAYNOTENOUGHMONEY));
} }
} }
}else { }else {
//Person they're trying to pay for is not jailed //Person they're trying to pay for is not jailed
sender.sendMessage(jm.getPlugin().getJailIO().getLanguageString(LangString.NOTJAILED, args[2])); sender.sendMessage(jm.getPlugin().getJailIO().getLanguageString(LangString.NOTJAILED, args[2]));
} }
} }
break; break;
default: default:
return false; return false;
} }
}else { }else {
jm.getPlugin().debug("Jail pay not enabled."); jm.getPlugin().debug("Jail pay not enabled.");
sender.sendMessage(jm.getPlugin().getJailIO().getLanguageString(LangString.PAYNOTENABLED)); sender.sendMessage(jm.getPlugin().getJailIO().getLanguageString(LangString.PAYNOTENABLED));
} }
return true; return true;
} }
} }
/* /*
* *
Messages: Messages:
MessageJailPayAmountForever: To get out of this mess, you will have to pay <Amount>. MessageJailPayAmountForever: To get out of this mess, you will have to pay <Amount>.
JailPayCannotPay: Sorry, money won't help you this time. JailPayCannotPay: Sorry, money won't help you this time.
JailPayCannotPayHim: Sorry, money won't help him this time. JailPayCannotPayHim: Sorry, money won't help him this time.
JailPayNotEnoughMoney: You don't have that much money! JailPayNotEnoughMoney: You don't have that much money!
JailPayCost: 1 minute of your sentence will cost you <MinutePrice>. That means that cost for releasing you out of the jail is <WholePrice>. JailPayCost: 1 minute of your sentence will cost you <MinutePrice>. That means that cost for releasing you out of the jail is <WholePrice>.
JailPayPaidReleased: You have just payed <Amount> and saved yourself from the jail! JailPayPaidReleased: You have just payed <Amount> and saved yourself from the jail!
JailPayPaidReleasedHim: You have just payed <Amount> and saved <Prisoner> from the jail! JailPayPaidReleasedHim: You have just payed <Amount> and saved <Prisoner> from the jail!
JailPayLoweredTime: You have just payed <Amount> and lowered your sentence to <NewTime> minutes! JailPayLoweredTime: You have just payed <Amount> and lowered your sentence to <NewTime> minutes!
JailPayLoweredTimeHim: You have just payed <Amount> and lowered <Prisoner>'s sentence to <NewTime> minutes! JailPayLoweredTimeHim: You have just payed <Amount> and lowered <Prisoner>'s sentence to <NewTime> minutes!
JailPay: JailPay:
PricePerMinute: 10 PricePerMinute: 10
PriceForInfiniteJail: 9999 PriceForInfiniteJail: 9999
Currency: 0 Currency: 0
*/ */

View File

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

View File

@ -1,36 +1,36 @@
package com.graywolf336.jail.command.subcommands; package com.graywolf336.jail.command.subcommands;
import org.bukkit.ChatColor; import org.bukkit.ChatColor;
import org.bukkit.command.CommandSender; import org.bukkit.command.CommandSender;
import com.graywolf336.jail.JailManager; import com.graywolf336.jail.JailManager;
import com.graywolf336.jail.command.Command; import com.graywolf336.jail.command.Command;
import com.graywolf336.jail.command.CommandInfo; import com.graywolf336.jail.command.CommandInfo;
import com.graywolf336.jail.enums.LangString; import com.graywolf336.jail.enums.LangString;
@CommandInfo( @CommandInfo(
maxArgs = 0, maxArgs = 0,
minimumArgs = 0, minimumArgs = 0,
needsPlayer = false, needsPlayer = false,
pattern = "reload|r", pattern = "reload|r",
permission = "jail.command.jailreload", permission = "jail.command.jailreload",
usage = "/jail reload" usage = "/jail reload"
) )
public class JailReloadCommand implements Command { public class JailReloadCommand implements Command {
public boolean execute(JailManager jm, CommandSender sender, String... args) { public boolean execute(JailManager jm, CommandSender sender, String... args) {
try { try {
jm.getPlugin().reloadConfig(); jm.getPlugin().reloadConfig();
jm.getPlugin().getJailIO().loadLanguage(); jm.getPlugin().getJailIO().loadLanguage();
jm.getPlugin().getJailIO().loadJails(); jm.getPlugin().getJailIO().loadJails();
jm.getPlugin().reloadScoreBoardManager(); jm.getPlugin().reloadScoreBoardManager();
jm.getPlugin().reloadJailSticks(); jm.getPlugin().reloadJailSticks();
jm.getPlugin().reloadJailPayManager(); jm.getPlugin().reloadJailPayManager();
sender.sendMessage(jm.getPlugin().getJailIO().getLanguageString(LangString.PLUGINRELOADED)); sender.sendMessage(jm.getPlugin().getJailIO().getLanguageString(LangString.PLUGINRELOADED));
}catch (Exception e) { }catch (Exception e) {
sender.sendMessage(ChatColor.RED + e.getMessage()); sender.sendMessage(ChatColor.RED + e.getMessage());
} }
return true; return true;
} }
} }

View File

@ -1,35 +1,35 @@
package com.graywolf336.jail.command.subcommands; package com.graywolf336.jail.command.subcommands;
import org.bukkit.command.CommandSender; import org.bukkit.command.CommandSender;
import com.graywolf336.jail.JailManager; import com.graywolf336.jail.JailManager;
import com.graywolf336.jail.command.Command; import com.graywolf336.jail.command.Command;
import com.graywolf336.jail.command.CommandInfo; import com.graywolf336.jail.command.CommandInfo;
import com.graywolf336.jail.enums.LangString; import com.graywolf336.jail.enums.LangString;
import com.graywolf336.jail.enums.Settings; import com.graywolf336.jail.enums.Settings;
@CommandInfo( @CommandInfo(
maxArgs = 0, maxArgs = 0,
minimumArgs = 0, minimumArgs = 0,
needsPlayer = true, needsPlayer = true,
pattern = "stick", pattern = "stick",
permission = "jail.usercmd.jailstick", permission = "jail.usercmd.jailstick",
usage = "/jail stick" usage = "/jail stick"
) )
public class JailStickCommand implements Command { public class JailStickCommand implements Command {
public boolean execute(JailManager jm, CommandSender sender, String... args) throws Exception { public boolean execute(JailManager jm, CommandSender sender, String... args) throws Exception {
if(jm.getPlugin().getConfig().getBoolean(Settings.JAILSTICKENABLED.getPath())) { if(jm.getPlugin().getConfig().getBoolean(Settings.JAILSTICKENABLED.getPath())) {
boolean using = jm.getPlugin().getJailStickManager().toggleUsingStick(sender.getName()); boolean using = jm.getPlugin().getJailStickManager().toggleUsingStick(sender.getName());
if(using) { if(using) {
sender.sendMessage(jm.getPlugin().getJailIO().getLanguageString(LangString.JAILSTICKENABLED)); sender.sendMessage(jm.getPlugin().getJailIO().getLanguageString(LangString.JAILSTICKENABLED));
}else { }else {
sender.sendMessage(jm.getPlugin().getJailIO().getLanguageString(LangString.JAILSTICKDISABLED)); sender.sendMessage(jm.getPlugin().getJailIO().getLanguageString(LangString.JAILSTICKDISABLED));
} }
}else { }else {
sender.sendMessage(jm.getPlugin().getJailIO().getLanguageString(LangString.JAILSTICKUSAGEDISABLED)); sender.sendMessage(jm.getPlugin().getJailIO().getLanguageString(LangString.JAILSTICKUSAGEDISABLED));
} }
return true; return true;
} }
} }

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

@ -1,221 +1,221 @@
package com.graywolf336.jail.enums; package com.graywolf336.jail.enums;
public enum LangString { public enum LangString {
//actions section //actions section
/** Section for when they break a block. */ /** Section for when they break a block. */
BLOCKBREAKING ("actions"), BLOCKBREAKING ("actions"),
/** Section for when they place a block. */ /** Section for when they place a block. */
BLOCKPLACING ("actions"), 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"), 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"), 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"), 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"), INTERACTIONITEMS ("actions"),
/** Section for when a player moves outside of the jail. */ /** Section for when a player moves outside of the jail. */
MOVING ("actions"), MOVING ("actions"),
//Jailing section //Jailing section
/** The message displayed when players are kicked for being afk. */ /** The message displayed when players are kicked for being afk. */
AFKKICKMESSAGE ("jailing"), AFKKICKMESSAGE ("jailing"),
/** The message sent when jailing someone that is already jailed. */ /** The message sent when jailing someone that is already jailed. */
ALREADYJAILED ("jailing"), 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"), 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"), 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"), 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"), 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"), 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"), CELLNOTEMPTY ("jailing"),
/** The message sent when someone is jailed without a reason. */ /** The message sent when someone is jailed without a reason. */
DEFAULTJAILEDREASON ("jailing"), 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"), FORCEUNJAILED ("jailing"),
/** The message sent when players are jailed without a reason. */ /** The message sent when players are jailed without a reason. */
JAILED ("jailing"), JAILED ("jailing"),
/** The message sent when players are jailed with a reason. */ /** The message sent when players are jailed with a reason. */
JAILEDWITHREASON ("jailing"), 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"), 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"), 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"), 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"), 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"), 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"), 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"), 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"), ONLINEJAIL ("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"), 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"), 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"), 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"), 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"), PROVIDEAJAIL ("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"), 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"), 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"), 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"), 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"), 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"), 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"), 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"), 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"), TRANSFERRED ("jailing"),
/** The message sent when players are released from jail. */ /** The message sent when players are released from jail. */
UNJAILED ("jailing"), UNJAILED ("jailing"),
/** The message went when an offline player is unjailed. */ /** The message went when an offline player is unjailed. */
WILLBEUNJAILED ("jailing"), WILLBEUNJAILED ("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"), YOUARENOTJAILED ("jailing"),
//Handcuffing section //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"), 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"), 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"), NOTHANDCUFFED ("handcuffing"),
/** The message sent to the handcuff on a successful handcuffing. */ /** The message sent to the handcuff on a successful handcuffing. */
HANDCUFFSON ("handcuffing"), HANDCUFFSON ("handcuffing"),
/** The message sent when players are handcuffed. */ /** The message sent when players are handcuffed. */
HANDCUFFED ("handcuffing"), HANDCUFFED ("handcuffing"),
/** The message sent to the player who has release handcuffs. */ /** The message sent to the player who has release handcuffs. */
HANDCUFFSRELEASED ("handcuffing"), 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"), UNHANDCUFFED ("handcuffing"),
//General section, used by different parts //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"), ALLJAILS ("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"), CELLREMOVALUNSUCCESSFUL ("general"),
/** The message sent whenever a cell is successfully removed. */ /** The message sent whenever a cell is successfully removed. */
CELLREMOVED ("general"), CELLREMOVED ("general"),
/** The simple word jailing to be put in other parts. */ /** The simple word jailing to be put in other parts. */
JAILING ("jailing"), JAILING ("jailing"),
/** 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"), JAILREMOVALUNSUCCESSFUL ("general"),
/** The message sent whenever a jail is successfully removed. */ /** The message sent whenever a jail is successfully removed. */
JAILREMOVED ("general"), 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"), 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"), 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"), 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"), 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"), NOCELLS ("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"), 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"), 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"), 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"), 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"), 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"), 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"), PLUGINRELOADED ("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"), 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"), 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"), RECORDTIMESJAILED ("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"), TIMEFORMAT ("general"),
/** The simple word transferring to be put in other parts. */ /** The simple word transferring to be put in other parts. */
TRANSFERRING ("general"), 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"), UNKNOWNCOMMAND ("general"),
//Jail pay //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"), 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"), 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"), 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"), 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"), 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"), 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"), PAYNOTENOUGHMONEYPROVIDED ("jailpay", "notenoughmoneyprovided"),
/** The message sent when they pay and get released. */ /** The message sent when they pay and get released. */
PAYPAIDRELEASED ("jailpay", "paidreleased"), 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", "PAYPAIDRELEASEDELSE"), PAYPAIDRELEASEDELSE ("jailpay", "PAYPAIDRELEASEDELSE"),
/** The message sent when they pay and lower their time. */ /** The message sent when they pay and lower their time. */
PAYPAIDLOWEREDTIME ("jailpay", "paidloweredtime"), 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"), PAYPAIDLOWEREDTIMEELSE ("jailpay", "paidloweredtimeelse"),
//Confirming action messages. //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"), ALREADY ("confirm"),
/** The message sent when their confirmation has expired. */ /** The message sent when their confirmation has expired. */
EXPIRED ("confirm"), 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"), 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"); START ("confirm");
private String section, name; private String section, name;
LangString(String section) { LangString(String section) {
this.section = section; this.section = section;
} }
LangString(String section, String name) { LangString(String section, String name) {
this.section = section; this.section = section;
this.name = name; this.name = name;
} }
/** Gets the section in the language file this is located at. */ /** Gets the section in the language file this is located at. */
public String getSection() { public String getSection() {
return this.section; return this.section;
} }
/** Returns the name of this enum if a custom one isn't present. */ /** Returns the name of this enum if a custom one isn't present. */
public String getName() { public String getName() {
return (name == null ? this.toString().toLowerCase() : name); return (name == null ? this.toString().toLowerCase() : name);
} }
} }

View File

@ -1,70 +1,70 @@
package com.graywolf336.jail.enums; package com.graywolf336.jail.enums;
public enum Settings { public enum Settings {
AUTOMATICMUTE("jailing.jail.automaticMute"), AUTOMATICMUTE("jailing.jail.automaticMute"),
BROADCASTJAILING("jailing.jail.broadcastJailing"), BROADCASTJAILING("jailing.jail.broadcastJailing"),
BLOCKBREAKPENALTY("jailing.during.blockBreakPenalty"), BLOCKBREAKPENALTY("jailing.during.blockBreakPenalty"),
BLOCKBREAKPROTECTION("jailing.during.blockBreakProtection"), BLOCKBREAKPROTECTION("jailing.during.blockBreakProtection"),
BLOCKBREAKWHITELIST("jailing.during.blockBreakWhiteList"), BLOCKBREAKWHITELIST("jailing.during.blockBreakWhiteList"),
BLOCKPLACEPENALTY("jailing.during.blockPlacePenalty"), BLOCKPLACEPENALTY("jailing.during.blockPlacePenalty"),
BLOCKPLACEPROTECTION("jailing.during.blockPlaceProtection"), BLOCKPLACEPROTECTION("jailing.during.blockPlaceProtection"),
BLOCKPLACEWHITELIST("jailing.during.blockPlaceWhiteList"), BLOCKPLACEWHITELIST("jailing.during.blockPlaceWhiteList"),
COMMANDSONJAIL("jailing.jail.commands"), COMMANDSONJAIL("jailing.jail.commands"),
COMMANDSONRELEASE("jailing.release.commands"), COMMANDSONRELEASE("jailing.release.commands"),
COMMANDPENALTY("jailing.during.commandPenalty"), COMMANDPENALTY("jailing.during.commandPenalty"),
COMMANDPROTECTION("jailing.during.commandProtection"), COMMANDPROTECTION("jailing.during.commandProtection"),
COMMANDWHITELIST("jailing.during.commandWhitelist"), COMMANDWHITELIST("jailing.during.commandWhitelist"),
COUNTDOWNTIMEOFFLINE("jailing.during.countDownTimeWhileOffline"), COUNTDOWNTIMEOFFLINE("jailing.during.countDownTimeWhileOffline"),
CROPTRAMPLINGPENALTY("jailing.during.cropTramplingPenalty"), CROPTRAMPLINGPENALTY("jailing.during.cropTramplingPenalty"),
CROPTRAMPLINGPROTECTION("jailing.during.cropTramplingProtection"), CROPTRAMPLINGPROTECTION("jailing.during.cropTramplingProtection"),
DEBUG("system.debug"), DEBUG("system.debug"),
DEFAULTJAIL("jailing.jail.defaultJail"), DEFAULTJAIL("jailing.jail.defaultJail"),
DELETEINVENTORY("jailing.jail.deleteInventory"), DELETEINVENTORY("jailing.jail.deleteInventory"),
ENDERMENPROTECTION("jails.endermenProtection"), ENDERMENPROTECTION("jails.endermenProtection"),
EXPLOSIONPROTECTION("jails.explosionProtection"), EXPLOSIONPROTECTION("jails.explosionProtection"),
FOODCONTROL("jailing.during.foodControl"), FOODCONTROL("jailing.during.foodControl"),
FOODCONTROLMAX("jailing.during.foodControlMax"), FOODCONTROLMAX("jailing.during.foodControlMax"),
FOODCONTROLMIN("jailing.during.foodControlMin"), FOODCONTROLMIN("jailing.during.foodControlMin"),
IGNORESLEEPINGSTATE("jailing.during.ignoreSleeping"), IGNORESLEEPINGSTATE("jailing.during.ignoreSleeping"),
JAILSTICKENABLED("jailstick.enabled"), JAILSTICKENABLED("jailstick.enabled"),
JAILSTICKSTICKS("jailstick.sticks"), JAILSTICKSTICKS("jailstick.sticks"),
JAILDEFAULTTIME("jailing.jail.defaultTime"), JAILDEFAULTTIME("jailing.jail.defaultTime"),
JAILEDGAMEMODE("jailing.jail.gameMode"), JAILEDGAMEMODE("jailing.jail.gameMode"),
JAILEDSTOREINVENTORY("jailing.jail.storeInventory"), JAILEDSTOREINVENTORY("jailing.jail.storeInventory"),
JAILPAYENABLED("jailpay.enabled"), JAILPAYENABLED("jailpay.enabled"),
JAILPAYITEM("jailpay.item"), JAILPAYITEM("jailpay.item"),
JAILPAYPRICEPERMINUTE ("jailpay.pricePerMinute"), JAILPAYPRICEPERMINUTE ("jailpay.pricePerMinute"),
JAILPAYPRICEINFINITE ("jailpay.priceInfinite"), JAILPAYPRICEINFINITE ("jailpay.priceInfinite"),
LOGJAILINGTOCONSOLE("jailing.jail.logToConsole"), LOGJAILINGTOCONSOLE("jailing.jail.logToConsole"),
MAXAFKTIME("jailing.during.maxAFKTime"), MAXAFKTIME("jailing.during.maxAFKTime"),
MOVEPENALTY("jailing.during.movePenalty"), MOVEPENALTY("jailing.during.movePenalty"),
MOVEPROTECTION("jailing.during.moveProtection"), MOVEPROTECTION("jailing.during.moveProtection"),
PREVENTINTERACTIONBLOCKS("jailing.during.preventInteractionBlocks"), PREVENTINTERACTIONBLOCKS("jailing.during.preventInteractionBlocks"),
PREVENTINTERACTIONBLOCKSPENALTY("jailing.during.preventInteractionBlocksPenalty"), PREVENTINTERACTIONBLOCKSPENALTY("jailing.during.preventInteractionBlocksPenalty"),
PREVENTINTERACTIONITEMS("jailing.during.preventInteractionItems"), PREVENTINTERACTIONITEMS("jailing.during.preventInteractionItems"),
PREVENTINTERACTIONITEMSPENALTY("jailing.during.preventInteractionItemsPenalty"), PREVENTINTERACTIONITEMSPENALTY("jailing.during.preventInteractionItemsPenalty"),
PRISONEROPENCHEST("jailing.during.openChest"), PRISONEROPENCHEST("jailing.during.openChest"),
RECIEVEMESSAGES("jailing.during.recieveMessages"), RECIEVEMESSAGES("jailing.during.recieveMessages"),
RELEASETOPREVIOUSPOSITION("jailing.release.backToPreviousPosition"), RELEASETOPREVIOUSPOSITION("jailing.release.backToPreviousPosition"),
RESTOREPREVIOUSGAMEMODE("jailing.release.restorePreviousGameMode"), RESTOREPREVIOUSGAMEMODE("jailing.release.restorePreviousGameMode"),
SCOREBOARDENABLED("jailing.during.scoreboard.enabled"), SCOREBOARDENABLED("jailing.during.scoreboard.enabled"),
SCOREBOARDTITLE("jailing.during.scoreboard.title"), SCOREBOARDTITLE("jailing.during.scoreboard.title"),
SCOREBOARDTIME("jailing.during.scoreboard.time"), SCOREBOARDTIME("jailing.during.scoreboard.time"),
TELEPORTONRELEASE("jailing.release.teleport"), TELEPORTONRELEASE("jailing.release.teleport"),
UPDATENOTIFICATIONS("system.updateNotifications"), UPDATENOTIFICATIONS("system.updateNotifications"),
USEBUKKITTIMER("system.useBukkitTimer"); USEBUKKITTIMER("system.useBukkitTimer");
private String path; private String path;
private Settings(String path) { private Settings(String path) {
this.path = path; this.path = path;
} }
/** /**
* Gets the path this setting is in config. * Gets the path this setting is in config.
* @return The path where this setting resides in the config. * @return The path where this setting resides in the config.
*/ */
public String getPath() { public String getPath() {
return this.path; return this.path;
} }
} }

View File

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

View File

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

View File

@ -1,73 +1,73 @@
package com.graywolf336.jail.events; package com.graywolf336.jail.events;
import org.bukkit.entity.Player; import org.bukkit.entity.Player;
import org.bukkit.event.Event; import org.bukkit.event.Event;
import org.bukkit.event.HandlerList; import org.bukkit.event.HandlerList;
import com.graywolf336.jail.beans.Cell; import com.graywolf336.jail.beans.Cell;
import com.graywolf336.jail.beans.Jail; import com.graywolf336.jail.beans.Jail;
import com.graywolf336.jail.beans.Prisoner; import com.graywolf336.jail.beans.Prisoner;
/** /**
* Event thrown after a prisoner is released. * Event thrown after a prisoner is released.
* *
* <p /> * <p />
* *
* This event is called before everything for the releasing takes place. * This event is called before everything for the releasing takes place.
* This event is called for informative purposes, see {@link PrisonerReleasedEvent} * This event is called for informative purposes, see {@link PrisonerReleasedEvent}
* for the event called after they get teleported out and all that fancy stuff. * for the event called after they get teleported out and all that fancy stuff.
* *
* @author graywolf336 * @author graywolf336
* @since 3.0.0 * @since 3.0.0
* @version 1.0.0 * @version 1.0.0
*/ */
public class PrePrisonerReleasedEvent extends Event { public class PrePrisonerReleasedEvent extends Event {
private static final HandlerList handlers = new HandlerList(); private static final HandlerList handlers = new HandlerList();
private Jail jail; private Jail jail;
private Cell cell; private Cell cell;
private Prisoner prisoner; private Prisoner prisoner;
private Player player; private Player player;
/** /**
* Creates a new {@link PrePrisonerReleasedEvent pre-prisoner released event} for the given player. * Creates a new {@link PrePrisonerReleasedEvent pre-prisoner released event} for the given player.
* *
* @param jail The jail the prisoner will be jailed at. * @param jail The jail the prisoner will be jailed at.
* @param cell The cell we're going to be sending the prisoner to, can be null. * @param cell The cell we're going to be sending the prisoner to, can be null.
* @param prisoner The prisoner data. * @param prisoner The prisoner data.
* @param player The player being jailed. * @param player The player being jailed.
*/ */
public PrePrisonerReleasedEvent(Jail jail, Cell cell, Prisoner prisoner, Player player) { public PrePrisonerReleasedEvent(Jail jail, Cell cell, Prisoner prisoner, Player player) {
this.jail = jail; this.jail = jail;
this.cell = cell; this.cell = cell;
this.prisoner = prisoner; this.prisoner = prisoner;
this.player = player; this.player = player;
} }
/** Gets the {@link Jail} this prisoner is coming from. */ /** Gets the {@link Jail} this prisoner is coming from. */
public Jail getJail() { public Jail getJail() {
return this.jail; return this.jail;
} }
/** Gets the cell where the prisoner was jailed in, null if they weren't in one. */ /** Gets the cell where the prisoner was jailed in, null if they weren't in one. */
public Cell getCell() { public Cell getCell() {
return this.cell; return this.cell;
} }
/** Gets the {@link Prisoner} data for this prisoner. */ /** Gets the {@link Prisoner} data for this prisoner. */
public Prisoner getPrisoner() { public Prisoner getPrisoner() {
return this.prisoner; return this.prisoner;
} }
/** Gets the instance of the player being released. */ /** Gets the instance of the player being released. */
public Player getPlayer() { public Player getPlayer() {
return this.player; return this.player;
} }
public static HandlerList getHandlerList() { public static HandlerList getHandlerList() {
return handlers; return handlers;
} }
public HandlerList getHandlers() { public HandlerList getHandlers() {
return handlers; return handlers;
} }
} }

View File

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

View File

@ -1,78 +1,78 @@
package com.graywolf336.jail.events; package com.graywolf336.jail.events;
import org.bukkit.entity.Player; import org.bukkit.entity.Player;
import org.bukkit.event.Event; import org.bukkit.event.Event;
import org.bukkit.event.HandlerList; import org.bukkit.event.HandlerList;
import com.graywolf336.jail.beans.Cell; import com.graywolf336.jail.beans.Cell;
import com.graywolf336.jail.beans.Jail; import com.graywolf336.jail.beans.Jail;
import com.graywolf336.jail.beans.Prisoner; import com.graywolf336.jail.beans.Prisoner;
/** /**
* Event thrown after a prisoner is put into jail. * 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 after everything for the jailing takes place.
* This event is called for informative purposes, see {@link PrePrisonerJailedEvent} * This event is called for informative purposes, see {@link PrePrisonerJailedEvent}
* for the event called before they teleported in and all that fancy stuff. * for the event called before they teleported in and all that fancy stuff.
* *
* @author graywolf336 * @author graywolf336
* @since 3.0.0 * @since 3.0.0
* @version 1.0.0 * @version 1.0.0
*/ */
public class PrisonerJailedEvent extends Event { public class PrisonerJailedEvent extends Event {
private static final HandlerList handlers = new HandlerList(); private static final HandlerList handlers = new HandlerList();
private Jail jail; private Jail jail;
private Cell cell; private Cell cell;
private Prisoner prisoner; private Prisoner prisoner;
private Player player; private Player player;
/** /**
* Creates a new {@link PrisonerJailedEvent prisoner jailed event} for the given player. * Creates a new {@link PrisonerJailedEvent prisoner jailed event} for the given player.
* *
* @param jail The jail the prisoner will be jailed at. * @param jail The jail the prisoner will be jailed at.
* @param cell The cell we're going to be sending the prisoner to, can be null. * @param cell The cell we're going to be sending the prisoner to, can be null.
* @param prisoner The prisoner data. * @param prisoner The prisoner data.
* @param player The player being jailed. * @param player The player being jailed.
*/ */
public PrisonerJailedEvent(Jail jail, Cell cell, Prisoner prisoner, Player player) { public PrisonerJailedEvent(Jail jail, Cell cell, Prisoner prisoner, Player player) {
this.jail = jail; this.jail = jail;
this.cell = cell; this.cell = cell;
this.prisoner = prisoner; this.prisoner = prisoner;
this.player = player; this.player = player;
} }
/** Gets the {@link Jail} this prisoner is being sent to. */ /** Gets the {@link Jail} this prisoner is being sent to. */
public Jail getJail() { public Jail getJail() {
return this.jail; return this.jail;
} }
/** Gets the cell we're going to be sending the prisoner to, can be null. */ /** Gets the cell we're going to be sending the prisoner to, can be null. */
public Cell getCell() { public Cell getCell() {
return this.cell; return this.cell;
} }
/** Gets the {@link Prisoner} data for this prisoner. */ /** Gets the {@link Prisoner} data for this prisoner. */
public Prisoner getPrisoner() { public Prisoner getPrisoner() {
return this.prisoner; return this.prisoner;
} }
/** Gets the instance of the player being jailed. */ /** Gets the instance of the player being jailed. */
public Player getPlayer() { public Player getPlayer() {
return this.player; return this.player;
} }
/** Gets the jailer who jailed this prisoner. */ /** Gets the jailer who jailed this prisoner. */
public String getJailer() { public String getJailer() {
return this.prisoner.getJailer(); return this.prisoner.getJailer();
} }
public static HandlerList getHandlerList() { public static HandlerList getHandlerList() {
return handlers; return handlers;
} }
public HandlerList getHandlers() { public HandlerList getHandlers() {
return handlers; return handlers;
} }
} }

View File

@ -1,73 +1,73 @@
package com.graywolf336.jail.events; package com.graywolf336.jail.events;
import org.bukkit.entity.Player; import org.bukkit.entity.Player;
import org.bukkit.event.Event; import org.bukkit.event.Event;
import org.bukkit.event.HandlerList; import org.bukkit.event.HandlerList;
import com.graywolf336.jail.beans.Cell; import com.graywolf336.jail.beans.Cell;
import com.graywolf336.jail.beans.Jail; import com.graywolf336.jail.beans.Jail;
import com.graywolf336.jail.beans.Prisoner; import com.graywolf336.jail.beans.Prisoner;
/** /**
* Event thrown after a prisoner is released. * Event thrown after a prisoner is released.
* *
* <p /> * <p />
* *
* This event is called after everything for the releasing takes place. * This event is called after everything for the releasing takes place.
* This event is called for informative purposes, see {@link PrePrisonerReleasedEvent} * This event is called for informative purposes, see {@link PrePrisonerReleasedEvent}
* for the event called before they teleported out and all that fancy stuff. * for the event called before they teleported out and all that fancy stuff.
* *
* @author graywolf336 * @author graywolf336
* @since 3.0.0 * @since 3.0.0
* @version 1.0.0 * @version 1.0.0
*/ */
public class PrisonerReleasedEvent extends Event { public class PrisonerReleasedEvent extends Event {
private static final HandlerList handlers = new HandlerList(); private static final HandlerList handlers = new HandlerList();
private Jail jail; private Jail jail;
private Cell cell; private Cell cell;
private Prisoner prisoner; private Prisoner prisoner;
private Player player; private Player player;
/** /**
* Creates a new {@link PrisonerReleasedEvent prisoner released event} for the given player. * Creates a new {@link PrisonerReleasedEvent prisoner released event} for the given player.
* *
* @param jail The jail the prisoner will be jailed at. * @param jail The jail the prisoner will be jailed at.
* @param cell The cell we're going to be sending the prisoner to, can be null. * @param cell The cell we're going to be sending the prisoner to, can be null.
* @param prisoner The prisoner data. * @param prisoner The prisoner data.
* @param player The player being jailed. * @param player The player being jailed.
*/ */
public PrisonerReleasedEvent(Jail jail, Cell cell, Prisoner prisoner, Player player) { public PrisonerReleasedEvent(Jail jail, Cell cell, Prisoner prisoner, Player player) {
this.jail = jail; this.jail = jail;
this.cell = cell; this.cell = cell;
this.prisoner = prisoner; this.prisoner = prisoner;
this.player = player; this.player = player;
} }
/** Gets the {@link Jail} this prisoner is coming from. */ /** Gets the {@link Jail} this prisoner is coming from. */
public Jail getJail() { public Jail getJail() {
return this.jail; return this.jail;
} }
/** Gets the cell where the prisoner was jailed in, null if they weren't in one. */ /** Gets the cell where the prisoner was jailed in, null if they weren't in one. */
public Cell getCell() { public Cell getCell() {
return this.cell; return this.cell;
} }
/** Gets the {@link Prisoner} data for this prisoner. */ /** Gets the {@link Prisoner} data for this prisoner. */
public Prisoner getPrisoner() { public Prisoner getPrisoner() {
return this.prisoner; return this.prisoner;
} }
/** Gets the instance of the player being released. */ /** Gets the instance of the player being released. */
public Player getPlayer() { public Player getPlayer() {
return this.player; return this.player;
} }
public static HandlerList getHandlerList() { public static HandlerList getHandlerList() {
return handlers; return handlers;
} }
public HandlerList getHandlers() { public HandlerList getHandlers() {
return handlers; return handlers;
} }
} }

View File

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

View File

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

View File

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

View File

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

View File

@ -1,73 +1,73 @@
package com.graywolf336.jail.listeners; package com.graywolf336.jail.listeners;
import org.bukkit.event.EventHandler; import org.bukkit.event.EventHandler;
import org.bukkit.event.EventPriority; import org.bukkit.event.EventPriority;
import org.bukkit.event.Listener; import org.bukkit.event.Listener;
import org.bukkit.event.player.PlayerJoinEvent; import org.bukkit.event.player.PlayerJoinEvent;
import org.bukkit.event.player.PlayerKickEvent; import org.bukkit.event.player.PlayerKickEvent;
import org.bukkit.event.player.PlayerQuitEvent; import org.bukkit.event.player.PlayerQuitEvent;
import com.graywolf336.jail.JailMain; import com.graywolf336.jail.JailMain;
import com.graywolf336.jail.beans.CachePrisoner; import com.graywolf336.jail.beans.CachePrisoner;
import com.graywolf336.jail.beans.Jail; import com.graywolf336.jail.beans.Jail;
import com.graywolf336.jail.beans.Prisoner; import com.graywolf336.jail.beans.Prisoner;
import com.graywolf336.jail.events.PrePrisonerTransferredEvent; import com.graywolf336.jail.events.PrePrisonerTransferredEvent;
import com.graywolf336.jail.events.PrisonerJailedEvent; import com.graywolf336.jail.events.PrisonerJailedEvent;
import com.graywolf336.jail.events.PrisonerReleasedEvent; import com.graywolf336.jail.events.PrisonerReleasedEvent;
import com.graywolf336.jail.events.PrisonerTransferredEvent; import com.graywolf336.jail.events.PrisonerTransferredEvent;
public class CacheListener implements Listener { public class CacheListener implements Listener {
private JailMain pl; private JailMain pl;
public CacheListener(JailMain plugin) { public CacheListener(JailMain plugin) {
this.pl = plugin; this.pl = plugin;
} }
@EventHandler(priority = EventPriority.LOWEST) @EventHandler(priority = EventPriority.LOWEST)
public void joinListener(PlayerJoinEvent event) { public void joinListener(PlayerJoinEvent event) {
if(pl.getJailManager().isPlayerJailed(event.getPlayer().getUniqueId())) { if(pl.getJailManager().isPlayerJailed(event.getPlayer().getUniqueId())) {
Jail j = pl.getJailManager().getJailPlayerIsIn(event.getPlayer().getUniqueId()); Jail j = pl.getJailManager().getJailPlayerIsIn(event.getPlayer().getUniqueId());
Prisoner p = j.getPrisoner(event.getPlayer().getUniqueId()); Prisoner p = j.getPrisoner(event.getPlayer().getUniqueId());
pl.getJailManager().addCacheObject(new CachePrisoner(j, p)); pl.getJailManager().addCacheObject(new CachePrisoner(j, p));
} }
} }
@EventHandler(priority = EventPriority.LOWEST) @EventHandler(priority = EventPriority.LOWEST)
public void leaveListener(PlayerQuitEvent event) { public void leaveListener(PlayerQuitEvent event) {
if(pl.getJailManager().inCache(event.getPlayer().getUniqueId())) { if(pl.getJailManager().inCache(event.getPlayer().getUniqueId())) {
pl.getJailManager().removeCacheObject(event.getPlayer().getUniqueId()); pl.getJailManager().removeCacheObject(event.getPlayer().getUniqueId());
} }
} }
@EventHandler(priority = EventPriority.LOWEST) @EventHandler(priority = EventPriority.LOWEST)
public void kickListener(PlayerKickEvent event) { public void kickListener(PlayerKickEvent event) {
if(pl.getJailManager().inCache(event.getPlayer().getUniqueId())) { if(pl.getJailManager().inCache(event.getPlayer().getUniqueId())) {
pl.getJailManager().removeCacheObject(event.getPlayer().getUniqueId()); pl.getJailManager().removeCacheObject(event.getPlayer().getUniqueId());
} }
} }
@EventHandler(priority = EventPriority.LOWEST) @EventHandler(priority = EventPriority.LOWEST)
public void jailListener(PrisonerJailedEvent event) { public void jailListener(PrisonerJailedEvent event) {
pl.getJailManager().addCacheObject(new CachePrisoner(event.getJail(), event.getPrisoner())); pl.getJailManager().addCacheObject(new CachePrisoner(event.getJail(), event.getPrisoner()));
} }
@EventHandler(priority = EventPriority.LOWEST) @EventHandler(priority = EventPriority.LOWEST)
public void releaseListener(PrisonerReleasedEvent event) { public void releaseListener(PrisonerReleasedEvent event) {
if(pl.getJailManager().inCache(event.getPlayer().getUniqueId())) { if(pl.getJailManager().inCache(event.getPlayer().getUniqueId())) {
pl.getJailManager().removeCacheObject(event.getPlayer().getUniqueId()); pl.getJailManager().removeCacheObject(event.getPlayer().getUniqueId());
} }
} }
@EventHandler(priority = EventPriority.LOWEST) @EventHandler(priority = EventPriority.LOWEST)
public void beforeTransferringListener(PrePrisonerTransferredEvent event) { public void beforeTransferringListener(PrePrisonerTransferredEvent event) {
if(pl.getJailManager().inCache(event.getPlayer().getUniqueId())) { if(pl.getJailManager().inCache(event.getPlayer().getUniqueId())) {
pl.getJailManager().removeCacheObject(event.getPlayer().getUniqueId()); pl.getJailManager().removeCacheObject(event.getPlayer().getUniqueId());
} }
} }
@EventHandler(priority = EventPriority.LOWEST) @EventHandler(priority = EventPriority.LOWEST)
public void transferListener(PrisonerTransferredEvent event) { public void transferListener(PrisonerTransferredEvent event) {
pl.getJailManager().addCacheObject(new CachePrisoner(event.getTargetJail(), event.getPrisoner())); pl.getJailManager().addCacheObject(new CachePrisoner(event.getTargetJail(), event.getPrisoner()));
} }
} }

View File

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

View File

@ -1,39 +1,39 @@
package com.graywolf336.jail.listeners; package com.graywolf336.jail.listeners;
import java.text.DateFormat; import java.text.DateFormat;
import java.text.SimpleDateFormat; import java.text.SimpleDateFormat;
import java.util.Date; import java.util.Date;
import org.bukkit.event.EventHandler; import org.bukkit.event.EventHandler;
import org.bukkit.event.Listener; import org.bukkit.event.Listener;
import com.graywolf336.jail.JailMain; import com.graywolf336.jail.JailMain;
import com.graywolf336.jail.enums.LangString; import com.graywolf336.jail.enums.LangString;
import com.graywolf336.jail.events.PrePrisonerJailedByJailStickEvent; import com.graywolf336.jail.events.PrePrisonerJailedByJailStickEvent;
import com.graywolf336.jail.events.PrePrisonerJailedEvent; import com.graywolf336.jail.events.PrePrisonerJailedEvent;
public class JailingListener implements Listener { public class JailingListener implements Listener {
private JailMain pl; private JailMain pl;
private DateFormat dateFormat; private DateFormat dateFormat;
public JailingListener(JailMain plugin) { public JailingListener(JailMain plugin) {
this.pl = plugin; this.pl = plugin;
this.dateFormat = new SimpleDateFormat(pl.getJailIO().getLanguageString(LangString.TIMEFORMAT)); this.dateFormat = new SimpleDateFormat(pl.getJailIO().getLanguageString(LangString.TIMEFORMAT));
} }
@EventHandler(ignoreCancelled=true) @EventHandler(ignoreCancelled=true)
public void preJailingListener(PrePrisonerJailedEvent event) { public void preJailingListener(PrePrisonerJailedEvent event) {
pl.getJailIO().addRecordEntry(event.getPrisoner().getUUID().toString(), pl.getJailIO().addRecordEntry(event.getPrisoner().getUUID().toString(),
event.getPrisoner().getLastKnownName(), event.getPrisoner().getLastKnownName(),
event.getPrisoner().getJailer(), dateFormat.format(new Date()), event.getPrisoner().getJailer(), dateFormat.format(new Date()),
event.getPrisoner().getRemainingTimeInMinutes(), event.getPrisoner().getReason()); event.getPrisoner().getRemainingTimeInMinutes(), event.getPrisoner().getReason());
} }
@EventHandler(ignoreCancelled=true) @EventHandler(ignoreCancelled=true)
public void preJailingListener(PrePrisonerJailedByJailStickEvent event) { public void preJailingListener(PrePrisonerJailedByJailStickEvent event) {
pl.getJailIO().addRecordEntry(event.getPrisoner().getUUID().toString(), pl.getJailIO().addRecordEntry(event.getPrisoner().getUUID().toString(),
event.getPrisoner().getLastKnownName(), event.getPrisoner().getLastKnownName(),
event.getPrisoner().getJailer(), dateFormat.format(new Date()), event.getPrisoner().getJailer(), dateFormat.format(new Date()),
event.getPrisoner().getRemainingTimeInMinutes(), event.getPrisoner().getReason()); event.getPrisoner().getRemainingTimeInMinutes(), event.getPrisoner().getReason());
} }
} }

View File

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

View File

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

View File

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

View File

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

View File

@ -1,73 +1,73 @@
system: system:
configVersion: 3 configVersion: 3
debug: false debug: false
language: 'en' language: 'en'
updateNotifications: true updateNotifications: true
useBukkitTimer: true useBukkitTimer: true
storage: storage:
type: 'flatfile' #can be flatfile, sqlite, or mysql type: 'flatfile' #can be flatfile, sqlite, or mysql
mysql: mysql:
host: 'localhost' host: 'localhost'
port: 3306 port: 3306
username: 'root' username: 'root'
password: 'password' password: 'password'
database: 'jailDatabase' database: 'jailDatabase'
prefix: 'j3_' prefix: 'j3_'
jailing: jailing:
during: during:
blockBreakPenalty: 5m blockBreakPenalty: 5m
blockBreakProtection: true blockBreakProtection: true
blockBreakWhiteList: ['crops', 'carrot', 'potato'] # these blocks can be broken at any time by prisoners blockBreakWhiteList: ['crops', 'carrot', 'potato'] # these blocks can be broken at any time by prisoners
blockPlacePenalty: 5m blockPlacePenalty: 5m
blockPlaceProtection: true blockPlaceProtection: true
blockPlaceWhiteList: ['crops', 'carrot', 'potato'] # these blocks can be placed at any time by prisoners blockPlaceWhiteList: ['crops', 'carrot', 'potato'] # these blocks can be placed at any time by prisoners
commandPenalty: 5m commandPenalty: 5m
commandProtection: true commandProtection: true
commandWhitelist: ['/ping', '/list', '/jail status', '/jail pay'] commandWhitelist: ['/ping', '/list', '/jail status', '/jail pay']
countDownTimeWhileOffline: false countDownTimeWhileOffline: false
cropTramplingPenalty: 5m cropTramplingPenalty: 5m
cropTramplingProtection: true cropTramplingProtection: true
foodControl: true foodControl: true
foodControlMax: 20 foodControlMax: 20
foodControlMin: 10 foodControlMin: 10
ignoreSleeping: true ignoreSleeping: true
maxAFKTime: 10m #in minutes maxAFKTime: 10m #in minutes
movePenalty: 10m movePenalty: 10m
moveProtection: true moveProtection: true
openChest: true openChest: true
preventInteractionBlocks: ['wooden_door', 'iron_door_block'] preventInteractionBlocks: ['wooden_door', 'iron_door_block']
preventInteractionBlocksPenalty: 5m preventInteractionBlocksPenalty: 5m
preventInteractionItems: [] preventInteractionItems: []
preventInteractionItemsPenalty: 5m preventInteractionItemsPenalty: 5m
recieveMessages: true recieveMessages: true
scoreboard: scoreboard:
enabled: false enabled: false
title: 'Jail Info' title: 'Jail Info'
time: '&aTime:' time: '&aTime:'
jail: jail:
automaticMute: true automaticMute: true
broadcastJailing: false broadcastJailing: false
commands: [] commands: []
defaultJail: nearest #the jail nearest to the player defaultJail: nearest #the jail nearest to the player
defaultTime: 30m #default the time to 30 minutes, if no time defaultTime: 30m #default the time to 30 minutes, if no time
deleteInventory: false deleteInventory: false
gameMode: adventure gameMode: adventure
logToConsole: true logToConsole: true
logToProfile: false logToProfile: false
storeInventory: true storeInventory: true
release: release:
backToPreviousPosition: false backToPreviousPosition: false
commands: [] commands: []
restorePreviousGameMode: false restorePreviousGameMode: false
teleport: true teleport: true
jails: jails:
endermenProtection: true endermenProtection: true
explosionProtection: true explosionProtection: true
jailpay: jailpay:
enabled: true enabled: true
item: air item: air
pricePerMinute: 1.5 pricePerMinute: 1.5
priceInfinite: 10000 priceInfinite: 10000
jailstick: jailstick:
enabled: true enabled: true
sticks: ["stick,30,,Running away"] sticks: ["stick,30,,Running away"]

View File

@ -1,97 +1,97 @@
language: language:
actions: actions:
blockbreaking: 'breaking a block' blockbreaking: 'breaking a block'
blockplacing: 'placing a block' blockplacing: 'placing a block'
command: 'trying to use a command' command: 'trying to use a command'
croptrampling: 'trampling crops' croptrampling: 'trampling crops'
interactionblocks: 'interacting with a block' interactionblocks: 'interacting with a block'
interactionitems: 'interacting with an item' interactionitems: 'interacting with an item'
moving: 'trying to escape' moving: 'trying to escape'
confirm: confirm:
already: "&cYou are already confirming something else, please type '&b/jail confirm&c' to confirm it." already: "&cYou are already confirming something else, please type '&b/jail confirm&c' to confirm it."
expired: '&cYour confirmation expired already, retype what you are trying to confirm.' expired: '&cYour confirmation expired already, retype what you are trying to confirm.'
nothing: '&cYou are not confirming anything.' nothing: '&cYou are not confirming anything.'
start: "&cPlease type '&b/jail confirm&c' to confirm we should continue." start: "&cPlease type '&b/jail confirm&c' to confirm we should continue."
general: general:
alljails: 'all the jails' alljails: 'all the jails'
cellremovalunsuccessful: '&cThe removal of cell %0% from jail %1% was unsuccessful because there is a prisoner in there still. Release or transfer before trying to remove the cell again.' cellremovalunsuccessful: '&cThe removal of cell %0% from jail %1% was unsuccessful because there is a prisoner in there still. Release or transfer before trying to remove the cell again.'
cellremoved: '&9Cell %0% has been successfully removed from the jail %1%.' cellremoved: '&9Cell %0% has been successfully removed from the jail %1%.'
jailing: '&9jailing' jailing: '&9jailing'
jailremovalunsuccessful: '&cThe removal of the jail %0% was unsuccessful because there are prisoners in there, please release or transfer them first.' jailremovalunsuccessful: '&cThe removal of the jail %0% was unsuccessful because there are prisoners in there, please release or transfer them first.'
jailremoved: '&9Jail %0% has been successfully deleted.' jailremoved: '&9Jail %0% has been successfully deleted.'
jailstickdisabled: '&3Jail stick usage: &cdisabled' jailstickdisabled: '&3Jail stick usage: &cdisabled'
jailstickenabled: '&3Jail stick usage: &aenabled' jailstickenabled: '&3Jail stick usage: &aenabled'
jailstickusagedisabled: '&cThe usage of Jail Sticks has been disabled by the Administrator.' jailstickusagedisabled: '&cThe usage of Jail Sticks has been disabled by the Administrator.'
nocell: '&cNo cell found by the name of %0% in the jail %1%.' nocell: '&cNo cell found by the name of %0% in the jail %1%.'
nocells: '&cNo cells found in the jail %0%.' nocells: '&cNo cells found in the jail %0%.'
nojail: '&cNo jail found by the name of %0%.' nojail: '&cNo jail found by the name of %0%.'
nojails: '&cThere are currently no jails.' nojails: '&cThere are currently no jails.'
nopermission: '&cInsufficient permission.' nopermission: '&cInsufficient permission.'
numberformatincorrect: '&cNumber format is incorrect.' numberformatincorrect: '&cNumber format is incorrect.'
playercontextrequired: '&cA player context is required for this.' playercontextrequired: '&cA player context is required for this.'
playernotonline: '&cThat player is not online!' playernotonline: '&cThat player is not online!'
pluginreloaded: '&9Jail data successfully reloaded.' pluginreloaded: '&9Jail data successfully reloaded.'
prisonerscleared: '&cAll the prisoners from %0% have been cleared.' prisonerscleared: '&cAll the prisoners from %0% have been cleared.'
recordentry: '&7[%0%]: &9%1% &fjailed by &9%2% &ffor &9%3% &fminutes with a reason of &9%4%&f. [%5%]' recordentry: '&7[%0%]: &9%1% &fjailed by &9%2% &ffor &9%3% &fminutes with a reason of &9%4%&f. [%5%]'
recordtimesjailed: '&c%0% has been jailed &a%1% &ctimes.' recordtimesjailed: '&c%0% has been jailed &a%1% &ctimes.'
timeformat: "MM/dd/yyyy HH:mm:ss" timeformat: "MM/dd/yyyy HH:mm:ss"
transferring: '&9transferring' transferring: '&9transferring'
unknowncommand: '&cNo commands registered by the name of %0%.' unknowncommand: '&cNo commands registered by the name of %0%.'
jailing: jailing:
afkkickmessage: '&cYou can not be afk while being jailed.' afkkickmessage: '&cYou can not be afk while being jailed.'
alreadyjailed: '&c%0% is already jailed.' alreadyjailed: '&c%0% is already jailed.'
broadcastmessageforever: '&9%0% has been jailed forever.' broadcastmessageforever: '&9%0% has been jailed forever.'
broadcastmessageforminutes: '&9%0% has been jailed for %1% minutes.' broadcastmessageforminutes: '&9%0% has been jailed for %1% minutes.'
broadcastunjailing: '&9%0% has been unjailed by %1%.' broadcastunjailing: '&9%0% has been unjailed by %1%.'
cancelledbyanotherplugin: '&cJailing %0% was cancelled by another plugin and they did not leave you a message.' cancelledbyanotherplugin: '&cJailing %0% was cancelled by another plugin and they did not leave you a message.'
cantbejailed: '&cThat player can not be jailed.' cantbejailed: '&cThat player can not be jailed.'
cellnotempty: '&cThe destination cell, %0%, already has a prisoner in it.' cellnotempty: '&cThe destination cell, %0%, already has a prisoner in it.'
defaultjailedreason: 'Breaking the rules.' defaultjailedreason: 'Breaking the rules.'
forceunjailed: '&c%0% was forcefully unjailed.' forceunjailed: '&c%0% was forcefully unjailed.'
jailed: '&cYou have been jailed!' jailed: '&cYou have been jailed!'
jailedwithreason: '&cYou have been jailed for: %0%' jailedwithreason: '&cYou have been jailed for: %0%'
muted: '&cStop talking, you are in jail.' muted: '&cStop talking, you are in jail.'
noemptycells: '&cNo empty cells were found for %0%, all them appear to be full.' noemptycells: '&cNo empty cells were found for %0%, all them appear to be full.'
noprisoners: '&9%0% is empty and contains no prisoners.' noprisoners: '&9%0% is empty and contains no prisoners.'
notjailed: '&c%0% is not jailed.' notjailed: '&c%0% is not jailed.'
nowmuted: '&9%0% is now muted.' nowmuted: '&9%0% is now muted.'
nowunmuted: '&9%0% is now unmuted.' nowunmuted: '&9%0% is now unmuted.'
offlinejail: '&2%0% is offline and will be jailed when they next come online for %1% minutes.' offlinejail: '&2%0% is offline and will be jailed when they next come online for %1% minutes.'
onlinejail: '&2%0% was jailed for %1% minutes.' onlinejail: '&2%0% was jailed for %1% minutes.'
prisonerstime: '&2%0% has %1% minutes remaining.' prisonerstime: '&2%0% has %1% minutes remaining.'
protectionmessage: '&c%0% minutes have been added to your time for %1%.' protectionmessage: '&c%0% minutes have been added to your time for %1%.'
protectionmessagenopenalty: '&cProtection enabled for %0%, do not do it again.' protectionmessagenopenalty: '&cProtection enabled for %0%, do not do it again.'
provideaplayer: '&cPlease provide a player when %0% &cthem.' provideaplayer: '&cPlease provide a player when %0% &cthem.'
provideajail: '&cPlease provide a jail to %0% &cthem to.' provideajail: '&cPlease provide a jail to %0% &cthem to.'
status: "&2You have been jailed with a reason of '%0%' by %1% and have %2% minutes remaining." status: "&2You have been jailed with a reason of '%0%' by %1% and have %2% minutes remaining."
suggestedcell: '&cAn empty cell in the same jail, %0%, was found: %1%' suggestedcell: '&cAn empty cell in the same jail, %0%, was found: %1%'
telein: "&9Teleported %0% to %1%'s teleport in location." telein: "&9Teleported %0% to %1%'s teleport in location."
teleout: "&9Teleported %0% to %1%'s teleport out location." teleout: "&9Teleported %0% to %1%'s teleport out location."
transferallcomplete: '&2Successfully transferred all the prisoners from %0% to %1%.' transferallcomplete: '&2Successfully transferred all the prisoners from %0% to %1%.'
transfercancelledbyanotherplugin: '&cTransferring %0% was cancelled by another plugin and they did not leave you a message.' transfercancelledbyanotherplugin: '&cTransferring %0% was cancelled by another plugin and they did not leave you a message.'
transfercompletecell: '&2Successfully transferred %0% to %1% in the cell %2%.' transfercompletecell: '&2Successfully transferred %0% to %1% in the cell %2%.'
transfercompletenocell: '&2Successfully transferred %0% to %1%.' transfercompletenocell: '&2Successfully transferred %0% to %1%.'
transferred: '&9You have been transferred to %0%.' transferred: '&9You have been transferred to %0%.'
unjailed: '&2You have been released! Please respect the server rules.' unjailed: '&2You have been released! Please respect the server rules.'
willbeunjailed: '&2%0% will be released the next time they log on.' willbeunjailed: '&2%0% will be released the next time they log on.'
youarenotjailed: '&2You are not jailed.' youarenotjailed: '&2You are not jailed.'
jailpay: jailpay:
cantpayforotherswhilejailed: '&cYou are jailed and as a result you can not pay for others.' cantpayforotherswhilejailed: '&cYou are jailed and as a result you can not pay for others.'
cost: '&9You have to pay %0% %1% per minute which equates to %2% %1%.' cost: '&9You have to pay %0% %1% per minute which equates to %2% %1%.'
costinfinite: '&9Since you are jailed forever, you have to pay %0% %1%.' costinfinite: '&9Since you are jailed forever, you have to pay %0% %1%.'
nonegativeamounts: '&cYou can not pay negative amounts.' nonegativeamounts: '&cYou can not pay negative amounts.'
notenabled: "&cSorry, money won't help this time." notenabled: "&cSorry, money won't help this time."
notenoughmoney: "&cYou don't have that much money!" notenoughmoney: "&cYou don't have that much money!"
notenoughmoneyprovided: "&cYou have not provided enough money to cover the sentence!" notenoughmoneyprovided: "&cYou have not provided enough money to cover the sentence!"
paidreleased: "&2You have just payed %0% and released yourself from jail!" paidreleased: "&2You have just payed %0% and released yourself from jail!"
paidreleasedelse: "&2You have just payed %0% and released %1% from jail!" paidreleasedelse: "&2You have just payed %0% and released %1% from jail!"
paidloweredtime: "&2You have just payed %0% and lowered your sentence to %1% minutes!" paidloweredtime: "&2You have just payed %0% and lowered your sentence to %1% minutes!"
paidloweredtimeelse: "&2You have just payed %0% and lowered %1%'s sentence to %2% minutes!" paidloweredtimeelse: "&2You have just payed %0% and lowered %1%'s sentence to %2% minutes!"
handcuffing: handcuffing:
cantbehandcuffed: '&9%0% &ccan not be handcuffed.' cantbehandcuffed: '&9%0% &ccan not be handcuffed.'
currentlyjailed: '&9%0% &cis currently jailed, you can not handcuff a prisoner.' currentlyjailed: '&9%0% &cis currently jailed, you can not handcuff a prisoner.'
nothandcuffed: '&9%0% &cdoes not have any handcuffs to remove!' nothandcuffed: '&9%0% &cdoes not have any handcuffs to remove!'
handcuffson: '&9%0% &ahas been handcuffed!' handcuffson: '&9%0% &ahas been handcuffed!'
handcuffed: '&cYou have been handcuffed.' handcuffed: '&cYou have been handcuffed.'
handcuffsreleased: '&9%0% &ahas been released from their handcuffs.' handcuffsreleased: '&9%0% &ahas been released from their handcuffs.'
unhandcuffed: '&aYour handcuffs have been removed.' unhandcuffed: '&aYour handcuffs have been removed.'

View File

@ -1,199 +1,199 @@
name: Jail name: Jail
main: com.graywolf336.jail.JailMain main: com.graywolf336.jail.JailMain
version: ${project.version}-b${BUILD_NUMBER} version: ${project.version}-b${BUILD_NUMBER}
description: Ban too harsh? Kick/mute/whatever not enough? Jail bad players! description: Ban too harsh? Kick/mute/whatever not enough? Jail bad players!
authors: [matejdro,multidude,graywolf336] authors: [matejdro,multidude,graywolf336]
website: dev.bukkit.org/server-mods/jail/ website: dev.bukkit.org/server-mods/jail/
softdepend: [WorldEdit, Vault] softdepend: [WorldEdit, Vault]
load: POSTWORLD load: POSTWORLD
commands: commands:
jailcreate: jailcreate:
description: Creates a new jail zone. description: Creates a new jail zone.
jailcreatecells: jailcreatecells:
description: Creates cells in existing jail zone. description: Creates cells in existing jail zone.
jailremove: jailremove:
description: Remove existing jail zone description: Remove existing jail zone
jail: jail:
description: Jail specified player for specified amount of time. description: Jail specified player for specified amount of time.
usage: /jail [p:name] (t:time) (j:Jail name) (c:Cell name) (m:Muted) (r:Reason) usage: /jail [p:name] (t:time) (j:Jail name) (c:Cell name) (m:Muted) (r:Reason)
unjail: unjail:
description: Release a player from jail. description: Release a player from jail.
unjailforce: unjailforce:
description: Remove player from the database. description: Remove player from the database.
jailclear: jailclear:
description: Unjail every player on the server. Use with caution! description: Unjail every player on the server. Use with caution!
jailclearforce: jailclearforce:
description: Remove every player from the jail database. description: Remove every player from the jail database.
jailtransfer: jailtransfer:
description: Transfer player from current jail to another description: Transfer player from current jail to another
jailtransferall: jailtransferall:
description: Transfer all players in one jail to another jail description: Transfer all players in one jail to another jail
jailcheck: jailcheck:
description: Check the status of the specified player description: Check the status of the specified player
jailtelein: jailtelein:
description: Teleport inside jail description: Teleport inside jail
jailteleout: jailteleout:
description: Teleport outside of the jail. description: Teleport outside of the jail.
jaillist: jaillist:
description: List all created jails description: List all created jails
jailstatus: jailstatus:
description: Check your current jail status description: Check your current jail status
jailmute: jailmute:
description: Toggle mute of the specified prisoner description: Toggle mute of the specified prisoner
jailstop: jailstop:
description: Stop any creation process. description: Stop any creation process.
jailset: jailset:
description: modify existing jail or prisoner. description: modify existing jail or prisoner.
usage: /jailset [player/jail/cell name] [property name] (property value) usage: /jailset [player/jail/cell name] [property name] (property value)
jailpay: jailpay:
description: Pay money to be released early. description: Pay money to be released early.
usage: /jailpay (amount) (prisoner name) usage: /jailpay (amount) (prisoner name)
jailremovecells: jailremovecells:
description: Remove all cells from specified jail. description: Remove all cells from specified jail.
jaillistcells: jaillistcells:
description: List all named cells from specified jail. description: List all named cells from specified jail.
jailstick: jailstick:
description: Toggle jailstick feature. description: Toggle jailstick feature.
jailcreatewe: jailcreatewe:
description: Create a new jail zone based on existing world guard region. description: Create a new jail zone based on existing world guard region.
jailremovecell: jailremovecell:
description: Remove one cell. description: Remove one cell.
jailreload: jailreload:
description: Reload jail data description: Reload jail data
jailrecord: jailrecord:
description: Shows a players record description: Shows a players record
jailversion: jailversion:
description: Shows the plugin version description: Shows the plugin version
votejail: votejail:
description: Allows players to vote to jail a player description: Allows players to vote to jail a player
handcuff: handcuff:
description: Allows the player to handcuff another player description: Allows the player to handcuff another player
unhandcuff: unhandcuff:
description: Allows the player to unhandcuff someone description: Allows the player to unhandcuff someone
togglejaildebug: togglejaildebug:
description: Toggles whether the plugin is in debugging state or not. description: Toggles whether the plugin is in debugging state or not.
permissions: permissions:
jail.*: jail.*:
children: children:
jail.command.*: true jail.command.*: true
jail.usercmd.*: true jail.usercmd.*: true
jail.modifyjail: true jail.modifyjail: true
jail.usejailstick280: true jail.usejailstick280: true
jail.canbestickjailed: true jail.canbestickjailed: true
jail.openchest: true jail.openchest: true
jail.canswear: true jail.canswear: true
jail.cantbejailed: true jail.cantbejailed: true
jail.command.*: jail.command.*:
description: access to all admin commands description: access to all admin commands
children: children:
jail.command.jailcreate: true jail.command.jailcreate: true
jail.command.jailcreatecells: true jail.command.jailcreatecells: true
jail.command.jailremove: true jail.command.jailremove: true
jail.command.jailremovecells: true jail.command.jailremovecells: true
jail.command.jail: true jail.command.jail: true
jail.command.unjail: true jail.command.unjail: true
jail.command.jailtransfer: true jail.command.jailtransfer: true
jail.command.jailtransferall: true jail.command.jailtransferall: true
jail.command.jailcheck: true jail.command.jailcheck: true
jail.command.jailtelein: true jail.command.jailtelein: true
jail.command.jailteleout: true jail.command.jailteleout: true
jail.command.jaillist: true jail.command.jaillist: true
jail.command.jaillistcells: true jail.command.jaillistcells: true
jail.command.unjailforce: true jail.command.unjailforce: true
jail.command.jailclear: true jail.command.jailclear: true
jail.command.jailclearforce: true jail.command.jailclearforce: true
jail.command.jailmute: true jail.command.jailmute: true
jail.command.jailstop: true jail.command.jailstop: true
jail.command.jailset: true jail.command.jailset: true
jail.command.jailcreatewe: true jail.command.jailcreatewe: true
jail.command.jailremovecell: true jail.command.jailremovecell: true
jail.command.jailreload: true jail.command.jailreload: true
jail.command.jailrecord: true jail.command.jailrecord: true
jail.command.handcuff: true jail.command.handcuff: true
jail.command.toggledebug: true jail.command.toggledebug: true
jail.usercmd.*: jail.usercmd.*:
description: access to all user commands description: access to all user commands
children: children:
jail.usercmd.jailstatus: true jail.usercmd.jailstatus: true
jail.usercmd.jailpay: true jail.usercmd.jailpay: true
jail.usercmd.jailstick: true jail.usercmd.jailstick: true
jail.usercmd.votejail: true jail.usercmd.votejail: true
jail.usercmd.votejail.player: true jail.usercmd.votejail.player: true
jail.usercmd.jailversion: true jail.usercmd.jailversion: true
jail.command.jail: jail.command.jail:
default: op default: op
jail.command.jailcreate: jail.command.jailcreate:
default: op default: op
jail.command.jailcreatecells: jail.command.jailcreatecells:
default: op default: op
jail.command.jailremove: jail.command.jailremove:
default: op default: op
jail.command.jailremovecells: jail.command.jailremovecells:
default: op default: op
jail.command.unjail: jail.command.unjail:
default: op default: op
jail.command.jailtransfer: jail.command.jailtransfer:
default: op default: op
jail.command.jailtransferall: jail.command.jailtransferall:
default: op default: op
jail.command.jailcheck: jail.command.jailcheck:
default: op default: op
jail.command.jailtelein: jail.command.jailtelein:
default: op default: op
jail.command.jailteleout: jail.command.jailteleout:
default: op default: op
jail.command.jaillist: jail.command.jaillist:
default: op default: op
jail.command.jaillistcells: jail.command.jaillistcells:
default: op default: op
jail.command.unjailforce: jail.command.unjailforce:
default: op default: op
jail.command.jailclear: jail.command.jailclear:
default: op default: op
jail.command.jailclearforce: jail.command.jailclearforce:
default: op default: op
jail.command.jailmute: jail.command.jailmute:
default: op default: op
jail.command.jailstop: jail.command.jailstop:
default: op default: op
jail.command.jailset: jail.command.jailset:
default: op default: op
jail.command.jailcreatewe: jail.command.jailcreatewe:
default: op default: op
jail.command.jailremovecell: jail.command.jailremovecell:
default: op default: op
jail.command.jailreload: jail.command.jailreload:
default: op default: op
jail.command.jailrecord: jail.command.jailrecord:
default: op default: op
jail.usercmd.jailversion: jail.usercmd.jailversion:
default: true default: true
jail.command.handcuff: jail.command.handcuff:
default: op default: op
jail.usercmd.jailvote: jail.usercmd.jailvote:
default: true default: true
jail.usercmd.jailvote.player: jail.usercmd.jailvote.player:
default: op default: op
jail.usercmd.jailvote.immune: jail.usercmd.jailvote.immune:
default: op default: op
jail.usercmd.jailstatus: jail.usercmd.jailstatus:
default: true default: true
jail.usercmd.jailpay: jail.usercmd.jailpay:
default: true default: true
jail.usercmd.jailstick: jail.usercmd.jailstick:
default: true default: true
jail.modifyjail: jail.modifyjail:
default: op default: op
jail.usejailstick280: jail.usejailstick280:
default: op default: op
description: change 280 for another jailstick item description: change 280 for another jailstick item
jail.canbestickjailed: jail.canbestickjailed:
default: true default: true
jail.openchest: jail.openchest:
default: op default: op
jail.canswear: jail.canswear:
default: op default: op
jail.cantbejailed: jail.cantbejailed:
default: op default: op
jail.command.toggledebug: jail.command.toggledebug:
default: op default: op

View File

@ -1,83 +1,83 @@
package test.java.com.graywolf336.jail; package test.java.com.graywolf336.jail;
import static org.junit.Assert.*; import static org.junit.Assert.*;
import static org.hamcrest.CoreMatchers.is; import static org.hamcrest.CoreMatchers.is;
import org.bukkit.plugin.PluginDescriptionFile; import org.bukkit.plugin.PluginDescriptionFile;
import org.junit.AfterClass; import org.junit.AfterClass;
import org.junit.BeforeClass; import org.junit.BeforeClass;
import org.junit.Test; import org.junit.Test;
import org.junit.runner.RunWith; import org.junit.runner.RunWith;
import org.powermock.core.classloader.annotations.PrepareForTest; import org.powermock.core.classloader.annotations.PrepareForTest;
import org.powermock.modules.junit4.PowerMockRunner; import org.powermock.modules.junit4.PowerMockRunner;
import test.java.com.graywolf336.jail.util.TestInstanceCreator; import test.java.com.graywolf336.jail.util.TestInstanceCreator;
import com.graywolf336.jail.JailMain; import com.graywolf336.jail.JailMain;
@RunWith(PowerMockRunner.class) @RunWith(PowerMockRunner.class)
@PrepareForTest({ JailMain.class, PluginDescriptionFile.class }) @PrepareForTest({ JailMain.class, PluginDescriptionFile.class })
public class TestJailStuff { public class TestJailStuff {
private static TestInstanceCreator creator; private static TestInstanceCreator creator;
private static JailMain main; private static JailMain main;
@BeforeClass @BeforeClass
public static void setUp() throws Exception { public static void setUp() throws Exception {
creator = new TestInstanceCreator(); creator = new TestInstanceCreator();
assertNotNull("The instance creator is null.", creator); assertNotNull("The instance creator is null.", creator);
assertTrue(creator.setup()); assertTrue(creator.setup());
main = creator.getMain(); main = creator.getMain();
assertNotNull("The JailMain class is null.", main); assertNotNull("The JailMain class is null.", main);
} }
@AfterClass @AfterClass
public static void tearDown() throws Exception { public static void tearDown() throws Exception {
creator.tearDown(); creator.tearDown();
main = null; main = null;
} }
@Test @Test
public void testForJails() { public void testForJails() {
assertNotNull("The HandCuffManager is null.", main.getHandCuffManager()); assertNotNull("The HandCuffManager is null.", main.getHandCuffManager());
assertNotNull("The JailIO is null.", main.getJailIO()); assertNotNull("The JailIO is null.", main.getJailIO());
assertNotNull("The JailManager is null.", main.getJailManager()); assertNotNull("The JailManager is null.", main.getJailManager());
assertNotNull("The HashSet for jails return is null.", main.getJailManager().getJails()); assertNotNull("The HashSet for jails return is null.", main.getJailManager().getJails());
assertThat(main, is(main.getJailManager().getPlugin())); assertThat(main, is(main.getJailManager().getPlugin()));
} }
@Test @Test
public void testDefaultConfig() { public void testDefaultConfig() {
assertEquals("The config version is not 3.", 3, main.getConfig().getInt("system.configVersion")); assertEquals("The config version is not 3.", 3, main.getConfig().getInt("system.configVersion"));
//This is enabled by default in testing. //This is enabled by default in testing.
//assertFalse("Default debugging is on.", main.getConfig().getBoolean("system.debug")); //assertFalse("Default debugging is on.", main.getConfig().getBoolean("system.debug"));
assertTrue("Default updating notifications is false.", main.getConfig().getBoolean("system.updateNotifications")); assertTrue("Default updating notifications is false.", main.getConfig().getBoolean("system.updateNotifications"));
//Storage system //Storage system
assertEquals("The default storage system is not flatfile.", "flatfile", main.getConfig().getString("storage.type")); assertEquals("The default storage system is not flatfile.", "flatfile", main.getConfig().getString("storage.type"));
assertEquals("The default mysql host is not localhost.", "localhost", main.getConfig().getString("storage.mysql.host")); assertEquals("The default mysql host is not localhost.", "localhost", main.getConfig().getString("storage.mysql.host"));
assertEquals("The default mysql port is not 3306.", 3306, main.getConfig().getInt("storage.mysql.port")); assertEquals("The default mysql port is not 3306.", 3306, main.getConfig().getInt("storage.mysql.port"));
assertEquals("The default mysql username is not root.", "root", main.getConfig().getString("storage.mysql.username")); assertEquals("The default mysql username is not root.", "root", main.getConfig().getString("storage.mysql.username"));
assertEquals("The default mysql password is not password.", "password", main.getConfig().getString("storage.mysql.password")); assertEquals("The default mysql password is not password.", "password", main.getConfig().getString("storage.mysql.password"));
//Settings pertaining to being jailed //Settings pertaining to being jailed
assertFalse("Default setting for counting down time while prisoner is offline is true.", main.getConfig().getBoolean("jailing.during.countDownTimeWhileOffline")); assertFalse("Default setting for counting down time while prisoner is offline is true.", main.getConfig().getBoolean("jailing.during.countDownTimeWhileOffline"));
assertTrue("Default setting for ignoring sleeping is false.", main.getConfig().getBoolean("jailing.during.ignoreSleeping")); assertTrue("Default setting for ignoring sleeping is false.", main.getConfig().getBoolean("jailing.during.ignoreSleeping"));
assertTrue("Default setting for opening a chest is false.", main.getConfig().getBoolean("jailing.during.openChest")); assertTrue("Default setting for opening a chest is false.", main.getConfig().getBoolean("jailing.during.openChest"));
//Settings pertaining to when jailed //Settings pertaining to when jailed
assertTrue("Default setting for automatically muting is false.", main.getConfig().getBoolean("jailing.jail.automaticMute")); assertTrue("Default setting for automatically muting is false.", main.getConfig().getBoolean("jailing.jail.automaticMute"));
assertFalse("Default setting for broadcasting a jailing is true.", main.getConfig().getBoolean("jailing.jail.broadcastJailing")); assertFalse("Default setting for broadcasting a jailing is true.", main.getConfig().getBoolean("jailing.jail.broadcastJailing"));
assertEquals("Default setting for commands contains information.", 0, main.getConfig().getList("jailing.jail.commands").size()); assertEquals("Default setting for commands contains information.", 0, main.getConfig().getList("jailing.jail.commands").size());
assertEquals("Default setting for default jail is not 'nearest' but something else.", "nearest", main.getConfig().getString("jailing.jail.defaultJail")); assertEquals("Default setting for default jail is not 'nearest' but something else.", "nearest", main.getConfig().getString("jailing.jail.defaultJail"));
assertEquals("Default setting for time is not 30 minutes.", "30m", main.getConfig().getString("jailing.jail.defaultTime")); assertEquals("Default setting for time is not 30 minutes.", "30m", main.getConfig().getString("jailing.jail.defaultTime"));
assertFalse("Default setting for deleting inventory is true.", main.getConfig().getBoolean("jailing.jail.deleteInventory")); assertFalse("Default setting for deleting inventory is true.", main.getConfig().getBoolean("jailing.jail.deleteInventory"));
assertTrue("Default setting for logging to console when someone is jailed is false.", main.getConfig().getBoolean("jailing.jail.logToConsole")); assertTrue("Default setting for logging to console when someone is jailed is false.", main.getConfig().getBoolean("jailing.jail.logToConsole"));
assertFalse("Default setting for logging to prisoner's profile is true.", main.getConfig().getBoolean("jailing.jail.logToProfile")); assertFalse("Default setting for logging to prisoner's profile is true.", main.getConfig().getBoolean("jailing.jail.logToProfile"));
assertTrue("Default setting for storing prisoner's inventory upon jailing is false.", main.getConfig().getBoolean("jailing.jail.storeInventory")); assertTrue("Default setting for storing prisoner's inventory upon jailing is false.", main.getConfig().getBoolean("jailing.jail.storeInventory"));
//Settings pertaining to after a prisoner is released //Settings pertaining to after a prisoner is released
assertFalse("Default setting for releasing back to previous position is true.", main.getConfig().getBoolean("jailing.release.backToPreviousPosition")); assertFalse("Default setting for releasing back to previous position is true.", main.getConfig().getBoolean("jailing.release.backToPreviousPosition"));
assertEquals("Default setting for commands contains information.", 0, main.getConfig().getList("jailing.release.commands").size()); assertEquals("Default setting for commands contains information.", 0, main.getConfig().getList("jailing.release.commands").size());
assertTrue("Default setting for teleporting them out of the jail is false.", main.getConfig().getBoolean("jailing.release.teleport")); assertTrue("Default setting for teleporting them out of the jail is false.", main.getConfig().getBoolean("jailing.release.teleport"));
} }
} }

View File

@ -1,50 +1,50 @@
package test.java.com.graywolf336.jail; package test.java.com.graywolf336.jail;
import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNull; import static org.junit.Assert.assertNull;
import org.junit.Test; import org.junit.Test;
import com.graywolf336.jail.command.commands.jewels.Jailing; import com.graywolf336.jail.command.commands.jewels.Jailing;
import com.graywolf336.jail.command.commands.jewels.Transfer; import com.graywolf336.jail.command.commands.jewels.Transfer;
import com.lexicalscope.jewel.cli.CliFactory; import com.lexicalscope.jewel.cli.CliFactory;
public class TestJewelCommands { public class TestJewelCommands {
@Test @Test
public void testJailJewel() { public void testJailJewel() {
String[] args = { "--player", "graywolf336", "-c", "testing", "-r", "This", "is", "a", "reason" }; String[] args = { "--player", "graywolf336", "-c", "testing", "-r", "This", "is", "a", "reason" };
Jailing j = CliFactory.parseArguments(Jailing.class, args); Jailing j = CliFactory.parseArguments(Jailing.class, args);
assertEquals("graywolf336", j.getPlayer()); assertEquals("graywolf336", j.getPlayer());
assertEquals("testing", j.getCell()); assertEquals("testing", j.getCell());
StringBuilder sb = new StringBuilder(); StringBuilder sb = new StringBuilder();
for(String s : j.getReason()) { for(String s : j.getReason()) {
sb.append(s).append(' '); sb.append(s).append(' ');
} }
sb.deleteCharAt(sb.length() - 1); sb.deleteCharAt(sb.length() - 1);
assertEquals("This is a reason", sb.toString()); assertEquals("This is a reason", sb.toString());
} }
@Test @Test
public void testTransferForJailAndCell() { public void testTransferForJailAndCell() {
String[] args = { "-p", "graywolf336", "-j", "hardcore", "-c", "cell_n01" }; String[] args = { "-p", "graywolf336", "-j", "hardcore", "-c", "cell_n01" };
Transfer t = CliFactory.parseArguments(Transfer.class, args); Transfer t = CliFactory.parseArguments(Transfer.class, args);
assertEquals("The player parsed is not what we expected.", "graywolf336", t.getPlayer()); assertEquals("The player parsed is not what we expected.", "graywolf336", t.getPlayer());
assertEquals("The jail parsed is not what we expected.", "hardcore", t.getJail()); assertEquals("The jail parsed is not what we expected.", "hardcore", t.getJail());
assertEquals("The cell parsed is not what we expected.", "cell_n01", t.getCell()); assertEquals("The cell parsed is not what we expected.", "cell_n01", t.getCell());
} }
@Test @Test
public void testTransferForNoCell() { public void testTransferForNoCell() {
String[] args = { "-p", "graywolf336", "-j", "hardcore" }; String[] args = { "-p", "graywolf336", "-j", "hardcore" };
Transfer t = CliFactory.parseArguments(Transfer.class, args); Transfer t = CliFactory.parseArguments(Transfer.class, args);
assertEquals("The player parsed is not what we expected.", "graywolf336", t.getPlayer()); assertEquals("The player parsed is not what we expected.", "graywolf336", t.getPlayer());
assertEquals("The jail parsed is not what we expected.", "hardcore", t.getJail()); assertEquals("The jail parsed is not what we expected.", "hardcore", t.getJail());
assertNull("The cell is not null?", t.getCell()); assertNull("The cell is not null?", t.getCell());
} }
} }

View File

@ -1,43 +1,43 @@
package test.java.com.graywolf336.jail; package test.java.com.graywolf336.jail;
import static org.junit.Assert.*; import static org.junit.Assert.*;
import static org.hamcrest.CoreMatchers.is; import static org.hamcrest.CoreMatchers.is;
import org.junit.Test; import org.junit.Test;
import com.graywolf336.jail.Util; import com.graywolf336.jail.Util;
public class TestTimeParsing { public class TestTimeParsing {
@Test @Test
public void testNoFormat() throws Exception { public void testNoFormat() throws Exception {
assertThat(60000L, is(Util.getTime("1"))); assertThat(60000L, is(Util.getTime("1")));
assertThat(360000L, is(Util.getTime("6"))); assertThat(360000L, is(Util.getTime("6")));
} }
@Test @Test
public void testSeconds() throws Exception { public void testSeconds() throws Exception {
assertThat(2000L, is(Util.getTime("2s"))); assertThat(2000L, is(Util.getTime("2s")));
assertThat(2000L, is(Util.getTime("2second"))); assertThat(2000L, is(Util.getTime("2second")));
assertThat(2000L, is(Util.getTime("2seconds"))); assertThat(2000L, is(Util.getTime("2seconds")));
} }
@Test @Test
public void testMinutes() throws Exception { public void testMinutes() throws Exception {
assertThat(60000L, is(Util.getTime("1m"))); assertThat(60000L, is(Util.getTime("1m")));
assertThat(60000L, is(Util.getTime("1minute"))); assertThat(60000L, is(Util.getTime("1minute")));
assertThat(60000L, is(Util.getTime("1minutes"))); assertThat(60000L, is(Util.getTime("1minutes")));
} }
@Test @Test
public void testHours() throws Exception { public void testHours() throws Exception {
assertThat(3600000L, is(Util.getTime("1h"))); assertThat(3600000L, is(Util.getTime("1h")));
assertThat(3600000L, is(Util.getTime("1hours"))); assertThat(3600000L, is(Util.getTime("1hours")));
} }
@Test @Test
public void testDays() throws Exception { public void testDays() throws Exception {
assertThat(86400000L, is(Util.getTime("1d"))); assertThat(86400000L, is(Util.getTime("1d")));
assertThat(86400000L, is(Util.getTime("1days"))); assertThat(86400000L, is(Util.getTime("1days")));
} }
} }

View File

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

View File

@ -1,215 +1,215 @@
package test.java.com.graywolf336.jail.util; package test.java.com.graywolf336.jail.util;
import java.io.File; import java.io.File;
import java.util.ArrayList; import java.util.ArrayList;
import java.util.HashMap; import java.util.HashMap;
import java.util.List; import java.util.List;
import java.util.Map; import java.util.Map;
import java.util.UUID; import java.util.UUID;
import java.util.WeakHashMap; import java.util.WeakHashMap;
import org.bukkit.Difficulty; import org.bukkit.Difficulty;
import org.bukkit.Location; import org.bukkit.Location;
import org.bukkit.Material; import org.bukkit.Material;
import org.bukkit.World; import org.bukkit.World;
import org.bukkit.WorldType; import org.bukkit.WorldType;
import org.bukkit.block.Block; import org.bukkit.block.Block;
import org.bukkit.generator.ChunkGenerator; import org.bukkit.generator.ChunkGenerator;
import org.mockito.invocation.InvocationOnMock; import org.mockito.invocation.InvocationOnMock;
import org.mockito.stubbing.Answer; import org.mockito.stubbing.Answer;
import static org.mockito.Mockito.*; import static org.mockito.Mockito.*;
public class MockWorldFactory { public class MockWorldFactory {
private static final Map<String, World> createdWorlds = new HashMap<String, World>(); private static final Map<String, World> createdWorlds = new HashMap<String, World>();
private static final Map<UUID, World> worldUIDS = new HashMap<UUID, World>(); private static final Map<UUID, World> worldUIDS = new HashMap<UUID, World>();
private static final Map<World, Boolean> pvpStates = new WeakHashMap<World, Boolean>(); private static final Map<World, Boolean> pvpStates = new WeakHashMap<World, Boolean>();
private static final Map<World, Boolean> keepSpawnInMemoryStates = new WeakHashMap<World, Boolean>(); private static final Map<World, Boolean> keepSpawnInMemoryStates = new WeakHashMap<World, Boolean>();
private static final Map<World, Difficulty> difficultyStates = new WeakHashMap<World, Difficulty>(); private static final Map<World, Difficulty> difficultyStates = new WeakHashMap<World, Difficulty>();
private MockWorldFactory() { private MockWorldFactory() {
} }
private static void registerWorld(World world) { private static void registerWorld(World world) {
createdWorlds.put(world.getName(), world); createdWorlds.put(world.getName(), world);
worldUIDS.put(world.getUID(), world); worldUIDS.put(world.getUID(), world);
new File(TestInstanceCreator.worldsDirectory, world.getName()).mkdir(); new File(TestInstanceCreator.worldsDirectory, world.getName()).mkdir();
} }
private static World basics(String world, World.Environment env, WorldType type) { private static World basics(String world, World.Environment env, WorldType type) {
World mockWorld = mock(World.class); World mockWorld = mock(World.class);
when(mockWorld.getName()).thenReturn(world); when(mockWorld.getName()).thenReturn(world);
when(mockWorld.getPVP()).thenAnswer(new Answer<Boolean>() { when(mockWorld.getPVP()).thenAnswer(new Answer<Boolean>() {
public Boolean answer(InvocationOnMock invocation) throws Throwable { public Boolean answer(InvocationOnMock invocation) throws Throwable {
World w = (World) invocation.getMock(); World w = (World) invocation.getMock();
if (!pvpStates.containsKey(w)) if (!pvpStates.containsKey(w))
pvpStates.put(w, true); // default value pvpStates.put(w, true); // default value
return pvpStates.get(w); return pvpStates.get(w);
} }
}); });
doAnswer(new Answer<Void>() { doAnswer(new Answer<Void>() {
public Void answer(InvocationOnMock invocation) throws Throwable { public Void answer(InvocationOnMock invocation) throws Throwable {
pvpStates.put((World) invocation.getMock(), (Boolean) invocation.getArguments()[0]); pvpStates.put((World) invocation.getMock(), (Boolean) invocation.getArguments()[0]);
return null; return null;
} }
}).when(mockWorld).setPVP(anyBoolean()); }).when(mockWorld).setPVP(anyBoolean());
when(mockWorld.getKeepSpawnInMemory()).thenAnswer(new Answer<Boolean>() { when(mockWorld.getKeepSpawnInMemory()).thenAnswer(new Answer<Boolean>() {
public Boolean answer(InvocationOnMock invocation) throws Throwable { public Boolean answer(InvocationOnMock invocation) throws Throwable {
World w = (World) invocation.getMock(); World w = (World) invocation.getMock();
if (!keepSpawnInMemoryStates.containsKey(w)) if (!keepSpawnInMemoryStates.containsKey(w))
keepSpawnInMemoryStates.put(w, true); // default value keepSpawnInMemoryStates.put(w, true); // default value
return keepSpawnInMemoryStates.get(w); return keepSpawnInMemoryStates.get(w);
} }
}); });
doAnswer(new Answer<Void>() { doAnswer(new Answer<Void>() {
public Void answer(InvocationOnMock invocation) throws Throwable { public Void answer(InvocationOnMock invocation) throws Throwable {
keepSpawnInMemoryStates.put((World) invocation.getMock(), (Boolean) invocation.getArguments()[0]); keepSpawnInMemoryStates.put((World) invocation.getMock(), (Boolean) invocation.getArguments()[0]);
return null; return null;
} }
}).when(mockWorld).setKeepSpawnInMemory(anyBoolean()); }).when(mockWorld).setKeepSpawnInMemory(anyBoolean());
when(mockWorld.getDifficulty()).thenAnswer(new Answer<Difficulty>() { when(mockWorld.getDifficulty()).thenAnswer(new Answer<Difficulty>() {
public Difficulty answer(InvocationOnMock invocation) throws Throwable { public Difficulty answer(InvocationOnMock invocation) throws Throwable {
World w = (World) invocation.getMock(); World w = (World) invocation.getMock();
if (!difficultyStates.containsKey(w)) if (!difficultyStates.containsKey(w))
difficultyStates.put(w, Difficulty.NORMAL); // default value difficultyStates.put(w, Difficulty.NORMAL); // default value
return difficultyStates.get(w); return difficultyStates.get(w);
} }
}); });
doAnswer(new Answer<Void>() { doAnswer(new Answer<Void>() {
public Void answer(InvocationOnMock invocation) throws Throwable { public Void answer(InvocationOnMock invocation) throws Throwable {
difficultyStates.put((World) invocation.getMock(), (Difficulty) invocation.getArguments()[0]); difficultyStates.put((World) invocation.getMock(), (Difficulty) invocation.getArguments()[0]);
return null; return null;
} }
}).when(mockWorld).setDifficulty(any(Difficulty.class)); }).when(mockWorld).setDifficulty(any(Difficulty.class));
when(mockWorld.getEnvironment()).thenReturn(env); when(mockWorld.getEnvironment()).thenReturn(env);
when(mockWorld.getWorldType()).thenReturn(type); when(mockWorld.getWorldType()).thenReturn(type);
when(mockWorld.getSpawnLocation()).thenReturn(new Location(mockWorld, 0, 64, 0)); when(mockWorld.getSpawnLocation()).thenReturn(new Location(mockWorld, 0, 64, 0));
when(mockWorld.getWorldFolder()).thenAnswer(new Answer<File>() { when(mockWorld.getWorldFolder()).thenAnswer(new Answer<File>() {
public File answer(InvocationOnMock invocation) throws Throwable { public File answer(InvocationOnMock invocation) throws Throwable {
if (!(invocation.getMock() instanceof World)) if (!(invocation.getMock() instanceof World))
return null; return null;
World thiss = (World) invocation.getMock(); World thiss = (World) invocation.getMock();
return new File(TestInstanceCreator.serverDirectory, thiss.getName()); return new File(TestInstanceCreator.serverDirectory, thiss.getName());
} }
}); });
when(mockWorld.getBlockAt(any(Location.class))).thenAnswer(new Answer<Block>() { when(mockWorld.getBlockAt(any(Location.class))).thenAnswer(new Answer<Block>() {
@SuppressWarnings("deprecation") @SuppressWarnings("deprecation")
public Block answer(InvocationOnMock invocation) throws Throwable { public Block answer(InvocationOnMock invocation) throws Throwable {
Location loc; Location loc;
try { try {
loc = (Location) invocation.getArguments()[0]; loc = (Location) invocation.getArguments()[0];
} catch (Exception e) { } catch (Exception e) {
return null; return null;
} }
Material blockType = Material.AIR; Material blockType = Material.AIR;
Block mockBlock = mock(Block.class); Block mockBlock = mock(Block.class);
if (loc.getBlockY() < 64) { if (loc.getBlockY() < 64) {
blockType = Material.DIRT; blockType = Material.DIRT;
} }
when(mockBlock.getType()).thenReturn(blockType); when(mockBlock.getType()).thenReturn(blockType);
when(mockBlock.getTypeId()).thenReturn(blockType.getId()); when(mockBlock.getTypeId()).thenReturn(blockType.getId());
when(mockBlock.getWorld()).thenReturn(loc.getWorld()); when(mockBlock.getWorld()).thenReturn(loc.getWorld());
when(mockBlock.getX()).thenReturn(loc.getBlockX()); when(mockBlock.getX()).thenReturn(loc.getBlockX());
when(mockBlock.getY()).thenReturn(loc.getBlockY()); when(mockBlock.getY()).thenReturn(loc.getBlockY());
when(mockBlock.getZ()).thenReturn(loc.getBlockZ()); when(mockBlock.getZ()).thenReturn(loc.getBlockZ());
when(mockBlock.getLocation()).thenReturn(loc); when(mockBlock.getLocation()).thenReturn(loc);
when(mockBlock.isEmpty()).thenReturn(blockType == Material.AIR); when(mockBlock.isEmpty()).thenReturn(blockType == Material.AIR);
return mockBlock; return mockBlock;
} }
}); });
when(mockWorld.getUID()).thenReturn(UUID.randomUUID()); when(mockWorld.getUID()).thenReturn(UUID.randomUUID());
return mockWorld; return mockWorld;
} }
private static World nullWorld(String world, World.Environment env, WorldType type) { private static World nullWorld(String world, World.Environment env, WorldType type) {
World mockWorld = mock(World.class); World mockWorld = mock(World.class);
when(mockWorld.getName()).thenReturn(world); when(mockWorld.getName()).thenReturn(world);
when(mockWorld.getEnvironment()).thenReturn(env); when(mockWorld.getEnvironment()).thenReturn(env);
when(mockWorld.getWorldType()).thenReturn(type); when(mockWorld.getWorldType()).thenReturn(type);
when(mockWorld.getSpawnLocation()).thenReturn(new Location(mockWorld, 0, 64, 0)); when(mockWorld.getSpawnLocation()).thenReturn(new Location(mockWorld, 0, 64, 0));
when(mockWorld.getWorldFolder()).thenAnswer(new Answer<File>() { when(mockWorld.getWorldFolder()).thenAnswer(new Answer<File>() {
public File answer(InvocationOnMock invocation) throws Throwable { public File answer(InvocationOnMock invocation) throws Throwable {
if (!(invocation.getMock() instanceof World)) if (!(invocation.getMock() instanceof World))
return null; return null;
World thiss = (World) invocation.getMock(); World thiss = (World) invocation.getMock();
return new File(TestInstanceCreator.serverDirectory, thiss.getName()); return new File(TestInstanceCreator.serverDirectory, thiss.getName());
} }
}); });
when(mockWorld.getBlockAt(any(Location.class))).thenAnswer(new Answer<Block>() { when(mockWorld.getBlockAt(any(Location.class))).thenAnswer(new Answer<Block>() {
@SuppressWarnings("deprecation") @SuppressWarnings("deprecation")
public Block answer(InvocationOnMock invocation) throws Throwable { public Block answer(InvocationOnMock invocation) throws Throwable {
Location loc; Location loc;
try { try {
loc = (Location) invocation.getArguments()[0]; loc = (Location) invocation.getArguments()[0];
} catch (Exception e) { } catch (Exception e) {
return null; return null;
} }
Block mockBlock = mock(Block.class); Block mockBlock = mock(Block.class);
Material blockType = Material.AIR; Material blockType = Material.AIR;
when(mockBlock.getType()).thenReturn(blockType); when(mockBlock.getType()).thenReturn(blockType);
when(mockBlock.getTypeId()).thenReturn(blockType.getId()); when(mockBlock.getTypeId()).thenReturn(blockType.getId());
when(mockBlock.getWorld()).thenReturn(loc.getWorld()); when(mockBlock.getWorld()).thenReturn(loc.getWorld());
when(mockBlock.getX()).thenReturn(loc.getBlockX()); when(mockBlock.getX()).thenReturn(loc.getBlockX());
when(mockBlock.getY()).thenReturn(loc.getBlockY()); when(mockBlock.getY()).thenReturn(loc.getBlockY());
when(mockBlock.getZ()).thenReturn(loc.getBlockZ()); when(mockBlock.getZ()).thenReturn(loc.getBlockZ());
when(mockBlock.getLocation()).thenReturn(loc); when(mockBlock.getLocation()).thenReturn(loc);
when(mockBlock.isEmpty()).thenReturn(blockType == Material.AIR); when(mockBlock.isEmpty()).thenReturn(blockType == Material.AIR);
return mockBlock; return mockBlock;
} }
}); });
return mockWorld; return mockWorld;
} }
public static World makeNewMockWorld(String world, World.Environment env, WorldType type) { public static World makeNewMockWorld(String world, World.Environment env, WorldType type) {
World w = basics(world, env, type); World w = basics(world, env, type);
registerWorld(w); registerWorld(w);
return w; return w;
} }
public static World makeNewNullMockWorld(String world, World.Environment env, WorldType type) { public static World makeNewNullMockWorld(String world, World.Environment env, WorldType type) {
World w = nullWorld(world, env, type); World w = nullWorld(world, env, type);
registerWorld(w); registerWorld(w);
return w; return w;
} }
public static World makeNewMockWorld(String world, World.Environment env, WorldType type, long seed, public static World makeNewMockWorld(String world, World.Environment env, WorldType type, long seed,
ChunkGenerator generator) { ChunkGenerator generator) {
World mockWorld = basics(world, env, type); World mockWorld = basics(world, env, type);
when(mockWorld.getGenerator()).thenReturn(generator); when(mockWorld.getGenerator()).thenReturn(generator);
when(mockWorld.getSeed()).thenReturn(seed); when(mockWorld.getSeed()).thenReturn(seed);
registerWorld(mockWorld); registerWorld(mockWorld);
return mockWorld; return mockWorld;
} }
public static World getWorld(String name) { public static World getWorld(String name) {
return createdWorlds.get(name); return createdWorlds.get(name);
} }
public static World getWorld(UUID worldUID) { public static World getWorld(UUID worldUID) {
return worldUIDS.get(worldUID); return worldUIDS.get(worldUID);
} }
public static List<World> getWorlds() { public static List<World> getWorlds() {
// we have to invert the order! // we have to invert the order!
ArrayList<World> myList = new ArrayList<World>(createdWorlds.values()); ArrayList<World> myList = new ArrayList<World>(createdWorlds.values());
List<World> retList = new ArrayList<World>(); List<World> retList = new ArrayList<World>();
for (int i = (myList.size() - 1); i >= 0; i--) { for (int i = (myList.size() - 1); i >= 0; i--) {
retList.add(myList.get(i)); retList.add(myList.get(i));
} }
return retList; return retList;
} }
public static void clearWorlds() { public static void clearWorlds() {
for (String name : createdWorlds.keySet()) for (String name : createdWorlds.keySet())
new File(TestInstanceCreator.worldsDirectory, name).delete(); new File(TestInstanceCreator.worldsDirectory, name).delete();
createdWorlds.clear(); createdWorlds.clear();
worldUIDS.clear(); worldUIDS.clear();
} }
} }

View File

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

View File

@ -1,52 +1,52 @@
package test.java.com.graywolf336.jail.util; package test.java.com.graywolf336.jail.util;
import java.util.logging.ConsoleHandler; import java.util.logging.ConsoleHandler;
import java.util.logging.Handler; import java.util.logging.Handler;
import java.util.logging.Level; import java.util.logging.Level;
import java.util.logging.LogRecord; import java.util.logging.LogRecord;
import java.util.logging.Logger; import java.util.logging.Logger;
public class Util { public class Util {
private Util() {} private Util() {}
public static final Logger logger = Logger.getLogger("Jail-Test"); public static final Logger logger = Logger.getLogger("Jail-Test");
static { static {
logger.setUseParentHandlers(false); logger.setUseParentHandlers(false);
Handler handler = new ConsoleHandler(); Handler handler = new ConsoleHandler();
handler.setFormatter(new TestLogFormatter()); handler.setFormatter(new TestLogFormatter());
Handler[] handlers = logger.getHandlers(); Handler[] handlers = logger.getHandlers();
for (Handler h : handlers) for (Handler h : handlers)
logger.removeHandler(h); logger.removeHandler(h);
logger.addHandler(handler); logger.addHandler(handler);
} }
public static void log(Throwable t) { public static void log(Throwable t) {
log(Level.WARNING, t.getLocalizedMessage(), t); log(Level.WARNING, t.getLocalizedMessage(), t);
} }
public static void log(Level level, Throwable t) { public static void log(Level level, Throwable t) {
log(level, t.getLocalizedMessage(), t); log(level, t.getLocalizedMessage(), t);
} }
public static void log(String message, Throwable t) { public static void log(String message, Throwable t) {
log(Level.WARNING, message, t); log(Level.WARNING, message, t);
} }
public static void log(Level level, String message, Throwable t) { public static void log(Level level, String message, Throwable t) {
LogRecord record = new LogRecord(level, message); LogRecord record = new LogRecord(level, message);
record.setThrown(t); record.setThrown(t);
logger.log(record); logger.log(record);
} }
public static void log(String message) { public static void log(String message) {
log(Level.INFO, message); log(Level.INFO, message);
} }
public static void log(Level level, String message) { public static void log(Level level, String message) {
logger.log(level, message); logger.log(level, message);
} }
} }