From d535b758d40a056adc231115a58c4b16258e80cb Mon Sep 17 00:00:00 2001 From: graywolf336 Date: Thu, 12 Jun 2014 10:44:13 -0500 Subject: [PATCH] Add .gitattributes --- .gitattributes | 38 + .gitignore | 86 +- README.md | 130 +- pom.xml | 436 +-- .../com/graywolf336/jail/HandCuffManager.java | 166 +- .../java/com/graywolf336/jail/JailIO.java | 2362 ++++++++--------- .../java/com/graywolf336/jail/JailMain.java | 542 ++-- .../com/graywolf336/jail/JailPayManager.java | 344 +-- .../graywolf336/jail/JailStickManager.java | 346 +-- .../java/com/graywolf336/jail/JailTimer.java | 224 +- .../com/graywolf336/jail/PrisonerManager.java | 1112 ++++---- .../graywolf336/jail/ScoreBoardManager.java | 208 +- src/main/java/com/graywolf336/jail/Util.java | 668 ++--- .../graywolf336/jail/beans/CachePrisoner.java | 56 +- .../graywolf336/jail/beans/ConfirmPlayer.java | 88 +- .../java/com/graywolf336/jail/beans/Jail.java | 764 +++--- .../com/graywolf336/jail/beans/Prisoner.java | 508 ++-- .../jail/beans/SimpleLocation.java | 206 +- .../com/graywolf336/jail/beans/Stick.java | 74 +- .../jail/command/CommandHandler.java | 346 +-- .../graywolf336/jail/command/JailHandler.java | 424 +-- .../command/commands/HandCuffCommand.java | 82 +- .../commands/ToggleJailDebugCommand.java | 48 +- .../command/commands/UnHandCuffCommand.java | 70 +- .../jail/command/commands/UnJailCommand.java | 128 +- .../command/commands/UnJailForceCommand.java | 76 +- .../jail/command/commands/jewels/Jailing.java | 64 +- .../command/commands/jewels/Transfer.java | 38 +- .../subcommands/JailCellCreateCommand.java | 132 +- .../jail/command/subcommands/JailCommand.java | 434 +-- .../subcommands/JailDeleteCellCommand.java | 62 +- .../subcommands/JailDeleteCellsCommand.java | 62 +- .../subcommands/JailDeleteCommand.java | 62 +- .../subcommands/JailListCellsCommand.java | 108 +- .../command/subcommands/JailListCommand.java | 126 +- .../command/subcommands/JailMuteCommand.java | 76 +- .../command/subcommands/JailPayCommand.java | 456 ++-- .../subcommands/JailRecordCommand.java | 90 +- .../subcommands/JailReloadCommand.java | 72 +- .../command/subcommands/JailStickCommand.java | 70 +- .../subcommands/JailTeleInCommand.java | 108 +- .../subcommands/JailTeleOutCommand.java | 108 +- .../command/subcommands/JailTimeCommand.java | 110 +- .../subcommands/JailTransferAllCommand.java | 112 +- .../subcommands/JailTransferCommand.java | 278 +- .../graywolf336/jail/enums/Confirmation.java | 28 +- .../graywolf336/jail/enums/LangString.java | 442 +-- .../com/graywolf336/jail/enums/Settings.java | 140 +- .../PrePrisonerJailedByJailStickEvent.java | 250 +- .../jail/events/PrePrisonerJailedEvent.java | 248 +- .../jail/events/PrePrisonerReleasedEvent.java | 146 +- .../events/PrePrisonerTransferredEvent.java | 304 +-- .../jail/events/PrisonerJailedEvent.java | 156 +- .../jail/events/PrisonerReleasedEvent.java | 146 +- .../jail/events/PrisonerTransferredEvent.java | 188 +- .../jail/legacy/LegacyManager.java | 888 +++---- .../jail/legacy/OldInputOutput.java | 478 ++-- .../graywolf336/jail/legacy/OldSettings.java | 66 +- .../jail/listeners/CacheListener.java | 146 +- .../jail/listeners/HandCuffListener.java | 224 +- .../jail/listeners/JailingListener.java | 78 +- .../jail/listeners/PlayerListener.java | 500 ++-- .../jail/listeners/ProtectionListener.java | 638 ++--- .../jail/steps/CellCreationSteps.java | 314 +-- .../jail/steps/JailCreationSteps.java | 292 +- src/main/resources/config.yml | 144 +- src/main/resources/en.yml | 192 +- src/main/resources/plugin.yml | 396 +-- .../com/graywolf336/jail/TestJailStuff.java | 166 +- .../graywolf336/jail/TestJewelCommands.java | 98 +- .../com/graywolf336/jail/TestTimeParsing.java | 86 +- .../jail/util/MockPlayerInventory.java | 600 ++--- .../jail/util/MockWorldFactory.java | 430 +-- .../jail/util/TestInstanceCreator.java | 670 ++--- .../java/com/graywolf336/jail/util/Util.java | 102 +- 75 files changed, 10347 insertions(+), 10309 deletions(-) create mode 100644 .gitattributes diff --git a/.gitattributes b/.gitattributes new file mode 100644 index 0000000..1afa3b5 --- /dev/null +++ b/.gitattributes @@ -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 diff --git a/.gitignore b/.gitignore index 1e7407a..5a73b9a 100644 --- a/.gitignore +++ b/.gitignore @@ -1,46 +1,46 @@ -# Compiled source # -################### -*.com -*.class -*.dll -*.exe -*.o -*.so - -# Packages # -############ -# it's better to unpack these files and commit the raw source -# git has its own built in compression methods -*.7z -*.dmg -*.gz -*.iso -*.jar -*.rar -*.tar -*.zip - -# Logs and databases # -###################### -*.log -*.sql -*.sqlite - -# OS generated files # -###################### -.DS_Store* -ehthumbs.db -Icon? -Thumbs.db - -# folders # -########### -bin/ -target/ -.settings/ -.classpath -.project -config.yml +# Compiled source # +################### +*.com +*.class +*.dll +*.exe +*.o +*.so + +# Packages # +############ +# it's better to unpack these files and commit the raw source +# git has its own built in compression methods +*.7z +*.dmg +*.gz +*.iso +*.jar +*.rar +*.tar +*.zip + +# Logs and databases # +###################### +*.log +*.sql +*.sqlite + +# OS generated files # +###################### +.DS_Store* +ehthumbs.db +Icon? +Thumbs.db + +# folders # +########### +bin/ +target/ +.settings/ +.classpath +.project +config.yml src/com/matejdro/ /dependency-reduced-pom.xml /global.yml diff --git a/README.md b/README.md index 42c0b33..e131ef2 100644 --- a/README.md +++ b/README.md @@ -1,66 +1,66 @@ -[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. - -**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/) - -Beta 2 Changes -=== -*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 -* 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) -* 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) -* 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 -* 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 -* - -Beta 1 Changes -=== -*Changes since alpha* -* 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 -* 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)) -* Added Jail Sticks, format of them has slightly changed ([#16](https://github.com/graywolf336/Jail/issues/16)) - -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 -* New language system -* New config system (per jail configs are going to make a come back) -* Items in the config use item names now, **not** the ids -* 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 -* If store inventory is not enabled, inventories are deleted upon jailing -* 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 - -ToDo -=== -* Jail pay -* Jail set -* Jail vote -* Jailing for swearing -* Guards (PlayerMoveProtectionAction - when they try to move do we teleport them back, let the guards get them, or nothing) -* Storing permissions -* Update Notifications -* Pages on jail list - -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) -* 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 -* 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 Previous Position is not converted. - -[Jail 3.0 JavaDoc](http://ci.graywolf336.com/job/Jail/javadoc) +[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. + +**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/) + +Beta 2 Changes +=== +*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 +* 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) +* 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) +* 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 +* 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 +* + +Beta 1 Changes +=== +*Changes since alpha* +* 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 +* 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)) +* Added Jail Sticks, format of them has slightly changed ([#16](https://github.com/graywolf336/Jail/issues/16)) + +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 +* New language system +* New config system (per jail configs are going to make a come back) +* Items in the config use item names now, **not** the ids +* 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 +* If store inventory is not enabled, inventories are deleted upon jailing +* 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 + +ToDo +=== +* Jail pay +* Jail set +* Jail vote +* Jailing for swearing +* Guards (PlayerMoveProtectionAction - when they try to move do we teleport them back, let the guards get them, or nothing) +* Storing permissions +* Update Notifications +* Pages on jail list + +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) +* 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 +* 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 Previous Position is not converted. + +[Jail 3.0 JavaDoc](http://ci.graywolf336.com/job/Jail/javadoc) ==== diff --git a/pom.xml b/pom.xml index 8827a80..c798fa2 100644 --- a/pom.xml +++ b/pom.xml @@ -1,219 +1,219 @@ - - - 4.0.0 - com.graywolf336 - Jail - 3.0.0-SNAPSHOT - Jail - Ban too harsh? Mute too weak? Kicking not enough? Jail them! - http://dev.bukkit.org/bukkit-plugins/jail/ - - http://ci.graywolf336.com/job/Jail/ - jenkins - - - http://dev.bukkit.org/bukkit-plugins/jail/tickets/ - Dev Bukkit - - - https://github.com/graywolf336/Jail - scm:git:git://github.com/graywolf336/Jail.git - scm:git:git:@github.com/graywolf336/Jail.git - - - - - vault-repo - http://nexus.theyeticave.net/content/repositories/pub_releases - - - - bukkit-repo - http://repo.bukkit.org/content/groups/public - - - - sk89q-repo - http://maven.sk89q.com/repo/ - - - - - - org.bukkit - bukkit - 1.7.9-R0.1-SNAPSHOT - jar - - - - org.bukkit - craftbukkit - 1.7.9-R0.1-SNAPSHOT - jar - - - - com.sk89q - worldedit - 5.5.7-SNAPSHOT - - - - net.milkbowl.vault - Vault - 1.2.27-SNAPSHOT - jar - - - - com.lexicalscope.jewelcli - jewelcli - 0.8.9 - - - - - junit - junit - 4.11 - - - org.powermock - powermock-module-junit4 - 1.5.5 - test - - - org.powermock - powermock-api-easymock - 1.5.5 - test - - - org.powermock - powermock-api-mockito - 1.5.5 - test - - - org.easymock - easymock - 3.2 - test - - - com.carrotsearch - junit-benchmarks - 0.7.2 - test - - - - - - target - target/classes - - clean install test - - - - . - true - ${basedir}/src/main/resources/ - - *.yml - - - - - - - ${basedir}/src/main/resources - - - - - - - - org.apache.maven.plugins - maven-compiler-plugin - 2.3.2 - - 1.6 - 1.6 - - - - - - org.apache.maven.plugins - maven-jar-plugin - 2.3.1 - - - - - - - - - org.apache.maven.plugins - maven-shade-plugin - 2.2 - - - package - - shade - - - - - com.lexicalscope.jewelcli:jewelcli - - - - - - - - - org.apache.maven.plugins - maven-surefire-plugin - 2.11 - - methods - 10 - - **/TestCommandSender.java - **/TestInstanceCreator.java - - - - - org.apache.maven.surefire - surefire-junit47 - 2.11 - - - - - - - - - repo-release - repo.graywolf336.com Releases - http://repo.graywolf336.com/content/repositories/releases/ - - - repo-snapshot - repo.graywolf336.com Snapshots - http://repo.graywolf336.com/content/repositories/snapshots/ - - + + + 4.0.0 + com.graywolf336 + Jail + 3.0.0-SNAPSHOT + Jail + Ban too harsh? Mute too weak? Kicking not enough? Jail them! + http://dev.bukkit.org/bukkit-plugins/jail/ + + http://ci.graywolf336.com/job/Jail/ + jenkins + + + http://dev.bukkit.org/bukkit-plugins/jail/tickets/ + Dev Bukkit + + + https://github.com/graywolf336/Jail + scm:git:git://github.com/graywolf336/Jail.git + scm:git:git:@github.com/graywolf336/Jail.git + + + + + vault-repo + http://nexus.theyeticave.net/content/repositories/pub_releases + + + + bukkit-repo + http://repo.bukkit.org/content/groups/public + + + + sk89q-repo + http://maven.sk89q.com/repo/ + + + + + + org.bukkit + bukkit + 1.7.9-R0.1-SNAPSHOT + jar + + + + org.bukkit + craftbukkit + 1.7.9-R0.1-SNAPSHOT + jar + + + + com.sk89q + worldedit + 5.5.7-SNAPSHOT + + + + net.milkbowl.vault + Vault + 1.2.27-SNAPSHOT + jar + + + + com.lexicalscope.jewelcli + jewelcli + 0.8.9 + + + + + junit + junit + 4.11 + + + org.powermock + powermock-module-junit4 + 1.5.5 + test + + + org.powermock + powermock-api-easymock + 1.5.5 + test + + + org.powermock + powermock-api-mockito + 1.5.5 + test + + + org.easymock + easymock + 3.2 + test + + + com.carrotsearch + junit-benchmarks + 0.7.2 + test + + + + + + target + target/classes + + clean install test + + + + . + true + ${basedir}/src/main/resources/ + + *.yml + + + + + + + ${basedir}/src/main/resources + + + + + + + + org.apache.maven.plugins + maven-compiler-plugin + 2.3.2 + + 1.6 + 1.6 + + + + + + org.apache.maven.plugins + maven-jar-plugin + 2.3.1 + + + + + + + + + org.apache.maven.plugins + maven-shade-plugin + 2.2 + + + package + + shade + + + + + com.lexicalscope.jewelcli:jewelcli + + + + + + + + + org.apache.maven.plugins + maven-surefire-plugin + 2.11 + + methods + 10 + + **/TestCommandSender.java + **/TestInstanceCreator.java + + + + + org.apache.maven.surefire + surefire-junit47 + 2.11 + + + + + + + + + repo-release + repo.graywolf336.com Releases + http://repo.graywolf336.com/content/repositories/releases/ + + + repo-snapshot + repo.graywolf336.com Snapshots + http://repo.graywolf336.com/content/repositories/snapshots/ + + \ No newline at end of file diff --git a/src/main/java/com/graywolf336/jail/HandCuffManager.java b/src/main/java/com/graywolf336/jail/HandCuffManager.java index d235c02..2123f1d 100644 --- a/src/main/java/com/graywolf336/jail/HandCuffManager.java +++ b/src/main/java/com/graywolf336/jail/HandCuffManager.java @@ -1,83 +1,83 @@ -package com.graywolf336.jail; - -import java.util.HashMap; -import java.util.UUID; - -import org.bukkit.Location; - -/** - * - * @author graywolf336 - * @since 2.6.3 - * @version 1.0.2 - */ -public class HandCuffManager { - private HashMap handcuffed; - private HashMap locs; - - /** Constructs a new HandCuff Manager, for handling all the handcuffing. */ - public HandCuffManager() { - this.handcuffed = new HashMap(); - this.locs = new HashMap(); - } - - /** - * Adds handcuffs to a player. - * - * @param uuid of the player - * @param location where the player was handcuffed, so they can't move - */ - public void addHandCuffs(UUID uuid, Location location) { - this.handcuffed.put(uuid, System.currentTimeMillis()); - this.locs.put(uuid, location); - } - - /** - * Removes the handcuffs from the given player. - * - * @param uuid of the person to remove the handcuffs from - */ - public void removeHandCuffs(UUID uuid) { - this.handcuffed.remove(uuid); - this.locs.remove(uuid); - } - - /** - * Gets if the player is handcuffed or not. - * - * @param uuid of the player to check - * @return true if they are handcuffed, false if not - */ - public boolean isHandCuffed(UUID uuid) { - return this.handcuffed.containsKey(uuid); - } - - /** - * Gets the next Long time we should send a message to the player. - * - * @param uuid of the player to get the name we're supposed to message them next - * @return long value of the system time in milliseconds - */ - public Long getNextMessageTime(UUID uuid) { - return this.handcuffed.get(uuid); - } - - /** - * Updates the time to the next 10 seconds from now to when we should send them a message. - * - * @param uuid of the player we're setting the message time to - */ - public void updateNextTime(UUID uuid) { - this.handcuffed.put(uuid, System.currentTimeMillis() + 10000); - } - - /** - * Gets the location where the given player was handcuffed at. - * - * @param uuid of the player get the location for - * @return the location where the player was handcuffed at - */ - public Location getLocation(UUID uuid) { - return this.locs.get(uuid); - } -} +package com.graywolf336.jail; + +import java.util.HashMap; +import java.util.UUID; + +import org.bukkit.Location; + +/** + * + * @author graywolf336 + * @since 2.6.3 + * @version 1.0.2 + */ +public class HandCuffManager { + private HashMap handcuffed; + private HashMap locs; + + /** Constructs a new HandCuff Manager, for handling all the handcuffing. */ + public HandCuffManager() { + this.handcuffed = new HashMap(); + this.locs = new HashMap(); + } + + /** + * Adds handcuffs to a player. + * + * @param uuid of the player + * @param location where the player was handcuffed, so they can't move + */ + public void addHandCuffs(UUID uuid, Location location) { + this.handcuffed.put(uuid, System.currentTimeMillis()); + this.locs.put(uuid, location); + } + + /** + * Removes the handcuffs from the given player. + * + * @param uuid of the person to remove the handcuffs from + */ + public void removeHandCuffs(UUID uuid) { + this.handcuffed.remove(uuid); + this.locs.remove(uuid); + } + + /** + * Gets if the player is handcuffed or not. + * + * @param uuid of the player to check + * @return true if they are handcuffed, false if not + */ + public boolean isHandCuffed(UUID uuid) { + return this.handcuffed.containsKey(uuid); + } + + /** + * Gets the next Long time we should send a message to the player. + * + * @param uuid of the player to get the name we're supposed to message them next + * @return long value of the system time in milliseconds + */ + public Long getNextMessageTime(UUID uuid) { + return this.handcuffed.get(uuid); + } + + /** + * Updates the time to the next 10 seconds from now to when we should send them a message. + * + * @param uuid of the player we're setting the message time to + */ + public void updateNextTime(UUID uuid) { + this.handcuffed.put(uuid, System.currentTimeMillis() + 10000); + } + + /** + * Gets the location where the given player was handcuffed at. + * + * @param uuid of the player get the location for + * @return the location where the player was handcuffed at + */ + public Location getLocation(UUID uuid) { + return this.locs.get(uuid); + } +} diff --git a/src/main/java/com/graywolf336/jail/JailIO.java b/src/main/java/com/graywolf336/jail/JailIO.java index a567718..a6a9834 100644 --- a/src/main/java/com/graywolf336/jail/JailIO.java +++ b/src/main/java/com/graywolf336/jail/JailIO.java @@ -1,1181 +1,1181 @@ -package com.graywolf336.jail; - -import java.io.File; -import java.io.IOException; -import java.io.InputStreamReader; -import java.sql.Blob; -import java.sql.Connection; -import java.sql.DriverManager; -import java.sql.PreparedStatement; -import java.sql.ResultSet; -import java.sql.SQLException; -import java.sql.Statement; -import java.util.ArrayList; -import java.util.LinkedList; -import java.util.List; -import java.util.Set; -import java.util.UUID; - -import org.bukkit.Location; -import org.bukkit.configuration.file.FileConfiguration; -import org.bukkit.configuration.file.YamlConfiguration; - -import com.graywolf336.jail.beans.Cell; -import com.graywolf336.jail.beans.Jail; -import com.graywolf336.jail.beans.Prisoner; -import com.graywolf336.jail.beans.SimpleLocation; -import com.graywolf336.jail.enums.LangString; - -/** - * Handles all the saving and loading of the plugin's data. - * - * @author graywolf336 - * @since 2.x.x - * @version 3.0.0 - * - */ -public class JailIO { - private JailMain pl; - private FileConfiguration flat, lang, records; - private Connection con; - private int storage; //0 = flatfile, 1 = sqlite, 2 = mysql - private String prefix; - - public JailIO(JailMain plugin) { - this.pl = plugin; - - String st = pl.getConfig().getString("storage.type", "flatfile"); - if(st.equalsIgnoreCase("sqlite")) { - storage = 1; - prefix = pl.getConfig().getString("storage.mysql.prefix"); - }else if(st.equalsIgnoreCase("mysql")) { - storage = 2; - prefix = pl.getConfig().getString("storage.mysql.prefix"); - }else { - storage = 0; - } - - pl.debug("The storage type " + st + " with the type being " + storage + "."); - if(!pl.inDebug()) pl.getLogger().info("Storage type selected: " + st); - } - - /** Loads the language file from disk, if there is none then we save the default one. */ - public void loadLanguage() { - String language = pl.getConfig().getString("system.language"); - boolean save = false; - File langFile = new File(pl.getDataFolder(), language + ".yml"); - - //File or folder already exists, let's check - if(langFile.exists()) { - if(langFile.isFile()) { - lang = YamlConfiguration.loadConfiguration(langFile); - pl.getLogger().info("Loaded the language: " + language); - }else { - pl.getLogger().severe("The language file can not be a folder."); - pl.getLogger().severe("As a result, we are reverting back to English as the language."); - lang = YamlConfiguration.loadConfiguration(new InputStreamReader(pl.getResource("en.yml"))); - save = true; - } - }else { - pl.getLogger().warning("Loading the default language of: en"); - pl.getLogger().warning("If you wish to change this, please rename 'en.yml' to whatever you wish and set the config value to the name of the file."); - lang = YamlConfiguration.loadConfiguration(new InputStreamReader(pl.getResource("en.yml"))); - save = true; - } - - //If we have flagged to save the language file, let's save it as en.yml as this flag usually means they didn't have it loaded. - if(save) { - try { - lang.save(new File(pl.getDataFolder(), "en.yml")); - } catch (IOException e) { - pl.getLogger().severe("Unable to save the language file: " + e.getMessage()); - } - } - } - - /** Returns the message in the language, no variables are replaced.*/ - public String getLanguageString(LangString langString) { - return getLanguageString(langString, new String[] {}); - } - - /** Returns the message in the language, no variables are replaced.*/ - public String getLanguageString(LangString langString, LangString langString2) { - return getLanguageString(langString, getLanguageString(langString2, new String[] {})); - } - - /** - * Returns the message in the language, with the provided variables being replaced. - * - * @param langString Which {@link LangString} we should be getting to send. - * @param variables All the variables to replace, in order from 0 to however many. - * @return The message as a colorful message or an empty message if that isn't defined in the language file. - */ - public String getLanguageString(LangString langString, String... variables) { - String message = lang.getString("language." + langString.getSection() + "." + langString.getName()); - - if(message == null) return ""; - - for (int i = 0; i < variables.length; i++) { - message = message.replaceAll("%" + i + "%", variables[i]); - } - - return Util.getColorfulMessage(message); - } - - /** Prepares the storage engine to be used, returns true if everything went good. */ - public boolean prepareStorage(boolean doInitialCreations) { - switch(storage) { - case 1: - try { - Class.forName("org.sqlite.JDBC"); - pl.getLogger().info("Connecting to the sqlite database."); - Connection sqliteConnection = DriverManager.getConnection("jdbc:sqlite:" + new File(pl.getDataFolder().getPath(), "jail3.sqlite").getPath()); - sqliteConnection.setAutoCommit(true); - this.con = sqliteConnection; - pl.debug("Connection created for sqlite."); - } catch (ClassNotFoundException e) { - e.printStackTrace(); - pl.getLogger().severe("---------- Jail Error!!! ----------"); - pl.getLogger().severe("Sqlite driver not found, disabling the plugin."); - return false; - } catch (SQLException e) { - e.printStackTrace(); - pl.getLogger().severe("---------- Jail Error!!! ----------"); - pl.getLogger().severe("Unable to connect to the sqlite database, please update your config accordingly."); - return false; - } - - break; - case 2: - try { - Class.forName("com.mysql.jdbc.Driver"); - pl.getLogger().info("Connecting to the MySQL database."); - Connection mysqlConnection = DriverManager.getConnection("jdbc:mysql://" + pl.getConfig().getString("storage.mysql.host") + ":" - + pl.getConfig().getString("storage.mysql.port") + "/" - + pl.getConfig().getString("storage.mysql.database"), pl.getConfig().getString("storage.mysql.username"), pl.getConfig().getString("storage.mysql.password")); - mysqlConnection.setAutoCommit(true); - this.con = mysqlConnection; - pl.debug("Connection created for MySQL."); - - if(doInitialCreations) createTables(); - } catch(ClassNotFoundException e) { - e.printStackTrace(); - pl.getLogger().severe("---------- Jail Error!!! ----------"); - pl.getLogger().severe("MySQL driver not found, disabling the plugin."); - return false; - } catch (SQLException e) { - e.printStackTrace(); - pl.getLogger().severe("---------- Jail Error!!! ----------"); - pl.getLogger().severe("Unable to connect to the MySQL database, please update your config accordingly."); - return false; - } - - break; - default: - flat = YamlConfiguration.loadConfiguration(new File(pl.getDataFolder(), "data.yml")); - records = YamlConfiguration.loadConfiguration(new File(pl.getDataFolder(), "records.yml")); - break; - } - - return true; - } - - /** - * Gets the connection for the sqlite and mysql, null if flatfile. - * - * @return The connection for the sql database. - */ - public Connection getConnection() { - switch(storage) { - case 1: - case 2: - if(con == null) this.prepareStorage(false); - try { - if(!con.isValid(10)) this.prepareStorage(false); - } catch (SQLException e) { - e.printStackTrace(); - pl.getLogger().severe("---------- Jail Error!!! ----------"); - pl.getLogger().severe("Unable to get a Sql connection, please see the error above and fix the problem."); - return null; - } - return con; - default: - return null; - } - } - - /** Closes the sql connection. */ - public void closeConnection() { - switch(storage) { - case 1: - case 2: - try { - if(con != null) { - con.close(); - con = null; - - pl.debug("Closed the SQL connection."); - } - } catch (SQLException e) { - e.printStackTrace(); - pl.getLogger().severe("---------- Jail Error!!! ----------"); - pl.getLogger().severe("Unable to close the SQL connection."); - } - - break; - default: - break; - } - } - - private void createTables() { - if(con == null) { - pl.debug("The connection was null when we tried to create a table."); - return; - } - - try { - Statement st = con.createStatement(); - switch(storage){ - case 1: - //TODO: yeah big time! - break; - case 2: - String jailCreateCmd = "CREATE TABLE IF NOT EXISTS `" + prefix + "jails` (" - + "`name` VARCHAR(250) NOT NULL," - + "`world` VARCHAR(250) NOT NULL COMMENT 'The world for the top, bottom, and teleport in.'," - + "`top.x` INT NOT NULL COMMENT 'The top coordinate x.'," - + "`top.y` INT NOT NULL COMMENT 'The top coordinate y.'," - + "`top.z` INT NOT NULL COMMENT 'The top coordinate z.'," - + "`bottom.x` INT NOT NULL COMMENT 'The bottom coordinate x.'," - + "`bottom.y` INT NOT NULL COMMENT 'The bottom coordinate y.'," - + "`bottom.z` INT NOT NULL COMMENT 'The bottom coordinate z.'," - + "`tps.in.x` DOUBLE NOT NULL COMMENT 'The teleport in x coordinate.'," - + "`tps.in.y` DOUBLE NOT NULL COMMENT 'The teleport in y coordinate.'," - + "`tps.in.z` DOUBLE NOT NULL COMMENT 'The teleport in z coordinate.'," - + "`tps.in.yaw` DOUBLE NOT NULL COMMENT 'The teleport in yaw.'," - + "`tps.in.pitch` DOUBLE NOT NULL COMMENT 'The teleport in pitch.'," - + "`tps.free.world` VARCHAR(250) NOT NULL COMMENT 'The teleport for being free world.'," - + "`tps.free.x` DOUBLE NOT NULL COMMENT 'The teleport for being free x coordinate.'," - + "`tps.free.y` DOUBLE NOT NULL COMMENT 'The teleport for being free y coordinate.'," - + "`tps.free.z` DOUBLE NOT NULL COMMENT 'The teleport for being free z coordinate.'," - + "`tps.free.yaw` DOUBLE NOT NULL COMMENT 'The teleport for being free yaw.'," - + "`tps.free.pitch` DOUBLE NOT NULL COMMENT 'The teleport for being free pitch.'," - + "PRIMARY KEY (`name`)," - + "UNIQUE INDEX `name_UNIQUE` (`name` ASC))" - + "COMMENT = 'Holds all the jails for the Bukkit Jail plugin.';"; - - //pl.debug(jailCreateCmd); - st.executeUpdate(jailCreateCmd); - - String cellCreateCmd = "CREATE TABLE IF NOT EXISTS `" + prefix + "cells` (" - + "`cellid` INT NOT NULL AUTO_INCREMENT COMMENT 'The cellid for the database.'," - + "`name` VARCHAR(250) NOT NULL COMMENT 'The name of the cell.'," - + "`jail` VARCHAR(250) NOT NULL COMMENT 'The name of the jail the cell is in.'," - + "`tp.x` DOUBLE NOT NULL COMMENT 'The teleport in x coordinate.'," - + "`tp.y` DOUBLE NOT NULL COMMENT 'The teleport in y coordinate.'," - + "`tp.z` DOUBLE NOT NULL COMMENT 'The teleport in z coordinate.'," - + "`tp.yaw` DOUBLE NOT NULL COMMENT 'The teleport in yaw.'," - + "`tp.pitch` DOUBLE NOT NULL COMMENT 'The teleport in pitch.'," - + "`chest.x` INT NULL COMMENT 'The chest x coordinate.'," - + "`chest.y` INT NULL COMMENT 'The chest y coordinate.'," - + "`chest.z` INT NULL COMMENT 'The chest z coordinate.'," - + "`signs` VARCHAR(250) NULL COMMENT 'A string containing the signs.'," - + "PRIMARY KEY (`cellid`)," - + "UNIQUE INDEX `cellid_UNIQUE` (`cellid` ASC))" - + "COMMENT = 'Contains all the cells for the jails.';"; - - //pl.debug(cellCreateCmd); - st.executeUpdate(cellCreateCmd); - - String prisCreateCmd = "CREATE TABLE IF NOT EXISTS `" + prefix + "prisoners` (" - + "`uuid` VARCHAR(36) NOT NULL COMMENT 'The UUID of the prisoner.'," - + "`name` VARCHAR(16) NOT NULL COMMENT 'The name of the prisoner.'," - + "`jail` VARCHAR(250) NOT NULL COMMENT 'The jail the prisoner is in.'," - + "`cell` VARCHAR(250) NULL COMMENT 'The cell the prisoner is in.'," - + "`muted` TINYINT NOT NULL COMMENT 'Whether the player is muted or not.'," - + "`time` INT NOT NULL COMMENT 'The remaining time the prisoner has.'," - + "`offlinePending` TINYINT NOT NULL COMMENT 'Whether the prisoner has something happened to them while they were offline.'," - + "`toBeTransferred` TINYINT NOT NULL COMMENT 'Whether the prisoner is to be transferred.'," - + "`jailer` VARCHAR(250) NOT NULL COMMENT 'The name of the person who jailed them.'," - + "`reason` VARCHAR(250) NOT NULL COMMENT 'The reason they are jailed.'," - + "`inventory` BLOB NULL COMMENT 'Their inventory in base64.'," - + "`armor` BLOB NULL COMMENT 'The armor in base64.'," - + "`previousLocation` VARCHAR(250) NULL COMMENT 'A string of their previous location.'," - + "`previousGameMode` VARCHAR(16) NULL COMMENT 'Their previous gamemode before they were jailed.'," - + "PRIMARY KEY (`uuid`)," - + "UNIQUE INDEX `uuid_UNIQUE` (`uuid` ASC))" - + "COMMENT = 'Contains all the prisoners, in cells and jails.';"; - - //pl.debug(prisCreateCmd); - st.executeUpdate(prisCreateCmd); - - String proCreateCmd = "CREATE TABLE IF NOT EXISTS `" + prefix + "records` (" - + "`recordid` INT NOT NULL AUTO_INCREMENT COMMENT 'Auto generated number for the records database.'," - + "`uuid` VARCHAR(36) NOT NULL COMMENT 'The UUID of the prisoner.'," - + "`username` VARCHAR(16) NOT NULL COMMENT 'The username of the prisoner.'," - + "`jailer` VARCHAR(250) NOT NULL COMMENT 'The name of the person who jailed the prisoner.'," - + "`date` VARCHAR(32) NOT NULL COMMENT 'A string of the date.'," - + "`time` INT NOT NULL COMMENT 'The milliseconds they were jailed for.'," - + "`reason` VARCHAR(250) NOT NULL COMMENT 'The reason they were jailed for.'," - + "PRIMARY KEY (`recordid`)," - + "UNIQUE INDEX `recordid_UNIQUE` (`recordid` ASC))" - + "COMMENT = 'Holds a history of all the times prisoners have been jailed.'"; - - //pl.debug(proCreateCmd); - st.executeUpdate(proCreateCmd); - st.close(); - break; - default: - break; - } - } catch (SQLException e) { - e.printStackTrace(); - pl.getLogger().severe("---------- Jail Error!!! ----------"); - pl.getLogger().severe("Error while creating the tables, please check the error and fix what is wrong."); - } - } - - /** - * Loads the jails, this should only be called after {@link #prepareStorage(boolean)}. - */ - public void loadJails() { - switch(storage) { - case 1: - case 2: - //load the jails from mysql and sqlite - long st = System.currentTimeMillis(); - - try { - if(con == null) this.prepareStorage(false); - PreparedStatement ps = con.prepareStatement("SELECT * FROM " + prefix + "jails"); - ResultSet set = ps.executeQuery(); - - while(set.next()) { - Jail j = new Jail(pl, set.getString("name")); - - j.setWorld(set.getString("world")); - j.setMaxPoint(new int[] { set.getInt("top.x"), set.getInt("top.y"), set.getInt("top.z") }); - j.setMinPoint(new int[] { set.getInt("bottom.x"), set.getInt("bottom.y"), set.getInt("bottom.z") }); - j.setTeleportIn(new Location(pl.getServer().getWorld(j.getWorldName()), set.getDouble("tps.in.x"), - set.getDouble("tps.in.y"), set.getDouble("tps.in.z"), - set.getFloat("tps.in.yaw"), set.getFloat("tps.in.pitch"))); - j.setTeleportFree(new Location(pl.getServer().getWorld(j.getWorldName()), set.getDouble("tps.free.x"), - set.getDouble("tps.free.y"), set.getDouble("tps.free.z"), - set.getFloat("tps.free.yaw"), set.getFloat("tps.free.pitch"))); - pl.getJailManager().addJail(j, false); - } - - set.close(); - ps.close(); - } catch (SQLException e) { - e.printStackTrace(); - pl.getLogger().severe("---------- Jail Error!!! ----------"); - pl.getLogger().severe("Error while loading the jails, please check the error and fix what is wrong."); - } - - //This list contains an integer which refers to the cellid column in sql - //this list only gets populated if there are cells which reference a jail - //that doesn't exist anymore - List cellsToRemove = new LinkedList(); - - try { - if(con == null) this.prepareStorage(false); - PreparedStatement ps = con.prepareStatement("SELECT * FROM " + prefix + "cells"); - ResultSet set = ps.executeQuery(); - - while(set.next()) { - Jail j = pl.getJailManager().getJail(set.getString("jail")); - - if(j != null) { - Cell c = new Cell(set.getString("name")); - c.setTeleport(new SimpleLocation(j.getWorldName(), set.getDouble("tp.x"), set.getDouble("tp.y"), set.getDouble("tp.z"), - set.getFloat("tp.yaw"), set.getFloat("tp.pitch"))); - - c.setChestLocation(new Location(j.getWorld(), set.getInt("chest.x"), set.getInt("chest.y"), set.getInt("chest.z"))); - - String cSigns = set.getString("signs"); - if(!cSigns.isEmpty()) { - String[] signs = cSigns.split(";"); - for(String s : signs) { - String[] co = s.split(","); - c.addSign(new SimpleLocation(co[0], co[1], co[2], co[3])); - } - } - - - j.addCell(c, false); - }else { - cellsToRemove.add(set.getInt("cellid")); - } - } - - pl.debug("There are " + cellsToRemove.size() + " cells we need to remove due to being invalid."); - - set.close(); - ps.close(); - } catch (SQLException e) { - e.printStackTrace(); - pl.getLogger().severe("---------- Jail Error!!! ----------"); - pl.getLogger().severe("Error while loading all of the cells, please check the error and fix what is wrong."); - } - - //Remove the invalid prisoners - if(cellsToRemove.size() != 0) { - String names = ""; - for(int c : cellsToRemove) { - if(names.isEmpty()) names = "'" + c + "'"; - else names += "," + "'" + c + "'"; - } - - try { - PreparedStatement cds = con.prepareStatement("delete from " + prefix + "cells where cellid in (" + names + ");"); - - pl.debug("Deleting old cells: 'delete from " + prefix + "cells where cellid in (" + names + ");'"); - - int count = cds.executeUpdate(); - pl.getLogger().info("Deleted " + count + " old cells which referenced a jail no longer valid: " + names); - cds.close(); - } catch (SQLException e) { - e.printStackTrace(); - pl.getLogger().severe("---------- Jail Error!!! ----------"); - pl.getLogger().severe("Error while deleting the old cells which don't have a valid jail, please check the error and fix what is wrong."); - } - } - - //This list contains a string which refers to the name of the prisoner in sql - //this list only gets populated if there are prisoners which reference a jail - //that doesn't exist anymore - List prisonersToRemove = new LinkedList(); - - try { - if(con == null) this.prepareStorage(false); - PreparedStatement ps = con.prepareStatement("SELECT * FROM " + prefix + "prisoners"); - ResultSet set = ps.executeQuery(); - - while(set.next()) { - Jail j = pl.getJailManager().getJail(set.getString("jail")); - - if(j != null) { - String cellname = set.getString("cell"); - Cell c = j.getCell(cellname); - - Prisoner p = new Prisoner(set.getString("uuid"), set.getString("name"), set.getBoolean("muted"), set.getLong("time"), set.getString("jailer"), set.getString("reason")); - p.setOfflinePending(set.getBoolean("offlinePending")); - p.setToBeTransferred(set.getBoolean("toBeTransferred")); - Blob inv = set.getBlob("inventory"); - p.setInventory(new String(inv.getBytes(1, (int) inv.length()))); - Blob ar = set.getBlob("armor"); - p.setArmor(new String(ar.getBytes(1, (int)ar.length()))); - p.setPreviousPosition(set.getString("previousLocation")); - p.setPreviousGameMode(set.getString("previousGameMode")); - - if(cellname == null || cellname.isEmpty()) { - j.addPrisoner(p); - }else if(c != null) { - c.setPrisoner(p); - }else { - //the prisoner is assigned to a cell which doesn't exist, so just put them into the jail - j.addPrisoner(p); - } - } else { - //if the jail doesn't exist, do the same as the cells - prisonersToRemove.add(set.getString("name")); - } - } - - set.close(); - ps.close(); - - pl.debug("There are " + prisonersToRemove.size() + " prisoners we need to remove due to being invalid."); - } catch (SQLException e) { - e.printStackTrace(); - pl.getLogger().severe("---------- Jail Error!!! ----------"); - pl.getLogger().severe("Error while loading all of the prisoners, please check the error and fix what is wrong."); - } - - //Remove the invalid prisoners - if(prisonersToRemove.size() != 0) { - String names = ""; - for(String s : prisonersToRemove) { - if(names.isEmpty()) names = "'" + s + "'"; - else names += "," + "'" + s + "'"; - } - - try { - PreparedStatement pds = con.prepareStatement("delete from " + prefix + "prisoners where name in (" + names + ");"); - - pl.debug("Deleting old prisoners: 'delete from " + prefix + "prisoners where name in (" + names + ");'"); - - int count = pds.executeUpdate(); - pl.getLogger().info("Deleted " + count + " old prisoners which referenced a jail no longer valid: " + names); - pds.close(); - } catch (SQLException e) { - e.printStackTrace(); - pl.getLogger().severe("---------- Jail Error!!! ----------"); - pl.getLogger().severe("Error while deleting the old prisoners which don't have a valid jail, please check the error and fix what is wrong."); - } - } - - pl.debug("Took " + (System.currentTimeMillis() - st) + " millis."); - break; - default: - //load the jails from flatfile - if(flat.isConfigurationSection("jails")) { - Set jails = flat.getConfigurationSection("jails").getKeys(false); - if(!jails.isEmpty()) { - for(String name : jails) { - loadJailFromFlatFile(name); - } - } - } - break; - } - - int js = pl.getJailManager().getJails().size(); - pl.getLogger().info("Loaded " + js + (js == 1 ? " jail." : " jails.")); - - int cs = pl.getJailManager().getAllCells().size(); - pl.getLogger().info("Loaded " + cs + (cs == 1 ? " cell." : " cells.")); - - int ps = pl.getJailManager().getAllPrisoners().size(); - pl.getLogger().info("Loaded " + ps + (ps == 1 ? " prisoner." : " prisoners.")); - } - - private void loadJailFromFlatFile(String name) { - String node = "jails." + name + "."; - String cNode = node + "cells."; - Jail j = new Jail(pl, name); - - j.setWorld(flat.getString(node + "world")); - j.setMaxPoint(new int[] {flat.getInt(node + "top.x"), flat.getInt(node + "top.y"), flat.getInt(node + "top.z")}); - j.setMinPoint(new int[] {flat.getInt(node + "bottom.x"), flat.getInt(node + "bottom.y"), flat.getInt(node + "bottom.z")}); - - j.setTeleportIn(new Location( - pl.getServer().getWorld(flat.getString(node + "world")), - flat.getDouble(node + "tps.in.x"), - flat.getDouble(node + "tps.in.y"), - flat.getDouble(node + "tps.in.z"), - (float) flat.getDouble(node + "tps.in.yaw"), - (float) flat.getDouble(node + "tps.in.pitch"))); - j.setTeleportFree(new Location( - pl.getServer().getWorld(flat.getString(node + "world")), - flat.getDouble(node + "tps.free.x"), - flat.getDouble(node + "tps.free.y"), - flat.getDouble(node + "tps.free.z"), - (float) flat.getDouble(node + "tps.free.yaw"), - (float) flat.getDouble(node + "tps.free.pitch"))); - - if(flat.isConfigurationSection(node + "cells")) { - Set cells = flat.getConfigurationSection(node + "cells").getKeys(false); - if(!cells.isEmpty()) { - for(String cell : cells) { - Cell c = new Cell(cell); - String cellNode = cNode + cell + "."; - - c.setTeleport(new SimpleLocation(j.getTeleportIn().getWorld().getName(), - flat.getDouble(cellNode + "tp.x"), - flat.getDouble(cellNode + "tp.y"), - flat.getDouble(cellNode + "tp.z"), - (float) flat.getDouble(cellNode + "tp.yaw"), - (float) flat.getDouble(cellNode + "tp.pitch"))); - c.setChestLocation(new Location(j.getTeleportIn().getWorld(), - flat.getInt(cellNode + "chest.x"), - flat.getInt(cellNode + "chest.y"), - flat.getInt(cellNode + "chest.z"))); - - for(String sign : flat.getStringList(cellNode + "signs")) { - String[] arr = sign.split(","); - c.addSign(new SimpleLocation(arr[0], - Double.valueOf(arr[1]), - Double.valueOf(arr[2]), - Double.valueOf(arr[3]), - Float.valueOf(arr[4]), - Float.valueOf(arr[5]))); - } - - if(flat.contains(cellNode + "prisoner")) { - Prisoner p = new Prisoner(flat.getString(cellNode + "prisoner.uuid"), - flat.getString(cellNode + "prisoner.name"), - flat.getBoolean(cellNode + "prisoner.muted"), - flat.getLong(cellNode + "prisoner.time"), - flat.getString(cellNode + "prisoner.jailer"), - flat.getString(cellNode + "prisoner.reason")); - p.setOfflinePending(flat.getBoolean(cellNode + "prisoner.offlinePending")); - p.setToBeTransferred(flat.getBoolean(cellNode + "prisoner.toBeTransferred")); - p.setPreviousPosition(flat.getString(cellNode + "prisoner.previousLocation")); - p.setPreviousGameMode(flat.getString(cellNode + "prisoner.previousGameMode")); - p.setInventory(flat.getString(cellNode + "prisoner.inventory", "")); - p.setArmor(flat.getString(cellNode + "prisoner.armor", "")); - c.setPrisoner(p); - } - - j.addCell(c, false); - } - } - } - - if(flat.isConfigurationSection(node + "prisoners")) { - Set prisoners = flat.getConfigurationSection(node + "prisoners").getKeys(false); - if(!prisoners.isEmpty()) { - for(String uuid : prisoners) { - String pNode = node + "prisoners." + uuid + "."; - Prisoner pris = new Prisoner(uuid, - flat.getString(pNode + "name"), - flat.getBoolean(pNode + "muted"), - flat.getLong(pNode + "time"), - flat.getString(pNode + "jailer"), - flat.getString(pNode + "reason")); - pris.setOfflinePending(flat.getBoolean(pNode + "offlinePending")); - pris.setToBeTransferred(flat.getBoolean(pNode + "toBeTransferred")); - pris.setPreviousPosition(flat.getString(pNode + "previousLocation")); - pris.setPreviousGameMode(flat.getString(pNode + "previousGameMode")); - pris.setInventory(flat.getString(pNode + "inventory", "")); - pris.setArmor(flat.getString(pNode + "armor", "")); - j.addPrisoner(pris); - } - } - } - - if(pl.getServer().getWorld(j.getWorldName()) != null) { - pl.getJailManager().addJail(j, false); - pl.getLogger().info("Loaded jail " + j.getName() + " with " + j.getAllPrisoners().size() + " prisoners and " + j.getCellCount() + " cells."); - } else - pl.getLogger().severe("Failed to load the jail " + j.getName() + " as the world '" + j.getWorldName() + "' does not exist (is null). Did you remove this world?"); - } - - /** Saves everything about a jail, don't usually call this. */ - public void saveEverything() { - long st = System.currentTimeMillis(); - - for(Jail j : pl.getJailManager().getJails()) { - saveJail(j); - - for(Cell c : j.getCells()) { - saveCell(j, c); - } - } - - pl.debug("Saving everything took " + (System.currentTimeMillis() - st) + " millis."); - } - - /** - * Saves the provided {@link Jail jail} to the storage system we are using. - * - * @param j The jail to save. - */ - public void saveJail(Jail j) { - switch(storage) { - case 1: - case 2: - long st = System.currentTimeMillis(); - - try { - if(con == null) this.prepareStorage(false); - PreparedStatement ps = con.prepareStatement("REPLACE INTO " - + prefix + "jails (`name`, `world`, `top.x`, `top.y`, `top.z`, `bottom.x`, `bottom.y`," - + "`bottom.z`, `tps.in.x`, `tps.in.y`, `tps.in.z`, `tps.in.yaw`, `tps.in.pitch`," - + "`tps.free.world`, `tps.free.x`, `tps.free.y`, `tps.free.z`, `tps.free.yaw`, `tps.free.pitch`)" - + "VALUES (?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)"); - - ps.setString(1, j.getName()); - ps.setString(2, j.getWorldName()); - ps.setInt(3, j.getMaxPoint().getBlockX()); - ps.setInt(4, j.getMaxPoint().getBlockY()); - ps.setInt(5, j.getMaxPoint().getBlockZ()); - ps.setInt(6, j.getMinPoint().getBlockX()); - ps.setInt(7, j.getMinPoint().getBlockY()); - ps.setInt(8, j.getMinPoint().getBlockZ()); - ps.setDouble(9, j.getTeleportIn().getX()); - ps.setDouble(10, j.getTeleportIn().getY()); - ps.setDouble(11, j.getTeleportIn().getZ()); - ps.setDouble(12, j.getTeleportIn().getYaw()); - ps.setDouble(13, j.getTeleportIn().getPitch()); - ps.setString(14, j.getTeleportFree().getWorld().getName()); - ps.setDouble(15, j.getTeleportFree().getX()); - ps.setDouble(16, j.getTeleportFree().getY()); - ps.setDouble(17, j.getTeleportFree().getZ()); - ps.setDouble(18, j.getTeleportFree().getYaw()); - ps.setDouble(19, j.getTeleportFree().getPitch()); - - ps.executeUpdate(); - ps.close(); - } catch (SQLException e) { - e.printStackTrace(); - pl.getLogger().severe("---------- Jail Error!!! ----------"); - pl.getLogger().severe("Error while saving the Jail '" + j.getName() + "' (not updating the prisoners), please check the error and fix what is wrong."); - } - - try { - if(con == null) this.prepareStorage(false); - - for(Cell c : j.getCells()) { - if(c.hasPrisoner()) { - Prisoner p = c.getPrisoner(); - PreparedStatement pPS = con.prepareStatement("REPLACE INTO `" + prefix + "prisoners` (`uuid`, `name`, `jail`, `cell`, `muted`, `time`," - + "`offlinePending`, `toBeTransferred`, `jailer`, `reason`, `inventory`, `armor`, `previousLocation`, `previousGameMode`)" - + "VALUES (?,?,?,?,?,?,?,?,?,?,?,?,?,?)"); - pPS.setString(1, p.getUUID().toString()); - pPS.setString(2, p.getLastKnownName()); - pPS.setString(3, j.getName()); - pPS.setString(4, c.getName()); - pPS.setBoolean(5, p.isMuted()); - pPS.setFloat(6, p.getRemainingTime()); - pPS.setBoolean(7, p.isOfflinePending()); - pPS.setBoolean(8, p.isToBeTransferred()); - pPS.setString(9, p.getJailer()); - pPS.setString(10, p.getReason()); - pPS.setBytes(11, p.getInventory().getBytes()); - pPS.setBytes(12, p.getArmor().getBytes()); - pPS.setString(13, p.getPreviousLocationString()); - pPS.setString(14, p.getPreviousGameMode().toString()); - - pPS.executeUpdate(); - pPS.close(); - } - } - } catch (SQLException e) { - e.printStackTrace(); - pl.getLogger().severe("---------- Jail Error!!! ----------"); - pl.getLogger().severe("Error while saving the cells of the Jail '" + j.getName() + "', please check the error and fix what is wrong."); - } - - try { - if(con == null) this.prepareStorage(false); - - for(Prisoner p : j.getPrisonersNotInCells().values()) { - PreparedStatement pPS = con.prepareStatement("REPLACE INTO `" + prefix + "prisoners` (`uuid`, `name`, `jail`, `cell`, `muted`, `time`," - + "`offlinePending`, `toBeTransferred`, `jailer`, `reason`, `inventory`, `armor`, `previousLocation`, `previousGameMode`) VALUES (?,?,?,?,?,?,?,?,?,?,?,?,?,?)"); - pPS.setString(1, p.getUUID().toString()); - pPS.setString(2, p.getLastKnownName()); - pPS.setString(3, j.getName()); - pPS.setString(4, ""); - pPS.setBoolean(5, p.isMuted()); - pPS.setFloat(6, p.getRemainingTime()); - pPS.setBoolean(7, p.isOfflinePending()); - pPS.setBoolean(8, p.isToBeTransferred()); - pPS.setString(9, p.getJailer()); - pPS.setString(10, p.getReason()); - pPS.setBytes(11, p.getInventory().getBytes()); - pPS.setBytes(12, p.getArmor().getBytes()); - pPS.setString(13, p.getPreviousLocationString()); - pPS.setString(14, p.getPreviousGameMode().toString()); - - pPS.executeUpdate(); - pPS.close(); - } - } catch (SQLException e) { - e.printStackTrace(); - pl.getLogger().severe("---------- Jail Error!!! ----------"); - pl.getLogger().severe("Error while saving the prisoners of the Jail '" + j.getName() + "', please check the error and fix what is wrong."); - } - - pl.debug("Took " + (System.currentTimeMillis() - st) + " millis."); - break; - default: - if(flat != null) { - String node = "jails." + j.getName() + "."; - - //Corners - flat.set(node + "world", j.getWorldName()); - flat.set(node + "top.x", j.getMaxPoint().getBlockX()); - flat.set(node + "top.y", j.getMaxPoint().getBlockY()); - flat.set(node + "top.z", j.getMaxPoint().getBlockZ()); - flat.set(node + "bottom.x", j.getMinPoint().getBlockX()); - flat.set(node + "bottom.y", j.getMinPoint().getBlockY()); - flat.set(node + "bottom.z", j.getMinPoint().getBlockZ()); - - //Tele in - flat.set(node + "tps.in.x", j.getTeleportIn().getX()); - flat.set(node + "tps.in.y", j.getTeleportIn().getY()); - flat.set(node + "tps.in.z", j.getTeleportIn().getZ()); - flat.set(node + "tps.in.yaw", j.getTeleportIn().getYaw()); - flat.set(node + "tps.in.pitch", j.getTeleportIn().getPitch()); - - //Tele out - flat.set(node + "tps.free.world", j.getTeleportFree().getWorld().getName()); - flat.set(node + "tps.free.x", j.getTeleportFree().getX()); - flat.set(node + "tps.free.y", j.getTeleportFree().getY()); - flat.set(node + "tps.free.z", j.getTeleportFree().getZ()); - flat.set(node + "tps.free.yaw", j.getTeleportFree().getYaw()); - flat.set(node + "tps.free.pitch", j.getTeleportFree().getPitch()); - - //Set all the cells to nothing, then we save each of them so no cells are left behind - flat.set(node + "cells", null); - for(Cell c : j.getCells()) { - String cNode = node + "cells." + c.getName() + "."; - - if(c.getTeleport() != null) { - flat.set(cNode + "tp.x", c.getTeleport().getX()); - flat.set(cNode + "tp.y", c.getTeleport().getY()); - flat.set(cNode + "tp.z", c.getTeleport().getZ()); - flat.set(cNode + "tp.yaw", c.getTeleport().getYaw()); - flat.set(cNode + "tp.pitch", c.getTeleport().getPitch()); - } - - if(c.getChestLocation() != null) { - flat.set(cNode + "chest.x", c.getChestLocation().getBlockX()); - flat.set(cNode + "chest.y", c.getChestLocation().getBlockY()); - flat.set(cNode + "chest.z", c.getChestLocation().getBlockZ()); - } - - String[] signs = new String[c.getSigns().size()]; - int count = 0; - for(SimpleLocation loc : c.getSigns()) { - signs[count] = loc.toString(); - count++; - } - - flat.set(cNode + "signs", signs); - - if(c.getPrisoner() != null) { - Prisoner p = c.getPrisoner(); - flat.set(cNode + "prisoner.uuid", p.getUUID().toString()); - flat.set(cNode + "prisoner.name", p.getLastKnownName()); - flat.set(cNode + "prisoner.muted", p.isMuted()); - flat.set(cNode + "prisoner.time", p.getRemainingTime()); - flat.set(cNode + "prisoner.offlinePending", p.isOfflinePending()); - flat.set(cNode + "prisoner.toBeTransferred", p.isToBeTransferred()); - flat.set(cNode + "prisoner.jailer", p.getJailer()); - flat.set(cNode + "prisoner.reason", p.getReason()); - flat.set(cNode + "prisoner.inventory", p.getInventory()); - flat.set(cNode + "prisoner.armor", p.getArmor()); - if(p.getPreviousLocationString() != null) - flat.set(cNode + "prisoner.previousLocation", p.getPreviousLocationString()); - if(p.getPreviousGameMode() != null) - flat.set(cNode + "prisoner.previousGameMode", p.getPreviousGameMode().toString()); - } - } - - //Null all the prisoners out before we save them again, this way no prisoners are left behind - flat.set(node + "prisoners", null); - for(Prisoner p : j.getPrisonersNotInCells().values()) { - String pNode = node + "prisoners." + p.getUUID().toString() + "."; - flat.set(pNode + "name", p.getLastKnownName()); - flat.set(pNode + "muted", p.isMuted()); - flat.set(pNode + "time", p.getRemainingTime()); - flat.set(pNode + "offlinePending", p.isOfflinePending()); - flat.set(pNode + "toBeTransferred", p.isToBeTransferred()); - flat.set(pNode + "jailer", p.getJailer()); - flat.set(pNode + "reason", p.getReason()); - flat.set(pNode + "inventory", p.getInventory()); - flat.set(pNode + "armor", p.getArmor()); - if(p.getPreviousLocationString() != null) - flat.set(pNode + "previousLocation", p.getPreviousLocationString()); - if(p.getPreviousGameMode() != null) - flat.set(pNode + "previousGameMode", p.getPreviousGameMode().toString()); - } - - try { - flat.save(new File(pl.getDataFolder(), "data.yml")); - } catch (IOException e) { - pl.getLogger().severe("Unable to save the Jail data: " + e.getMessage()); - } - }else { - pl.getLogger().severe("Storage not enabled, could not save the jail " + j.getName()); - } - break; - } - } - - public void saveCell(Jail j, Cell c) { - switch(storage) { - case 1: - case 2: - try { - if(con == null) this.prepareStorage(false); - - PreparedStatement cPS = con.prepareStatement("INSERT INTO `" + prefix + "cells` (`name`, `jail`, `tp.x`, `tp.y`, `tp.z`, `tp.yaw`," - + "`tp.pitch`, `chest.x`, `chest.y`, `chest.z`, `signs`) VALUES (?,?,?,?,?,?,?,?,?,?,?)"); - - cPS.setString(1, c.getName()); - cPS.setString(2, j.getName()); - cPS.setDouble(3, c.getTeleport().getX()); - cPS.setDouble(4, c.getTeleport().getY()); - cPS.setDouble(5, c.getTeleport().getZ()); - cPS.setDouble(6, c.getTeleport().getYaw()); - cPS.setDouble(7, c.getTeleport().getPitch()); - - if(c.hasChest()) { - cPS.setInt(8, c.getChestLocation().getBlockX()); - cPS.setInt(9, c.getChestLocation().getBlockY()); - cPS.setInt(10, c.getChestLocation().getBlockZ()); - }else { - cPS.setNull(8, java.sql.Types.INTEGER); - cPS.setNull(9, java.sql.Types.INTEGER); - cPS.setNull(10, java.sql.Types.INTEGER); - } - - cPS.setString(11, c.getSignString()); - - cPS.executeUpdate(); - cPS.close(); - - if(c.hasPrisoner()) { - Prisoner p = c.getPrisoner(); - PreparedStatement pPS = con.prepareStatement("REPLACE INTO `" + prefix + "prisoners` (`uuid`, `name`, `jail`, `cell`, `muted`, `time`," - + "`offlinePending`, `toBeTransferred`, `jailer`, `reason`, `inventory`, `armor`, `previousLocation`, `previousGameMode`) VALUES (?,?,?,?,?,?,?,?,?,?,?,?,?,?)"); - pPS.setString(1, p.getUUID().toString()); - pPS.setString(2, p.getLastKnownName()); - pPS.setString(3, j.getName()); - pPS.setString(4, c.getName()); - pPS.setBoolean(5, p.isMuted()); - pPS.setFloat(6, p.getRemainingTime()); - pPS.setBoolean(7, p.isOfflinePending()); - pPS.setBoolean(8, p.isToBeTransferred()); - pPS.setString(9, p.getJailer()); - pPS.setString(10, p.getReason()); - pPS.setBytes(11, p.getInventory().getBytes()); - pPS.setBytes(12, p.getArmor().getBytes()); - pPS.setString(13, p.getPreviousLocationString()); - pPS.setString(14, p.getPreviousGameMode().toString()); - - pPS.executeUpdate(); - pPS.close(); - } - } catch (SQLException e) { - e.printStackTrace(); - pl.getLogger().severe("---------- Jail Error!!! ----------"); - pl.getLogger().severe("Error while saving the cell '" + c.getName() + "' of the Jail '" + j.getName() + "', please check the error and fix what is wrong."); - } - - break; - default: - this.saveJail(j); - break; - } - } - - /** - * Removes the prisoner from the storage system. - * - * @param j the jail which the prisoner is in. - * @param p the prisoner data - */ - public void removePrisoner(Jail j, Prisoner p) { - this.removePrisoner(j, null, p); - } - - /** - * Removes the prisoner from the storage system. - * - * @param j the jail which the prisoner is in. - * @param c the cell which the prisoner is in, null if none - * @param p the prisoner data - */ - public void removePrisoner(Jail j, Cell c, Prisoner p) { - switch(storage) { - case 1: - case 2: - try { - PreparedStatement pp = con.prepareStatement("delete from `" + prefix + "prisoners` where uuid = ? limit 1;"); - pp.setString(1, p.getUUID().toString()); - - pl.debug("Removing " + p.getLastKnownName() + " (" + p.getUUID().toString() + ") from MySQL database."); - - pp.executeUpdate(); - pp.close(); - } catch (SQLException e) { - e.printStackTrace(); - pl.getLogger().severe("---------- Jail Error!!! ----------"); - pl.getLogger().severe("Error while removing the prisoner '" + p.getLastKnownName() + "' from the database, please check the error and fix what is wrong."); - } - break; - default: - if(c == null) - flat.set("jails." + j.getName() + ".prisoners." + p.getUUID().toString(), null); - else - flat.set("jails." + j.getName() + "." + c.getName() + ".prisoner", null); - - try { - flat.save(new File(pl.getDataFolder(), "data.yml")); - } catch (IOException e) { - pl.getLogger().severe("Unable to save the Jail data: " + e.getMessage()); - } - break; - } - } - - /** - * Removes the provided cell from the jail. - * - * @param j instance of the jail the cell is in - * @param c instance of the cell we are removing - */ - public void removeCell(Jail j, Cell c) { - //Clear the inventory before we delete it - if(c.hasChest()) c.getChest().getInventory().clear(); - - //transfer the prisoner if it has one - if(c.hasPrisoner()) { - pl.getLogger().warning("Removing of cell '" + c.getName() + "' from the jail '" + j.getName() + "' failed as it has a prisoner."); - return; - } - - switch(storage) { - case 1: - case 2: - try { - PreparedStatement p = con.prepareStatement("delete from `" + prefix + "cells` where name = ? and jail = ? limit 1;"); - p.setString(1, c.getName()); - p.setString(2, j.getName()); - - p.executeUpdate(); - p.close(); - } catch (SQLException e) { - e.printStackTrace(); - pl.getLogger().severe("---------- Jail Error!!! ----------"); - pl.getLogger().severe("Error while removing the cell '" + c.getName() + "' from the Jail '" + j.getName() + "', please check the error and fix what is wrong."); - } - break; - default: - if(flat != null) { - flat.set("jails." + j.getName() + "cells." + c.getName(), null); - - try { - flat.save(new File(pl.getDataFolder(), "data.yml")); - } catch (IOException e) { - e.printStackTrace(); - pl.getLogger().severe("---------- Jail Error!!! ----------"); - pl.getLogger().severe("Removing of the cell '" + c.getName() + "' from the jail '" + j.getName() + "' errored out while on saving."); - } - } - break; - } - } - - /** - * Removes a jail from the storage system. - * - * @param j the jail instance to remove. - */ - public void removeJail(Jail j) { - String name = j.getName(); - - switch(storage) { - case 1: - case 2: - for(Cell c : j.getCells()) { - removeCell(j, c); - } - - try { - PreparedStatement p = con.prepareStatement("delete from `" + prefix + "jails` where name = ?"); - p.setString(1, name); - - p.executeUpdate(); - p.close(); - } catch (SQLException e) { - e.printStackTrace(); - pl.getLogger().severe("---------- Jail Error!!! ----------"); - pl.getLogger().severe("Error while removing the Jail '" + j.getName() + "', please check the error and fix what is wrong."); - } - break; - default: - flat.set("jails." + name, null); - - try { - flat.save(new File(pl.getDataFolder(), "data.yml")); - } catch (IOException e) { - e.printStackTrace(); - pl.getLogger().severe("---------- Jail Error!!! ----------"); - pl.getLogger().severe("Removing of the jail '" + j.getName() + "' errored out while on saving."); - } - break; - } - } - - /** - * Adds an entry to the database/file for the user, logging when they was jailed. - * - * @param uuid of the player - * @param username of the player - * @param jailer who jailed them - * @param date string of when they are jailed - * @param time of the player's sentence - * @param reason the player is jailed - */ - public void addRecordEntry(String uuid, String username, String jailer, String date, long time, String reason) { - switch(storage) { - case 1: - break; - case 2: - try { - PreparedStatement p = con.prepareStatement("insert into `" + prefix + "records` (`uuid`, `username`, `jailer`, `date`, `time`, `reason`) VALUES (?,?,?,?,?,?);"); - p.setString(1, uuid); - p.setString(2, username); - p.setString(3, jailer); - p.setString(4, date); - p.setLong(5, time); - p.setString(6, reason); - - p.executeUpdate(); - p.close(); - } catch (SQLException e) { - e.printStackTrace(); - pl.getLogger().severe("---------- Jail Error!!! ----------"); - pl.getLogger().severe("Error while adding a record entry for '" + username + "', please check the error and fix what is wrong."); - } - break; - default: - if(records == null) records = YamlConfiguration.loadConfiguration(new File(pl.getDataFolder(), "records.yml")); - - List previous = records.getStringList(uuid); - previous.add(this.getLanguageString(LangString.RECORDENTRY, new String[] { date, username, jailer, String.valueOf(time), reason, uuid })); - - records.set(username, previous); - - try { - records.save(new File(pl.getDataFolder(), "records.yml")); - } catch (IOException e) { - e.printStackTrace(); - pl.getLogger().severe("---------- Jail Error!!! ----------"); - pl.getLogger().severe("Saving the records.yml file failed while putting an entry in for '" + username + "'."); - } - break; - } - } - - /** - * Gets all the record entries for the given player. - * - * @param username the of the prisoner's records to get. - * @return A List of strings containing the record entries. - * @deprecated This calls getOfflinePlayer which is a blocking call from Bukkit - */ - public List getRecordEntries(String username) { - UUID uuid = pl.getServer().getOfflinePlayer(username).getUniqueId(); - List entries = new ArrayList(); - - switch(storage) { - case 1: - break; - case 2: - try { - PreparedStatement ps = con.prepareStatement("SELECT * FROM " + prefix + "records where uuid = ?"); - ps.setString(1, uuid.toString()); - ResultSet set = ps.executeQuery(); - - while(set.next()) { - entries.add(this.getLanguageString(LangString.RECORDENTRY, - new String[] { set.getString("date"), set.getString("username"), set.getString("jailer"), String.valueOf(set.getLong("time")), set.getString("reason") })); - } - - set.close(); - ps.close(); - } catch (SQLException e) { - e.printStackTrace(); - pl.getLogger().severe("---------- Jail Error!!! ----------"); - pl.getLogger().severe("Error while getting all the record entries for '" + uuid + "', please check the error and fix what is wrong."); - } - break; - default: - if(records == null) records = YamlConfiguration.loadConfiguration(new File(pl.getDataFolder(), "records.yml")); - - entries = records.getStringList(uuid.toString()); - break; - } - - return entries; - } -} +package com.graywolf336.jail; + +import java.io.File; +import java.io.IOException; +import java.io.InputStreamReader; +import java.sql.Blob; +import java.sql.Connection; +import java.sql.DriverManager; +import java.sql.PreparedStatement; +import java.sql.ResultSet; +import java.sql.SQLException; +import java.sql.Statement; +import java.util.ArrayList; +import java.util.LinkedList; +import java.util.List; +import java.util.Set; +import java.util.UUID; + +import org.bukkit.Location; +import org.bukkit.configuration.file.FileConfiguration; +import org.bukkit.configuration.file.YamlConfiguration; + +import com.graywolf336.jail.beans.Cell; +import com.graywolf336.jail.beans.Jail; +import com.graywolf336.jail.beans.Prisoner; +import com.graywolf336.jail.beans.SimpleLocation; +import com.graywolf336.jail.enums.LangString; + +/** + * Handles all the saving and loading of the plugin's data. + * + * @author graywolf336 + * @since 2.x.x + * @version 3.0.0 + * + */ +public class JailIO { + private JailMain pl; + private FileConfiguration flat, lang, records; + private Connection con; + private int storage; //0 = flatfile, 1 = sqlite, 2 = mysql + private String prefix; + + public JailIO(JailMain plugin) { + this.pl = plugin; + + String st = pl.getConfig().getString("storage.type", "flatfile"); + if(st.equalsIgnoreCase("sqlite")) { + storage = 1; + prefix = pl.getConfig().getString("storage.mysql.prefix"); + }else if(st.equalsIgnoreCase("mysql")) { + storage = 2; + prefix = pl.getConfig().getString("storage.mysql.prefix"); + }else { + storage = 0; + } + + pl.debug("The storage type " + st + " with the type being " + storage + "."); + if(!pl.inDebug()) pl.getLogger().info("Storage type selected: " + st); + } + + /** Loads the language file from disk, if there is none then we save the default one. */ + public void loadLanguage() { + String language = pl.getConfig().getString("system.language"); + boolean save = false; + File langFile = new File(pl.getDataFolder(), language + ".yml"); + + //File or folder already exists, let's check + if(langFile.exists()) { + if(langFile.isFile()) { + lang = YamlConfiguration.loadConfiguration(langFile); + pl.getLogger().info("Loaded the language: " + language); + }else { + pl.getLogger().severe("The language file can not be a folder."); + pl.getLogger().severe("As a result, we are reverting back to English as the language."); + lang = YamlConfiguration.loadConfiguration(new InputStreamReader(pl.getResource("en.yml"))); + save = true; + } + }else { + pl.getLogger().warning("Loading the default language of: en"); + pl.getLogger().warning("If you wish to change this, please rename 'en.yml' to whatever you wish and set the config value to the name of the file."); + lang = YamlConfiguration.loadConfiguration(new InputStreamReader(pl.getResource("en.yml"))); + save = true; + } + + //If we have flagged to save the language file, let's save it as en.yml as this flag usually means they didn't have it loaded. + if(save) { + try { + lang.save(new File(pl.getDataFolder(), "en.yml")); + } catch (IOException e) { + pl.getLogger().severe("Unable to save the language file: " + e.getMessage()); + } + } + } + + /** Returns the message in the language, no variables are replaced.*/ + public String getLanguageString(LangString langString) { + return getLanguageString(langString, new String[] {}); + } + + /** Returns the message in the language, no variables are replaced.*/ + public String getLanguageString(LangString langString, LangString langString2) { + return getLanguageString(langString, getLanguageString(langString2, new String[] {})); + } + + /** + * Returns the message in the language, with the provided variables being replaced. + * + * @param langString Which {@link LangString} we should be getting to send. + * @param variables All the variables to replace, in order from 0 to however many. + * @return The message as a colorful message or an empty message if that isn't defined in the language file. + */ + public String getLanguageString(LangString langString, String... variables) { + String message = lang.getString("language." + langString.getSection() + "." + langString.getName()); + + if(message == null) return ""; + + for (int i = 0; i < variables.length; i++) { + message = message.replaceAll("%" + i + "%", variables[i]); + } + + return Util.getColorfulMessage(message); + } + + /** Prepares the storage engine to be used, returns true if everything went good. */ + public boolean prepareStorage(boolean doInitialCreations) { + switch(storage) { + case 1: + try { + Class.forName("org.sqlite.JDBC"); + pl.getLogger().info("Connecting to the sqlite database."); + Connection sqliteConnection = DriverManager.getConnection("jdbc:sqlite:" + new File(pl.getDataFolder().getPath(), "jail3.sqlite").getPath()); + sqliteConnection.setAutoCommit(true); + this.con = sqliteConnection; + pl.debug("Connection created for sqlite."); + } catch (ClassNotFoundException e) { + e.printStackTrace(); + pl.getLogger().severe("---------- Jail Error!!! ----------"); + pl.getLogger().severe("Sqlite driver not found, disabling the plugin."); + return false; + } catch (SQLException e) { + e.printStackTrace(); + pl.getLogger().severe("---------- Jail Error!!! ----------"); + pl.getLogger().severe("Unable to connect to the sqlite database, please update your config accordingly."); + return false; + } + + break; + case 2: + try { + Class.forName("com.mysql.jdbc.Driver"); + pl.getLogger().info("Connecting to the MySQL database."); + Connection mysqlConnection = DriverManager.getConnection("jdbc:mysql://" + pl.getConfig().getString("storage.mysql.host") + ":" + + pl.getConfig().getString("storage.mysql.port") + "/" + + pl.getConfig().getString("storage.mysql.database"), pl.getConfig().getString("storage.mysql.username"), pl.getConfig().getString("storage.mysql.password")); + mysqlConnection.setAutoCommit(true); + this.con = mysqlConnection; + pl.debug("Connection created for MySQL."); + + if(doInitialCreations) createTables(); + } catch(ClassNotFoundException e) { + e.printStackTrace(); + pl.getLogger().severe("---------- Jail Error!!! ----------"); + pl.getLogger().severe("MySQL driver not found, disabling the plugin."); + return false; + } catch (SQLException e) { + e.printStackTrace(); + pl.getLogger().severe("---------- Jail Error!!! ----------"); + pl.getLogger().severe("Unable to connect to the MySQL database, please update your config accordingly."); + return false; + } + + break; + default: + flat = YamlConfiguration.loadConfiguration(new File(pl.getDataFolder(), "data.yml")); + records = YamlConfiguration.loadConfiguration(new File(pl.getDataFolder(), "records.yml")); + break; + } + + return true; + } + + /** + * Gets the connection for the sqlite and mysql, null if flatfile. + * + * @return The connection for the sql database. + */ + public Connection getConnection() { + switch(storage) { + case 1: + case 2: + if(con == null) this.prepareStorage(false); + try { + if(!con.isValid(10)) this.prepareStorage(false); + } catch (SQLException e) { + e.printStackTrace(); + pl.getLogger().severe("---------- Jail Error!!! ----------"); + pl.getLogger().severe("Unable to get a Sql connection, please see the error above and fix the problem."); + return null; + } + return con; + default: + return null; + } + } + + /** Closes the sql connection. */ + public void closeConnection() { + switch(storage) { + case 1: + case 2: + try { + if(con != null) { + con.close(); + con = null; + + pl.debug("Closed the SQL connection."); + } + } catch (SQLException e) { + e.printStackTrace(); + pl.getLogger().severe("---------- Jail Error!!! ----------"); + pl.getLogger().severe("Unable to close the SQL connection."); + } + + break; + default: + break; + } + } + + private void createTables() { + if(con == null) { + pl.debug("The connection was null when we tried to create a table."); + return; + } + + try { + Statement st = con.createStatement(); + switch(storage){ + case 1: + //TODO: yeah big time! + break; + case 2: + String jailCreateCmd = "CREATE TABLE IF NOT EXISTS `" + prefix + "jails` (" + + "`name` VARCHAR(250) NOT NULL," + + "`world` VARCHAR(250) NOT NULL COMMENT 'The world for the top, bottom, and teleport in.'," + + "`top.x` INT NOT NULL COMMENT 'The top coordinate x.'," + + "`top.y` INT NOT NULL COMMENT 'The top coordinate y.'," + + "`top.z` INT NOT NULL COMMENT 'The top coordinate z.'," + + "`bottom.x` INT NOT NULL COMMENT 'The bottom coordinate x.'," + + "`bottom.y` INT NOT NULL COMMENT 'The bottom coordinate y.'," + + "`bottom.z` INT NOT NULL COMMENT 'The bottom coordinate z.'," + + "`tps.in.x` DOUBLE NOT NULL COMMENT 'The teleport in x coordinate.'," + + "`tps.in.y` DOUBLE NOT NULL COMMENT 'The teleport in y coordinate.'," + + "`tps.in.z` DOUBLE NOT NULL COMMENT 'The teleport in z coordinate.'," + + "`tps.in.yaw` DOUBLE NOT NULL COMMENT 'The teleport in yaw.'," + + "`tps.in.pitch` DOUBLE NOT NULL COMMENT 'The teleport in pitch.'," + + "`tps.free.world` VARCHAR(250) NOT NULL COMMENT 'The teleport for being free world.'," + + "`tps.free.x` DOUBLE NOT NULL COMMENT 'The teleport for being free x coordinate.'," + + "`tps.free.y` DOUBLE NOT NULL COMMENT 'The teleport for being free y coordinate.'," + + "`tps.free.z` DOUBLE NOT NULL COMMENT 'The teleport for being free z coordinate.'," + + "`tps.free.yaw` DOUBLE NOT NULL COMMENT 'The teleport for being free yaw.'," + + "`tps.free.pitch` DOUBLE NOT NULL COMMENT 'The teleport for being free pitch.'," + + "PRIMARY KEY (`name`)," + + "UNIQUE INDEX `name_UNIQUE` (`name` ASC))" + + "COMMENT = 'Holds all the jails for the Bukkit Jail plugin.';"; + + //pl.debug(jailCreateCmd); + st.executeUpdate(jailCreateCmd); + + String cellCreateCmd = "CREATE TABLE IF NOT EXISTS `" + prefix + "cells` (" + + "`cellid` INT NOT NULL AUTO_INCREMENT COMMENT 'The cellid for the database.'," + + "`name` VARCHAR(250) NOT NULL COMMENT 'The name of the cell.'," + + "`jail` VARCHAR(250) NOT NULL COMMENT 'The name of the jail the cell is in.'," + + "`tp.x` DOUBLE NOT NULL COMMENT 'The teleport in x coordinate.'," + + "`tp.y` DOUBLE NOT NULL COMMENT 'The teleport in y coordinate.'," + + "`tp.z` DOUBLE NOT NULL COMMENT 'The teleport in z coordinate.'," + + "`tp.yaw` DOUBLE NOT NULL COMMENT 'The teleport in yaw.'," + + "`tp.pitch` DOUBLE NOT NULL COMMENT 'The teleport in pitch.'," + + "`chest.x` INT NULL COMMENT 'The chest x coordinate.'," + + "`chest.y` INT NULL COMMENT 'The chest y coordinate.'," + + "`chest.z` INT NULL COMMENT 'The chest z coordinate.'," + + "`signs` VARCHAR(250) NULL COMMENT 'A string containing the signs.'," + + "PRIMARY KEY (`cellid`)," + + "UNIQUE INDEX `cellid_UNIQUE` (`cellid` ASC))" + + "COMMENT = 'Contains all the cells for the jails.';"; + + //pl.debug(cellCreateCmd); + st.executeUpdate(cellCreateCmd); + + String prisCreateCmd = "CREATE TABLE IF NOT EXISTS `" + prefix + "prisoners` (" + + "`uuid` VARCHAR(36) NOT NULL COMMENT 'The UUID of the prisoner.'," + + "`name` VARCHAR(16) NOT NULL COMMENT 'The name of the prisoner.'," + + "`jail` VARCHAR(250) NOT NULL COMMENT 'The jail the prisoner is in.'," + + "`cell` VARCHAR(250) NULL COMMENT 'The cell the prisoner is in.'," + + "`muted` TINYINT NOT NULL COMMENT 'Whether the player is muted or not.'," + + "`time` INT NOT NULL COMMENT 'The remaining time the prisoner has.'," + + "`offlinePending` TINYINT NOT NULL COMMENT 'Whether the prisoner has something happened to them while they were offline.'," + + "`toBeTransferred` TINYINT NOT NULL COMMENT 'Whether the prisoner is to be transferred.'," + + "`jailer` VARCHAR(250) NOT NULL COMMENT 'The name of the person who jailed them.'," + + "`reason` VARCHAR(250) NOT NULL COMMENT 'The reason they are jailed.'," + + "`inventory` BLOB NULL COMMENT 'Their inventory in base64.'," + + "`armor` BLOB NULL COMMENT 'The armor in base64.'," + + "`previousLocation` VARCHAR(250) NULL COMMENT 'A string of their previous location.'," + + "`previousGameMode` VARCHAR(16) NULL COMMENT 'Their previous gamemode before they were jailed.'," + + "PRIMARY KEY (`uuid`)," + + "UNIQUE INDEX `uuid_UNIQUE` (`uuid` ASC))" + + "COMMENT = 'Contains all the prisoners, in cells and jails.';"; + + //pl.debug(prisCreateCmd); + st.executeUpdate(prisCreateCmd); + + String proCreateCmd = "CREATE TABLE IF NOT EXISTS `" + prefix + "records` (" + + "`recordid` INT NOT NULL AUTO_INCREMENT COMMENT 'Auto generated number for the records database.'," + + "`uuid` VARCHAR(36) NOT NULL COMMENT 'The UUID of the prisoner.'," + + "`username` VARCHAR(16) NOT NULL COMMENT 'The username of the prisoner.'," + + "`jailer` VARCHAR(250) NOT NULL COMMENT 'The name of the person who jailed the prisoner.'," + + "`date` VARCHAR(32) NOT NULL COMMENT 'A string of the date.'," + + "`time` INT NOT NULL COMMENT 'The milliseconds they were jailed for.'," + + "`reason` VARCHAR(250) NOT NULL COMMENT 'The reason they were jailed for.'," + + "PRIMARY KEY (`recordid`)," + + "UNIQUE INDEX `recordid_UNIQUE` (`recordid` ASC))" + + "COMMENT = 'Holds a history of all the times prisoners have been jailed.'"; + + //pl.debug(proCreateCmd); + st.executeUpdate(proCreateCmd); + st.close(); + break; + default: + break; + } + } catch (SQLException e) { + e.printStackTrace(); + pl.getLogger().severe("---------- Jail Error!!! ----------"); + pl.getLogger().severe("Error while creating the tables, please check the error and fix what is wrong."); + } + } + + /** + * Loads the jails, this should only be called after {@link #prepareStorage(boolean)}. + */ + public void loadJails() { + switch(storage) { + case 1: + case 2: + //load the jails from mysql and sqlite + long st = System.currentTimeMillis(); + + try { + if(con == null) this.prepareStorage(false); + PreparedStatement ps = con.prepareStatement("SELECT * FROM " + prefix + "jails"); + ResultSet set = ps.executeQuery(); + + while(set.next()) { + Jail j = new Jail(pl, set.getString("name")); + + j.setWorld(set.getString("world")); + j.setMaxPoint(new int[] { set.getInt("top.x"), set.getInt("top.y"), set.getInt("top.z") }); + j.setMinPoint(new int[] { set.getInt("bottom.x"), set.getInt("bottom.y"), set.getInt("bottom.z") }); + j.setTeleportIn(new Location(pl.getServer().getWorld(j.getWorldName()), set.getDouble("tps.in.x"), + set.getDouble("tps.in.y"), set.getDouble("tps.in.z"), + set.getFloat("tps.in.yaw"), set.getFloat("tps.in.pitch"))); + j.setTeleportFree(new Location(pl.getServer().getWorld(j.getWorldName()), set.getDouble("tps.free.x"), + set.getDouble("tps.free.y"), set.getDouble("tps.free.z"), + set.getFloat("tps.free.yaw"), set.getFloat("tps.free.pitch"))); + pl.getJailManager().addJail(j, false); + } + + set.close(); + ps.close(); + } catch (SQLException e) { + e.printStackTrace(); + pl.getLogger().severe("---------- Jail Error!!! ----------"); + pl.getLogger().severe("Error while loading the jails, please check the error and fix what is wrong."); + } + + //This list contains an integer which refers to the cellid column in sql + //this list only gets populated if there are cells which reference a jail + //that doesn't exist anymore + List cellsToRemove = new LinkedList(); + + try { + if(con == null) this.prepareStorage(false); + PreparedStatement ps = con.prepareStatement("SELECT * FROM " + prefix + "cells"); + ResultSet set = ps.executeQuery(); + + while(set.next()) { + Jail j = pl.getJailManager().getJail(set.getString("jail")); + + if(j != null) { + Cell c = new Cell(set.getString("name")); + c.setTeleport(new SimpleLocation(j.getWorldName(), set.getDouble("tp.x"), set.getDouble("tp.y"), set.getDouble("tp.z"), + set.getFloat("tp.yaw"), set.getFloat("tp.pitch"))); + + c.setChestLocation(new Location(j.getWorld(), set.getInt("chest.x"), set.getInt("chest.y"), set.getInt("chest.z"))); + + String cSigns = set.getString("signs"); + if(!cSigns.isEmpty()) { + String[] signs = cSigns.split(";"); + for(String s : signs) { + String[] co = s.split(","); + c.addSign(new SimpleLocation(co[0], co[1], co[2], co[3])); + } + } + + + j.addCell(c, false); + }else { + cellsToRemove.add(set.getInt("cellid")); + } + } + + pl.debug("There are " + cellsToRemove.size() + " cells we need to remove due to being invalid."); + + set.close(); + ps.close(); + } catch (SQLException e) { + e.printStackTrace(); + pl.getLogger().severe("---------- Jail Error!!! ----------"); + pl.getLogger().severe("Error while loading all of the cells, please check the error and fix what is wrong."); + } + + //Remove the invalid prisoners + if(cellsToRemove.size() != 0) { + String names = ""; + for(int c : cellsToRemove) { + if(names.isEmpty()) names = "'" + c + "'"; + else names += "," + "'" + c + "'"; + } + + try { + PreparedStatement cds = con.prepareStatement("delete from " + prefix + "cells where cellid in (" + names + ");"); + + pl.debug("Deleting old cells: 'delete from " + prefix + "cells where cellid in (" + names + ");'"); + + int count = cds.executeUpdate(); + pl.getLogger().info("Deleted " + count + " old cells which referenced a jail no longer valid: " + names); + cds.close(); + } catch (SQLException e) { + e.printStackTrace(); + pl.getLogger().severe("---------- Jail Error!!! ----------"); + pl.getLogger().severe("Error while deleting the old cells which don't have a valid jail, please check the error and fix what is wrong."); + } + } + + //This list contains a string which refers to the name of the prisoner in sql + //this list only gets populated if there are prisoners which reference a jail + //that doesn't exist anymore + List prisonersToRemove = new LinkedList(); + + try { + if(con == null) this.prepareStorage(false); + PreparedStatement ps = con.prepareStatement("SELECT * FROM " + prefix + "prisoners"); + ResultSet set = ps.executeQuery(); + + while(set.next()) { + Jail j = pl.getJailManager().getJail(set.getString("jail")); + + if(j != null) { + String cellname = set.getString("cell"); + Cell c = j.getCell(cellname); + + Prisoner p = new Prisoner(set.getString("uuid"), set.getString("name"), set.getBoolean("muted"), set.getLong("time"), set.getString("jailer"), set.getString("reason")); + p.setOfflinePending(set.getBoolean("offlinePending")); + p.setToBeTransferred(set.getBoolean("toBeTransferred")); + Blob inv = set.getBlob("inventory"); + p.setInventory(new String(inv.getBytes(1, (int) inv.length()))); + Blob ar = set.getBlob("armor"); + p.setArmor(new String(ar.getBytes(1, (int)ar.length()))); + p.setPreviousPosition(set.getString("previousLocation")); + p.setPreviousGameMode(set.getString("previousGameMode")); + + if(cellname == null || cellname.isEmpty()) { + j.addPrisoner(p); + }else if(c != null) { + c.setPrisoner(p); + }else { + //the prisoner is assigned to a cell which doesn't exist, so just put them into the jail + j.addPrisoner(p); + } + } else { + //if the jail doesn't exist, do the same as the cells + prisonersToRemove.add(set.getString("name")); + } + } + + set.close(); + ps.close(); + + pl.debug("There are " + prisonersToRemove.size() + " prisoners we need to remove due to being invalid."); + } catch (SQLException e) { + e.printStackTrace(); + pl.getLogger().severe("---------- Jail Error!!! ----------"); + pl.getLogger().severe("Error while loading all of the prisoners, please check the error and fix what is wrong."); + } + + //Remove the invalid prisoners + if(prisonersToRemove.size() != 0) { + String names = ""; + for(String s : prisonersToRemove) { + if(names.isEmpty()) names = "'" + s + "'"; + else names += "," + "'" + s + "'"; + } + + try { + PreparedStatement pds = con.prepareStatement("delete from " + prefix + "prisoners where name in (" + names + ");"); + + pl.debug("Deleting old prisoners: 'delete from " + prefix + "prisoners where name in (" + names + ");'"); + + int count = pds.executeUpdate(); + pl.getLogger().info("Deleted " + count + " old prisoners which referenced a jail no longer valid: " + names); + pds.close(); + } catch (SQLException e) { + e.printStackTrace(); + pl.getLogger().severe("---------- Jail Error!!! ----------"); + pl.getLogger().severe("Error while deleting the old prisoners which don't have a valid jail, please check the error and fix what is wrong."); + } + } + + pl.debug("Took " + (System.currentTimeMillis() - st) + " millis."); + break; + default: + //load the jails from flatfile + if(flat.isConfigurationSection("jails")) { + Set jails = flat.getConfigurationSection("jails").getKeys(false); + if(!jails.isEmpty()) { + for(String name : jails) { + loadJailFromFlatFile(name); + } + } + } + break; + } + + int js = pl.getJailManager().getJails().size(); + pl.getLogger().info("Loaded " + js + (js == 1 ? " jail." : " jails.")); + + int cs = pl.getJailManager().getAllCells().size(); + pl.getLogger().info("Loaded " + cs + (cs == 1 ? " cell." : " cells.")); + + int ps = pl.getJailManager().getAllPrisoners().size(); + pl.getLogger().info("Loaded " + ps + (ps == 1 ? " prisoner." : " prisoners.")); + } + + private void loadJailFromFlatFile(String name) { + String node = "jails." + name + "."; + String cNode = node + "cells."; + Jail j = new Jail(pl, name); + + j.setWorld(flat.getString(node + "world")); + j.setMaxPoint(new int[] {flat.getInt(node + "top.x"), flat.getInt(node + "top.y"), flat.getInt(node + "top.z")}); + j.setMinPoint(new int[] {flat.getInt(node + "bottom.x"), flat.getInt(node + "bottom.y"), flat.getInt(node + "bottom.z")}); + + j.setTeleportIn(new Location( + pl.getServer().getWorld(flat.getString(node + "world")), + flat.getDouble(node + "tps.in.x"), + flat.getDouble(node + "tps.in.y"), + flat.getDouble(node + "tps.in.z"), + (float) flat.getDouble(node + "tps.in.yaw"), + (float) flat.getDouble(node + "tps.in.pitch"))); + j.setTeleportFree(new Location( + pl.getServer().getWorld(flat.getString(node + "world")), + flat.getDouble(node + "tps.free.x"), + flat.getDouble(node + "tps.free.y"), + flat.getDouble(node + "tps.free.z"), + (float) flat.getDouble(node + "tps.free.yaw"), + (float) flat.getDouble(node + "tps.free.pitch"))); + + if(flat.isConfigurationSection(node + "cells")) { + Set cells = flat.getConfigurationSection(node + "cells").getKeys(false); + if(!cells.isEmpty()) { + for(String cell : cells) { + Cell c = new Cell(cell); + String cellNode = cNode + cell + "."; + + c.setTeleport(new SimpleLocation(j.getTeleportIn().getWorld().getName(), + flat.getDouble(cellNode + "tp.x"), + flat.getDouble(cellNode + "tp.y"), + flat.getDouble(cellNode + "tp.z"), + (float) flat.getDouble(cellNode + "tp.yaw"), + (float) flat.getDouble(cellNode + "tp.pitch"))); + c.setChestLocation(new Location(j.getTeleportIn().getWorld(), + flat.getInt(cellNode + "chest.x"), + flat.getInt(cellNode + "chest.y"), + flat.getInt(cellNode + "chest.z"))); + + for(String sign : flat.getStringList(cellNode + "signs")) { + String[] arr = sign.split(","); + c.addSign(new SimpleLocation(arr[0], + Double.valueOf(arr[1]), + Double.valueOf(arr[2]), + Double.valueOf(arr[3]), + Float.valueOf(arr[4]), + Float.valueOf(arr[5]))); + } + + if(flat.contains(cellNode + "prisoner")) { + Prisoner p = new Prisoner(flat.getString(cellNode + "prisoner.uuid"), + flat.getString(cellNode + "prisoner.name"), + flat.getBoolean(cellNode + "prisoner.muted"), + flat.getLong(cellNode + "prisoner.time"), + flat.getString(cellNode + "prisoner.jailer"), + flat.getString(cellNode + "prisoner.reason")); + p.setOfflinePending(flat.getBoolean(cellNode + "prisoner.offlinePending")); + p.setToBeTransferred(flat.getBoolean(cellNode + "prisoner.toBeTransferred")); + p.setPreviousPosition(flat.getString(cellNode + "prisoner.previousLocation")); + p.setPreviousGameMode(flat.getString(cellNode + "prisoner.previousGameMode")); + p.setInventory(flat.getString(cellNode + "prisoner.inventory", "")); + p.setArmor(flat.getString(cellNode + "prisoner.armor", "")); + c.setPrisoner(p); + } + + j.addCell(c, false); + } + } + } + + if(flat.isConfigurationSection(node + "prisoners")) { + Set prisoners = flat.getConfigurationSection(node + "prisoners").getKeys(false); + if(!prisoners.isEmpty()) { + for(String uuid : prisoners) { + String pNode = node + "prisoners." + uuid + "."; + Prisoner pris = new Prisoner(uuid, + flat.getString(pNode + "name"), + flat.getBoolean(pNode + "muted"), + flat.getLong(pNode + "time"), + flat.getString(pNode + "jailer"), + flat.getString(pNode + "reason")); + pris.setOfflinePending(flat.getBoolean(pNode + "offlinePending")); + pris.setToBeTransferred(flat.getBoolean(pNode + "toBeTransferred")); + pris.setPreviousPosition(flat.getString(pNode + "previousLocation")); + pris.setPreviousGameMode(flat.getString(pNode + "previousGameMode")); + pris.setInventory(flat.getString(pNode + "inventory", "")); + pris.setArmor(flat.getString(pNode + "armor", "")); + j.addPrisoner(pris); + } + } + } + + if(pl.getServer().getWorld(j.getWorldName()) != null) { + pl.getJailManager().addJail(j, false); + pl.getLogger().info("Loaded jail " + j.getName() + " with " + j.getAllPrisoners().size() + " prisoners and " + j.getCellCount() + " cells."); + } else + pl.getLogger().severe("Failed to load the jail " + j.getName() + " as the world '" + j.getWorldName() + "' does not exist (is null). Did you remove this world?"); + } + + /** Saves everything about a jail, don't usually call this. */ + public void saveEverything() { + long st = System.currentTimeMillis(); + + for(Jail j : pl.getJailManager().getJails()) { + saveJail(j); + + for(Cell c : j.getCells()) { + saveCell(j, c); + } + } + + pl.debug("Saving everything took " + (System.currentTimeMillis() - st) + " millis."); + } + + /** + * Saves the provided {@link Jail jail} to the storage system we are using. + * + * @param j The jail to save. + */ + public void saveJail(Jail j) { + switch(storage) { + case 1: + case 2: + long st = System.currentTimeMillis(); + + try { + if(con == null) this.prepareStorage(false); + PreparedStatement ps = con.prepareStatement("REPLACE INTO " + + prefix + "jails (`name`, `world`, `top.x`, `top.y`, `top.z`, `bottom.x`, `bottom.y`," + + "`bottom.z`, `tps.in.x`, `tps.in.y`, `tps.in.z`, `tps.in.yaw`, `tps.in.pitch`," + + "`tps.free.world`, `tps.free.x`, `tps.free.y`, `tps.free.z`, `tps.free.yaw`, `tps.free.pitch`)" + + "VALUES (?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)"); + + ps.setString(1, j.getName()); + ps.setString(2, j.getWorldName()); + ps.setInt(3, j.getMaxPoint().getBlockX()); + ps.setInt(4, j.getMaxPoint().getBlockY()); + ps.setInt(5, j.getMaxPoint().getBlockZ()); + ps.setInt(6, j.getMinPoint().getBlockX()); + ps.setInt(7, j.getMinPoint().getBlockY()); + ps.setInt(8, j.getMinPoint().getBlockZ()); + ps.setDouble(9, j.getTeleportIn().getX()); + ps.setDouble(10, j.getTeleportIn().getY()); + ps.setDouble(11, j.getTeleportIn().getZ()); + ps.setDouble(12, j.getTeleportIn().getYaw()); + ps.setDouble(13, j.getTeleportIn().getPitch()); + ps.setString(14, j.getTeleportFree().getWorld().getName()); + ps.setDouble(15, j.getTeleportFree().getX()); + ps.setDouble(16, j.getTeleportFree().getY()); + ps.setDouble(17, j.getTeleportFree().getZ()); + ps.setDouble(18, j.getTeleportFree().getYaw()); + ps.setDouble(19, j.getTeleportFree().getPitch()); + + ps.executeUpdate(); + ps.close(); + } catch (SQLException e) { + e.printStackTrace(); + pl.getLogger().severe("---------- Jail Error!!! ----------"); + pl.getLogger().severe("Error while saving the Jail '" + j.getName() + "' (not updating the prisoners), please check the error and fix what is wrong."); + } + + try { + if(con == null) this.prepareStorage(false); + + for(Cell c : j.getCells()) { + if(c.hasPrisoner()) { + Prisoner p = c.getPrisoner(); + PreparedStatement pPS = con.prepareStatement("REPLACE INTO `" + prefix + "prisoners` (`uuid`, `name`, `jail`, `cell`, `muted`, `time`," + + "`offlinePending`, `toBeTransferred`, `jailer`, `reason`, `inventory`, `armor`, `previousLocation`, `previousGameMode`)" + + "VALUES (?,?,?,?,?,?,?,?,?,?,?,?,?,?)"); + pPS.setString(1, p.getUUID().toString()); + pPS.setString(2, p.getLastKnownName()); + pPS.setString(3, j.getName()); + pPS.setString(4, c.getName()); + pPS.setBoolean(5, p.isMuted()); + pPS.setFloat(6, p.getRemainingTime()); + pPS.setBoolean(7, p.isOfflinePending()); + pPS.setBoolean(8, p.isToBeTransferred()); + pPS.setString(9, p.getJailer()); + pPS.setString(10, p.getReason()); + pPS.setBytes(11, p.getInventory().getBytes()); + pPS.setBytes(12, p.getArmor().getBytes()); + pPS.setString(13, p.getPreviousLocationString()); + pPS.setString(14, p.getPreviousGameMode().toString()); + + pPS.executeUpdate(); + pPS.close(); + } + } + } catch (SQLException e) { + e.printStackTrace(); + pl.getLogger().severe("---------- Jail Error!!! ----------"); + pl.getLogger().severe("Error while saving the cells of the Jail '" + j.getName() + "', please check the error and fix what is wrong."); + } + + try { + if(con == null) this.prepareStorage(false); + + for(Prisoner p : j.getPrisonersNotInCells().values()) { + PreparedStatement pPS = con.prepareStatement("REPLACE INTO `" + prefix + "prisoners` (`uuid`, `name`, `jail`, `cell`, `muted`, `time`," + + "`offlinePending`, `toBeTransferred`, `jailer`, `reason`, `inventory`, `armor`, `previousLocation`, `previousGameMode`) VALUES (?,?,?,?,?,?,?,?,?,?,?,?,?,?)"); + pPS.setString(1, p.getUUID().toString()); + pPS.setString(2, p.getLastKnownName()); + pPS.setString(3, j.getName()); + pPS.setString(4, ""); + pPS.setBoolean(5, p.isMuted()); + pPS.setFloat(6, p.getRemainingTime()); + pPS.setBoolean(7, p.isOfflinePending()); + pPS.setBoolean(8, p.isToBeTransferred()); + pPS.setString(9, p.getJailer()); + pPS.setString(10, p.getReason()); + pPS.setBytes(11, p.getInventory().getBytes()); + pPS.setBytes(12, p.getArmor().getBytes()); + pPS.setString(13, p.getPreviousLocationString()); + pPS.setString(14, p.getPreviousGameMode().toString()); + + pPS.executeUpdate(); + pPS.close(); + } + } catch (SQLException e) { + e.printStackTrace(); + pl.getLogger().severe("---------- Jail Error!!! ----------"); + pl.getLogger().severe("Error while saving the prisoners of the Jail '" + j.getName() + "', please check the error and fix what is wrong."); + } + + pl.debug("Took " + (System.currentTimeMillis() - st) + " millis."); + break; + default: + if(flat != null) { + String node = "jails." + j.getName() + "."; + + //Corners + flat.set(node + "world", j.getWorldName()); + flat.set(node + "top.x", j.getMaxPoint().getBlockX()); + flat.set(node + "top.y", j.getMaxPoint().getBlockY()); + flat.set(node + "top.z", j.getMaxPoint().getBlockZ()); + flat.set(node + "bottom.x", j.getMinPoint().getBlockX()); + flat.set(node + "bottom.y", j.getMinPoint().getBlockY()); + flat.set(node + "bottom.z", j.getMinPoint().getBlockZ()); + + //Tele in + flat.set(node + "tps.in.x", j.getTeleportIn().getX()); + flat.set(node + "tps.in.y", j.getTeleportIn().getY()); + flat.set(node + "tps.in.z", j.getTeleportIn().getZ()); + flat.set(node + "tps.in.yaw", j.getTeleportIn().getYaw()); + flat.set(node + "tps.in.pitch", j.getTeleportIn().getPitch()); + + //Tele out + flat.set(node + "tps.free.world", j.getTeleportFree().getWorld().getName()); + flat.set(node + "tps.free.x", j.getTeleportFree().getX()); + flat.set(node + "tps.free.y", j.getTeleportFree().getY()); + flat.set(node + "tps.free.z", j.getTeleportFree().getZ()); + flat.set(node + "tps.free.yaw", j.getTeleportFree().getYaw()); + flat.set(node + "tps.free.pitch", j.getTeleportFree().getPitch()); + + //Set all the cells to nothing, then we save each of them so no cells are left behind + flat.set(node + "cells", null); + for(Cell c : j.getCells()) { + String cNode = node + "cells." + c.getName() + "."; + + if(c.getTeleport() != null) { + flat.set(cNode + "tp.x", c.getTeleport().getX()); + flat.set(cNode + "tp.y", c.getTeleport().getY()); + flat.set(cNode + "tp.z", c.getTeleport().getZ()); + flat.set(cNode + "tp.yaw", c.getTeleport().getYaw()); + flat.set(cNode + "tp.pitch", c.getTeleport().getPitch()); + } + + if(c.getChestLocation() != null) { + flat.set(cNode + "chest.x", c.getChestLocation().getBlockX()); + flat.set(cNode + "chest.y", c.getChestLocation().getBlockY()); + flat.set(cNode + "chest.z", c.getChestLocation().getBlockZ()); + } + + String[] signs = new String[c.getSigns().size()]; + int count = 0; + for(SimpleLocation loc : c.getSigns()) { + signs[count] = loc.toString(); + count++; + } + + flat.set(cNode + "signs", signs); + + if(c.getPrisoner() != null) { + Prisoner p = c.getPrisoner(); + flat.set(cNode + "prisoner.uuid", p.getUUID().toString()); + flat.set(cNode + "prisoner.name", p.getLastKnownName()); + flat.set(cNode + "prisoner.muted", p.isMuted()); + flat.set(cNode + "prisoner.time", p.getRemainingTime()); + flat.set(cNode + "prisoner.offlinePending", p.isOfflinePending()); + flat.set(cNode + "prisoner.toBeTransferred", p.isToBeTransferred()); + flat.set(cNode + "prisoner.jailer", p.getJailer()); + flat.set(cNode + "prisoner.reason", p.getReason()); + flat.set(cNode + "prisoner.inventory", p.getInventory()); + flat.set(cNode + "prisoner.armor", p.getArmor()); + if(p.getPreviousLocationString() != null) + flat.set(cNode + "prisoner.previousLocation", p.getPreviousLocationString()); + if(p.getPreviousGameMode() != null) + flat.set(cNode + "prisoner.previousGameMode", p.getPreviousGameMode().toString()); + } + } + + //Null all the prisoners out before we save them again, this way no prisoners are left behind + flat.set(node + "prisoners", null); + for(Prisoner p : j.getPrisonersNotInCells().values()) { + String pNode = node + "prisoners." + p.getUUID().toString() + "."; + flat.set(pNode + "name", p.getLastKnownName()); + flat.set(pNode + "muted", p.isMuted()); + flat.set(pNode + "time", p.getRemainingTime()); + flat.set(pNode + "offlinePending", p.isOfflinePending()); + flat.set(pNode + "toBeTransferred", p.isToBeTransferred()); + flat.set(pNode + "jailer", p.getJailer()); + flat.set(pNode + "reason", p.getReason()); + flat.set(pNode + "inventory", p.getInventory()); + flat.set(pNode + "armor", p.getArmor()); + if(p.getPreviousLocationString() != null) + flat.set(pNode + "previousLocation", p.getPreviousLocationString()); + if(p.getPreviousGameMode() != null) + flat.set(pNode + "previousGameMode", p.getPreviousGameMode().toString()); + } + + try { + flat.save(new File(pl.getDataFolder(), "data.yml")); + } catch (IOException e) { + pl.getLogger().severe("Unable to save the Jail data: " + e.getMessage()); + } + }else { + pl.getLogger().severe("Storage not enabled, could not save the jail " + j.getName()); + } + break; + } + } + + public void saveCell(Jail j, Cell c) { + switch(storage) { + case 1: + case 2: + try { + if(con == null) this.prepareStorage(false); + + PreparedStatement cPS = con.prepareStatement("INSERT INTO `" + prefix + "cells` (`name`, `jail`, `tp.x`, `tp.y`, `tp.z`, `tp.yaw`," + + "`tp.pitch`, `chest.x`, `chest.y`, `chest.z`, `signs`) VALUES (?,?,?,?,?,?,?,?,?,?,?)"); + + cPS.setString(1, c.getName()); + cPS.setString(2, j.getName()); + cPS.setDouble(3, c.getTeleport().getX()); + cPS.setDouble(4, c.getTeleport().getY()); + cPS.setDouble(5, c.getTeleport().getZ()); + cPS.setDouble(6, c.getTeleport().getYaw()); + cPS.setDouble(7, c.getTeleport().getPitch()); + + if(c.hasChest()) { + cPS.setInt(8, c.getChestLocation().getBlockX()); + cPS.setInt(9, c.getChestLocation().getBlockY()); + cPS.setInt(10, c.getChestLocation().getBlockZ()); + }else { + cPS.setNull(8, java.sql.Types.INTEGER); + cPS.setNull(9, java.sql.Types.INTEGER); + cPS.setNull(10, java.sql.Types.INTEGER); + } + + cPS.setString(11, c.getSignString()); + + cPS.executeUpdate(); + cPS.close(); + + if(c.hasPrisoner()) { + Prisoner p = c.getPrisoner(); + PreparedStatement pPS = con.prepareStatement("REPLACE INTO `" + prefix + "prisoners` (`uuid`, `name`, `jail`, `cell`, `muted`, `time`," + + "`offlinePending`, `toBeTransferred`, `jailer`, `reason`, `inventory`, `armor`, `previousLocation`, `previousGameMode`) VALUES (?,?,?,?,?,?,?,?,?,?,?,?,?,?)"); + pPS.setString(1, p.getUUID().toString()); + pPS.setString(2, p.getLastKnownName()); + pPS.setString(3, j.getName()); + pPS.setString(4, c.getName()); + pPS.setBoolean(5, p.isMuted()); + pPS.setFloat(6, p.getRemainingTime()); + pPS.setBoolean(7, p.isOfflinePending()); + pPS.setBoolean(8, p.isToBeTransferred()); + pPS.setString(9, p.getJailer()); + pPS.setString(10, p.getReason()); + pPS.setBytes(11, p.getInventory().getBytes()); + pPS.setBytes(12, p.getArmor().getBytes()); + pPS.setString(13, p.getPreviousLocationString()); + pPS.setString(14, p.getPreviousGameMode().toString()); + + pPS.executeUpdate(); + pPS.close(); + } + } catch (SQLException e) { + e.printStackTrace(); + pl.getLogger().severe("---------- Jail Error!!! ----------"); + pl.getLogger().severe("Error while saving the cell '" + c.getName() + "' of the Jail '" + j.getName() + "', please check the error and fix what is wrong."); + } + + break; + default: + this.saveJail(j); + break; + } + } + + /** + * Removes the prisoner from the storage system. + * + * @param j the jail which the prisoner is in. + * @param p the prisoner data + */ + public void removePrisoner(Jail j, Prisoner p) { + this.removePrisoner(j, null, p); + } + + /** + * Removes the prisoner from the storage system. + * + * @param j the jail which the prisoner is in. + * @param c the cell which the prisoner is in, null if none + * @param p the prisoner data + */ + public void removePrisoner(Jail j, Cell c, Prisoner p) { + switch(storage) { + case 1: + case 2: + try { + PreparedStatement pp = con.prepareStatement("delete from `" + prefix + "prisoners` where uuid = ? limit 1;"); + pp.setString(1, p.getUUID().toString()); + + pl.debug("Removing " + p.getLastKnownName() + " (" + p.getUUID().toString() + ") from MySQL database."); + + pp.executeUpdate(); + pp.close(); + } catch (SQLException e) { + e.printStackTrace(); + pl.getLogger().severe("---------- Jail Error!!! ----------"); + pl.getLogger().severe("Error while removing the prisoner '" + p.getLastKnownName() + "' from the database, please check the error and fix what is wrong."); + } + break; + default: + if(c == null) + flat.set("jails." + j.getName() + ".prisoners." + p.getUUID().toString(), null); + else + flat.set("jails." + j.getName() + "." + c.getName() + ".prisoner", null); + + try { + flat.save(new File(pl.getDataFolder(), "data.yml")); + } catch (IOException e) { + pl.getLogger().severe("Unable to save the Jail data: " + e.getMessage()); + } + break; + } + } + + /** + * Removes the provided cell from the jail. + * + * @param j instance of the jail the cell is in + * @param c instance of the cell we are removing + */ + public void removeCell(Jail j, Cell c) { + //Clear the inventory before we delete it + if(c.hasChest()) c.getChest().getInventory().clear(); + + //transfer the prisoner if it has one + if(c.hasPrisoner()) { + pl.getLogger().warning("Removing of cell '" + c.getName() + "' from the jail '" + j.getName() + "' failed as it has a prisoner."); + return; + } + + switch(storage) { + case 1: + case 2: + try { + PreparedStatement p = con.prepareStatement("delete from `" + prefix + "cells` where name = ? and jail = ? limit 1;"); + p.setString(1, c.getName()); + p.setString(2, j.getName()); + + p.executeUpdate(); + p.close(); + } catch (SQLException e) { + e.printStackTrace(); + pl.getLogger().severe("---------- Jail Error!!! ----------"); + pl.getLogger().severe("Error while removing the cell '" + c.getName() + "' from the Jail '" + j.getName() + "', please check the error and fix what is wrong."); + } + break; + default: + if(flat != null) { + flat.set("jails." + j.getName() + "cells." + c.getName(), null); + + try { + flat.save(new File(pl.getDataFolder(), "data.yml")); + } catch (IOException e) { + e.printStackTrace(); + pl.getLogger().severe("---------- Jail Error!!! ----------"); + pl.getLogger().severe("Removing of the cell '" + c.getName() + "' from the jail '" + j.getName() + "' errored out while on saving."); + } + } + break; + } + } + + /** + * Removes a jail from the storage system. + * + * @param j the jail instance to remove. + */ + public void removeJail(Jail j) { + String name = j.getName(); + + switch(storage) { + case 1: + case 2: + for(Cell c : j.getCells()) { + removeCell(j, c); + } + + try { + PreparedStatement p = con.prepareStatement("delete from `" + prefix + "jails` where name = ?"); + p.setString(1, name); + + p.executeUpdate(); + p.close(); + } catch (SQLException e) { + e.printStackTrace(); + pl.getLogger().severe("---------- Jail Error!!! ----------"); + pl.getLogger().severe("Error while removing the Jail '" + j.getName() + "', please check the error and fix what is wrong."); + } + break; + default: + flat.set("jails." + name, null); + + try { + flat.save(new File(pl.getDataFolder(), "data.yml")); + } catch (IOException e) { + e.printStackTrace(); + pl.getLogger().severe("---------- Jail Error!!! ----------"); + pl.getLogger().severe("Removing of the jail '" + j.getName() + "' errored out while on saving."); + } + break; + } + } + + /** + * Adds an entry to the database/file for the user, logging when they was jailed. + * + * @param uuid of the player + * @param username of the player + * @param jailer who jailed them + * @param date string of when they are jailed + * @param time of the player's sentence + * @param reason the player is jailed + */ + public void addRecordEntry(String uuid, String username, String jailer, String date, long time, String reason) { + switch(storage) { + case 1: + break; + case 2: + try { + PreparedStatement p = con.prepareStatement("insert into `" + prefix + "records` (`uuid`, `username`, `jailer`, `date`, `time`, `reason`) VALUES (?,?,?,?,?,?);"); + p.setString(1, uuid); + p.setString(2, username); + p.setString(3, jailer); + p.setString(4, date); + p.setLong(5, time); + p.setString(6, reason); + + p.executeUpdate(); + p.close(); + } catch (SQLException e) { + e.printStackTrace(); + pl.getLogger().severe("---------- Jail Error!!! ----------"); + pl.getLogger().severe("Error while adding a record entry for '" + username + "', please check the error and fix what is wrong."); + } + break; + default: + if(records == null) records = YamlConfiguration.loadConfiguration(new File(pl.getDataFolder(), "records.yml")); + + List previous = records.getStringList(uuid); + previous.add(this.getLanguageString(LangString.RECORDENTRY, new String[] { date, username, jailer, String.valueOf(time), reason, uuid })); + + records.set(username, previous); + + try { + records.save(new File(pl.getDataFolder(), "records.yml")); + } catch (IOException e) { + e.printStackTrace(); + pl.getLogger().severe("---------- Jail Error!!! ----------"); + pl.getLogger().severe("Saving the records.yml file failed while putting an entry in for '" + username + "'."); + } + break; + } + } + + /** + * Gets all the record entries for the given player. + * + * @param username the of the prisoner's records to get. + * @return A List of strings containing the record entries. + * @deprecated This calls getOfflinePlayer which is a blocking call from Bukkit + */ + public List getRecordEntries(String username) { + UUID uuid = pl.getServer().getOfflinePlayer(username).getUniqueId(); + List entries = new ArrayList(); + + switch(storage) { + case 1: + break; + case 2: + try { + PreparedStatement ps = con.prepareStatement("SELECT * FROM " + prefix + "records where uuid = ?"); + ps.setString(1, uuid.toString()); + ResultSet set = ps.executeQuery(); + + while(set.next()) { + entries.add(this.getLanguageString(LangString.RECORDENTRY, + new String[] { set.getString("date"), set.getString("username"), set.getString("jailer"), String.valueOf(set.getLong("time")), set.getString("reason") })); + } + + set.close(); + ps.close(); + } catch (SQLException e) { + e.printStackTrace(); + pl.getLogger().severe("---------- Jail Error!!! ----------"); + pl.getLogger().severe("Error while getting all the record entries for '" + uuid + "', please check the error and fix what is wrong."); + } + break; + default: + if(records == null) records = YamlConfiguration.loadConfiguration(new File(pl.getDataFolder(), "records.yml")); + + entries = records.getStringList(uuid.toString()); + break; + } + + return entries; + } +} diff --git a/src/main/java/com/graywolf336/jail/JailMain.java b/src/main/java/com/graywolf336/jail/JailMain.java index 8ee024d..c07cfb2 100644 --- a/src/main/java/com/graywolf336/jail/JailMain.java +++ b/src/main/java/com/graywolf336/jail/JailMain.java @@ -1,271 +1,271 @@ -package com.graywolf336.jail; - -import org.bukkit.command.Command; -import org.bukkit.command.CommandSender; -import org.bukkit.plugin.PluginManager; -import org.bukkit.plugin.java.JavaPlugin; - -import com.graywolf336.jail.beans.Jail; -import com.graywolf336.jail.beans.Prisoner; -import com.graywolf336.jail.command.CommandHandler; -import com.graywolf336.jail.command.JailHandler; -import com.graywolf336.jail.enums.Settings; -import com.graywolf336.jail.legacy.LegacyManager; -import com.graywolf336.jail.listeners.BlockListener; -import com.graywolf336.jail.listeners.CacheListener; -import com.graywolf336.jail.listeners.EntityListener; -import com.graywolf336.jail.listeners.HandCuffListener; -import com.graywolf336.jail.listeners.JailingListener; -import com.graywolf336.jail.listeners.MoveProtectionListener; -import com.graywolf336.jail.listeners.PlayerListener; -import com.graywolf336.jail.listeners.ProtectionListener; - -/** - * The main class for this Jail plugin, holds instances of vital classes. - * - * @author graywolf336 - * @since 1.x.x - * @version 3.0.0 - */ -public class JailMain extends JavaPlugin { - private CommandHandler cmdHand; - private HandCuffManager hcm; - private JailHandler jh; - private JailIO io; - private JailManager jm; - private JailPayManager jpm; - private JailStickManager jsm; - private JailTimer jt; - private PrisonerManager pm; - private ScoreBoardManager sbm; - private MoveProtectionListener mpl; - private boolean debug = false; - - public void onEnable() { - loadConfig(); - - debug = getConfig().getBoolean(Settings.DEBUG.getPath()); - if(debug) getLogger().info("Debugging enabled."); - - hcm = new HandCuffManager(); - jm = new JailManager(this); - - //Try to load the old stuff before we load anything, esp the storage stuff - LegacyManager lm = new LegacyManager(this); - if(lm.doWeNeedToConvert()) { - lm.convertOldData(); - if(!lm.wasAnythingConverted()) getLogger().severe("We was unable to convert some, or all, of the old data."); - } - - io = new JailIO(this); - io.loadLanguage(); - - //If the prepareStorage returns false, we need to disable the plugin - if(!io.prepareStorage(true)) { - this.getLogger().severe("An error occured while preparing the connection to the storage, please see the error above for more information."); - this.getServer().getPluginManager().disablePlugin(this); - return; - } - - io.loadJails(); - - //If we converted something, let's save EVERYTHING including the cells - if(lm.wasAnythingConverted()) { - io.saveEverything(); - } - - cmdHand = new CommandHandler(this); - jh = new JailHandler(this); - pm = new PrisonerManager(this); - jsm = new JailStickManager(this); - - PluginManager plm = this.getServer().getPluginManager(); - plm.registerEvents(new BlockListener(this), this); - plm.registerEvents(new CacheListener(this), this); - plm.registerEvents(new EntityListener(this), this); - plm.registerEvents(new HandCuffListener(this), this); - plm.registerEvents(new JailingListener(this), this); - plm.registerEvents(new PlayerListener(this), this); - plm.registerEvents(new ProtectionListener(this), this); - - //Only register the move protection listener if this is enabled in the - //config when we first start the plugin. The reason for this change is - //that the move event is called a ton of times per single move and so - //not registering this event listener will hopefully safe some performance. - //But doing this also forces people to restart their server if they to - //enable it after disabling it. - if(getConfig().getBoolean(Settings.MOVEPROTECTION.getPath())) { - this.mpl = new MoveProtectionListener(this); - plm.registerEvents(this.mpl, this); - } - - jt = new JailTimer(this); - - reloadJailPayManager(); - - sbm = new ScoreBoardManager(this); - - getLogger().info("Completed enablement."); - } - - public void onDisable() { - if(jm != null) - for(Jail j : jm.getJails()) - io.saveJail(j); - - if(jt != null) - if(jt.getTimer() != null) - jt.getTimer().stop(); - - if(io != null) - io.closeConnection(); - - jt = null; - sbm = null; - jpm = null; - cmdHand = null; - pm = null; - jm = null; - jsm = null; - io = null; - hcm = null; - } - - private void loadConfig() { - //Only create the default config if it doesn't exist - saveDefaultConfig(); - - //Append new key-value pairs to the config - getConfig().options().copyDefaults(true); - - // Set the header and save - getConfig().options().header(getHeader()); - saveConfig(); - } - - private String getHeader() { - String sep = System.getProperty("line.separator"); - - return "###################" + sep - + "Jail v" + this.getDescription().getVersion() + " config file" + sep - + "Note: You -must- use spaces instead of tabs!" + sep + - "###################"; - } - - /* Majority of the new command system was heavily influenced by the MobArena. - * Thank you garbagemule for the great system you have in place there. - * - * Send the command off to the CommandHandler class, that way this main class doesn't get clogged up. - */ - public boolean onCommand(CommandSender sender, Command command, String commandLabel, String[] args) { - if(commandLabel.equalsIgnoreCase("jail") || commandLabel.equalsIgnoreCase("j")) { - jh.parseCommand(jm, sender, args); - }else { - cmdHand.handleCommand(jm, sender, command.getName().toLowerCase(), args); - } - - return true;//Always return true here, that way we can handle the help and command usage ourself. - } - - /** Reloads the scoreboard manager class, useful when something is changed int he config about it. */ - public void reloadScoreBoardManager() { - this.sbm.removeAllScoreboards(); - this.sbm = null; - this.sbm = new ScoreBoardManager(this); - - if(getConfig().getBoolean(Settings.SCOREBOARDENABLED.getPath())) { - for(Jail j : jm.getJails()) { - for(Prisoner p : j.getAllPrisoners().values()) { - if(getServer().getPlayer(p.getUUID()) != null) { - this.sbm.addScoreBoard(getServer().getPlayer(p.getUUID()), p); - } - } - } - } - } - - /** Reloads the Jail Sticks, so the new ones can be loaded from the config. */ - public void reloadJailSticks() { - this.jsm.removeAllStickUsers(); - this.jsm = null; - this.jsm = new JailStickManager(this); - } - - /** - * Reloads the {@link JailPayManager}. - * - * @throws Exception If we couldn't successfully create a new Jail Pay Manager instance. - */ - public void reloadJailPayManager() { - this.jpm = null; - - if(getConfig().getBoolean(Settings.JAILPAYENABLED.getPath())) { - if(getServer().getPluginManager().isPluginEnabled("Vault")) { - this.jpm = new JailPayManager(this); - }else { - getConfig().set(Settings.JAILPAYENABLED.getPath(), false); - getLogger().severe("Jail Pay couldn't find an economy, disabling Jail Pay."); - } - } - } - - /** Gets the {@link HandCuffManager} instance. */ - public HandCuffManager getHandCuffManager() { - return this.hcm; - } - - /** Gets the {@link JailIO} instance. */ - public JailIO getJailIO() { - return this.io; - } - - /** Gets the {@link JailManager} instance. */ - public JailManager getJailManager() { - return this.jm; - } - - /** Gets the {@link JailPayManager} instance. */ - public JailPayManager getJailPayManager() { - return this.jpm; - } - - /** Gets the {@link PrisonerManager} instance. */ - public PrisonerManager getPrisonerManager() { - return this.pm; - } - - /** Gets the {@link JailStickManager} instance. */ - public JailStickManager getJailStickManager() { - return this.jsm; - } - - /** Gets the {@link ScoreBoardManager} instance. */ - public ScoreBoardManager getScoreBoardManager() { - return this.sbm; - } - - /** Sets whether the plugin is in debugging or not. */ - public boolean setDebugging(boolean debug) { - this.debug = debug; - - //Save whether we are debugging when we disable the plugin - getConfig().set(Settings.DEBUG.getPath(), this.debug); - saveConfig(); - - return this.debug; - } - - /** Returns if the plugin is in debug state or not. */ - public boolean inDebug() { - return this.debug; - } - - /** Logs a debugging message to the console if debugging is enabled. */ - public void debug(String message) { - if(inDebug()) getLogger().info("[Debug]: " + message); - } - - public MoveProtectionListener getPlayerMoveListener() { - return this.mpl; - } -} +package com.graywolf336.jail; + +import org.bukkit.command.Command; +import org.bukkit.command.CommandSender; +import org.bukkit.plugin.PluginManager; +import org.bukkit.plugin.java.JavaPlugin; + +import com.graywolf336.jail.beans.Jail; +import com.graywolf336.jail.beans.Prisoner; +import com.graywolf336.jail.command.CommandHandler; +import com.graywolf336.jail.command.JailHandler; +import com.graywolf336.jail.enums.Settings; +import com.graywolf336.jail.legacy.LegacyManager; +import com.graywolf336.jail.listeners.BlockListener; +import com.graywolf336.jail.listeners.CacheListener; +import com.graywolf336.jail.listeners.EntityListener; +import com.graywolf336.jail.listeners.HandCuffListener; +import com.graywolf336.jail.listeners.JailingListener; +import com.graywolf336.jail.listeners.MoveProtectionListener; +import com.graywolf336.jail.listeners.PlayerListener; +import com.graywolf336.jail.listeners.ProtectionListener; + +/** + * The main class for this Jail plugin, holds instances of vital classes. + * + * @author graywolf336 + * @since 1.x.x + * @version 3.0.0 + */ +public class JailMain extends JavaPlugin { + private CommandHandler cmdHand; + private HandCuffManager hcm; + private JailHandler jh; + private JailIO io; + private JailManager jm; + private JailPayManager jpm; + private JailStickManager jsm; + private JailTimer jt; + private PrisonerManager pm; + private ScoreBoardManager sbm; + private MoveProtectionListener mpl; + private boolean debug = false; + + public void onEnable() { + loadConfig(); + + debug = getConfig().getBoolean(Settings.DEBUG.getPath()); + if(debug) getLogger().info("Debugging enabled."); + + hcm = new HandCuffManager(); + jm = new JailManager(this); + + //Try to load the old stuff before we load anything, esp the storage stuff + LegacyManager lm = new LegacyManager(this); + if(lm.doWeNeedToConvert()) { + lm.convertOldData(); + if(!lm.wasAnythingConverted()) getLogger().severe("We was unable to convert some, or all, of the old data."); + } + + io = new JailIO(this); + io.loadLanguage(); + + //If the prepareStorage returns false, we need to disable the plugin + if(!io.prepareStorage(true)) { + this.getLogger().severe("An error occured while preparing the connection to the storage, please see the error above for more information."); + this.getServer().getPluginManager().disablePlugin(this); + return; + } + + io.loadJails(); + + //If we converted something, let's save EVERYTHING including the cells + if(lm.wasAnythingConverted()) { + io.saveEverything(); + } + + cmdHand = new CommandHandler(this); + jh = new JailHandler(this); + pm = new PrisonerManager(this); + jsm = new JailStickManager(this); + + PluginManager plm = this.getServer().getPluginManager(); + plm.registerEvents(new BlockListener(this), this); + plm.registerEvents(new CacheListener(this), this); + plm.registerEvents(new EntityListener(this), this); + plm.registerEvents(new HandCuffListener(this), this); + plm.registerEvents(new JailingListener(this), this); + plm.registerEvents(new PlayerListener(this), this); + plm.registerEvents(new ProtectionListener(this), this); + + //Only register the move protection listener if this is enabled in the + //config when we first start the plugin. The reason for this change is + //that the move event is called a ton of times per single move and so + //not registering this event listener will hopefully safe some performance. + //But doing this also forces people to restart their server if they to + //enable it after disabling it. + if(getConfig().getBoolean(Settings.MOVEPROTECTION.getPath())) { + this.mpl = new MoveProtectionListener(this); + plm.registerEvents(this.mpl, this); + } + + jt = new JailTimer(this); + + reloadJailPayManager(); + + sbm = new ScoreBoardManager(this); + + getLogger().info("Completed enablement."); + } + + public void onDisable() { + if(jm != null) + for(Jail j : jm.getJails()) + io.saveJail(j); + + if(jt != null) + if(jt.getTimer() != null) + jt.getTimer().stop(); + + if(io != null) + io.closeConnection(); + + jt = null; + sbm = null; + jpm = null; + cmdHand = null; + pm = null; + jm = null; + jsm = null; + io = null; + hcm = null; + } + + private void loadConfig() { + //Only create the default config if it doesn't exist + saveDefaultConfig(); + + //Append new key-value pairs to the config + getConfig().options().copyDefaults(true); + + // Set the header and save + getConfig().options().header(getHeader()); + saveConfig(); + } + + private String getHeader() { + String sep = System.getProperty("line.separator"); + + return "###################" + sep + + "Jail v" + this.getDescription().getVersion() + " config file" + sep + + "Note: You -must- use spaces instead of tabs!" + sep + + "###################"; + } + + /* Majority of the new command system was heavily influenced by the MobArena. + * Thank you garbagemule for the great system you have in place there. + * + * Send the command off to the CommandHandler class, that way this main class doesn't get clogged up. + */ + public boolean onCommand(CommandSender sender, Command command, String commandLabel, String[] args) { + if(commandLabel.equalsIgnoreCase("jail") || commandLabel.equalsIgnoreCase("j")) { + jh.parseCommand(jm, sender, args); + }else { + cmdHand.handleCommand(jm, sender, command.getName().toLowerCase(), args); + } + + return true;//Always return true here, that way we can handle the help and command usage ourself. + } + + /** Reloads the scoreboard manager class, useful when something is changed int he config about it. */ + public void reloadScoreBoardManager() { + this.sbm.removeAllScoreboards(); + this.sbm = null; + this.sbm = new ScoreBoardManager(this); + + if(getConfig().getBoolean(Settings.SCOREBOARDENABLED.getPath())) { + for(Jail j : jm.getJails()) { + for(Prisoner p : j.getAllPrisoners().values()) { + if(getServer().getPlayer(p.getUUID()) != null) { + this.sbm.addScoreBoard(getServer().getPlayer(p.getUUID()), p); + } + } + } + } + } + + /** Reloads the Jail Sticks, so the new ones can be loaded from the config. */ + public void reloadJailSticks() { + this.jsm.removeAllStickUsers(); + this.jsm = null; + this.jsm = new JailStickManager(this); + } + + /** + * Reloads the {@link JailPayManager}. + * + * @throws Exception If we couldn't successfully create a new Jail Pay Manager instance. + */ + public void reloadJailPayManager() { + this.jpm = null; + + if(getConfig().getBoolean(Settings.JAILPAYENABLED.getPath())) { + if(getServer().getPluginManager().isPluginEnabled("Vault")) { + this.jpm = new JailPayManager(this); + }else { + getConfig().set(Settings.JAILPAYENABLED.getPath(), false); + getLogger().severe("Jail Pay couldn't find an economy, disabling Jail Pay."); + } + } + } + + /** Gets the {@link HandCuffManager} instance. */ + public HandCuffManager getHandCuffManager() { + return this.hcm; + } + + /** Gets the {@link JailIO} instance. */ + public JailIO getJailIO() { + return this.io; + } + + /** Gets the {@link JailManager} instance. */ + public JailManager getJailManager() { + return this.jm; + } + + /** Gets the {@link JailPayManager} instance. */ + public JailPayManager getJailPayManager() { + return this.jpm; + } + + /** Gets the {@link PrisonerManager} instance. */ + public PrisonerManager getPrisonerManager() { + return this.pm; + } + + /** Gets the {@link JailStickManager} instance. */ + public JailStickManager getJailStickManager() { + return this.jsm; + } + + /** Gets the {@link ScoreBoardManager} instance. */ + public ScoreBoardManager getScoreBoardManager() { + return this.sbm; + } + + /** Sets whether the plugin is in debugging or not. */ + public boolean setDebugging(boolean debug) { + this.debug = debug; + + //Save whether we are debugging when we disable the plugin + getConfig().set(Settings.DEBUG.getPath(), this.debug); + saveConfig(); + + return this.debug; + } + + /** Returns if the plugin is in debug state or not. */ + public boolean inDebug() { + return this.debug; + } + + /** Logs a debugging message to the console if debugging is enabled. */ + public void debug(String message) { + if(inDebug()) getLogger().info("[Debug]: " + message); + } + + public MoveProtectionListener getPlayerMoveListener() { + return this.mpl; + } +} diff --git a/src/main/java/com/graywolf336/jail/JailPayManager.java b/src/main/java/com/graywolf336/jail/JailPayManager.java index 550cf2a..699434a 100644 --- a/src/main/java/com/graywolf336/jail/JailPayManager.java +++ b/src/main/java/com/graywolf336/jail/JailPayManager.java @@ -1,172 +1,172 @@ -package com.graywolf336.jail; - -import net.milkbowl.vault.economy.Economy; - -import org.bukkit.Material; -import org.bukkit.entity.Player; -import org.bukkit.inventory.ItemStack; -import org.bukkit.plugin.RegisteredServiceProvider; - -import com.graywolf336.jail.beans.Prisoner; -import com.graywolf336.jail.enums.Settings; - -public class JailPayManager { - private Economy economy = null; - private double minteCost, infiniteCost; - private Material item; - private boolean infinite, timed; - - public JailPayManager(JailMain plugin) { - this.item = Material.getMaterial(plugin.getConfig().getString(Settings.JAILPAYITEM.getPath().toUpperCase())); - if(this.item == null) this.item = Material.AIR; - - this.minteCost = plugin.getConfig().getDouble(Settings.JAILPAYPRICEPERMINUTE.getPath()); - - if(!this.usingItemsForPayment()) { - if(!this.setupEconomy(plugin)) { - plugin.getConfig().set(Settings.JAILPAYENABLED.getPath(), false); - } - } - - this.timed = plugin.getConfig().getDouble(Settings.JAILPAYPRICEPERMINUTE.getPath()) != 0; - this.infinite = plugin.getConfig().getDouble(Settings.JAILPAYPRICEINFINITE.getPath()) != 0; - } - - /** Checks if paying for infinite is enabled. */ - public boolean isInfiniteEnabled() { - return this.infinite; - } - - /** Checks if paying for timed is enabled. */ - public boolean isTimedEnabled() { - return this.timed; - } - - /** Gets how much it cost per minute in string format. */ - public String getCostPerMinute() { - return String.valueOf(this.minteCost); - } - - /** - * Calculates how much players have to pay to get completely free. - * - * @param prisoner data of who we're calculating - * @return The economy cost the prisoner will need to pay to get completely free. - */ - public double calculateBill(Prisoner prisoner) { - return prisoner.getRemainingTime() > 0 ? prisoner.getRemainingTimeInMinutes() * this.minteCost : infiniteCost; - } - - /** Gets how many minutes someone is paying for (rounds to the lowest number). */ - public long getMinutesPayingFor(double amount) { - return (long) Math.floor(amount / this.minteCost); - } - - /** Returns if we are using items for payment instead of economy. */ - public boolean usingItemsForPayment() { - return this.item != Material.AIR; - } - - /** - * Gets the {@link Material} it costs for jail pay, will be air if using economy. - * - * @return The item type it costs, air if using virtual economy. - */ - public Material getItemItCost() { - return this.item; - } - - /** - * Checks if the player has enough money/items to pay what they have said they want to. - * - * @param p The player who is doing the paying. - * @param amt The amount to check they if they have. - * @return true if they have enough, false if not. - */ - public boolean hasEnoughToPay(Player p, double amt) { - if(this.usingItemsForPayment()) { - return p.getInventory().contains(this.item, (int) Math.ceil(amt)); - }else { - - return this.economy.has(p.getName(), amt); - } - } - - /** - * Pays the required fees from the given player, removing items or money from economy. - * - * @param p The player who is paying. - * @param amt The amount of items or money to withdraw from the player. - */ - public void pay(Player p, double amt) { - if(this.usingItemsForPayment()) { - int amtNeeded = (int) Math.ceil(amt); - - for (int i = 0; i < p.getInventory().getSize(); i++) { - ItemStack it = p.getInventory().getItem(i); - - //The item is either air or we doesn't match out needs - if(it == null || it.getType() != this.item) continue; - - //If the itemstack has more than or equal to the amount - //that we need, remove it and subject from the amt needed - if (amtNeeded >= it.getAmount()) { - amtNeeded -= it.getAmount(); - p.getInventory().clear(i); - } else { - //Otherwise, subject from the itemstack just the amount we need - it.setAmount(it.getAmount() - amtNeeded); - p.getInventory().setItem(i, it); - amtNeeded = 0; - } - - if (amtNeeded == 0) break; - } - }else { - this.economy.withdrawPlayer(p.getName(), amt); - } - } - - /** Gets the name of the item in nice capitals. */ - public String getCurrencyName(){ - if(this.usingItemsForPayment()) { - String name = item.toString().replaceAll("_", " "); - - if(name.contains(" ")){ - String[] split = name.split(" "); - for(int i=0; i < split.length; i++){ - split[i] = split[i].substring(0, 1).toUpperCase() + split[i].substring(1).toLowerCase(); - } - - name = ""; - for(String s : split){ - name += " " + s; - } - - name = name.substring(1); - } else { - name = name.substring(0, 1).toUpperCase() + name.substring(1).toLowerCase(); - } - - return name; - }else { - return this.economy.currencyNamePlural(); - } - } - - /** Returns the economy provider to do transaction with. */ - public Economy getEconomy() { - return this.economy; - } - - private boolean setupEconomy(JailMain plugin) { - if (economy != null) return true; - - RegisteredServiceProvider economyProvider = plugin.getServer().getServicesManager().getRegistration(net.milkbowl.vault.economy.Economy.class); - if (economyProvider != null) { - economy = economyProvider.getProvider(); - } - - return (economy != null); - } -} +package com.graywolf336.jail; + +import net.milkbowl.vault.economy.Economy; + +import org.bukkit.Material; +import org.bukkit.entity.Player; +import org.bukkit.inventory.ItemStack; +import org.bukkit.plugin.RegisteredServiceProvider; + +import com.graywolf336.jail.beans.Prisoner; +import com.graywolf336.jail.enums.Settings; + +public class JailPayManager { + private Economy economy = null; + private double minteCost, infiniteCost; + private Material item; + private boolean infinite, timed; + + public JailPayManager(JailMain plugin) { + this.item = Material.getMaterial(plugin.getConfig().getString(Settings.JAILPAYITEM.getPath().toUpperCase())); + if(this.item == null) this.item = Material.AIR; + + this.minteCost = plugin.getConfig().getDouble(Settings.JAILPAYPRICEPERMINUTE.getPath()); + + if(!this.usingItemsForPayment()) { + if(!this.setupEconomy(plugin)) { + plugin.getConfig().set(Settings.JAILPAYENABLED.getPath(), false); + } + } + + this.timed = plugin.getConfig().getDouble(Settings.JAILPAYPRICEPERMINUTE.getPath()) != 0; + this.infinite = plugin.getConfig().getDouble(Settings.JAILPAYPRICEINFINITE.getPath()) != 0; + } + + /** Checks if paying for infinite is enabled. */ + public boolean isInfiniteEnabled() { + return this.infinite; + } + + /** Checks if paying for timed is enabled. */ + public boolean isTimedEnabled() { + return this.timed; + } + + /** Gets how much it cost per minute in string format. */ + public String getCostPerMinute() { + return String.valueOf(this.minteCost); + } + + /** + * Calculates how much players have to pay to get completely free. + * + * @param prisoner data of who we're calculating + * @return The economy cost the prisoner will need to pay to get completely free. + */ + public double calculateBill(Prisoner prisoner) { + return prisoner.getRemainingTime() > 0 ? prisoner.getRemainingTimeInMinutes() * this.minteCost : infiniteCost; + } + + /** Gets how many minutes someone is paying for (rounds to the lowest number). */ + public long getMinutesPayingFor(double amount) { + return (long) Math.floor(amount / this.minteCost); + } + + /** Returns if we are using items for payment instead of economy. */ + public boolean usingItemsForPayment() { + return this.item != Material.AIR; + } + + /** + * Gets the {@link Material} it costs for jail pay, will be air if using economy. + * + * @return The item type it costs, air if using virtual economy. + */ + public Material getItemItCost() { + return this.item; + } + + /** + * Checks if the player has enough money/items to pay what they have said they want to. + * + * @param p The player who is doing the paying. + * @param amt The amount to check they if they have. + * @return true if they have enough, false if not. + */ + public boolean hasEnoughToPay(Player p, double amt) { + if(this.usingItemsForPayment()) { + return p.getInventory().contains(this.item, (int) Math.ceil(amt)); + }else { + + return this.economy.has(p.getName(), amt); + } + } + + /** + * Pays the required fees from the given player, removing items or money from economy. + * + * @param p The player who is paying. + * @param amt The amount of items or money to withdraw from the player. + */ + public void pay(Player p, double amt) { + if(this.usingItemsForPayment()) { + int amtNeeded = (int) Math.ceil(amt); + + for (int i = 0; i < p.getInventory().getSize(); i++) { + ItemStack it = p.getInventory().getItem(i); + + //The item is either air or we doesn't match out needs + if(it == null || it.getType() != this.item) continue; + + //If the itemstack has more than or equal to the amount + //that we need, remove it and subject from the amt needed + if (amtNeeded >= it.getAmount()) { + amtNeeded -= it.getAmount(); + p.getInventory().clear(i); + } else { + //Otherwise, subject from the itemstack just the amount we need + it.setAmount(it.getAmount() - amtNeeded); + p.getInventory().setItem(i, it); + amtNeeded = 0; + } + + if (amtNeeded == 0) break; + } + }else { + this.economy.withdrawPlayer(p.getName(), amt); + } + } + + /** Gets the name of the item in nice capitals. */ + public String getCurrencyName(){ + if(this.usingItemsForPayment()) { + String name = item.toString().replaceAll("_", " "); + + if(name.contains(" ")){ + String[] split = name.split(" "); + for(int i=0; i < split.length; i++){ + split[i] = split[i].substring(0, 1).toUpperCase() + split[i].substring(1).toLowerCase(); + } + + name = ""; + for(String s : split){ + name += " " + s; + } + + name = name.substring(1); + } else { + name = name.substring(0, 1).toUpperCase() + name.substring(1).toLowerCase(); + } + + return name; + }else { + return this.economy.currencyNamePlural(); + } + } + + /** Returns the economy provider to do transaction with. */ + public Economy getEconomy() { + return this.economy; + } + + private boolean setupEconomy(JailMain plugin) { + if (economy != null) return true; + + RegisteredServiceProvider economyProvider = plugin.getServer().getServicesManager().getRegistration(net.milkbowl.vault.economy.Economy.class); + if (economyProvider != null) { + economy = economyProvider.getProvider(); + } + + return (economy != null); + } +} diff --git a/src/main/java/com/graywolf336/jail/JailStickManager.java b/src/main/java/com/graywolf336/jail/JailStickManager.java index 782f648..f6fab71 100644 --- a/src/main/java/com/graywolf336/jail/JailStickManager.java +++ b/src/main/java/com/graywolf336/jail/JailStickManager.java @@ -1,173 +1,173 @@ -package com.graywolf336.jail; - -import java.util.ArrayList; -import java.util.HashMap; - -import org.bukkit.Material; -import org.bukkit.configuration.file.FileConfiguration; -import org.bukkit.entity.Player; - -import com.graywolf336.jail.beans.Stick; -import com.graywolf336.jail.enums.Settings; - -/** - * Manages the jail stick users. - * - * @author graywolf336 - * @version 1.0.2 - * @since 3.0.0 - * - */ -public class JailStickManager { - private ArrayList stickers; - private HashMap sticks; - - public JailStickManager(JailMain plugin) { - this.stickers = new ArrayList(); - this.sticks = new HashMap(); - - this.loadJailSticks(plugin); - } - - private void loadJailSticks(JailMain pl) { - FileConfiguration config = pl.getConfig(); - - //item name,time,jail name,reason - for(String s : config.getStringList(Settings.JAILSTICKSTICKS.getPath())) { - pl.debug(s); - String[] a = s.split(","); - - //Check if the jail given, if any, exists - if(!a[2].isEmpty()) { - if(!pl.getJailManager().isValidJail(a[2])) { - pl.getLogger().severe(s); - pl.getLogger().severe("The above jail stick configuration is invalid and references a jail that doesn't exist."); - continue; - } - } - - Material m = Material.getMaterial(a[0].toUpperCase()); - if(this.sticks.containsKey(m)) { - pl.getLogger().severe(s); - pl.getLogger().severe("You can not use the same item for two different Jail Sticks. This already exists as a Jail Stick: " + a[0]); - continue; - } - - try { - this.sticks.put(m, new Stick(a[2], a[3], Long.valueOf(a[1]))); - }catch (Exception e) { - e.printStackTrace(); - pl.getLogger().severe(s); - pl.getLogger().severe("Unable to create a new stick for " + a[0] + ", see the exception above for details."); - continue; - } - } - - int c = sticks.size(); - pl.getLogger().info("Loaded " + c + " jail stick" + (c == 1 ? "" : "s") + "."); - } - - /** - * Gets the {@link Stick jail stick} by the provided {@link Material}, can be null. - * - * @param mat of the stick to get - * @return The {@link Stick jail stick} - */ - public Stick getStick(Material mat) { - return this.sticks.get(mat); - } - - /** Checks if the provided Material is a valid {@link Stick jail stick}. */ - public boolean isValidStick(Material mat) { - return this.sticks.containsKey(mat); - } - - /** - * Adds a player to be using a jail stick, with the player instance. - * - * @param player to add - */ - public void addUsingStick(Player player) { - this.stickers.add(player.getName()); - } - - /** - * Adds a player to be using a jail stick, with their username. - * - * @param name of the player to add - */ - public void addUsingStick(String name) { - this.stickers.add(name); - } - - /** - * Removes a player from using a jail stick, with the player instance. - * - * @param player to remove using a jail stick - */ - public void removeUsingStick(Player player) { - this.stickers.remove(player.getName()); - } - - /** - * Removes a player from using a jail stick, with their username. - * - * @param name of the player to remove using a jail stick - */ - public void removeUsingStick(String name) { - this.stickers.remove(name); - } - - /** - * Returns whether or not the player is using a jail stick. - * - * @param player to check if using one - * @return true if the player is using a jail stick, false if not - */ - public boolean isUsingJailStick(Player player) { - return this.stickers.contains(player.getName()); - } - - /** - * Returns whether or not the player is using a jail stick. - * - * @param name of the player to check if using one - * @return true if the player is using a jail stick, false if not - */ - public boolean isUsingJailStick(String name) { - return this.stickers.contains(name); - } - - /** - * Toggles whether the player is using a jail stick, returning the true if enabled false if disabled. - * - * @param player to toggle using a stick - * @return true if we enabled it, false if we disabled it. - */ - public boolean toggleUsingStick(Player player) { - return this.toggleUsingStick(player.getName()); - } - - /** - * Toggles whether the player is using a jail stick, returning the true if enabled false if disabled. - * - * @param name of the person to toggle - * @return true if we enabled it, false if we disabled it. - */ - public boolean toggleUsingStick(String name) { - if(this.stickers.contains(name)) { - this.stickers.remove(name); - return false; - }else { - this.stickers.add(name); - return true; - } - } - - /** Removes all the users currently using the sticks. */ - public void removeAllStickUsers() { - for(String s: stickers) { - this.removeUsingStick(s); - } - } -} +package com.graywolf336.jail; + +import java.util.ArrayList; +import java.util.HashMap; + +import org.bukkit.Material; +import org.bukkit.configuration.file.FileConfiguration; +import org.bukkit.entity.Player; + +import com.graywolf336.jail.beans.Stick; +import com.graywolf336.jail.enums.Settings; + +/** + * Manages the jail stick users. + * + * @author graywolf336 + * @version 1.0.2 + * @since 3.0.0 + * + */ +public class JailStickManager { + private ArrayList stickers; + private HashMap sticks; + + public JailStickManager(JailMain plugin) { + this.stickers = new ArrayList(); + this.sticks = new HashMap(); + + this.loadJailSticks(plugin); + } + + private void loadJailSticks(JailMain pl) { + FileConfiguration config = pl.getConfig(); + + //item name,time,jail name,reason + for(String s : config.getStringList(Settings.JAILSTICKSTICKS.getPath())) { + pl.debug(s); + String[] a = s.split(","); + + //Check if the jail given, if any, exists + if(!a[2].isEmpty()) { + if(!pl.getJailManager().isValidJail(a[2])) { + pl.getLogger().severe(s); + pl.getLogger().severe("The above jail stick configuration is invalid and references a jail that doesn't exist."); + continue; + } + } + + Material m = Material.getMaterial(a[0].toUpperCase()); + if(this.sticks.containsKey(m)) { + pl.getLogger().severe(s); + pl.getLogger().severe("You can not use the same item for two different Jail Sticks. This already exists as a Jail Stick: " + a[0]); + continue; + } + + try { + this.sticks.put(m, new Stick(a[2], a[3], Long.valueOf(a[1]))); + }catch (Exception e) { + e.printStackTrace(); + pl.getLogger().severe(s); + pl.getLogger().severe("Unable to create a new stick for " + a[0] + ", see the exception above for details."); + continue; + } + } + + int c = sticks.size(); + pl.getLogger().info("Loaded " + c + " jail stick" + (c == 1 ? "" : "s") + "."); + } + + /** + * Gets the {@link Stick jail stick} by the provided {@link Material}, can be null. + * + * @param mat of the stick to get + * @return The {@link Stick jail stick} + */ + public Stick getStick(Material mat) { + return this.sticks.get(mat); + } + + /** Checks if the provided Material is a valid {@link Stick jail stick}. */ + public boolean isValidStick(Material mat) { + return this.sticks.containsKey(mat); + } + + /** + * Adds a player to be using a jail stick, with the player instance. + * + * @param player to add + */ + public void addUsingStick(Player player) { + this.stickers.add(player.getName()); + } + + /** + * Adds a player to be using a jail stick, with their username. + * + * @param name of the player to add + */ + public void addUsingStick(String name) { + this.stickers.add(name); + } + + /** + * Removes a player from using a jail stick, with the player instance. + * + * @param player to remove using a jail stick + */ + public void removeUsingStick(Player player) { + this.stickers.remove(player.getName()); + } + + /** + * Removes a player from using a jail stick, with their username. + * + * @param name of the player to remove using a jail stick + */ + public void removeUsingStick(String name) { + this.stickers.remove(name); + } + + /** + * Returns whether or not the player is using a jail stick. + * + * @param player to check if using one + * @return true if the player is using a jail stick, false if not + */ + public boolean isUsingJailStick(Player player) { + return this.stickers.contains(player.getName()); + } + + /** + * Returns whether or not the player is using a jail stick. + * + * @param name of the player to check if using one + * @return true if the player is using a jail stick, false if not + */ + public boolean isUsingJailStick(String name) { + return this.stickers.contains(name); + } + + /** + * Toggles whether the player is using a jail stick, returning the true if enabled false if disabled. + * + * @param player to toggle using a stick + * @return true if we enabled it, false if we disabled it. + */ + public boolean toggleUsingStick(Player player) { + return this.toggleUsingStick(player.getName()); + } + + /** + * Toggles whether the player is using a jail stick, returning the true if enabled false if disabled. + * + * @param name of the person to toggle + * @return true if we enabled it, false if we disabled it. + */ + public boolean toggleUsingStick(String name) { + if(this.stickers.contains(name)) { + this.stickers.remove(name); + return false; + }else { + this.stickers.add(name); + return true; + } + } + + /** Removes all the users currently using the sticks. */ + public void removeAllStickUsers() { + for(String s: stickers) { + this.removeUsingStick(s); + } + } +} diff --git a/src/main/java/com/graywolf336/jail/JailTimer.java b/src/main/java/com/graywolf336/jail/JailTimer.java index a226f96..b38e8a2 100644 --- a/src/main/java/com/graywolf336/jail/JailTimer.java +++ b/src/main/java/com/graywolf336/jail/JailTimer.java @@ -1,112 +1,112 @@ -package com.graywolf336.jail; - -import java.awt.event.ActionEvent; -import java.awt.event.ActionListener; - -import javax.swing.Timer; - -import org.bukkit.entity.Player; - -import com.graywolf336.jail.beans.Jail; -import com.graywolf336.jail.beans.Prisoner; -import com.graywolf336.jail.enums.LangString; -import com.graywolf336.jail.enums.Settings; - -/** - * Contains all the logic for counting down the time of the prisoners time. - * - * @author graywolf336 - * @since 2.x.x - * @version 3.0.0 - * - */ -public class JailTimer { - private JailMain pl; - private Timer timer; - private Long lastTime; - - public JailTimer(JailMain plugin) { - this.pl = plugin; - - this.lastTime = System.currentTimeMillis(); - if(pl.getConfig().getBoolean(Settings.USEBUKKITTIMER.getPath())) { - pl.getLogger().info("Using the Bukkit Scheduler."); - pl.getServer().getScheduler().scheduleSyncRepeatingTask(pl, new TimeEvent(), 20, 20); - }else { - pl.getLogger().info("Using the Java Timer."); - timer = new Timer(1000, new ActionListener () { - public void actionPerformed (ActionEvent event) { - pl.getServer().getScheduler().scheduleSyncDelayedTask(pl, new TimeEvent()); - }; - }); - - timer.start(); - } - } - - /** Returns the instance of this timer. */ - public Timer getTimer() { - return this.timer; - } - - class TimeEvent implements Runnable { - public void run() { - long timePassed; - - //Let's check if more than 10 seconds has passed since the - //last time we checked - if (System.currentTimeMillis() - lastTime >= 10000) { - //set the time passed to the current time minus the last time we checked - timePassed = System.currentTimeMillis() - lastTime; - lastTime = System.currentTimeMillis(); - }else { - //Less than 10 seconds has past when we last ran this - //so let's wait till the next round before we do this - return; - } - - for(Jail j : pl.getJailManager().getJails()) { - for(Prisoner p : j.getAllPrisoners().values()) { - //only execute this code if the prisoner's time is more than 0 milliseconds - if(p.getRemainingTime() > 0) { - Player player = pl.getServer().getPlayer(p.getUUID()); - - //Check if the player is offline - if(player == null) { - //if they are offline AND the config has counting down the time - //while the prisoner is offline, then let's do it - if(pl.getConfig().getBoolean(Settings.COUNTDOWNTIMEOFFLINE.getPath())) { - //Set their remaining time but if it is less than zero, set it to zero - p.setRemainingTime(Math.max(0, p.getRemainingTime() - timePassed)); - if(p.getRemainingTime() == 0) pl.getPrisonerManager().releasePrisoner(player, p); - } - }else { - //The prisoner isn't offline, so let's count down - //Set their remaining time but if it is less than zero, set it to zero - p.setRemainingTime(Math.max(0, p.getRemainingTime() - timePassed)); - if(p.getRemainingTime() == 0) pl.getPrisonerManager().releasePrisoner(player, p); - - //Now, let's set and check their afk time - //add the time passed to their current afk time - try { - long afk = Util.getTime(pl.getConfig().getString(Settings.MAXAFKTIME.getPath())); - if(afk > 0) { - p.setAFKTime(p.getAFKTime() + timePassed); - if(p.getAFKTime() > afk) { - p.setAFKTime(0); - player.kickPlayer(pl.getJailIO().getLanguageString(LangString.AFKKICKMESSAGE)); - } - } - } catch (Exception e) { - pl.getLogger().severe("Error while processing the max afk time: " + e.getMessage()); - } - } - } - } - - //Save all the prisoners and jails after we're done - pl.getJailIO().saveJail(j); - } - } - } -} +package com.graywolf336.jail; + +import java.awt.event.ActionEvent; +import java.awt.event.ActionListener; + +import javax.swing.Timer; + +import org.bukkit.entity.Player; + +import com.graywolf336.jail.beans.Jail; +import com.graywolf336.jail.beans.Prisoner; +import com.graywolf336.jail.enums.LangString; +import com.graywolf336.jail.enums.Settings; + +/** + * Contains all the logic for counting down the time of the prisoners time. + * + * @author graywolf336 + * @since 2.x.x + * @version 3.0.0 + * + */ +public class JailTimer { + private JailMain pl; + private Timer timer; + private Long lastTime; + + public JailTimer(JailMain plugin) { + this.pl = plugin; + + this.lastTime = System.currentTimeMillis(); + if(pl.getConfig().getBoolean(Settings.USEBUKKITTIMER.getPath())) { + pl.getLogger().info("Using the Bukkit Scheduler."); + pl.getServer().getScheduler().scheduleSyncRepeatingTask(pl, new TimeEvent(), 20, 20); + }else { + pl.getLogger().info("Using the Java Timer."); + timer = new Timer(1000, new ActionListener () { + public void actionPerformed (ActionEvent event) { + pl.getServer().getScheduler().scheduleSyncDelayedTask(pl, new TimeEvent()); + }; + }); + + timer.start(); + } + } + + /** Returns the instance of this timer. */ + public Timer getTimer() { + return this.timer; + } + + class TimeEvent implements Runnable { + public void run() { + long timePassed; + + //Let's check if more than 10 seconds has passed since the + //last time we checked + if (System.currentTimeMillis() - lastTime >= 10000) { + //set the time passed to the current time minus the last time we checked + timePassed = System.currentTimeMillis() - lastTime; + lastTime = System.currentTimeMillis(); + }else { + //Less than 10 seconds has past when we last ran this + //so let's wait till the next round before we do this + return; + } + + for(Jail j : pl.getJailManager().getJails()) { + for(Prisoner p : j.getAllPrisoners().values()) { + //only execute this code if the prisoner's time is more than 0 milliseconds + if(p.getRemainingTime() > 0) { + Player player = pl.getServer().getPlayer(p.getUUID()); + + //Check if the player is offline + if(player == null) { + //if they are offline AND the config has counting down the time + //while the prisoner is offline, then let's do it + if(pl.getConfig().getBoolean(Settings.COUNTDOWNTIMEOFFLINE.getPath())) { + //Set their remaining time but if it is less than zero, set it to zero + p.setRemainingTime(Math.max(0, p.getRemainingTime() - timePassed)); + if(p.getRemainingTime() == 0) pl.getPrisonerManager().releasePrisoner(player, p); + } + }else { + //The prisoner isn't offline, so let's count down + //Set their remaining time but if it is less than zero, set it to zero + p.setRemainingTime(Math.max(0, p.getRemainingTime() - timePassed)); + if(p.getRemainingTime() == 0) pl.getPrisonerManager().releasePrisoner(player, p); + + //Now, let's set and check their afk time + //add the time passed to their current afk time + try { + long afk = Util.getTime(pl.getConfig().getString(Settings.MAXAFKTIME.getPath())); + if(afk > 0) { + p.setAFKTime(p.getAFKTime() + timePassed); + if(p.getAFKTime() > afk) { + p.setAFKTime(0); + player.kickPlayer(pl.getJailIO().getLanguageString(LangString.AFKKICKMESSAGE)); + } + } + } catch (Exception e) { + pl.getLogger().severe("Error while processing the max afk time: " + e.getMessage()); + } + } + } + } + + //Save all the prisoners and jails after we're done + pl.getJailIO().saveJail(j); + } + } + } +} diff --git a/src/main/java/com/graywolf336/jail/PrisonerManager.java b/src/main/java/com/graywolf336/jail/PrisonerManager.java index 55b27e5..dcc82a1 100644 --- a/src/main/java/com/graywolf336/jail/PrisonerManager.java +++ b/src/main/java/com/graywolf336/jail/PrisonerManager.java @@ -1,556 +1,556 @@ -package com.graywolf336.jail; - -import java.util.UUID; - -import org.bukkit.GameMode; -import org.bukkit.Material; -import org.bukkit.entity.Player; -import org.bukkit.inventory.Inventory; -import org.bukkit.inventory.ItemStack; - -import com.graywolf336.jail.beans.Cell; -import com.graywolf336.jail.beans.Jail; -import com.graywolf336.jail.beans.Prisoner; -import com.graywolf336.jail.enums.LangString; -import com.graywolf336.jail.enums.Settings; -import com.graywolf336.jail.events.PrePrisonerReleasedEvent; -import com.graywolf336.jail.events.PrisonerJailedEvent; -import com.graywolf336.jail.events.PrisonerReleasedEvent; -import com.graywolf336.jail.events.PrisonerTransferredEvent; - -/** - * Provides methods, non-statically, that do the preparing of jails and handle all the good stuff like that. - * - * @author graywolf336 - * @since 2.x.x - * @version 3.0.0 - */ -public class PrisonerManager { - private JailMain pl; - - public PrisonerManager(JailMain plugin) { - this.pl = plugin; - } - - /** - * Does everything preparing for the jailing of the provided prisoner, if they are online it forwards it to {@link #jailPrisoner(Jail, Cell, Player, Prisoner)}. - * - *

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

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

- * - * Throws an exception if either the jail is null or the prisoner is null. - * - * @param jail where the prisoner is located at - * @param cell which the prisoner is in, can be null - * @param player instance for the prisoner we're unjailing - * @param prisoner data where everything resides - * @throws Exception - */ - public void unJail(Jail jail, Cell cell, Player player, Prisoner prisoner) throws Exception { - //Do some checks of whether the passed params are null. - if(jail == null) - throw new Exception("The jail can not be null."); - - if(prisoner == null) - throw new Exception("Prisoner data can not be null."); - - //Throw the custom event which is called before we start releasing them - PrePrisonerReleasedEvent preEvent = new PrePrisonerReleasedEvent(jail, cell, prisoner, player); - pl.getServer().getPluginManager().callEvent(preEvent); - - //We are getting ready to teleport them, so set it to true so that - //the *future* move checkers won't be canceling our moving. - prisoner.setTeleporting(true); - - //In case they have somehow got on a vehicle, let's unmount - //them so we can possibly teleport them - if(player.isInsideVehicle()) { - player.getVehicle().eject(); - player.getPassenger().eject(); - player.eject(); - } - - //In case we had set their sleeping state to be ignored - //let's enable their sleeping state taking place again - player.setSleepingIgnored(false); - - //If the config has us teleporting them back to their - //previous position then let's do that - boolean tpd = false; - if(pl.getConfig().getBoolean(Settings.RELEASETOPREVIOUSPOSITION.getPath(), false)) { - if(prisoner.getPreviousLocation() != null) - tpd = player.teleport(prisoner.getPreviousLocation()); - } - - //If they haven't already been teleported and the config has us to teleport on release, - //then we teleport players to the jail's free spot - if(!tpd && pl.getConfig().getBoolean(Settings.TELEPORTONRELEASE.getPath(), true)) { - player.teleport(jail.getTeleportFree()); - } - - //If we are to restore their previous gamemode and we have it stored, - //then by all means let's restore it - if(pl.getConfig().getBoolean(Settings.RESTOREPREVIOUSGAMEMODE.getPath(), false)) { - player.setGameMode(prisoner.getPreviousGameMode()); - } - - //Now, let's restore their inventory - //if the cell isn't null, let's check if the cell has a chest and if so then try out best to restore - //the prisoner's inventory from that - if(cell != null) { - if(cell.hasChest()) { - Inventory chest = cell.getChest().getInventory(); - - for (ItemStack item : chest.getContents()) { - if (item == null || item.getType() == Material.AIR) continue; - - if(item.getType().toString().toLowerCase().contains("helmet") && (player.getInventory().getHelmet() == null || player.getInventory().getHelmet().getType() == Material.AIR)) { - player.getInventory().setHelmet(item); - } else if(item.getType().toString().toLowerCase().contains("chestplate") && (player.getInventory().getChestplate() == null || player.getInventory().getChestplate().getType() == Material.AIR)) { - player.getInventory().setChestplate(item); - } else if(item.getType().toString().toLowerCase().contains("leg") && (player.getInventory().getLeggings() == null || player.getInventory().getLeggings().getType() == Material.AIR)) { - player.getInventory().setLeggings(item); - } else if(item.getType().toString().toLowerCase().contains("boots") && (player.getInventory().getBoots() == null || player.getInventory().getBoots().getType() == Material.AIR)) { - player.getInventory().setBoots(item); - } else if (player.getInventory().firstEmpty() == -1) { - player.getWorld().dropItem(player.getLocation(), item); - } else { - player.getInventory().addItem(item); - } - } - - chest.clear(); - }else { - Util.restoreInventory(player, prisoner); - } - - pl.getJailIO().removePrisoner(jail, cell, prisoner); - cell.removePrisoner(); - }else { - Util.restoreInventory(player, prisoner); - - pl.getJailIO().removePrisoner(jail, prisoner); - jail.removePrisoner(prisoner); - } - - //Get the commands to execute prisoners are unjailed - //replace all of the %p% so that the commands can have a player name in them - for(String command : pl.getConfig().getStringList(Settings.COMMANDSONRELEASE.getPath())) { - command = command.replaceAll("%p%", player.getName()); - pl.getServer().dispatchCommand(pl.getServer().getConsoleSender(), command); - } - - //Remove the scoreboard to them if it is enabled - if(pl.getConfig().getBoolean(Settings.SCOREBOARDENABLED.getPath())) { - pl.getScoreBoardManager().removeScoreBoard(player); - } - - //Call the prisoner released event as we have released them. - PrisonerReleasedEvent event = new PrisonerReleasedEvent(jail, cell, prisoner, player); - pl.getServer().getPluginManager().callEvent(event); - - player.sendMessage(pl.getJailIO().getLanguageString(LangString.UNJAILED)); - } - - /** Forcefully releases a {@link Prisoner prisoner} from {@link Jail}. */ - public void forceRelease(Prisoner prisoner) { - Jail j = pl.getJailManager().getJailPrisonerIsIn(prisoner); - forceUnJail(j, j.getCellPrisonerIsIn(prisoner.getUUID()), pl.getServer().getPlayer(prisoner.getUUID()), prisoner); - } - - /** Forcefully unjails a {@link Prisoner prisoner} from {@link Jail}. */ - public void forceUnJail(Jail jail, Cell cell, Player player, Prisoner prisoner) { - if(player == null) { - //Player is offline, we just forcefully remove them from the database - pl.getJailIO().removePrisoner(jail, cell, prisoner); - - if(cell == null) { - jail.removePrisoner(prisoner); - }else { - cell.removePrisoner(); - } - }else { - try { - unJail(jail, cell, player, prisoner); - } catch (Exception e) { - releasePrisoner(player, prisoner); - } - } - } - - /** - * Transfers the prisoner from one jail, or cell, to another jail, and/or cell. - * - * @param originJail The jail where they are coming from. - * @param originCell The cell where they are coming from. - * @param targetJail The jail we're transferring them from. - * @param targetCell The cell we're putting them into. - * @param prisoner The prisoner data we're handling. - */ - public void transferPrisoner(Jail originJail, Cell originCell, Jail targetJail, Cell targetCell, Prisoner prisoner) { - Player player = pl.getServer().getPlayer(prisoner.getUUID()); - - //If there is no origin cell, then we need to basically just put them to their targetJail - if(originCell == null) { - //But first thing is first, let's check if there is a targetCell we're putting them in - if(targetCell == null) { - //There is no cell, so we're just going to be putting them into - //the target jail and that's it - targetJail.addPrisoner(prisoner); - //Now then let's remove them from their old jail - originJail.removePrisoner(prisoner); - - //If the player is not online, trigger them to be teleported when they - //come online again - if(player == null) { - //Set them to have an action on offline pending, so it gets triggered - prisoner.setOfflinePending(true); - //Now let's set them to be transferred when they come online next - prisoner.setToBeTransferred(true); - }else { - prisoner.setTeleporting(true); - player.teleport(targetJail.getTeleportIn()); - prisoner.setTeleporting(false); - player.sendMessage(pl.getJailIO().getLanguageString(LangString.TRANSFERRED, targetJail.getName())); - } - }else { - //They are set to go to the targetCell, so handle accordingly - targetCell.setPrisoner(prisoner); - - //If the player is not online, trigger them to be teleported when they - //come online again - if(player == null) { - //Set them to have an action on offline pending, so it gets triggered - prisoner.setOfflinePending(true); - //Now let's set them to be transferred when they come online next - prisoner.setToBeTransferred(true); - }else { - prisoner.setTeleporting(true); - player.teleport(targetCell.getTeleport()); - prisoner.setTeleporting(false); - player.sendMessage(pl.getJailIO().getLanguageString(LangString.TRANSFERRED, targetJail.getName())); - } - } - }else { - //They are being transferred from a cell, so we need to handle getting the inventory - //and all that sort of stuff from the old cell before we transfer them over to the new cell - - //If they're not being sent to a cell any more, handle that differently as well - if(targetCell == null) { - //Add them to the target jail - targetJail.addPrisoner(prisoner); - //Next, remove them from the cell - originCell.removePrisoner(); - - //If the cell they came from has any items from their inventory, - //let's get it all and store it - if(originCell.hasChest()) { - //Convert the inventory to base64 string and store it in the prisoner's file - prisoner.setInventory(Util.toBase64(originCell.getChest().getInventory())); - //Clear the origin cell's inventory so nothing is left behind - originCell.getChest().getInventory().clear(); - } - }else { - //They are being transferred to a cell in another cell, - //we aren't going to do any sanity checks as we hope the method that is - //calling this one does those sanity checks for us. - - //Set the cell's prisoner to this one - targetCell.setPrisoner(prisoner); - //Remove the prisoner from the old one - originCell.removePrisoner(); - - //Check if the origin cell has a chest, put all the player's inventory into it - if(originCell.hasChest()) { - //If the targetCell has a chest - if(targetCell.hasChest()) { - //Loop through the origin's chest inventory and add it to the target cell's chest - for(ItemStack i : originCell.getChest().getInventory().getContents()) { - targetCell.getChest().getInventory().addItem(i); - } - - //Clear the origin cell's chest as it is clear now - originCell.getChest().getInventory().clear(); - }else { - //targetCell has no chest so we aren't going to try and put anything into it - - //Convert the inventory to base64 string and store it in the prisoner's file - prisoner.setInventory(Util.toBase64(originCell.getChest().getInventory())); - //Clear the origin cell's inventory so nothing is left behind - originCell.getChest().getInventory().clear(); - } - } - } - } - - //Throw our custom event PrisonerTransferredEvent to say it was successful - PrisonerTransferredEvent event = new PrisonerTransferredEvent(originJail, originCell, targetJail, targetCell, prisoner, player); - pl.getServer().getPluginManager().callEvent(event); - } -} +package com.graywolf336.jail; + +import java.util.UUID; + +import org.bukkit.GameMode; +import org.bukkit.Material; +import org.bukkit.entity.Player; +import org.bukkit.inventory.Inventory; +import org.bukkit.inventory.ItemStack; + +import com.graywolf336.jail.beans.Cell; +import com.graywolf336.jail.beans.Jail; +import com.graywolf336.jail.beans.Prisoner; +import com.graywolf336.jail.enums.LangString; +import com.graywolf336.jail.enums.Settings; +import com.graywolf336.jail.events.PrePrisonerReleasedEvent; +import com.graywolf336.jail.events.PrisonerJailedEvent; +import com.graywolf336.jail.events.PrisonerReleasedEvent; +import com.graywolf336.jail.events.PrisonerTransferredEvent; + +/** + * Provides methods, non-statically, that do the preparing of jails and handle all the good stuff like that. + * + * @author graywolf336 + * @since 2.x.x + * @version 3.0.0 + */ +public class PrisonerManager { + private JailMain pl; + + public PrisonerManager(JailMain plugin) { + this.pl = plugin; + } + + /** + * Does everything preparing for the jailing of the provided prisoner, if they are online it forwards it to {@link #jailPrisoner(Jail, Cell, Player, Prisoner)}. + * + *

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

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

+ * + * Throws an exception if either the jail is null or the prisoner is null. + * + * @param jail where the prisoner is located at + * @param cell which the prisoner is in, can be null + * @param player instance for the prisoner we're unjailing + * @param prisoner data where everything resides + * @throws Exception + */ + public void unJail(Jail jail, Cell cell, Player player, Prisoner prisoner) throws Exception { + //Do some checks of whether the passed params are null. + if(jail == null) + throw new Exception("The jail can not be null."); + + if(prisoner == null) + throw new Exception("Prisoner data can not be null."); + + //Throw the custom event which is called before we start releasing them + PrePrisonerReleasedEvent preEvent = new PrePrisonerReleasedEvent(jail, cell, prisoner, player); + pl.getServer().getPluginManager().callEvent(preEvent); + + //We are getting ready to teleport them, so set it to true so that + //the *future* move checkers won't be canceling our moving. + prisoner.setTeleporting(true); + + //In case they have somehow got on a vehicle, let's unmount + //them so we can possibly teleport them + if(player.isInsideVehicle()) { + player.getVehicle().eject(); + player.getPassenger().eject(); + player.eject(); + } + + //In case we had set their sleeping state to be ignored + //let's enable their sleeping state taking place again + player.setSleepingIgnored(false); + + //If the config has us teleporting them back to their + //previous position then let's do that + boolean tpd = false; + if(pl.getConfig().getBoolean(Settings.RELEASETOPREVIOUSPOSITION.getPath(), false)) { + if(prisoner.getPreviousLocation() != null) + tpd = player.teleport(prisoner.getPreviousLocation()); + } + + //If they haven't already been teleported and the config has us to teleport on release, + //then we teleport players to the jail's free spot + if(!tpd && pl.getConfig().getBoolean(Settings.TELEPORTONRELEASE.getPath(), true)) { + player.teleport(jail.getTeleportFree()); + } + + //If we are to restore their previous gamemode and we have it stored, + //then by all means let's restore it + if(pl.getConfig().getBoolean(Settings.RESTOREPREVIOUSGAMEMODE.getPath(), false)) { + player.setGameMode(prisoner.getPreviousGameMode()); + } + + //Now, let's restore their inventory + //if the cell isn't null, let's check if the cell has a chest and if so then try out best to restore + //the prisoner's inventory from that + if(cell != null) { + if(cell.hasChest()) { + Inventory chest = cell.getChest().getInventory(); + + for (ItemStack item : chest.getContents()) { + if (item == null || item.getType() == Material.AIR) continue; + + if(item.getType().toString().toLowerCase().contains("helmet") && (player.getInventory().getHelmet() == null || player.getInventory().getHelmet().getType() == Material.AIR)) { + player.getInventory().setHelmet(item); + } else if(item.getType().toString().toLowerCase().contains("chestplate") && (player.getInventory().getChestplate() == null || player.getInventory().getChestplate().getType() == Material.AIR)) { + player.getInventory().setChestplate(item); + } else if(item.getType().toString().toLowerCase().contains("leg") && (player.getInventory().getLeggings() == null || player.getInventory().getLeggings().getType() == Material.AIR)) { + player.getInventory().setLeggings(item); + } else if(item.getType().toString().toLowerCase().contains("boots") && (player.getInventory().getBoots() == null || player.getInventory().getBoots().getType() == Material.AIR)) { + player.getInventory().setBoots(item); + } else if (player.getInventory().firstEmpty() == -1) { + player.getWorld().dropItem(player.getLocation(), item); + } else { + player.getInventory().addItem(item); + } + } + + chest.clear(); + }else { + Util.restoreInventory(player, prisoner); + } + + pl.getJailIO().removePrisoner(jail, cell, prisoner); + cell.removePrisoner(); + }else { + Util.restoreInventory(player, prisoner); + + pl.getJailIO().removePrisoner(jail, prisoner); + jail.removePrisoner(prisoner); + } + + //Get the commands to execute prisoners are unjailed + //replace all of the %p% so that the commands can have a player name in them + for(String command : pl.getConfig().getStringList(Settings.COMMANDSONRELEASE.getPath())) { + command = command.replaceAll("%p%", player.getName()); + pl.getServer().dispatchCommand(pl.getServer().getConsoleSender(), command); + } + + //Remove the scoreboard to them if it is enabled + if(pl.getConfig().getBoolean(Settings.SCOREBOARDENABLED.getPath())) { + pl.getScoreBoardManager().removeScoreBoard(player); + } + + //Call the prisoner released event as we have released them. + PrisonerReleasedEvent event = new PrisonerReleasedEvent(jail, cell, prisoner, player); + pl.getServer().getPluginManager().callEvent(event); + + player.sendMessage(pl.getJailIO().getLanguageString(LangString.UNJAILED)); + } + + /** Forcefully releases a {@link Prisoner prisoner} from {@link Jail}. */ + public void forceRelease(Prisoner prisoner) { + Jail j = pl.getJailManager().getJailPrisonerIsIn(prisoner); + forceUnJail(j, j.getCellPrisonerIsIn(prisoner.getUUID()), pl.getServer().getPlayer(prisoner.getUUID()), prisoner); + } + + /** Forcefully unjails a {@link Prisoner prisoner} from {@link Jail}. */ + public void forceUnJail(Jail jail, Cell cell, Player player, Prisoner prisoner) { + if(player == null) { + //Player is offline, we just forcefully remove them from the database + pl.getJailIO().removePrisoner(jail, cell, prisoner); + + if(cell == null) { + jail.removePrisoner(prisoner); + }else { + cell.removePrisoner(); + } + }else { + try { + unJail(jail, cell, player, prisoner); + } catch (Exception e) { + releasePrisoner(player, prisoner); + } + } + } + + /** + * Transfers the prisoner from one jail, or cell, to another jail, and/or cell. + * + * @param originJail The jail where they are coming from. + * @param originCell The cell where they are coming from. + * @param targetJail The jail we're transferring them from. + * @param targetCell The cell we're putting them into. + * @param prisoner The prisoner data we're handling. + */ + public void transferPrisoner(Jail originJail, Cell originCell, Jail targetJail, Cell targetCell, Prisoner prisoner) { + Player player = pl.getServer().getPlayer(prisoner.getUUID()); + + //If there is no origin cell, then we need to basically just put them to their targetJail + if(originCell == null) { + //But first thing is first, let's check if there is a targetCell we're putting them in + if(targetCell == null) { + //There is no cell, so we're just going to be putting them into + //the target jail and that's it + targetJail.addPrisoner(prisoner); + //Now then let's remove them from their old jail + originJail.removePrisoner(prisoner); + + //If the player is not online, trigger them to be teleported when they + //come online again + if(player == null) { + //Set them to have an action on offline pending, so it gets triggered + prisoner.setOfflinePending(true); + //Now let's set them to be transferred when they come online next + prisoner.setToBeTransferred(true); + }else { + prisoner.setTeleporting(true); + player.teleport(targetJail.getTeleportIn()); + prisoner.setTeleporting(false); + player.sendMessage(pl.getJailIO().getLanguageString(LangString.TRANSFERRED, targetJail.getName())); + } + }else { + //They are set to go to the targetCell, so handle accordingly + targetCell.setPrisoner(prisoner); + + //If the player is not online, trigger them to be teleported when they + //come online again + if(player == null) { + //Set them to have an action on offline pending, so it gets triggered + prisoner.setOfflinePending(true); + //Now let's set them to be transferred when they come online next + prisoner.setToBeTransferred(true); + }else { + prisoner.setTeleporting(true); + player.teleport(targetCell.getTeleport()); + prisoner.setTeleporting(false); + player.sendMessage(pl.getJailIO().getLanguageString(LangString.TRANSFERRED, targetJail.getName())); + } + } + }else { + //They are being transferred from a cell, so we need to handle getting the inventory + //and all that sort of stuff from the old cell before we transfer them over to the new cell + + //If they're not being sent to a cell any more, handle that differently as well + if(targetCell == null) { + //Add them to the target jail + targetJail.addPrisoner(prisoner); + //Next, remove them from the cell + originCell.removePrisoner(); + + //If the cell they came from has any items from their inventory, + //let's get it all and store it + if(originCell.hasChest()) { + //Convert the inventory to base64 string and store it in the prisoner's file + prisoner.setInventory(Util.toBase64(originCell.getChest().getInventory())); + //Clear the origin cell's inventory so nothing is left behind + originCell.getChest().getInventory().clear(); + } + }else { + //They are being transferred to a cell in another cell, + //we aren't going to do any sanity checks as we hope the method that is + //calling this one does those sanity checks for us. + + //Set the cell's prisoner to this one + targetCell.setPrisoner(prisoner); + //Remove the prisoner from the old one + originCell.removePrisoner(); + + //Check if the origin cell has a chest, put all the player's inventory into it + if(originCell.hasChest()) { + //If the targetCell has a chest + if(targetCell.hasChest()) { + //Loop through the origin's chest inventory and add it to the target cell's chest + for(ItemStack i : originCell.getChest().getInventory().getContents()) { + targetCell.getChest().getInventory().addItem(i); + } + + //Clear the origin cell's chest as it is clear now + originCell.getChest().getInventory().clear(); + }else { + //targetCell has no chest so we aren't going to try and put anything into it + + //Convert the inventory to base64 string and store it in the prisoner's file + prisoner.setInventory(Util.toBase64(originCell.getChest().getInventory())); + //Clear the origin cell's inventory so nothing is left behind + originCell.getChest().getInventory().clear(); + } + } + } + } + + //Throw our custom event PrisonerTransferredEvent to say it was successful + PrisonerTransferredEvent event = new PrisonerTransferredEvent(originJail, originCell, targetJail, targetCell, prisoner, player); + pl.getServer().getPluginManager().callEvent(event); + } +} diff --git a/src/main/java/com/graywolf336/jail/ScoreBoardManager.java b/src/main/java/com/graywolf336/jail/ScoreBoardManager.java index 0c8f0a2..3e23c3b 100644 --- a/src/main/java/com/graywolf336/jail/ScoreBoardManager.java +++ b/src/main/java/com/graywolf336/jail/ScoreBoardManager.java @@ -1,104 +1,104 @@ -package com.graywolf336.jail; - -import java.util.HashMap; -import java.util.UUID; - -import org.bukkit.OfflinePlayer; -import org.bukkit.entity.Player; -import org.bukkit.scoreboard.DisplaySlot; -import org.bukkit.scoreboard.Objective; -import org.bukkit.scoreboard.Scoreboard; -import org.bukkit.scoreboard.ScoreboardManager; - -import com.graywolf336.jail.beans.Jail; -import com.graywolf336.jail.beans.Prisoner; -import com.graywolf336.jail.enums.Settings; - -public class ScoreBoardManager { - private JailMain pl; - private ScoreboardManager man; - private HashMap boards; - private OfflinePlayer time; - - public ScoreBoardManager(JailMain plugin) { - this.pl = plugin; - this.man = plugin.getServer().getScoreboardManager(); - this.boards = new HashMap(); - this.time = plugin.getServer().getOfflinePlayer(Util.getColorfulMessage(pl.getConfig().getString(Settings.SCOREBOARDTIME.getPath()))); - - //Start the task if it is enabled - if(plugin.getConfig().getBoolean(Settings.SCOREBOARDENABLED.getPath())) { - plugin.getServer().getScheduler().scheduleSyncRepeatingTask(plugin, new Runnable() { - public void run() { - updatePrisonersTime(); - } - }, 200L, 100L); - } - } - - /** - * Adds the jailing score board to the player if they don't have one, otherwise it just updates it. - * - * @param player of whom to add the scoreboard to. - * @param pris data for the provided prisoner - */ - public void addScoreBoard(Player player, Prisoner pris) { - if(!boards.containsKey(player.getUniqueId())) { - boards.put(player.getUniqueId(), man.getNewScoreboard()); - Objective o = boards.get(player.getUniqueId()).registerNewObjective("test", "dummy"); - o.setDisplaySlot(DisplaySlot.SIDEBAR); - o.setDisplayName(Util.getColorfulMessage(pl.getConfig().getString(Settings.SCOREBOARDTITLE.getPath()))); - o.getScore(time).setScore(pris.getRemainingTimeInMinutesInt()); - player.setScoreboard(boards.get(player.getUniqueId())); - }else { - updatePrisonersBoard(player, pris); - } - } - - /** - * Removes a player's jail scoreboard for their jail time and sets it to the main one. - * - * @param player of whom to remove the scoreboard for. - */ - public void removeScoreBoard(Player player) { - boards.remove(player.getUniqueId()); - //TODO: See if this works or if we need to set it to a new one - player.setScoreboard(man.getMainScoreboard()); - } - - /** Removes all of the scoreboards from the prisoners. */ - public void removeAllScoreboards() { - HashMap temp = new HashMap(boards); - - for(UUID id : temp.keySet()) { - Player p = pl.getServer().getPlayer(id); - - if(p != null) { - p.setScoreboard(man.getMainScoreboard()); - } - - boards.remove(id); - } - } - - /** Updates the prisoners time on their scoreboard. */ - private void updatePrisonersTime() { - for(Jail j : pl.getJailManager().getJails()) { - for(Prisoner p : j.getAllPrisoners().values()) { - if(pl.getServer().getPlayer(p.getUUID()) != null) { - addScoreBoard(pl.getServer().getPlayer(p.getUUID()), p); - } - } - } - } - - /** - * Updates a player's time in the scoreboard. - * - * @param player of whom to update the scoreboard for. - * @param pris data for the player - */ - private void updatePrisonersBoard(Player player, Prisoner pris) { - boards.get(player.getUniqueId()).getObjective("test").getScore(time).setScore(pris.getRemainingTimeInMinutesInt()); - } -} +package com.graywolf336.jail; + +import java.util.HashMap; +import java.util.UUID; + +import org.bukkit.OfflinePlayer; +import org.bukkit.entity.Player; +import org.bukkit.scoreboard.DisplaySlot; +import org.bukkit.scoreboard.Objective; +import org.bukkit.scoreboard.Scoreboard; +import org.bukkit.scoreboard.ScoreboardManager; + +import com.graywolf336.jail.beans.Jail; +import com.graywolf336.jail.beans.Prisoner; +import com.graywolf336.jail.enums.Settings; + +public class ScoreBoardManager { + private JailMain pl; + private ScoreboardManager man; + private HashMap boards; + private OfflinePlayer time; + + public ScoreBoardManager(JailMain plugin) { + this.pl = plugin; + this.man = plugin.getServer().getScoreboardManager(); + this.boards = new HashMap(); + this.time = plugin.getServer().getOfflinePlayer(Util.getColorfulMessage(pl.getConfig().getString(Settings.SCOREBOARDTIME.getPath()))); + + //Start the task if it is enabled + if(plugin.getConfig().getBoolean(Settings.SCOREBOARDENABLED.getPath())) { + plugin.getServer().getScheduler().scheduleSyncRepeatingTask(plugin, new Runnable() { + public void run() { + updatePrisonersTime(); + } + }, 200L, 100L); + } + } + + /** + * Adds the jailing score board to the player if they don't have one, otherwise it just updates it. + * + * @param player of whom to add the scoreboard to. + * @param pris data for the provided prisoner + */ + public void addScoreBoard(Player player, Prisoner pris) { + if(!boards.containsKey(player.getUniqueId())) { + boards.put(player.getUniqueId(), man.getNewScoreboard()); + Objective o = boards.get(player.getUniqueId()).registerNewObjective("test", "dummy"); + o.setDisplaySlot(DisplaySlot.SIDEBAR); + o.setDisplayName(Util.getColorfulMessage(pl.getConfig().getString(Settings.SCOREBOARDTITLE.getPath()))); + o.getScore(time).setScore(pris.getRemainingTimeInMinutesInt()); + player.setScoreboard(boards.get(player.getUniqueId())); + }else { + updatePrisonersBoard(player, pris); + } + } + + /** + * Removes a player's jail scoreboard for their jail time and sets it to the main one. + * + * @param player of whom to remove the scoreboard for. + */ + public void removeScoreBoard(Player player) { + boards.remove(player.getUniqueId()); + //TODO: See if this works or if we need to set it to a new one + player.setScoreboard(man.getMainScoreboard()); + } + + /** Removes all of the scoreboards from the prisoners. */ + public void removeAllScoreboards() { + HashMap temp = new HashMap(boards); + + for(UUID id : temp.keySet()) { + Player p = pl.getServer().getPlayer(id); + + if(p != null) { + p.setScoreboard(man.getMainScoreboard()); + } + + boards.remove(id); + } + } + + /** Updates the prisoners time on their scoreboard. */ + private void updatePrisonersTime() { + for(Jail j : pl.getJailManager().getJails()) { + for(Prisoner p : j.getAllPrisoners().values()) { + if(pl.getServer().getPlayer(p.getUUID()) != null) { + addScoreBoard(pl.getServer().getPlayer(p.getUUID()), p); + } + } + } + } + + /** + * Updates a player's time in the scoreboard. + * + * @param player of whom to update the scoreboard for. + * @param pris data for the player + */ + private void updatePrisonersBoard(Player player, Prisoner pris) { + boards.get(player.getUniqueId()).getObjective("test").getScore(time).setScore(pris.getRemainingTimeInMinutesInt()); + } +} diff --git a/src/main/java/com/graywolf336/jail/Util.java b/src/main/java/com/graywolf336/jail/Util.java index 8fa5efd..41ad1ab 100644 --- a/src/main/java/com/graywolf336/jail/Util.java +++ b/src/main/java/com/graywolf336/jail/Util.java @@ -1,334 +1,334 @@ -package com.graywolf336.jail; - -import java.io.ByteArrayInputStream; -import java.io.ByteArrayOutputStream; -import java.io.IOException; -import java.util.LinkedList; -import java.util.List; -import java.util.concurrent.TimeUnit; -import java.util.regex.Matcher; -import java.util.regex.Pattern; - -import org.bukkit.Bukkit; -import org.bukkit.ChatColor; -import org.bukkit.Material; -import org.bukkit.entity.Player; -import org.bukkit.inventory.Inventory; -import org.bukkit.inventory.ItemStack; -import org.bukkit.inventory.PlayerInventory; -import org.bukkit.inventory.meta.ItemMeta; -import org.bukkit.util.Vector; -import org.bukkit.util.io.BukkitObjectInputStream; -import org.bukkit.util.io.BukkitObjectOutputStream; -import org.yaml.snakeyaml.external.biz.base64Coder.Base64Coder; - -import com.graywolf336.jail.beans.Prisoner; - -/** - * Provides a variety of methods, static, that are used throughout the plugin. - * - * @author graywolf336 - * @since 2.x.x - * @version 3.0.0 - */ -public class Util { - private final static Pattern DURATION_PATTERN = Pattern.compile("^(\\d+)\\s*(m(?:inute)?s?|h(?:ours?)?|d(?:ays?)?|s(?:econd)?s?)?$", Pattern.CASE_INSENSITIVE); - - /** - * Checks if the first {@link Vector} is inside this region. - * - * @param point The point to check - * @param first point of the region - * @param second second point of the region - * @return True if all the coords of the first vector are in the entire region. - */ - public static boolean isInsideAB(Vector point, Vector first, Vector second) { - boolean x = isInside(point.getBlockX(), first.getBlockX(), second.getBlockX()); - boolean y = isInside(point.getBlockY(), first.getBlockY(), second.getBlockY()); - boolean z = isInside(point.getBlockZ(), first.getBlockZ(), second.getBlockZ()); - - return x && y && z; - } - - /** - * Checks if two numbers are inside a point, or something. - * - *

- * - * @param loc The location. - * @param first The first point - * @param second The second point - * @return true if they are inside, false if not. - */ - private static boolean isInside(int loc, int first, int second) { - int point1 = 0; - int point2 = 0; - if (first < second) { - point1 = first; - point2 = second; - } else { - point2 = first; - point1 = second; - } - - return (point1 <= loc) && (loc <= point2); - } - - /** - * Checks if the given string is inside the list, ignoring the casing. - * - *

- * - * @param list of strings to check - * @param value to check - * @return true if the list contains the provided value, false if it doesn't - */ - public static boolean isStringInsideList(List list, String value) { - boolean r = false; - for(String s : list) - if(s.equalsIgnoreCase(value)) - return true; - - return r; - } - - /** Returns a colorful message from the color codes. */ - public static String getColorfulMessage(String message) { - return message.replaceAll("(?i)&([0-9abcdefklmnor])", "\u00A7$1"); - } - - /** Returns the wand used throughout the different creation steps. */ - public static ItemStack getWand() { - ItemStack wand = new ItemStack(Material.WOOD_SWORD); - ItemMeta meta = wand.getItemMeta(); - meta.setDisplayName(ChatColor.AQUA + "Jail Wand"); - LinkedList lore = new LinkedList(); - lore.add(ChatColor.BLUE + "The wand for creating"); - lore.add(ChatColor.BLUE + "a jail or cell."); - meta.setLore(lore); - wand.setItemMeta(meta); - - return wand; - } - - /** - * Converts a string like '20minutes' into the appropriate amount of milliseconds. - * - * @param time The string to convert. - * @return The time in milliseconds that is converted. - * @throws Exception if there are no matches - */ - public static Long getTime(String time) throws Exception { - if(time.equalsIgnoreCase("-1")) return -1L; - - Long t = 10L; - Matcher match = DURATION_PATTERN.matcher(time); - - if (match.matches()) { - String units = match.group(2); - if ("seconds".equals(units) || "second".equals(units) || "s".equals(units)) - t = TimeUnit.MILLISECONDS.convert(Long.valueOf(match.group(1)), TimeUnit.SECONDS); - else if ("minutes".equals(units) || "minute".equals(units) || "mins".equals(units) || "min".equals(units) || "m".equals(units)) - t = TimeUnit.MILLISECONDS.convert(Long.valueOf(match.group(1)), TimeUnit.MINUTES); - else if ("hours".equals(units) || "hour".equals(units) || "h".equals(units)) - t = TimeUnit.MILLISECONDS.convert(Long.valueOf(match.group(1)), TimeUnit.HOURS); - else if ("days".equals(units) || "day".equals(units) || "d".equals(units)) - t = TimeUnit.MILLISECONDS.convert(Long.valueOf(match.group(1)), TimeUnit.DAYS); - else { - try { - t = TimeUnit.MILLISECONDS.convert(Long.parseLong(time), TimeUnit.MINUTES); - }catch(NumberFormatException e) { - throw new Exception("Invalid format."); - } - } - }else { - throw new Exception("Invalid format."); - } - - 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. - * - * @param playerInventory to turn into an array of strings. - * @return Array of strings: [ main content, armor content ] - * @throws IllegalStateException - */ - public static String[] playerInventoryToBase64(PlayerInventory playerInventory) throws IllegalStateException { - //get the main content part, this doesn't return the armor - String content = toBase64(playerInventory); - String armor = itemStackArrayToBase64(playerInventory.getArmorContents()); - - return new String[] { content, armor }; - } - - /** - * - * A method to serialize an {@link ItemStack} array to Base64 String. - * - *

- * - * Based off of {@link #toBase64(Inventory)}. - * - * @param items to turn into a Base64 String. - * @return Base64 string of the items. - * @throws IllegalStateException - */ - public static String itemStackArrayToBase64(ItemStack[] items) throws IllegalStateException { - try { - ByteArrayOutputStream outputStream = new ByteArrayOutputStream(); - BukkitObjectOutputStream dataOutput = new BukkitObjectOutputStream(outputStream); - - // Write the size of the inventory - dataOutput.writeInt(items.length); - - // Save every element in the list - for (int i = 0; i < items.length; i++) { - dataOutput.writeObject(items[i]); - } - - // Serialize that array - dataOutput.close(); - return Base64Coder.encodeLines(outputStream.toByteArray()); - } catch (Exception e) { - throw new IllegalStateException("Unable to save item stacks.", e); - } - } - - /** - * A method to serialize an inventory to Base64 string. - * - *

- * - * Special thanks to Comphenix in the Bukkit forums or also known - * as aadnk on GitHub. - * - * Original Source - * - * @param inventory to serialize - * @return Base64 string of the provided inventory - * @throws IllegalStateException - */ - public static String toBase64(Inventory inventory) throws IllegalStateException { - try { - ByteArrayOutputStream outputStream = new ByteArrayOutputStream(); - BukkitObjectOutputStream dataOutput = new BukkitObjectOutputStream(outputStream); - - // Write the size of the inventory - dataOutput.writeInt(inventory.getSize()); - - // Save every element in the list - for (int i = 0; i < inventory.getSize(); i++) { - dataOutput.writeObject(inventory.getItem(i)); - } - - // Serialize that array - dataOutput.close(); - return Base64Coder.encodeLines(outputStream.toByteArray()); - } catch (Exception e) { - throw new IllegalStateException("Unable to save item stacks.", e); - } - } - - /** - * - * A method to get an {@link Inventory} from an encoded, Base64, string. - * - *

- * - * Special thanks to Comphenix in the Bukkit forums or also known - * as aadnk on GitHub. - * - * Original Source - * - * @param data Base64 string of data containing an inventory. - * @return Inventory created from the Base64 string. - * @throws IOException - */ - public static Inventory fromBase64(String data) throws IOException { - if(data.isEmpty()) Bukkit.getServer().createInventory(null, 0); - - try { - ByteArrayInputStream inputStream = new ByteArrayInputStream(Base64Coder.decodeLines(data)); - BukkitObjectInputStream dataInput = new BukkitObjectInputStream(inputStream); - Inventory inventory = Bukkit.getServer().createInventory(null, dataInput.readInt()); - - // Read the serialized inventory - for (int i = 0; i < inventory.getSize(); i++) { - inventory.setItem(i, (ItemStack) dataInput.readObject()); - } - - dataInput.close(); - return inventory; - } catch (ClassNotFoundException e) { - throw new IOException("Unable to decode class type.", e); - } - } - - /** - * Gets an array of ItemStacks from Base64 string. - * - *

- * - * Base off of {@link #fromBase64(String)}. - * - * @param data Base64 string to convert to ItemStack array. - * @return ItemStack array created from the Base64 string. - * @throws IOException - */ - public static ItemStack[] itemStackArrayFromBase64(String data) throws IOException { - if(data.isEmpty()) return new ItemStack[] {}; - - try { - ByteArrayInputStream inputStream = new ByteArrayInputStream(Base64Coder.decodeLines(data)); - BukkitObjectInputStream dataInput = new BukkitObjectInputStream(inputStream); - ItemStack[] items = new ItemStack[dataInput.readInt()]; - - // Read the serialized inventory - for (int i = 0; i < items.length; i++) { - items[i] = (ItemStack) dataInput.readObject(); - } - - dataInput.close(); - return items; - } catch (ClassNotFoundException e) { - throw new IOException("Unable to decode class type.", e); - } - } - - public static void restoreInventory(Player player, Prisoner prisoner) { - try { - Inventory content = Util.fromBase64(prisoner.getInventory()); - ItemStack[] armor = Util.itemStackArrayFromBase64(prisoner.getArmor()); - - for(ItemStack item : armor) { - if(item == null) - continue; - else if(item.getType().toString().toLowerCase().contains("helmet")) - player.getInventory().setHelmet(item); - else if(item.getType().toString().toLowerCase().contains("chestplate")) - player.getInventory().setChestplate(item); - else if(item.getType().toString().toLowerCase().contains("leg")) - player.getInventory().setLeggings(item); - else if(item.getType().toString().toLowerCase().contains("boots")) - player.getInventory().setBoots(item); - else if (player.getInventory().firstEmpty() == -1) - player.getWorld().dropItem(player.getLocation(), item); - else - player.getInventory().addItem(item); - } - - for(ItemStack item : content.getContents()) { - if(item == null) continue; - else if(player.getInventory().firstEmpty() == -1) - player.getWorld().dropItem(player.getLocation(), item); - else - player.getInventory().addItem(item); - } - } catch (IOException e) { - e.printStackTrace(); - Bukkit.getLogger().severe("Unable to restore " + player.getName() + "'s inventory."); - } - } -} +package com.graywolf336.jail; + +import java.io.ByteArrayInputStream; +import java.io.ByteArrayOutputStream; +import java.io.IOException; +import java.util.LinkedList; +import java.util.List; +import java.util.concurrent.TimeUnit; +import java.util.regex.Matcher; +import java.util.regex.Pattern; + +import org.bukkit.Bukkit; +import org.bukkit.ChatColor; +import org.bukkit.Material; +import org.bukkit.entity.Player; +import org.bukkit.inventory.Inventory; +import org.bukkit.inventory.ItemStack; +import org.bukkit.inventory.PlayerInventory; +import org.bukkit.inventory.meta.ItemMeta; +import org.bukkit.util.Vector; +import org.bukkit.util.io.BukkitObjectInputStream; +import org.bukkit.util.io.BukkitObjectOutputStream; +import org.yaml.snakeyaml.external.biz.base64Coder.Base64Coder; + +import com.graywolf336.jail.beans.Prisoner; + +/** + * Provides a variety of methods, static, that are used throughout the plugin. + * + * @author graywolf336 + * @since 2.x.x + * @version 3.0.0 + */ +public class Util { + private final static Pattern DURATION_PATTERN = Pattern.compile("^(\\d+)\\s*(m(?:inute)?s?|h(?:ours?)?|d(?:ays?)?|s(?:econd)?s?)?$", Pattern.CASE_INSENSITIVE); + + /** + * Checks if the first {@link Vector} is inside this region. + * + * @param point The point to check + * @param first point of the region + * @param second second point of the region + * @return True if all the coords of the first vector are in the entire region. + */ + public static boolean isInsideAB(Vector point, Vector first, Vector second) { + boolean x = isInside(point.getBlockX(), first.getBlockX(), second.getBlockX()); + boolean y = isInside(point.getBlockY(), first.getBlockY(), second.getBlockY()); + boolean z = isInside(point.getBlockZ(), first.getBlockZ(), second.getBlockZ()); + + return x && y && z; + } + + /** + * Checks if two numbers are inside a point, or something. + * + *

+ * + * @param loc The location. + * @param first The first point + * @param second The second point + * @return true if they are inside, false if not. + */ + private static boolean isInside(int loc, int first, int second) { + int point1 = 0; + int point2 = 0; + if (first < second) { + point1 = first; + point2 = second; + } else { + point2 = first; + point1 = second; + } + + return (point1 <= loc) && (loc <= point2); + } + + /** + * Checks if the given string is inside the list, ignoring the casing. + * + *

+ * + * @param list of strings to check + * @param value to check + * @return true if the list contains the provided value, false if it doesn't + */ + public static boolean isStringInsideList(List list, String value) { + boolean r = false; + for(String s : list) + if(s.equalsIgnoreCase(value)) + return true; + + return r; + } + + /** Returns a colorful message from the color codes. */ + public static String getColorfulMessage(String message) { + return message.replaceAll("(?i)&([0-9abcdefklmnor])", "\u00A7$1"); + } + + /** Returns the wand used throughout the different creation steps. */ + public static ItemStack getWand() { + ItemStack wand = new ItemStack(Material.WOOD_SWORD); + ItemMeta meta = wand.getItemMeta(); + meta.setDisplayName(ChatColor.AQUA + "Jail Wand"); + LinkedList lore = new LinkedList(); + lore.add(ChatColor.BLUE + "The wand for creating"); + lore.add(ChatColor.BLUE + "a jail or cell."); + meta.setLore(lore); + wand.setItemMeta(meta); + + return wand; + } + + /** + * Converts a string like '20minutes' into the appropriate amount of milliseconds. + * + * @param time The string to convert. + * @return The time in milliseconds that is converted. + * @throws Exception if there are no matches + */ + public static Long getTime(String time) throws Exception { + if(time.equalsIgnoreCase("-1")) return -1L; + + Long t = 10L; + Matcher match = DURATION_PATTERN.matcher(time); + + if (match.matches()) { + String units = match.group(2); + if ("seconds".equals(units) || "second".equals(units) || "s".equals(units)) + t = TimeUnit.MILLISECONDS.convert(Long.valueOf(match.group(1)), TimeUnit.SECONDS); + else if ("minutes".equals(units) || "minute".equals(units) || "mins".equals(units) || "min".equals(units) || "m".equals(units)) + t = TimeUnit.MILLISECONDS.convert(Long.valueOf(match.group(1)), TimeUnit.MINUTES); + else if ("hours".equals(units) || "hour".equals(units) || "h".equals(units)) + t = TimeUnit.MILLISECONDS.convert(Long.valueOf(match.group(1)), TimeUnit.HOURS); + else if ("days".equals(units) || "day".equals(units) || "d".equals(units)) + t = TimeUnit.MILLISECONDS.convert(Long.valueOf(match.group(1)), TimeUnit.DAYS); + else { + try { + t = TimeUnit.MILLISECONDS.convert(Long.parseLong(time), TimeUnit.MINUTES); + }catch(NumberFormatException e) { + throw new Exception("Invalid format."); + } + } + }else { + throw new Exception("Invalid format."); + } + + 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. + * + * @param playerInventory to turn into an array of strings. + * @return Array of strings: [ main content, armor content ] + * @throws IllegalStateException + */ + public static String[] playerInventoryToBase64(PlayerInventory playerInventory) throws IllegalStateException { + //get the main content part, this doesn't return the armor + String content = toBase64(playerInventory); + String armor = itemStackArrayToBase64(playerInventory.getArmorContents()); + + return new String[] { content, armor }; + } + + /** + * + * A method to serialize an {@link ItemStack} array to Base64 String. + * + *

+ * + * Based off of {@link #toBase64(Inventory)}. + * + * @param items to turn into a Base64 String. + * @return Base64 string of the items. + * @throws IllegalStateException + */ + public static String itemStackArrayToBase64(ItemStack[] items) throws IllegalStateException { + try { + ByteArrayOutputStream outputStream = new ByteArrayOutputStream(); + BukkitObjectOutputStream dataOutput = new BukkitObjectOutputStream(outputStream); + + // Write the size of the inventory + dataOutput.writeInt(items.length); + + // Save every element in the list + for (int i = 0; i < items.length; i++) { + dataOutput.writeObject(items[i]); + } + + // Serialize that array + dataOutput.close(); + return Base64Coder.encodeLines(outputStream.toByteArray()); + } catch (Exception e) { + throw new IllegalStateException("Unable to save item stacks.", e); + } + } + + /** + * A method to serialize an inventory to Base64 string. + * + *

+ * + * Special thanks to Comphenix in the Bukkit forums or also known + * as aadnk on GitHub. + * + * Original Source + * + * @param inventory to serialize + * @return Base64 string of the provided inventory + * @throws IllegalStateException + */ + public static String toBase64(Inventory inventory) throws IllegalStateException { + try { + ByteArrayOutputStream outputStream = new ByteArrayOutputStream(); + BukkitObjectOutputStream dataOutput = new BukkitObjectOutputStream(outputStream); + + // Write the size of the inventory + dataOutput.writeInt(inventory.getSize()); + + // Save every element in the list + for (int i = 0; i < inventory.getSize(); i++) { + dataOutput.writeObject(inventory.getItem(i)); + } + + // Serialize that array + dataOutput.close(); + return Base64Coder.encodeLines(outputStream.toByteArray()); + } catch (Exception e) { + throw new IllegalStateException("Unable to save item stacks.", e); + } + } + + /** + * + * A method to get an {@link Inventory} from an encoded, Base64, string. + * + *

+ * + * Special thanks to Comphenix in the Bukkit forums or also known + * as aadnk on GitHub. + * + * Original Source + * + * @param data Base64 string of data containing an inventory. + * @return Inventory created from the Base64 string. + * @throws IOException + */ + public static Inventory fromBase64(String data) throws IOException { + if(data.isEmpty()) Bukkit.getServer().createInventory(null, 0); + + try { + ByteArrayInputStream inputStream = new ByteArrayInputStream(Base64Coder.decodeLines(data)); + BukkitObjectInputStream dataInput = new BukkitObjectInputStream(inputStream); + Inventory inventory = Bukkit.getServer().createInventory(null, dataInput.readInt()); + + // Read the serialized inventory + for (int i = 0; i < inventory.getSize(); i++) { + inventory.setItem(i, (ItemStack) dataInput.readObject()); + } + + dataInput.close(); + return inventory; + } catch (ClassNotFoundException e) { + throw new IOException("Unable to decode class type.", e); + } + } + + /** + * Gets an array of ItemStacks from Base64 string. + * + *

+ * + * Base off of {@link #fromBase64(String)}. + * + * @param data Base64 string to convert to ItemStack array. + * @return ItemStack array created from the Base64 string. + * @throws IOException + */ + public static ItemStack[] itemStackArrayFromBase64(String data) throws IOException { + if(data.isEmpty()) return new ItemStack[] {}; + + try { + ByteArrayInputStream inputStream = new ByteArrayInputStream(Base64Coder.decodeLines(data)); + BukkitObjectInputStream dataInput = new BukkitObjectInputStream(inputStream); + ItemStack[] items = new ItemStack[dataInput.readInt()]; + + // Read the serialized inventory + for (int i = 0; i < items.length; i++) { + items[i] = (ItemStack) dataInput.readObject(); + } + + dataInput.close(); + return items; + } catch (ClassNotFoundException e) { + throw new IOException("Unable to decode class type.", e); + } + } + + public static void restoreInventory(Player player, Prisoner prisoner) { + try { + Inventory content = Util.fromBase64(prisoner.getInventory()); + ItemStack[] armor = Util.itemStackArrayFromBase64(prisoner.getArmor()); + + for(ItemStack item : armor) { + if(item == null) + continue; + else if(item.getType().toString().toLowerCase().contains("helmet")) + player.getInventory().setHelmet(item); + else if(item.getType().toString().toLowerCase().contains("chestplate")) + player.getInventory().setChestplate(item); + else if(item.getType().toString().toLowerCase().contains("leg")) + player.getInventory().setLeggings(item); + else if(item.getType().toString().toLowerCase().contains("boots")) + player.getInventory().setBoots(item); + else if (player.getInventory().firstEmpty() == -1) + player.getWorld().dropItem(player.getLocation(), item); + else + player.getInventory().addItem(item); + } + + for(ItemStack item : content.getContents()) { + if(item == null) continue; + else if(player.getInventory().firstEmpty() == -1) + player.getWorld().dropItem(player.getLocation(), item); + else + player.getInventory().addItem(item); + } + } catch (IOException e) { + e.printStackTrace(); + Bukkit.getLogger().severe("Unable to restore " + player.getName() + "'s inventory."); + } + } +} diff --git a/src/main/java/com/graywolf336/jail/beans/CachePrisoner.java b/src/main/java/com/graywolf336/jail/beans/CachePrisoner.java index 9aa8853..03988b9 100644 --- a/src/main/java/com/graywolf336/jail/beans/CachePrisoner.java +++ b/src/main/java/com/graywolf336/jail/beans/CachePrisoner.java @@ -1,28 +1,28 @@ -package com.graywolf336.jail.beans; - -/** - * An object for storing online cached prisoners. - * - * @author graywolf336 - * @since 3.0.0 - * @version 1.0.0 - */ -public class CachePrisoner { - private Jail jail; - private Prisoner p; - - public CachePrisoner(Jail jail, Prisoner prisoner) { - this.jail = jail; - this.p = prisoner; - } - - /** Gets the Jail this cache is in. */ - public Jail getJail() { - return this.jail; - } - - /** Gets the Prisoner in this cache. */ - public Prisoner getPrisoner() { - return this.p; - } -} +package com.graywolf336.jail.beans; + +/** + * An object for storing online cached prisoners. + * + * @author graywolf336 + * @since 3.0.0 + * @version 1.0.0 + */ +public class CachePrisoner { + private Jail jail; + private Prisoner p; + + public CachePrisoner(Jail jail, Prisoner prisoner) { + this.jail = jail; + this.p = prisoner; + } + + /** Gets the Jail this cache is in. */ + public Jail getJail() { + return this.jail; + } + + /** Gets the Prisoner in this cache. */ + public Prisoner getPrisoner() { + return this.p; + } +} diff --git a/src/main/java/com/graywolf336/jail/beans/ConfirmPlayer.java b/src/main/java/com/graywolf336/jail/beans/ConfirmPlayer.java index 4415cbc..f9b3af8 100644 --- a/src/main/java/com/graywolf336/jail/beans/ConfirmPlayer.java +++ b/src/main/java/com/graywolf336/jail/beans/ConfirmPlayer.java @@ -1,44 +1,44 @@ -package com.graywolf336.jail.beans; - -import com.graywolf336.jail.enums.Confirmation; - -/** - * Holds data for when a player is confirming a command. - * - * @author graywolf336 - * @version 1.0.0 - * @since 3.0.0 - */ -public class ConfirmPlayer { - private String name; - private String[] args; - private Confirmation confirm; - private Long expires; - - public ConfirmPlayer(String name, String[] args, Confirmation confirm) { - this.name = name; - this.args = args; - this.confirm = confirm; - this.expires = System.currentTimeMillis() + 5000L; - } - - /** Returns the name of the thing needing to confirm. */ - public String getName() { - return this.name; - } - - /** Returns the initial arguments they sent with their command. */ - public String[] getArguments() { - return this.args; - } - - /** Returns what they are {@link Confirmation confirming}. */ - public Confirmation getConfirming() { - return this.confirm; - } - - /** Returns the time in milliseconds their confirmation time frame expires. */ - public Long getExpiryTime() { - return this.expires; - } -} +package com.graywolf336.jail.beans; + +import com.graywolf336.jail.enums.Confirmation; + +/** + * Holds data for when a player is confirming a command. + * + * @author graywolf336 + * @version 1.0.0 + * @since 3.0.0 + */ +public class ConfirmPlayer { + private String name; + private String[] args; + private Confirmation confirm; + private Long expires; + + public ConfirmPlayer(String name, String[] args, Confirmation confirm) { + this.name = name; + this.args = args; + this.confirm = confirm; + this.expires = System.currentTimeMillis() + 5000L; + } + + /** Returns the name of the thing needing to confirm. */ + public String getName() { + return this.name; + } + + /** Returns the initial arguments they sent with their command. */ + public String[] getArguments() { + return this.args; + } + + /** Returns what they are {@link Confirmation confirming}. */ + public Confirmation getConfirming() { + return this.confirm; + } + + /** Returns the time in milliseconds their confirmation time frame expires. */ + public Long getExpiryTime() { + return this.expires; + } +} diff --git a/src/main/java/com/graywolf336/jail/beans/Jail.java b/src/main/java/com/graywolf336/jail/beans/Jail.java index 16f3fb3..129cbc7 100644 --- a/src/main/java/com/graywolf336/jail/beans/Jail.java +++ b/src/main/java/com/graywolf336/jail/beans/Jail.java @@ -1,382 +1,382 @@ -package com.graywolf336.jail.beans; - -import java.util.HashMap; -import java.util.HashSet; -import java.util.UUID; - -import org.bukkit.Location; -import org.bukkit.World; -import org.bukkit.block.Sign; -import org.bukkit.entity.Player; -import org.bukkit.util.Vector; - -import com.graywolf336.jail.JailMain; -import com.graywolf336.jail.Util; - -/** Represents a Jail, contains the prisoners and the cells. - * - * @author graywolf336 - * @since 3.0.0 - * @version 1.0.3 - */ -public class Jail { - private JailMain plugin; - private HashMap cells; - private HashMap nocellPrisoners;//prisoners who aren't in a cell - private String name = "", world = ""; - private int minX, minY, minZ, maxX, maxY, maxZ; - private Location in, free; - - public Jail(JailMain plugin, String name) { - this.plugin = plugin; - this.name = name; - cells = new HashMap(); - nocellPrisoners = new HashMap(); - } - - /** Gets the instance of the plugin's main class. */ - public JailMain getPlugin() { - return this.plugin; - } - - /** Sets the name of the jail. */ - public void setName(String name) { - this.name = name; - } - - /** Gets the name of the jail. */ - public String getName() { - return this.name; - } - - /** Sets the location of the minimum point to the given location's coordinates. */ - public void setMinPoint(Location location) { - if(this.world.isEmpty()) this.world = location.getWorld().getName(); - - this.minX = location.getBlockX(); - this.minY = location.getBlockY(); - this.minZ = location.getBlockZ(); - } - - /** Accepts an array of ints as the coord, where 0 = x, 1 = y, 2 = z. */ - public void setMinPoint(int[] coords) { - if(coords.length != 3) return; - - this.minX = coords[0]; - this.minY = coords[1]; - this.minZ = coords[2]; - } - - /** Gets the minimum point as a Bukkit Location class. */ - public Location getMinPoint() { - return new Location(plugin.getServer().getWorld(world), minX, minY, minZ); - } - - /** Sets the location of the maximum point to the given location's coordinates. */ - public void setMaxPoint(Location location) { - if(this.world.isEmpty()) this.world = location.getWorld().getName(); - - this.maxX = location.getBlockX(); - this.maxY = location.getBlockY(); - this.maxZ = location.getBlockZ(); - } - - /** Gets the minimum point as a Bukkit Location class. */ - public Location getMaxPoint() { - return new Location(plugin.getServer().getWorld(world), maxX, maxY, maxZ); - } - - /** Accepts an array of ints as the coord, where 0 = x, 1 = y, 2 = z. */ - public void setMaxPoint(int[] coords) { - if(coords.length != 3) return; - - this.maxX = coords[0]; - this.maxY = coords[1]; - this.maxZ = coords[2]; - } - - /** Sets the name of the world this Jail is in. */ - public void setWorld(String name) { - this.world = name; - } - - /** Gets the name of the world this Jail is in. */ - public String getWorldName() { - return this.world; - } - - /** Gets the instance of the {@link World world} this Jail is in. */ - public World getWorld() { - return plugin.getServer().getWorld(world); - } - - /** Sets the {@link Location location} of the teleport in. */ - public void setTeleportIn(Location location) { - if(this.world.isEmpty()) this.world = location.getWorld().getName(); - - this.in = location; - } - - /** Gets the {@link Location location} of the teleport in. */ - public Location getTeleportIn() { - return this.in; - } - - /** Sets the {@link Location location} of the teleport for the free spot. */ - public void setTeleportFree(Location location) { - this.free = location; - } - - /** Gets the {@link Location location} of the teleport free spot.*/ - public Location getTeleportFree() { - return this.free; - } - - /** Add a prisoner to this jail. */ - public void addPrisoner(Prisoner p) { - this.nocellPrisoners.put(p.getUUID(), p); - } - - /** Removes a prisoner from this jail, doesn't remove it from the cell. */ - public void removePrisoner(Prisoner p) { - this.nocellPrisoners.remove(p); - } - - /** Adds a cell to the Jail. */ - public void addCell(Cell cell, boolean save) { - if(save) plugin.getJailIO().saveCell(this, cell); - this.cells.put(cell.getName(), cell); - } - - /** Gets the cell with the given name. */ - public Cell getCell(String name) { - return this.cells.get(name); - } - - /** Checks if the given name is a valid cell. */ - public boolean isValidCell(String name) { - return this.cells.get(name) != null; - } - - /** Removes the cell from the jail. */ - public void removeCell(String name) { - Cell c = this.cells.get(name); - //If we have a chest, clear the inventory - if(c.hasChest()) { - c.getChest().getInventory().clear(); - } - - //For each sign, clear the lines on the sign - for(SimpleLocation s : c.getSigns()) { - if(s.getLocation().getBlock() instanceof Sign) { - Sign sign = (Sign) s.getLocation().getBlock(); - for(int i = 0; i < 4; i++) { - sign.setLine(i, ""); - } - } - } - - //remove the information from the storage first as it requires an instance - plugin.getJailIO().removeCell(this, c); - //now remove it from the local storage - this.cells.remove(name); - } - - /** Returns the cell which the given player name is jailed in, null if not. */ - public Cell getCellPrisonerIsIn(UUID uuid) { - for(Cell c : cells.values()) - if(c.hasPrisoner()) - if(c.getPrisoner().getUUID().equals(uuid)) - return c; - - return null; - } - - /** Returns the first empty cell, returns null if there aren't any cells or any free cells. */ - public Cell getFirstEmptyCell() { - for(Cell c : getCells()) - if(c.hasPrisoner()) - continue; - else - return c; - - return null; - } - - /** Gets the amount of cells the jail. */ - public int getCellCount() { - return this.cells.size(); - } - - /** Gets all the cells in the jail. */ - public HashSet getCells() { - return new HashSet(this.cells.values()); - } - - /** Gets the closest cell to the provided location, via the teleport in location of the cells. */ - public Cell getNearestCell(Location loc) { - Cell cell = null; - double distance = -1; - - for(Cell c : getCells()) { - //Check if the worlds are the same, if not we can't calculate anything - if(c.getTeleport().getWorld().getName().equalsIgnoreCase(loc.getWorld().getName())) { - //They are in the same world - double dist = c.getTeleport().distance(loc); - if (dist < distance || distance < 0) { - cell = c; - distance = dist; - } - }else { - //If they aren't, return the first cell found. - return c; - } - } - - return cell; - } - - /** Clears all the prisoners from this Jail. */ - public void clearPrisoners() { - //Remove the prisoners from all the cells - for(Cell c : getCells()) { - c.removePrisoner(); - } - - //Replace all the current no cell prisoners with - //a new hashset of prisoners. - this.nocellPrisoners = new HashMap(); - } - - /** Gets a HashMap of all the prisoners, the ones in cells and ones who aren't. */ - public HashMap getAllPrisoners() { - HashMap all = new HashMap(nocellPrisoners); //initalize the temp one to return with the prisoners not in any cells - - for(Cell c : cells.values()) - if(c.hasPrisoner()) - all.put(c.getPrisoner().getUUID(), c.getPrisoner()); - - return all; - } - - /** Gets a HashSet of the prisoners in cells. */ - public HashSet getPrisonersInCells() { - HashSet all = new HashSet(); - - for(Cell c : getCells()) - if(c.hasPrisoner()) - all.add(c.getPrisoner()); - - return all; - } - - /** Gets a HashSet of the prisoners not in cells.*/ - public HashMap getPrisonersNotInCells() { - return this.nocellPrisoners; - } - - /** - * Returns whether the player is a prisoner in the system, whether in a cell or no cell. - * - * @param player The {@link Player player instance} of the person we're checking. - * @return true if is jailed, false if not. - */ - public boolean isPlayerJailed(Player player) { - return this.isPlayerAPrisoner(player.getUniqueId()); - } - - /** - * Returns whether the uuid of a player is a prisoner in the system, whether in a cell or no cell. - * - * @param uuid The uuid of the person we're checking. - * @return true if is jailed, false if not. - */ - public boolean isPlayerJailed(UUID uuid) { - return this.isPlayerAPrisoner(uuid); - } - - /** - * Returns whether the uuid of a player is a prisoner in this jail, no matter if they're in a cell or not. - * - * @param uuid The name of the person we're checking. - * @return true if is a prisoner, false if not. - */ - private boolean isPlayerAPrisoner(UUID uuid) { - return this.getAllPrisoners().containsKey(uuid); - } - - /** - * Checks if the given uuid of a player is a prisoner in a cell. - * - * @param uuid of the prisoner to check. - * @return true if is jailed in a cell, false if not. - */ - public boolean isJailedInACell(UUID uuid) { - if(this.nocellPrisoners.containsKey(uuid)) return false; - - for(Cell c : cells.values()) - if(c.getPrisoner() != null) - if(c.getPrisoner().getUUID().equals(uuid)) - return true; - - return false; - } - - /** - * Gets the {@link Prisoner prisoner} instance for the given name. - * - * @param name The name of the prisoner to get. - * @return the prisoner instance, can be null - */ - public Prisoner getPrisonerByLastKnownName(String name) { - for(Prisoner p : this.getAllPrisoners().values()) - if(p.getLastKnownName().equalsIgnoreCase(name)) - return p; - - return null; - } - - /** - * Gets the {@link Prisoner prisoner} instance for the given uuid. - * - * @param uuid The uuid of the prisoner to get. - * @return the prisoner instance, can be null - */ - public Prisoner getPrisoner(UUID uuid) { - if(this.nocellPrisoners.containsKey(uuid)) return this.nocellPrisoners.get(uuid); - - for(Cell c : cells.values()) - if(c.hasPrisoner()) - if(c.getPrisoner().getUUID().equals(uuid)) - return c.getPrisoner(); - - return null; - } - - /** - * Returns the squared distance between teleport location of this jail - * and specified location in blocks. If locations are not in same world, - * distance cannot be calculated and it will return Integer.MAX_VALUE. - * - * @param loc The location to check - * @return Distance between the location provided and the teleport in location. - */ - public double getDistance(Location loc) { - if (loc.getWorld().getName().equalsIgnoreCase(getTeleportIn().getWorld().getName())) return (double) Integer.MAX_VALUE; - else return loc.distance(getTeleportIn()); - } - - /** - * Returns whether the given location is inside this Jail. - * - * @param loc to check whether is inside this jail - * @return True if the location is in the jail, false if it isn't - */ - public boolean isInside(Location loc) { - if(loc.getWorld().getName().equalsIgnoreCase(world)) { - return Util.isInsideAB(loc.toVector(), new Vector(minX, minY, minZ), new Vector(maxX, maxY, maxZ)); - }else { - return false; - } - } -} +package com.graywolf336.jail.beans; + +import java.util.HashMap; +import java.util.HashSet; +import java.util.UUID; + +import org.bukkit.Location; +import org.bukkit.World; +import org.bukkit.block.Sign; +import org.bukkit.entity.Player; +import org.bukkit.util.Vector; + +import com.graywolf336.jail.JailMain; +import com.graywolf336.jail.Util; + +/** Represents a Jail, contains the prisoners and the cells. + * + * @author graywolf336 + * @since 3.0.0 + * @version 1.0.3 + */ +public class Jail { + private JailMain plugin; + private HashMap cells; + private HashMap nocellPrisoners;//prisoners who aren't in a cell + private String name = "", world = ""; + private int minX, minY, minZ, maxX, maxY, maxZ; + private Location in, free; + + public Jail(JailMain plugin, String name) { + this.plugin = plugin; + this.name = name; + cells = new HashMap(); + nocellPrisoners = new HashMap(); + } + + /** Gets the instance of the plugin's main class. */ + public JailMain getPlugin() { + return this.plugin; + } + + /** Sets the name of the jail. */ + public void setName(String name) { + this.name = name; + } + + /** Gets the name of the jail. */ + public String getName() { + return this.name; + } + + /** Sets the location of the minimum point to the given location's coordinates. */ + public void setMinPoint(Location location) { + if(this.world.isEmpty()) this.world = location.getWorld().getName(); + + this.minX = location.getBlockX(); + this.minY = location.getBlockY(); + this.minZ = location.getBlockZ(); + } + + /** Accepts an array of ints as the coord, where 0 = x, 1 = y, 2 = z. */ + public void setMinPoint(int[] coords) { + if(coords.length != 3) return; + + this.minX = coords[0]; + this.minY = coords[1]; + this.minZ = coords[2]; + } + + /** Gets the minimum point as a Bukkit Location class. */ + public Location getMinPoint() { + return new Location(plugin.getServer().getWorld(world), minX, minY, minZ); + } + + /** Sets the location of the maximum point to the given location's coordinates. */ + public void setMaxPoint(Location location) { + if(this.world.isEmpty()) this.world = location.getWorld().getName(); + + this.maxX = location.getBlockX(); + this.maxY = location.getBlockY(); + this.maxZ = location.getBlockZ(); + } + + /** Gets the minimum point as a Bukkit Location class. */ + public Location getMaxPoint() { + return new Location(plugin.getServer().getWorld(world), maxX, maxY, maxZ); + } + + /** Accepts an array of ints as the coord, where 0 = x, 1 = y, 2 = z. */ + public void setMaxPoint(int[] coords) { + if(coords.length != 3) return; + + this.maxX = coords[0]; + this.maxY = coords[1]; + this.maxZ = coords[2]; + } + + /** Sets the name of the world this Jail is in. */ + public void setWorld(String name) { + this.world = name; + } + + /** Gets the name of the world this Jail is in. */ + public String getWorldName() { + return this.world; + } + + /** Gets the instance of the {@link World world} this Jail is in. */ + public World getWorld() { + return plugin.getServer().getWorld(world); + } + + /** Sets the {@link Location location} of the teleport in. */ + public void setTeleportIn(Location location) { + if(this.world.isEmpty()) this.world = location.getWorld().getName(); + + this.in = location; + } + + /** Gets the {@link Location location} of the teleport in. */ + public Location getTeleportIn() { + return this.in; + } + + /** Sets the {@link Location location} of the teleport for the free spot. */ + public void setTeleportFree(Location location) { + this.free = location; + } + + /** Gets the {@link Location location} of the teleport free spot.*/ + public Location getTeleportFree() { + return this.free; + } + + /** Add a prisoner to this jail. */ + public void addPrisoner(Prisoner p) { + this.nocellPrisoners.put(p.getUUID(), p); + } + + /** Removes a prisoner from this jail, doesn't remove it from the cell. */ + public void removePrisoner(Prisoner p) { + this.nocellPrisoners.remove(p); + } + + /** Adds a cell to the Jail. */ + public void addCell(Cell cell, boolean save) { + if(save) plugin.getJailIO().saveCell(this, cell); + this.cells.put(cell.getName(), cell); + } + + /** Gets the cell with the given name. */ + public Cell getCell(String name) { + return this.cells.get(name); + } + + /** Checks if the given name is a valid cell. */ + public boolean isValidCell(String name) { + return this.cells.get(name) != null; + } + + /** Removes the cell from the jail. */ + public void removeCell(String name) { + Cell c = this.cells.get(name); + //If we have a chest, clear the inventory + if(c.hasChest()) { + c.getChest().getInventory().clear(); + } + + //For each sign, clear the lines on the sign + for(SimpleLocation s : c.getSigns()) { + if(s.getLocation().getBlock() instanceof Sign) { + Sign sign = (Sign) s.getLocation().getBlock(); + for(int i = 0; i < 4; i++) { + sign.setLine(i, ""); + } + } + } + + //remove the information from the storage first as it requires an instance + plugin.getJailIO().removeCell(this, c); + //now remove it from the local storage + this.cells.remove(name); + } + + /** Returns the cell which the given player name is jailed in, null if not. */ + public Cell getCellPrisonerIsIn(UUID uuid) { + for(Cell c : cells.values()) + if(c.hasPrisoner()) + if(c.getPrisoner().getUUID().equals(uuid)) + return c; + + return null; + } + + /** Returns the first empty cell, returns null if there aren't any cells or any free cells. */ + public Cell getFirstEmptyCell() { + for(Cell c : getCells()) + if(c.hasPrisoner()) + continue; + else + return c; + + return null; + } + + /** Gets the amount of cells the jail. */ + public int getCellCount() { + return this.cells.size(); + } + + /** Gets all the cells in the jail. */ + public HashSet getCells() { + return new HashSet(this.cells.values()); + } + + /** Gets the closest cell to the provided location, via the teleport in location of the cells. */ + public Cell getNearestCell(Location loc) { + Cell cell = null; + double distance = -1; + + for(Cell c : getCells()) { + //Check if the worlds are the same, if not we can't calculate anything + if(c.getTeleport().getWorld().getName().equalsIgnoreCase(loc.getWorld().getName())) { + //They are in the same world + double dist = c.getTeleport().distance(loc); + if (dist < distance || distance < 0) { + cell = c; + distance = dist; + } + }else { + //If they aren't, return the first cell found. + return c; + } + } + + return cell; + } + + /** Clears all the prisoners from this Jail. */ + public void clearPrisoners() { + //Remove the prisoners from all the cells + for(Cell c : getCells()) { + c.removePrisoner(); + } + + //Replace all the current no cell prisoners with + //a new hashset of prisoners. + this.nocellPrisoners = new HashMap(); + } + + /** Gets a HashMap of all the prisoners, the ones in cells and ones who aren't. */ + public HashMap getAllPrisoners() { + HashMap all = new HashMap(nocellPrisoners); //initalize the temp one to return with the prisoners not in any cells + + for(Cell c : cells.values()) + if(c.hasPrisoner()) + all.put(c.getPrisoner().getUUID(), c.getPrisoner()); + + return all; + } + + /** Gets a HashSet of the prisoners in cells. */ + public HashSet getPrisonersInCells() { + HashSet all = new HashSet(); + + for(Cell c : getCells()) + if(c.hasPrisoner()) + all.add(c.getPrisoner()); + + return all; + } + + /** Gets a HashSet of the prisoners not in cells.*/ + public HashMap getPrisonersNotInCells() { + return this.nocellPrisoners; + } + + /** + * Returns whether the player is a prisoner in the system, whether in a cell or no cell. + * + * @param player The {@link Player player instance} of the person we're checking. + * @return true if is jailed, false if not. + */ + public boolean isPlayerJailed(Player player) { + return this.isPlayerAPrisoner(player.getUniqueId()); + } + + /** + * Returns whether the uuid of a player is a prisoner in the system, whether in a cell or no cell. + * + * @param uuid The uuid of the person we're checking. + * @return true if is jailed, false if not. + */ + public boolean isPlayerJailed(UUID uuid) { + return this.isPlayerAPrisoner(uuid); + } + + /** + * Returns whether the uuid of a player is a prisoner in this jail, no matter if they're in a cell or not. + * + * @param uuid The name of the person we're checking. + * @return true if is a prisoner, false if not. + */ + private boolean isPlayerAPrisoner(UUID uuid) { + return this.getAllPrisoners().containsKey(uuid); + } + + /** + * Checks if the given uuid of a player is a prisoner in a cell. + * + * @param uuid of the prisoner to check. + * @return true if is jailed in a cell, false if not. + */ + public boolean isJailedInACell(UUID uuid) { + if(this.nocellPrisoners.containsKey(uuid)) return false; + + for(Cell c : cells.values()) + if(c.getPrisoner() != null) + if(c.getPrisoner().getUUID().equals(uuid)) + return true; + + return false; + } + + /** + * Gets the {@link Prisoner prisoner} instance for the given name. + * + * @param name The name of the prisoner to get. + * @return the prisoner instance, can be null + */ + public Prisoner getPrisonerByLastKnownName(String name) { + for(Prisoner p : this.getAllPrisoners().values()) + if(p.getLastKnownName().equalsIgnoreCase(name)) + return p; + + return null; + } + + /** + * Gets the {@link Prisoner prisoner} instance for the given uuid. + * + * @param uuid The uuid of the prisoner to get. + * @return the prisoner instance, can be null + */ + public Prisoner getPrisoner(UUID uuid) { + if(this.nocellPrisoners.containsKey(uuid)) return this.nocellPrisoners.get(uuid); + + for(Cell c : cells.values()) + if(c.hasPrisoner()) + if(c.getPrisoner().getUUID().equals(uuid)) + return c.getPrisoner(); + + return null; + } + + /** + * Returns the squared distance between teleport location of this jail + * and specified location in blocks. If locations are not in same world, + * distance cannot be calculated and it will return Integer.MAX_VALUE. + * + * @param loc The location to check + * @return Distance between the location provided and the teleport in location. + */ + public double getDistance(Location loc) { + if (loc.getWorld().getName().equalsIgnoreCase(getTeleportIn().getWorld().getName())) return (double) Integer.MAX_VALUE; + else return loc.distance(getTeleportIn()); + } + + /** + * Returns whether the given location is inside this Jail. + * + * @param loc to check whether is inside this jail + * @return True if the location is in the jail, false if it isn't + */ + public boolean isInside(Location loc) { + if(loc.getWorld().getName().equalsIgnoreCase(world)) { + return Util.isInsideAB(loc.toVector(), new Vector(minX, minY, minZ), new Vector(maxX, maxY, maxZ)); + }else { + return false; + } + } +} diff --git a/src/main/java/com/graywolf336/jail/beans/Prisoner.java b/src/main/java/com/graywolf336/jail/beans/Prisoner.java index c60c9ea..945aeb1 100644 --- a/src/main/java/com/graywolf336/jail/beans/Prisoner.java +++ b/src/main/java/com/graywolf336/jail/beans/Prisoner.java @@ -1,254 +1,254 @@ -package com.graywolf336.jail.beans; - -import java.util.UUID; -import java.util.concurrent.TimeUnit; - -import org.bukkit.Bukkit; -import org.bukkit.GameMode; -import org.bukkit.Location; - -/** - * Represents a Prisoner, player who is jailed, and contains all the information about him/her. - * - * @author graywolf336 - * @since 2.x.x - * @version 3.0.1 - */ -public class Prisoner { - private String uuid, name, jailer, reason, inventory, armor; - private boolean muted, offlinePending, teleporting, toBeTransferred; - private long time, afk; - private Location previousPosition; - private GameMode previousGameMode; - - /** - * Creates a new prisoner with a name and whether they are muted or not. - * - * @param uuid The uuid of the prisoner - * @param name The name of the prisoner - * @param muted Whether the prisoner is muted or not - * @param time The amount of remaining time the prisoner has - * @param jailer The name of the person who jailed this prisoner - * @param reason The reason why this prisoner is in jail - */ - public Prisoner(String uuid, String name, boolean muted, long time, String jailer, String reason) { - this.uuid = uuid; - this.name = name; - this.muted = muted; - this.time = time; - this.jailer = jailer; - this.reason = reason; - this.offlinePending = false; - this.teleporting = false; - this.toBeTransferred = false; - this.previousPosition = null; - this.previousGameMode = GameMode.SURVIVAL; - this.inventory = ""; - this.armor = ""; - this.afk = 0; - } - - /** Returns the UUID of the prisoner. */ - public UUID getUUID() { - return UUID.fromString(this.uuid); - } - - /** Gets the name of this prisoner. */ - public String getLastKnownName() { - return this.name; - } - - /** Sets the name of this prisoner. */ - public String setLastKnownName(String username) { - this.name = username; - return this.name; - } - - /** Gets the reason this player was jailed for. */ - public String getReason() { - return this.reason; - } - - /** Sets the reason this player was jailed for. */ - public void setReason(String reason) { - this.reason = reason; - } - - /** Gets the person who jailed this prisoner. */ - public String getJailer() { - return this.jailer; - } - - /** Sets the person who jailed this prisoner. */ - public void setJailer(String jailer) { - this.jailer = jailer; - } - - /** Gets whether the prisoner is muted or not. */ - public boolean isMuted() { - return this.muted; - } - - /** Sets whether the prisoner is muted or not. */ - public void setMuted(boolean muted) { - this.muted = muted; - } - - /** Gets the remaining time the prisoner has. */ - public long getRemainingTime() { - return this.time; - } - - /** Gets the remaining time the prisoner has in minutes. */ - public long getRemainingTimeInMinutes() { - return TimeUnit.MINUTES.convert(time, TimeUnit.MILLISECONDS); - } - - /** Gets the remaining time the prison has in minutes except only in int format. */ - public int getRemainingTimeInMinutesInt() { - return (int) this.getRemainingTimeInMinutes(); - } - - /** - * Sets the remaining time the prisoner has left. - * - * @param time The amount of time left, in milliseconds. - */ - public void setRemainingTime(long time) { - this.time = time; - } - - /** - * Adds the given time to the remaining time the prisoner has left. - * - * @param time to add to the prisoner's remaining time. - * @return the new remaining time the prisoner has - */ - public long addTime(long time) { - this.time += time; - return this.time; - } - - /** - * Subtracts the given time from the remaining time the prisoner has left. - * - * @param time to subtract from the prisoner's remaining time. - * @return the new remaining time the prisoner has - */ - public long subtractTime(long time) { - this.time -= time; - return this.time; - } - - /** Gets whether the player is offline or not. */ - public boolean isOfflinePending() { - return this.offlinePending; - } - - /** Sets whether the player is offline or not. */ - public void setOfflinePending(boolean offline) { - this.offlinePending = offline; - } - - /** Gets whether the player is being teleported or not. */ - public boolean isTeleporting() { - return this.teleporting; - } - - /** Sets whether the player is being teleported or not. */ - public void setTeleporting(boolean teleport) { - this.teleporting = teleport; - } - - /** Gets whether the prisoner is going to be transferred or not, mainly for teleporting on join purposes. */ - public boolean isToBeTransferred() { - return this.toBeTransferred; - } - - /** Sets whether the prisoner is going to be transferred or not, mainly for teleporting on join purposes. */ - public void setToBeTransferred(boolean transferred) { - this.toBeTransferred = transferred; - } - - /** Gets the previous location of this player, can be null. */ - public Location getPreviousLocation() { - return this.previousPosition; - } - - /** Gets the previous location of this player, separated by a comma. */ - public String getPreviousLocationString() { - if(previousPosition == null) return ""; - else return previousPosition.getWorld().getName() + "," + - previousPosition.getX() + "," + - previousPosition.getY() + "," + - previousPosition.getZ() + "," + - previousPosition.getYaw() + "," + - previousPosition.getPitch(); - } - - /** Sets the previous location of this player. */ - public void setPreviousPosition(Location location) { - this.previousPosition = location; - } - - /** Sets the previous location of this player from a comma separated string. */ - public void setPreviousPosition(String location) { - if(location == null) return; - if(location.isEmpty()) return; - - String[] s = location.split(","); - this.previousPosition = new Location(Bukkit.getWorld(s[0]), - Double.valueOf(s[1]), - Double.valueOf(s[2]), - Double.valueOf(s[3]), - Float.valueOf(s[4]), - Float.valueOf(s[5])); - } - - /** Gets the previous gamemode of this player. */ - public GameMode getPreviousGameMode() { - return this.previousGameMode; - } - - /** Sets the previous gamemode of this player. */ - public void setPreviousGameMode(GameMode previous) { - this.previousGameMode = previous; - } - - /** Sets the previous gamemode of this player based upon the provided string. */ - public void setPreviousGameMode(String previous) { - if(previous == null) return; - else if(previous.isEmpty()) return; - else this.previousGameMode = GameMode.valueOf(previous); - } - - /** Gets the inventory string for this player, it is encoded in Base64 string. */ - public String getInventory() { - return this.inventory; - } - - /** Sets the inventory Base64 string. */ - public void setInventory(String inventory) { - this.inventory = inventory; - } - - /** Gets the armor content, encoded in Base64 string. */ - public String getArmor() { - return this.armor; - } - - /** Sets the armor inventory Base64 string. */ - public void setArmor(String armor) { - this.armor = armor; - } - - /** Gets the time, in milliseconds, this prisoner has been afk. */ - public long getAFKTime() { - return this.afk; - } - - /** Sets the time, in milliseconds, this prisoner has been afk. */ - public void setAFKTime(long time) { - this.afk = time; - } -} +package com.graywolf336.jail.beans; + +import java.util.UUID; +import java.util.concurrent.TimeUnit; + +import org.bukkit.Bukkit; +import org.bukkit.GameMode; +import org.bukkit.Location; + +/** + * Represents a Prisoner, player who is jailed, and contains all the information about him/her. + * + * @author graywolf336 + * @since 2.x.x + * @version 3.0.1 + */ +public class Prisoner { + private String uuid, name, jailer, reason, inventory, armor; + private boolean muted, offlinePending, teleporting, toBeTransferred; + private long time, afk; + private Location previousPosition; + private GameMode previousGameMode; + + /** + * Creates a new prisoner with a name and whether they are muted or not. + * + * @param uuid The uuid of the prisoner + * @param name The name of the prisoner + * @param muted Whether the prisoner is muted or not + * @param time The amount of remaining time the prisoner has + * @param jailer The name of the person who jailed this prisoner + * @param reason The reason why this prisoner is in jail + */ + public Prisoner(String uuid, String name, boolean muted, long time, String jailer, String reason) { + this.uuid = uuid; + this.name = name; + this.muted = muted; + this.time = time; + this.jailer = jailer; + this.reason = reason; + this.offlinePending = false; + this.teleporting = false; + this.toBeTransferred = false; + this.previousPosition = null; + this.previousGameMode = GameMode.SURVIVAL; + this.inventory = ""; + this.armor = ""; + this.afk = 0; + } + + /** Returns the UUID of the prisoner. */ + public UUID getUUID() { + return UUID.fromString(this.uuid); + } + + /** Gets the name of this prisoner. */ + public String getLastKnownName() { + return this.name; + } + + /** Sets the name of this prisoner. */ + public String setLastKnownName(String username) { + this.name = username; + return this.name; + } + + /** Gets the reason this player was jailed for. */ + public String getReason() { + return this.reason; + } + + /** Sets the reason this player was jailed for. */ + public void setReason(String reason) { + this.reason = reason; + } + + /** Gets the person who jailed this prisoner. */ + public String getJailer() { + return this.jailer; + } + + /** Sets the person who jailed this prisoner. */ + public void setJailer(String jailer) { + this.jailer = jailer; + } + + /** Gets whether the prisoner is muted or not. */ + public boolean isMuted() { + return this.muted; + } + + /** Sets whether the prisoner is muted or not. */ + public void setMuted(boolean muted) { + this.muted = muted; + } + + /** Gets the remaining time the prisoner has. */ + public long getRemainingTime() { + return this.time; + } + + /** Gets the remaining time the prisoner has in minutes. */ + public long getRemainingTimeInMinutes() { + return TimeUnit.MINUTES.convert(time, TimeUnit.MILLISECONDS); + } + + /** Gets the remaining time the prison has in minutes except only in int format. */ + public int getRemainingTimeInMinutesInt() { + return (int) this.getRemainingTimeInMinutes(); + } + + /** + * Sets the remaining time the prisoner has left. + * + * @param time The amount of time left, in milliseconds. + */ + public void setRemainingTime(long time) { + this.time = time; + } + + /** + * Adds the given time to the remaining time the prisoner has left. + * + * @param time to add to the prisoner's remaining time. + * @return the new remaining time the prisoner has + */ + public long addTime(long time) { + this.time += time; + return this.time; + } + + /** + * Subtracts the given time from the remaining time the prisoner has left. + * + * @param time to subtract from the prisoner's remaining time. + * @return the new remaining time the prisoner has + */ + public long subtractTime(long time) { + this.time -= time; + return this.time; + } + + /** Gets whether the player is offline or not. */ + public boolean isOfflinePending() { + return this.offlinePending; + } + + /** Sets whether the player is offline or not. */ + public void setOfflinePending(boolean offline) { + this.offlinePending = offline; + } + + /** Gets whether the player is being teleported or not. */ + public boolean isTeleporting() { + return this.teleporting; + } + + /** Sets whether the player is being teleported or not. */ + public void setTeleporting(boolean teleport) { + this.teleporting = teleport; + } + + /** Gets whether the prisoner is going to be transferred or not, mainly for teleporting on join purposes. */ + public boolean isToBeTransferred() { + return this.toBeTransferred; + } + + /** Sets whether the prisoner is going to be transferred or not, mainly for teleporting on join purposes. */ + public void setToBeTransferred(boolean transferred) { + this.toBeTransferred = transferred; + } + + /** Gets the previous location of this player, can be null. */ + public Location getPreviousLocation() { + return this.previousPosition; + } + + /** Gets the previous location of this player, separated by a comma. */ + public String getPreviousLocationString() { + if(previousPosition == null) return ""; + else return previousPosition.getWorld().getName() + "," + + previousPosition.getX() + "," + + previousPosition.getY() + "," + + previousPosition.getZ() + "," + + previousPosition.getYaw() + "," + + previousPosition.getPitch(); + } + + /** Sets the previous location of this player. */ + public void setPreviousPosition(Location location) { + this.previousPosition = location; + } + + /** Sets the previous location of this player from a comma separated string. */ + public void setPreviousPosition(String location) { + if(location == null) return; + if(location.isEmpty()) return; + + String[] s = location.split(","); + this.previousPosition = new Location(Bukkit.getWorld(s[0]), + Double.valueOf(s[1]), + Double.valueOf(s[2]), + Double.valueOf(s[3]), + Float.valueOf(s[4]), + Float.valueOf(s[5])); + } + + /** Gets the previous gamemode of this player. */ + public GameMode getPreviousGameMode() { + return this.previousGameMode; + } + + /** Sets the previous gamemode of this player. */ + public void setPreviousGameMode(GameMode previous) { + this.previousGameMode = previous; + } + + /** Sets the previous gamemode of this player based upon the provided string. */ + public void setPreviousGameMode(String previous) { + if(previous == null) return; + else if(previous.isEmpty()) return; + else this.previousGameMode = GameMode.valueOf(previous); + } + + /** Gets the inventory string for this player, it is encoded in Base64 string. */ + public String getInventory() { + return this.inventory; + } + + /** Sets the inventory Base64 string. */ + public void setInventory(String inventory) { + this.inventory = inventory; + } + + /** Gets the armor content, encoded in Base64 string. */ + public String getArmor() { + return this.armor; + } + + /** Sets the armor inventory Base64 string. */ + public void setArmor(String armor) { + this.armor = armor; + } + + /** Gets the time, in milliseconds, this prisoner has been afk. */ + public long getAFKTime() { + return this.afk; + } + + /** Sets the time, in milliseconds, this prisoner has been afk. */ + public void setAFKTime(long time) { + this.afk = time; + } +} diff --git a/src/main/java/com/graywolf336/jail/beans/SimpleLocation.java b/src/main/java/com/graywolf336/jail/beans/SimpleLocation.java index f263a01..ec2c73c 100644 --- a/src/main/java/com/graywolf336/jail/beans/SimpleLocation.java +++ b/src/main/java/com/graywolf336/jail/beans/SimpleLocation.java @@ -1,103 +1,103 @@ -package com.graywolf336.jail.beans; - -import org.bukkit.Bukkit; -import org.bukkit.Location; -import org.bukkit.World; - -/** - * Simple location class which doesn't store any instances of {@link World worlds} or {@link org.bukkit.block.Block blocks}, just uses strings, floats, and doubles. - * - * @author graywolf336 - * @since 3.0.0 - * @version 1.1.1 - */ -public class SimpleLocation { - private String world; - private double x, y, z; - private float yaw, pitch; - - /** - * Creates a new SimpleLocation with each detail provided separately. - * - * @param world as a string - * @param x coordinate as a double - * @param y coordinate as a double - * @param z coordinate as a double - * @param yaw as a float - * @param pitch as a float - */ - public SimpleLocation(String world, double x, double y, double z, float yaw, float pitch) { - this.world = world; - this.x = x; - this.y = y; - this.z = z; - this.yaw = yaw; - this.pitch = pitch; - } - - /** - * Creates a new SimpleLocation with all the detail provided from {@link Location}. - * - * @param location to convert to a SimpleLocation - */ - public SimpleLocation(Location location) { - this.world = location.getWorld().getName(); - this.x = location.getX(); - this.y = location.getY(); - this.z = location.getZ(); - this.yaw = location.getYaw(); - this.pitch = location.getPitch(); - } - - /** - * Creates a new Simple Location with all the inputs being in string. - * - * @param world the name of the world - * @param x coordinate as a string - * @param y coordinate as a string - * @param z coordinate as a string - */ - public SimpleLocation(String world, String x, String y, String z) { - this.world = world; - this.x = Double.valueOf(x); - this.y = Double.valueOf(y); - this.z = Double.valueOf(z); - this.yaw = 0; - this.pitch = 0; - } - - /** - * Creates a new SimpleLocation with each detail provided separately. - * - * @param world as a string - * @param x coordinate as a double - * @param y coordinate as a double - * @param z coordinate as a double - */ - public SimpleLocation(String world, double x, double y, double z) { - this.world = world; - this.x = x; - this.y = y; - this.z = z; - } - - /** Returns the instance from Bukkit of the world this location is in. */ - public World getWorld() { - return Bukkit.getWorld(world); - } - - /** Returns the name of the world this location is in. */ - public String getWorldName() { - return this.world; - } - - /** Returns a new {@link Location} from this SimpleLocation. */ - public Location getLocation() { - return new Location(Bukkit.getWorld(world), x, y, z, yaw, pitch); - } - - @Override - public String toString() { - return world + "," + x + "," + y + "," + z + "," + yaw + "," + pitch; - } -} +package com.graywolf336.jail.beans; + +import org.bukkit.Bukkit; +import org.bukkit.Location; +import org.bukkit.World; + +/** + * Simple location class which doesn't store any instances of {@link World worlds} or {@link org.bukkit.block.Block blocks}, just uses strings, floats, and doubles. + * + * @author graywolf336 + * @since 3.0.0 + * @version 1.1.1 + */ +public class SimpleLocation { + private String world; + private double x, y, z; + private float yaw, pitch; + + /** + * Creates a new SimpleLocation with each detail provided separately. + * + * @param world as a string + * @param x coordinate as a double + * @param y coordinate as a double + * @param z coordinate as a double + * @param yaw as a float + * @param pitch as a float + */ + public SimpleLocation(String world, double x, double y, double z, float yaw, float pitch) { + this.world = world; + this.x = x; + this.y = y; + this.z = z; + this.yaw = yaw; + this.pitch = pitch; + } + + /** + * Creates a new SimpleLocation with all the detail provided from {@link Location}. + * + * @param location to convert to a SimpleLocation + */ + public SimpleLocation(Location location) { + this.world = location.getWorld().getName(); + this.x = location.getX(); + this.y = location.getY(); + this.z = location.getZ(); + this.yaw = location.getYaw(); + this.pitch = location.getPitch(); + } + + /** + * Creates a new Simple Location with all the inputs being in string. + * + * @param world the name of the world + * @param x coordinate as a string + * @param y coordinate as a string + * @param z coordinate as a string + */ + public SimpleLocation(String world, String x, String y, String z) { + this.world = world; + this.x = Double.valueOf(x); + this.y = Double.valueOf(y); + this.z = Double.valueOf(z); + this.yaw = 0; + this.pitch = 0; + } + + /** + * Creates a new SimpleLocation with each detail provided separately. + * + * @param world as a string + * @param x coordinate as a double + * @param y coordinate as a double + * @param z coordinate as a double + */ + public SimpleLocation(String world, double x, double y, double z) { + this.world = world; + this.x = x; + this.y = y; + this.z = z; + } + + /** Returns the instance from Bukkit of the world this location is in. */ + public World getWorld() { + return Bukkit.getWorld(world); + } + + /** Returns the name of the world this location is in. */ + public String getWorldName() { + return this.world; + } + + /** Returns a new {@link Location} from this SimpleLocation. */ + public Location getLocation() { + return new Location(Bukkit.getWorld(world), x, y, z, yaw, pitch); + } + + @Override + public String toString() { + return world + "," + x + "," + y + "," + z + "," + yaw + "," + pitch; + } +} diff --git a/src/main/java/com/graywolf336/jail/beans/Stick.java b/src/main/java/com/graywolf336/jail/beans/Stick.java index bebc578..175af9c 100644 --- a/src/main/java/com/graywolf336/jail/beans/Stick.java +++ b/src/main/java/com/graywolf336/jail/beans/Stick.java @@ -1,37 +1,37 @@ -package com.graywolf336.jail.beans; - -/** - * Represents a Jail Stick, contains all the information. - * - * @author graywolf336 - * @version 1.0.1 - * @since 3.0.0 - * - */ -public class Stick { - private String jail, reason; - private long time; - - public Stick(String jail, String reason, long time) { - this.jail = jail; - this.reason = reason; - this.time = time; - } - - public String getJail() { - return this.jail; - } - - public String getReason() { - return this.reason; - } - - public long getTime() { - return this.time; - } - - @Override - public String toString() { - return time + "," + jail + "," + reason; - } -} +package com.graywolf336.jail.beans; + +/** + * Represents a Jail Stick, contains all the information. + * + * @author graywolf336 + * @version 1.0.1 + * @since 3.0.0 + * + */ +public class Stick { + private String jail, reason; + private long time; + + public Stick(String jail, String reason, long time) { + this.jail = jail; + this.reason = reason; + this.time = time; + } + + public String getJail() { + return this.jail; + } + + public String getReason() { + return this.reason; + } + + public long getTime() { + return this.time; + } + + @Override + public String toString() { + return time + "," + jail + "," + reason; + } +} diff --git a/src/main/java/com/graywolf336/jail/command/CommandHandler.java b/src/main/java/com/graywolf336/jail/command/CommandHandler.java index 7180192..00f4b7d 100644 --- a/src/main/java/com/graywolf336/jail/command/CommandHandler.java +++ b/src/main/java/com/graywolf336/jail/command/CommandHandler.java @@ -1,173 +1,173 @@ -package com.graywolf336.jail.command; - -import java.util.ArrayList; -import java.util.LinkedHashMap; -import java.util.List; -import java.util.Map.Entry; - -import org.bukkit.command.CommandSender; -import org.bukkit.entity.Player; - -import com.graywolf336.jail.JailMain; -import com.graywolf336.jail.JailManager; -import com.graywolf336.jail.command.commands.HandCuffCommand; -import com.graywolf336.jail.command.commands.ToggleJailDebugCommand; -import com.graywolf336.jail.command.commands.UnHandCuffCommand; -import com.graywolf336.jail.command.commands.UnJailForceCommand; -import com.graywolf336.jail.command.commands.UnJailCommand; -import com.graywolf336.jail.enums.LangString; - -/** - * Where all the commands are registered at and handled, processed, at. - * - * @author graywolf336 - * @since 3.0.0 - * @version 1.0.2 - * - */ -public class CommandHandler { - private LinkedHashMap commands; - - public CommandHandler(JailMain plugin) { - commands = new LinkedHashMap(); - loadCommands(); - - plugin.debug("Loaded " + commands.size() + " commands."); - } - - /** - * Handles the given command and checks that the command is in valid form. - * - *

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

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

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

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

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

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

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

    + *
  1. If they have permission for it, if they don't then we send them a message stating so.
  2. + *
  3. If the command needs a player instance, if so we send a message stating that.
  4. + *
  5. If the required minimum arguments have been passed, if not sends the usage.
  6. + *
  7. If the required maximum arguments have been passed (if there is a max, -1 if no max), if not sends the usage.
  8. + *
  9. Then executes, upon failed execution it sends the usage command.
  10. + *
+ * + * @param jailmanager The instance of {@link JailManager}. + * @param sender The sender of the command. + * @param args The arguments passed to the command. + */ + public boolean parseCommand(JailManager jailmanager, CommandSender sender, String[] args) { + Command c = null; + + //If they didn't provide any arguments (aka just: /jail) then we will need to send them some help + if(args.length == 0) { + //TODO: Create the help page(s) + c = getMatches("jail").get(0); + + }else { + //Get the matches from the first argument passed + List matches = getMatches(args[0]); + + if(matches.size() == 0) { + //No matches found, thus it is more likely than not they are trying to jail someone + c = getMatches("jail").get(0); + + } else if(matches.size() > 1) { + //If there was found more than one match + //then let's send the usage of each match to the sender + for(Command cmd : matches) + showUsage(sender, cmd); + return true; + + }else { + //Only one match was found, so let's continue + c = matches.get(0); + } + } + + CommandInfo i = c.getClass().getAnnotation(CommandInfo.class); + + // First, let's check if the sender has permission for the command. + if(!i.permission().isEmpty()) { + if(!sender.hasPermission(i.permission())) { + jailmanager.getPlugin().debug("Sender has no permission."); + sender.sendMessage(jailmanager.getPlugin().getJailIO().getLanguageString(LangString.NOPERMISSION)); + return true; + } + } + + // Next, let's check if we need a player and then if the sender is actually a player + if(i.needsPlayer() && !(sender instanceof Player)) { + jailmanager.getPlugin().debug("Sender is not a player."); + sender.sendMessage(jailmanager.getPlugin().getJailIO().getLanguageString(LangString.PLAYERCONTEXTREQUIRED)); + return true; + } + + // Now, let's check the size of the arguments passed. If it is shorter than the minimum required args, let's show the usage. + // The reason we are subtracting one is because the command is now `/jail ` and the subcommand is viewed as an argument + if(args.length - 1 < i.minimumArgs()) { + jailmanager.getPlugin().debug("Sender didn't provide enough arguments."); + showUsage(sender, c); + return true; + } + + // Then, if the maximumArgs doesn't equal -1, we need to check if the size of the arguments passed is greater than the maximum args. + // The reason we are subtracting one is because the command is now `/jail ` and the subcommand is viewed as an argument + if(i.maxArgs() != -1 && i.maxArgs() < args.length - 1) { + jailmanager.getPlugin().debug("Sender provided too many arguments."); + showUsage(sender, c); + return true; + } + + // Since everything has been checked and we're all clear, let's execute it. + // But if get back false, let's show the usage message. + try { + if(!c.execute(jailmanager, sender, args)) { + showUsage(sender, c); + return true; + }else { + return true; + } + } catch (Exception e) { + if(jailmanager.getPlugin().inDebug()) { + e.printStackTrace(); + } + + jailmanager.getPlugin().getLogger().severe("An error occured while handling the command: " + i.usage()); + showUsage(sender, c); + return true; + } + } + + private List getMatches(String command) { + List result = new ArrayList(); + + for(Entry entry : commands.entrySet()) { + if(command.matches(entry.getKey())) { + result.add(entry.getValue()); + } + } + + return result; + } + + /** + * Shows the usage information to the sender, if they have permission. + * + * @param sender The sender of the command + * @param command The command to send usage of. + */ + private void showUsage(CommandSender sender, Command command) { + CommandInfo info = command.getClass().getAnnotation(CommandInfo.class); + if(!sender.hasPermission(info.permission())) return; + + sender.sendMessage(info.usage()); + } + + private void loadCommands() { + load(JailCellCreateCommand.class); + load(JailCheckCommand.class); + load(JailClearCommand.class); + load(JailClearForceCommand.class); + load(JailCommand.class); + load(JailConfirmCommand.class); + load(JailCreateCommand.class); + load(JailDeleteCellCommand.class); + load(JailDeleteCellsCommand.class); + load(JailDeleteCommand.class); + load(JailListCellsCommand.class); + load(JailListCommand.class); + load(JailMuteCommand.class); + load(JailPayCommand.class); + load(JailRecordCommand.class); + load(JailReloadCommand.class); + load(JailStatusCommand.class); + load(JailStopCommand.class); + load(JailTeleInCommand.class); + load(JailTeleOutCommand.class); + load(JailTimeCommand.class); + load(JailTransferAllCommand.class); + load(JailTransferCommand.class); + load(JailVersionCommand.class); + } + + private void load(Class c) { + CommandInfo info = c.getAnnotation(CommandInfo.class); + if(info == null) return; + + try { + commands.put(info.pattern(), c.newInstance()); + }catch(Exception e) { + e.printStackTrace(); + } + } +} diff --git a/src/main/java/com/graywolf336/jail/command/commands/HandCuffCommand.java b/src/main/java/com/graywolf336/jail/command/commands/HandCuffCommand.java index 9336800..a941c99 100644 --- a/src/main/java/com/graywolf336/jail/command/commands/HandCuffCommand.java +++ b/src/main/java/com/graywolf336/jail/command/commands/HandCuffCommand.java @@ -1,41 +1,41 @@ -package com.graywolf336.jail.command.commands; - -import org.bukkit.command.CommandSender; -import org.bukkit.entity.Player; - -import com.graywolf336.jail.JailManager; -import com.graywolf336.jail.command.Command; -import com.graywolf336.jail.command.CommandInfo; -import com.graywolf336.jail.enums.LangString; - -@CommandInfo( - maxArgs = 1, - minimumArgs = 1, - needsPlayer = false, - pattern = "handcuff|hc", - permission = "jail.command.handcuff", - usage = "/handcuff [player]" - ) -public class HandCuffCommand implements Command { - public boolean execute(JailManager jm, CommandSender sender, String... args) { - Player player = jm.getPlugin().getServer().getPlayer(args[0]); - - if(player == null) { - sender.sendMessage(jm.getPlugin().getJailIO().getLanguageString(LangString.PLAYERNOTONLINE)); - }else if(player.hasPermission("jail.cantbehandcuffed")) { - sender.sendMessage(jm.getPlugin().getJailIO().getLanguageString(LangString.CANTBEHANDCUFFED, new String[] { player.getName() })); - }else if(jm.isPlayerJailed(player.getUniqueId())) { - sender.sendMessage(jm.getPlugin().getJailIO().getLanguageString(LangString.CURRENTLYJAILEDHANDCUFF, new String[] { player.getName() })); - }else if(jm.getPlugin().getHandCuffManager().isHandCuffed(player.getUniqueId())) { - sender.sendMessage(jm.getPlugin().getJailIO().getLanguageString(LangString.HANDCUFFSRELEASED, new String[] { player.getName() })); - jm.getPlugin().getHandCuffManager().removeHandCuffs(player.getUniqueId()); - player.sendMessage(jm.getPlugin().getJailIO().getLanguageString(LangString.UNHANDCUFFED)); - }else { - jm.getPlugin().getHandCuffManager().addHandCuffs(player.getUniqueId(), player.getLocation()); - sender.sendMessage(jm.getPlugin().getJailIO().getLanguageString(LangString.HANDCUFFSON, new String[] { player.getName() })); - player.sendMessage(jm.getPlugin().getJailIO().getLanguageString(LangString.HANDCUFFED)); - } - - return true; - } -} +package com.graywolf336.jail.command.commands; + +import org.bukkit.command.CommandSender; +import org.bukkit.entity.Player; + +import com.graywolf336.jail.JailManager; +import com.graywolf336.jail.command.Command; +import com.graywolf336.jail.command.CommandInfo; +import com.graywolf336.jail.enums.LangString; + +@CommandInfo( + maxArgs = 1, + minimumArgs = 1, + needsPlayer = false, + pattern = "handcuff|hc", + permission = "jail.command.handcuff", + usage = "/handcuff [player]" + ) +public class HandCuffCommand implements Command { + public boolean execute(JailManager jm, CommandSender sender, String... args) { + Player player = jm.getPlugin().getServer().getPlayer(args[0]); + + if(player == null) { + sender.sendMessage(jm.getPlugin().getJailIO().getLanguageString(LangString.PLAYERNOTONLINE)); + }else if(player.hasPermission("jail.cantbehandcuffed")) { + sender.sendMessage(jm.getPlugin().getJailIO().getLanguageString(LangString.CANTBEHANDCUFFED, new String[] { player.getName() })); + }else if(jm.isPlayerJailed(player.getUniqueId())) { + sender.sendMessage(jm.getPlugin().getJailIO().getLanguageString(LangString.CURRENTLYJAILEDHANDCUFF, new String[] { player.getName() })); + }else if(jm.getPlugin().getHandCuffManager().isHandCuffed(player.getUniqueId())) { + sender.sendMessage(jm.getPlugin().getJailIO().getLanguageString(LangString.HANDCUFFSRELEASED, new String[] { player.getName() })); + jm.getPlugin().getHandCuffManager().removeHandCuffs(player.getUniqueId()); + player.sendMessage(jm.getPlugin().getJailIO().getLanguageString(LangString.UNHANDCUFFED)); + }else { + jm.getPlugin().getHandCuffManager().addHandCuffs(player.getUniqueId(), player.getLocation()); + sender.sendMessage(jm.getPlugin().getJailIO().getLanguageString(LangString.HANDCUFFSON, new String[] { player.getName() })); + player.sendMessage(jm.getPlugin().getJailIO().getLanguageString(LangString.HANDCUFFED)); + } + + return true; + } +} diff --git a/src/main/java/com/graywolf336/jail/command/commands/ToggleJailDebugCommand.java b/src/main/java/com/graywolf336/jail/command/commands/ToggleJailDebugCommand.java index 3739de5..a0b6a35 100644 --- a/src/main/java/com/graywolf336/jail/command/commands/ToggleJailDebugCommand.java +++ b/src/main/java/com/graywolf336/jail/command/commands/ToggleJailDebugCommand.java @@ -1,24 +1,24 @@ -package com.graywolf336.jail.command.commands; - -import org.bukkit.ChatColor; -import org.bukkit.command.CommandSender; - -import com.graywolf336.jail.JailManager; -import com.graywolf336.jail.command.Command; -import com.graywolf336.jail.command.CommandInfo; - -@CommandInfo( - maxArgs = 0, - minimumArgs = 0, - needsPlayer = false, - pattern = "togglejaildebug|tjd", - permission = "jail.command.toggledebug", - usage = "/togglejaildebug" - ) -public class ToggleJailDebugCommand implements Command { - public boolean execute(JailManager jm, CommandSender sender, String... args) { - boolean debug = jm.getPlugin().setDebugging(!jm.getPlugin().inDebug()); - sender.sendMessage("Jail debugging is now: " + (debug ? ChatColor.GREEN + "enabled" : ChatColor.RED + "disabled")); - return true; - } -} +package com.graywolf336.jail.command.commands; + +import org.bukkit.ChatColor; +import org.bukkit.command.CommandSender; + +import com.graywolf336.jail.JailManager; +import com.graywolf336.jail.command.Command; +import com.graywolf336.jail.command.CommandInfo; + +@CommandInfo( + maxArgs = 0, + minimumArgs = 0, + needsPlayer = false, + pattern = "togglejaildebug|tjd", + permission = "jail.command.toggledebug", + usage = "/togglejaildebug" + ) +public class ToggleJailDebugCommand implements Command { + public boolean execute(JailManager jm, CommandSender sender, String... args) { + boolean debug = jm.getPlugin().setDebugging(!jm.getPlugin().inDebug()); + sender.sendMessage("Jail debugging is now: " + (debug ? ChatColor.GREEN + "enabled" : ChatColor.RED + "disabled")); + return true; + } +} diff --git a/src/main/java/com/graywolf336/jail/command/commands/UnHandCuffCommand.java b/src/main/java/com/graywolf336/jail/command/commands/UnHandCuffCommand.java index 78d3af5..8b92d9a 100644 --- a/src/main/java/com/graywolf336/jail/command/commands/UnHandCuffCommand.java +++ b/src/main/java/com/graywolf336/jail/command/commands/UnHandCuffCommand.java @@ -1,35 +1,35 @@ -package com.graywolf336.jail.command.commands; - -import org.bukkit.command.CommandSender; -import org.bukkit.entity.Player; - -import com.graywolf336.jail.JailManager; -import com.graywolf336.jail.command.Command; -import com.graywolf336.jail.command.CommandInfo; -import com.graywolf336.jail.enums.LangString; - -@CommandInfo( - maxArgs = 1, - minimumArgs = 1, - needsPlayer = false, - pattern = "unhandcuff|uhc", - permission = "jail.command.handcuff", - usage = "/unhandcuff [player]" - ) -public class UnHandCuffCommand implements Command { - public boolean execute(JailManager jm, CommandSender sender, String... args) { - Player player = jm.getPlugin().getServer().getPlayerExact(args[0]); - - if(player == null) { - sender.sendMessage(jm.getPlugin().getJailIO().getLanguageString(LangString.PLAYERNOTONLINE)); - }else if(jm.getPlugin().getHandCuffManager().isHandCuffed(player.getUniqueId())) { - sender.sendMessage(jm.getPlugin().getJailIO().getLanguageString(LangString.HANDCUFFSRELEASED, new String[] { player.getName() })); - jm.getPlugin().getHandCuffManager().removeHandCuffs(player.getUniqueId()); - player.sendMessage(jm.getPlugin().getJailIO().getLanguageString(LangString.UNHANDCUFFED)); - }else { - sender.sendMessage(jm.getPlugin().getJailIO().getLanguageString(LangString.NOTHANDCUFFED, new String[] { player.getName() })); - } - - return true; - } -} +package com.graywolf336.jail.command.commands; + +import org.bukkit.command.CommandSender; +import org.bukkit.entity.Player; + +import com.graywolf336.jail.JailManager; +import com.graywolf336.jail.command.Command; +import com.graywolf336.jail.command.CommandInfo; +import com.graywolf336.jail.enums.LangString; + +@CommandInfo( + maxArgs = 1, + minimumArgs = 1, + needsPlayer = false, + pattern = "unhandcuff|uhc", + permission = "jail.command.handcuff", + usage = "/unhandcuff [player]" + ) +public class UnHandCuffCommand implements Command { + public boolean execute(JailManager jm, CommandSender sender, String... args) { + Player player = jm.getPlugin().getServer().getPlayerExact(args[0]); + + if(player == null) { + sender.sendMessage(jm.getPlugin().getJailIO().getLanguageString(LangString.PLAYERNOTONLINE)); + }else if(jm.getPlugin().getHandCuffManager().isHandCuffed(player.getUniqueId())) { + sender.sendMessage(jm.getPlugin().getJailIO().getLanguageString(LangString.HANDCUFFSRELEASED, new String[] { player.getName() })); + jm.getPlugin().getHandCuffManager().removeHandCuffs(player.getUniqueId()); + player.sendMessage(jm.getPlugin().getJailIO().getLanguageString(LangString.UNHANDCUFFED)); + }else { + sender.sendMessage(jm.getPlugin().getJailIO().getLanguageString(LangString.NOTHANDCUFFED, new String[] { player.getName() })); + } + + return true; + } +} diff --git a/src/main/java/com/graywolf336/jail/command/commands/UnJailCommand.java b/src/main/java/com/graywolf336/jail/command/commands/UnJailCommand.java index bf2c452..db8b5d6 100644 --- a/src/main/java/com/graywolf336/jail/command/commands/UnJailCommand.java +++ b/src/main/java/com/graywolf336/jail/command/commands/UnJailCommand.java @@ -1,64 +1,64 @@ -package com.graywolf336.jail.command.commands; - -import org.bukkit.ChatColor; -import org.bukkit.command.CommandSender; -import org.bukkit.entity.Player; - -import com.graywolf336.jail.JailManager; -import com.graywolf336.jail.beans.Jail; -import com.graywolf336.jail.beans.Prisoner; -import com.graywolf336.jail.command.Command; -import com.graywolf336.jail.command.CommandInfo; -import com.graywolf336.jail.enums.LangString; -import com.graywolf336.jail.enums.Settings; - -@CommandInfo( - maxArgs = 1, - minimumArgs = 1, - needsPlayer = false, - pattern = "unjail|uj", - permission = "jail.command.unjail", - usage = "/unjail [player]" - ) -public class UnJailCommand implements Command { - - public boolean execute(JailManager jm, CommandSender sender, String... args) { - //Check if the player is jailed - if(jm.isPlayerJailedByLastKnownUsername(args[0])) { - Jail j = jm.getJailPlayerIsInByLastKnownName(args[0]); - Prisoner pris = j.getPrisonerByLastKnownName(args[0]); - Player p = jm.getPlugin().getServer().getPlayer(pris.getUUID()); - - //Check if the player is on the server or not - if(p == null) { - //Check if the player has offline pending and their remaining time is above 0, if so then - //forceably unjail them - if(pris.isOfflinePending() && pris.getRemainingTime() != 0L) { - jm.getPlugin().getPrisonerManager().forceUnJail(j, j.getCellPrisonerIsIn(pris.getUUID()), p, pris); - sender.sendMessage(jm.getPlugin().getJailIO().getLanguageString(LangString.FORCEUNJAILED, args[0])); - }else { - //The player is not, so we'll set the remaining time to zero and do it when they login next - pris.setRemainingTime(0L); - pris.setOfflinePending(true); - sender.sendMessage(jm.getPlugin().getJailIO().getLanguageString(LangString.WILLBEUNJAILED, args[0])); - } - }else { - //Player is online, so let's try unjailing them - try { - jm.getPlugin().getPrisonerManager().unJail(j, j.getCellPrisonerIsIn(pris.getUUID()), p, pris); - } catch (Exception e) { - sender.sendMessage(ChatColor.RED + e.getMessage()); - } - } - - 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() }))); - } - }else { - //The player is not currently jailed - sender.sendMessage(jm.getPlugin().getJailIO().getLanguageString(LangString.NOTJAILED, args[0])); - } - - return true; - } -} +package com.graywolf336.jail.command.commands; + +import org.bukkit.ChatColor; +import org.bukkit.command.CommandSender; +import org.bukkit.entity.Player; + +import com.graywolf336.jail.JailManager; +import com.graywolf336.jail.beans.Jail; +import com.graywolf336.jail.beans.Prisoner; +import com.graywolf336.jail.command.Command; +import com.graywolf336.jail.command.CommandInfo; +import com.graywolf336.jail.enums.LangString; +import com.graywolf336.jail.enums.Settings; + +@CommandInfo( + maxArgs = 1, + minimumArgs = 1, + needsPlayer = false, + pattern = "unjail|uj", + permission = "jail.command.unjail", + usage = "/unjail [player]" + ) +public class UnJailCommand implements Command { + + public boolean execute(JailManager jm, CommandSender sender, String... args) { + //Check if the player is jailed + if(jm.isPlayerJailedByLastKnownUsername(args[0])) { + Jail j = jm.getJailPlayerIsInByLastKnownName(args[0]); + Prisoner pris = j.getPrisonerByLastKnownName(args[0]); + Player p = jm.getPlugin().getServer().getPlayer(pris.getUUID()); + + //Check if the player is on the server or not + if(p == null) { + //Check if the player has offline pending and their remaining time is above 0, if so then + //forceably unjail them + if(pris.isOfflinePending() && pris.getRemainingTime() != 0L) { + jm.getPlugin().getPrisonerManager().forceUnJail(j, j.getCellPrisonerIsIn(pris.getUUID()), p, pris); + sender.sendMessage(jm.getPlugin().getJailIO().getLanguageString(LangString.FORCEUNJAILED, args[0])); + }else { + //The player is not, so we'll set the remaining time to zero and do it when they login next + pris.setRemainingTime(0L); + pris.setOfflinePending(true); + sender.sendMessage(jm.getPlugin().getJailIO().getLanguageString(LangString.WILLBEUNJAILED, args[0])); + } + }else { + //Player is online, so let's try unjailing them + try { + jm.getPlugin().getPrisonerManager().unJail(j, j.getCellPrisonerIsIn(pris.getUUID()), p, pris); + } catch (Exception e) { + sender.sendMessage(ChatColor.RED + e.getMessage()); + } + } + + 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() }))); + } + }else { + //The player is not currently jailed + sender.sendMessage(jm.getPlugin().getJailIO().getLanguageString(LangString.NOTJAILED, args[0])); + } + + return true; + } +} diff --git a/src/main/java/com/graywolf336/jail/command/commands/UnJailForceCommand.java b/src/main/java/com/graywolf336/jail/command/commands/UnJailForceCommand.java index 7201004..e33f0e0 100644 --- a/src/main/java/com/graywolf336/jail/command/commands/UnJailForceCommand.java +++ b/src/main/java/com/graywolf336/jail/command/commands/UnJailForceCommand.java @@ -1,38 +1,38 @@ -package com.graywolf336.jail.command.commands; - -import org.bukkit.ChatColor; -import org.bukkit.command.CommandSender; - -import com.graywolf336.jail.JailManager; -import com.graywolf336.jail.command.Command; -import com.graywolf336.jail.command.CommandInfo; -import com.graywolf336.jail.enums.LangString; -import com.graywolf336.jail.enums.Settings; - -@CommandInfo( - maxArgs = 1, - minimumArgs = 1, - needsPlayer = false, - pattern = "unjailforce|ujf", - permission = "jail.command.unjailforce", - usage = "/unjailforce [player]" - ) -public class UnJailForceCommand implements Command { - - public boolean execute(JailManager jm, CommandSender sender, String... args) { - //Check if the player is jailed - if(jm.isPlayerJailedByLastKnownUsername(args[0])) { - jm.getPlugin().getPrisonerManager().forceRelease(jm.getPrisonerByLastKnownName(args[0])); - sender.sendMessage(jm.getPlugin().getJailIO().getLanguageString(LangString.FORCEUNJAILED, args[0])); - - 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() }))); - } - }else { - //The player is not currently jailed - sender.sendMessage(jm.getPlugin().getJailIO().getLanguageString(LangString.NOTJAILED, args[0])); - } - - return true; - } -} +package com.graywolf336.jail.command.commands; + +import org.bukkit.ChatColor; +import org.bukkit.command.CommandSender; + +import com.graywolf336.jail.JailManager; +import com.graywolf336.jail.command.Command; +import com.graywolf336.jail.command.CommandInfo; +import com.graywolf336.jail.enums.LangString; +import com.graywolf336.jail.enums.Settings; + +@CommandInfo( + maxArgs = 1, + minimumArgs = 1, + needsPlayer = false, + pattern = "unjailforce|ujf", + permission = "jail.command.unjailforce", + usage = "/unjailforce [player]" + ) +public class UnJailForceCommand implements Command { + + public boolean execute(JailManager jm, CommandSender sender, String... args) { + //Check if the player is jailed + if(jm.isPlayerJailedByLastKnownUsername(args[0])) { + jm.getPlugin().getPrisonerManager().forceRelease(jm.getPrisonerByLastKnownName(args[0])); + sender.sendMessage(jm.getPlugin().getJailIO().getLanguageString(LangString.FORCEUNJAILED, args[0])); + + 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() }))); + } + }else { + //The player is not currently jailed + sender.sendMessage(jm.getPlugin().getJailIO().getLanguageString(LangString.NOTJAILED, args[0])); + } + + return true; + } +} diff --git a/src/main/java/com/graywolf336/jail/command/commands/jewels/Jailing.java b/src/main/java/com/graywolf336/jail/command/commands/jewels/Jailing.java index a7dc5ff..d44d543 100644 --- a/src/main/java/com/graywolf336/jail/command/commands/jewels/Jailing.java +++ b/src/main/java/com/graywolf336/jail/command/commands/jewels/Jailing.java @@ -1,32 +1,32 @@ -package com.graywolf336.jail.command.commands.jewels; - -import java.util.List; - -import com.lexicalscope.jewel.cli.Option; - -public interface Jailing { - - @Option(longName={"player", "pl"}, shortName="p", description = "the player's name") - public String getPlayer(); - - @Option(longName={"time", "length"}, shortName="t", description = "the amount of time") - public String getTime(); - - @Option(longName={"jail", "prison"}, shortName="j", description = "the jail") - public String getJail(); - - @Option(longName={"cell"}, shortName="c", description = "the cell") - public String getCell(); - - @Option(longName={"muted", "canttalk"}, shortName="m", description = "whether the prisoner is muted or not") - public boolean getMuted(); - - @Option(longName={"reason"}, shortName="r", description = "the reason this player is being jailed") - public List getReason(); - - public boolean isTime(); - public boolean isJail(); - public boolean isCell(); - public boolean isMuted(); - public boolean isReason(); -} +package com.graywolf336.jail.command.commands.jewels; + +import java.util.List; + +import com.lexicalscope.jewel.cli.Option; + +public interface Jailing { + + @Option(longName={"player", "pl"}, shortName="p", description = "the player's name") + public String getPlayer(); + + @Option(longName={"time", "length"}, shortName="t", description = "the amount of time") + public String getTime(); + + @Option(longName={"jail", "prison"}, shortName="j", description = "the jail") + public String getJail(); + + @Option(longName={"cell"}, shortName="c", description = "the cell") + public String getCell(); + + @Option(longName={"muted", "canttalk"}, shortName="m", description = "whether the prisoner is muted or not") + public boolean getMuted(); + + @Option(longName={"reason"}, shortName="r", description = "the reason this player is being jailed") + public List getReason(); + + public boolean isTime(); + public boolean isJail(); + public boolean isCell(); + public boolean isMuted(); + public boolean isReason(); +} diff --git a/src/main/java/com/graywolf336/jail/command/commands/jewels/Transfer.java b/src/main/java/com/graywolf336/jail/command/commands/jewels/Transfer.java index 33fe388..4f5b397 100644 --- a/src/main/java/com/graywolf336/jail/command/commands/jewels/Transfer.java +++ b/src/main/java/com/graywolf336/jail/command/commands/jewels/Transfer.java @@ -1,19 +1,19 @@ -package com.graywolf336.jail.command.commands.jewels; - -import com.lexicalscope.jewel.cli.Option; - -public interface Transfer { - - @Option(longName={"player", "pl"}, shortName="p", description = "the player's name") - public String getPlayer(); - - @Option(longName={"jail", "prison"}, shortName="j", description = "the jail") - public String getJail(); - - @Option(longName={"cell"}, shortName="c", description = "the cell") - public String getCell(); - - public boolean isPlayer(); - public boolean isJail(); - public boolean isCell(); -} +package com.graywolf336.jail.command.commands.jewels; + +import com.lexicalscope.jewel.cli.Option; + +public interface Transfer { + + @Option(longName={"player", "pl"}, shortName="p", description = "the player's name") + public String getPlayer(); + + @Option(longName={"jail", "prison"}, shortName="j", description = "the jail") + public String getJail(); + + @Option(longName={"cell"}, shortName="c", description = "the cell") + public String getCell(); + + public boolean isPlayer(); + public boolean isJail(); + public boolean isCell(); +} diff --git a/src/main/java/com/graywolf336/jail/command/subcommands/JailCellCreateCommand.java b/src/main/java/com/graywolf336/jail/command/subcommands/JailCellCreateCommand.java index c12ee65..02a80cd 100644 --- a/src/main/java/com/graywolf336/jail/command/subcommands/JailCellCreateCommand.java +++ b/src/main/java/com/graywolf336/jail/command/subcommands/JailCellCreateCommand.java @@ -1,66 +1,66 @@ -package com.graywolf336.jail.command.subcommands; - -import org.bukkit.ChatColor; -import org.bukkit.command.CommandSender; -import org.bukkit.entity.Player; - -import com.graywolf336.jail.JailManager; -import com.graywolf336.jail.beans.Jail; -import com.graywolf336.jail.command.Command; -import com.graywolf336.jail.command.CommandInfo; - -@CommandInfo( - maxArgs = 2, - minimumArgs = 1, - needsPlayer = true, - pattern = "createcell|cc", - permission = "jail.command.jailcreatecells", - usage = "/jail cellcreate [jail] (cellname)" - ) -public class JailCellCreateCommand implements Command { - - public boolean execute(JailManager jm, CommandSender sender, String... args) { - Player player = (Player) sender; - String name = player.getName(); - String jail = args[1].toLowerCase(); - String cell = ""; - - //Only get the cell name they provide if they provide it - if(args.length >= 3) { - cell = args[2]; - } - - //Check if the player is currently creating something else - if(jm.isCreatingSomething(name)) { - String message = jm.getStepMessage(name); - if(!message.isEmpty()) { - player.sendMessage(ChatColor.RED + message); - }else { - player.sendMessage(ChatColor.RED + "You're already creating something else, please finish it or cancel."); - } - }else { - //Not creating anything, so let them create some cells. - if(jm.isValidJail(jail)) { - Jail j = jm.getJail(jail); - - //If they didn't provide a cell name, let's provide one ourself. - if(cell.isEmpty()) cell = "cell_n" + (j.getCellCount() + 1); - - if(j.getCell(cell) == null) { - if(jm.addCreatingCell(name, jail, cell)) { - jm.getCellCreationSteps().startStepping(player); - }else { - player.sendMessage(ChatColor.RED + "Appears you're creating a cell or something went wrong on our side."); - } - }else { - player.sendMessage(ChatColor.RED + "There's already a cell with the name '" + cell + "', please pick a new one or remove that cell."); - } - }else { - player.sendMessage(ChatColor.RED + "No such jail found by the name of '" + jail + "'."); - } - } - - return true; - } - -} +package com.graywolf336.jail.command.subcommands; + +import org.bukkit.ChatColor; +import org.bukkit.command.CommandSender; +import org.bukkit.entity.Player; + +import com.graywolf336.jail.JailManager; +import com.graywolf336.jail.beans.Jail; +import com.graywolf336.jail.command.Command; +import com.graywolf336.jail.command.CommandInfo; + +@CommandInfo( + maxArgs = 2, + minimumArgs = 1, + needsPlayer = true, + pattern = "createcell|cc", + permission = "jail.command.jailcreatecells", + usage = "/jail cellcreate [jail] (cellname)" + ) +public class JailCellCreateCommand implements Command { + + public boolean execute(JailManager jm, CommandSender sender, String... args) { + Player player = (Player) sender; + String name = player.getName(); + String jail = args[1].toLowerCase(); + String cell = ""; + + //Only get the cell name they provide if they provide it + if(args.length >= 3) { + cell = args[2]; + } + + //Check if the player is currently creating something else + if(jm.isCreatingSomething(name)) { + String message = jm.getStepMessage(name); + if(!message.isEmpty()) { + player.sendMessage(ChatColor.RED + message); + }else { + player.sendMessage(ChatColor.RED + "You're already creating something else, please finish it or cancel."); + } + }else { + //Not creating anything, so let them create some cells. + if(jm.isValidJail(jail)) { + Jail j = jm.getJail(jail); + + //If they didn't provide a cell name, let's provide one ourself. + if(cell.isEmpty()) cell = "cell_n" + (j.getCellCount() + 1); + + if(j.getCell(cell) == null) { + if(jm.addCreatingCell(name, jail, cell)) { + jm.getCellCreationSteps().startStepping(player); + }else { + player.sendMessage(ChatColor.RED + "Appears you're creating a cell or something went wrong on our side."); + } + }else { + player.sendMessage(ChatColor.RED + "There's already a cell with the name '" + cell + "', please pick a new one or remove that cell."); + } + }else { + player.sendMessage(ChatColor.RED + "No such jail found by the name of '" + jail + "'."); + } + } + + return true; + } + +} diff --git a/src/main/java/com/graywolf336/jail/command/subcommands/JailCommand.java b/src/main/java/com/graywolf336/jail/command/subcommands/JailCommand.java index b7fbff2..9795447 100644 --- a/src/main/java/com/graywolf336/jail/command/subcommands/JailCommand.java +++ b/src/main/java/com/graywolf336/jail/command/subcommands/JailCommand.java @@ -1,217 +1,217 @@ -package com.graywolf336.jail.command.subcommands; - -import java.util.Arrays; -import java.util.LinkedList; -import java.util.List; - -import org.bukkit.ChatColor; -import org.bukkit.command.CommandSender; -import org.bukkit.entity.Player; - -import com.graywolf336.jail.JailManager; -import com.graywolf336.jail.Util; -import com.graywolf336.jail.beans.Cell; -import com.graywolf336.jail.beans.Jail; -import com.graywolf336.jail.beans.Prisoner; -import com.graywolf336.jail.command.Command; -import com.graywolf336.jail.command.CommandInfo; -import com.graywolf336.jail.command.commands.jewels.Jailing; -import com.graywolf336.jail.enums.LangString; -import com.graywolf336.jail.enums.Settings; -import com.graywolf336.jail.events.PrePrisonerJailedEvent; -import com.lexicalscope.jewel.cli.ArgumentValidationException; -import com.lexicalscope.jewel.cli.CliFactory; - -@CommandInfo( - maxArgs = -1, - minimumArgs = 0, - needsPlayer = false, - pattern = "jail|j", - permission = "jail.command.jail", - usage = "/jail [name] (-t time) (-j JailName) (-c CellName) (-m Muted) (-r A reason for jailing)" - ) -public class JailCommand implements Command { - - /* - * Executes the command. Checks the following: - * - * - If there are any jails. - * - If the command can be parsed correctly. - * - If the player is already jailed. - * - If the given time can be parsed correctly, defaults to what is defined in the config - * - If the jail is reasonable or not, else sets the one from the config - * - If the cell is not empty then checks to be sure that cell exists - * - If the prisoner is online or not. - */ - public boolean execute(JailManager jm, CommandSender sender, String... args) { - - if(jm.getJails().isEmpty()) { - sender.sendMessage(jm.getPlugin().getJailIO().getLanguageString(LangString.NOJAILS)); - return true; - } - - //This is just to add the -p param so CliFactory doesn't blow up - List arguments = new LinkedList(Arrays.asList(args)); - //Only add the "-p" if it doesn't already contain it, this way people can do `/jail -p check` in the event someone - //has a name which is one of our subcommands - if(!arguments.contains("-p")) arguments.add(0, "-p"); - - Jailing params = null; - - try { - params = CliFactory.parseArguments(Jailing.class, arguments.toArray(new String[arguments.size()])); - }catch(ArgumentValidationException e) { - sender.sendMessage(ChatColor.RED + e.getMessage()); - return true; - } - - //Check if they've actually given us a player to jail - if(params.getPlayer() == null) { - sender.sendMessage(jm.getPlugin().getJailIO().getLanguageString(LangString.PROVIDEAPLAYER, LangString.JAILING)); - return true; - }else { - jm.getPlugin().debug("We are getting ready to handle jailing: " + params.getPlayer()); - } - - //Check if the given player is already jailed or not - if(jm.isPlayerJailedByLastKnownUsername(params.getPlayer())) { - sender.sendMessage(jm.getPlugin().getJailIO().getLanguageString(LangString.ALREADYJAILED, params.getPlayer())); - return true; - } - - //Try to parse the time, if they give us nothing in the time parameter then we get the default time - //from the config and if that isn't there then we default to thirty minutes. - Long time = 10L; - try { - if(params.getTime() == null) { - time = Util.getTime(jm.getPlugin().getConfig().getString(Settings.JAILDEFAULTTIME.getPath(), "30m")); - }else if(params.getTime() == String.valueOf(-1)) { - time = -1L; - }else { - time = Util.getTime(params.getTime()); - } - }catch(Exception e) { - sender.sendMessage(jm.getPlugin().getJailIO().getLanguageString(LangString.NUMBERFORMATINCORRECT)); - return true; - } - - //Check the jail params. If it is empty, let's get the default jail - //from the config. If that is nearest, let's make a call to getting the nearest jail to - //the sender but otherwise if it isn't nearest then let's set it to the default jail - //which is defined in the config. - String jailName = ""; - if(params.getJail() == null) { - String dJail = jm.getPlugin().getConfig().getString(Settings.DEFAULTJAIL.getPath()); - - if(dJail.equalsIgnoreCase("nearest")) { - jailName = jm.getNearestJail(sender).getName(); - }else { - jailName = jm.getPlugin().getConfig().getString(Settings.DEFAULTJAIL.getPath()); - } - }else if(jm.getJail(params.getJail()) == null) { - sender.sendMessage(jm.getPlugin().getJailIO().getLanguageString(LangString.NOJAIL, params.getJail())); - return true; - }else { - jailName = params.getJail(); - } - - //Check if the cell is defined, and if so check to be sure it exists. - if(params.getCell() != null) { - if(jm.getJail(params.getJail()).getCell(params.getCell()) == null) { - //There is no cell by that name - sender.sendMessage(jm.getPlugin().getJailIO().getLanguageString(LangString.NOCELL, new String[] { params.getCell(), params.getJail() })); - return true; - }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 - sender.sendMessage(jm.getPlugin().getJailIO().getLanguageString(LangString.CELLNOTEMPTY, params.getCell())); - Cell suggestedCell = jm.getJail(params.getJail()).getFirstEmptyCell(); - if(suggestedCell != null) { - sender.sendMessage(jm.getPlugin().getJailIO().getLanguageString(LangString.SUGGESTEDCELL, new String[] { params.getJail(), suggestedCell.getName() })); - }else { - sender.sendMessage(jm.getPlugin().getJailIO().getLanguageString(LangString.NOEMPTYCELLS, params.getJail())); - } - - return true; - } - } - - //If the jailer gave no reason, then let's get the default reason - String reason = ""; - if(params.getReason() == null) { - reason = jm.getPlugin().getJailIO().getLanguageString(LangString.DEFAULTJAILEDREASON); - }else { - StringBuilder sb = new StringBuilder(); - for(String s : params.getReason()) { - sb.append(s).append(' '); - } - - sb.deleteCharAt(sb.length() - 1); - reason = sb.toString(); - } - - //If the config has automatic muting, then let's set them as muted - boolean muted = params.getMuted(); - if(jm.getPlugin().getConfig().getBoolean(Settings.AUTOMATICMUTE.getPath())) { - muted = true; - } - - Player p = jm.getPlugin().getServer().getPlayer(params.getPlayer()); - - //If the player instance is not null and the player has the permission - //'jail.cantbejailed' then don't allow this to happen - if(p != null && p.hasPermission("jail.cantbejailed")) { - sender.sendMessage(jm.getPlugin().getJailIO().getLanguageString(LangString.CANTBEJAILED)); - return true; - } - - String uuid = ""; - if(p == null) { - //TODO: Make this whole jail command non-blocking - uuid = jm.getPlugin().getServer().getOfflinePlayer(params.getPlayer()).getUniqueId().toString(); - }else { - uuid = p.getUniqueId().toString(); - } - - //Get the jail instance from the name of jail in the params. - Jail j = jm.getJail(jailName); - Cell c = j.getCell(params.getCell()); - Prisoner pris = new Prisoner(uuid, params.getPlayer(), muted, time, sender.getName(), reason); - - //call the event - PrePrisonerJailedEvent event = new PrePrisonerJailedEvent(j, c, pris, p, p == null, pris.getJailer()); - jm.getPlugin().getServer().getPluginManager().callEvent(event); - - //check if the event is cancelled - if(event.isCancelled()) { - if(event.getCancelledMessage().isEmpty()) - sender.sendMessage(jm.getPlugin().getJailIO().getLanguageString(LangString.CANCELLEDBYANOTHERPLUGIN, params.getPlayer())); - else - sender.sendMessage(event.getCancelledMessage()); - - return true; - } - - //recall data from the event - j = event.getJail(); - c = event.getCell(); - pris = event.getPrisoner(); - p = event.getPlayer(); - - //Player is not online - if(p == null) { - sender.sendMessage(jm.getPlugin().getJailIO().getLanguageString(LangString.OFFLINEJAIL, new String[] { pris.getLastKnownName(), String.valueOf(pris.getRemainingTimeInMinutes()) })); - }else { - //Player *is* online - sender.sendMessage(jm.getPlugin().getJailIO().getLanguageString(LangString.ONLINEJAIL, new String[] { pris.getLastKnownName(), String.valueOf(pris.getRemainingTimeInMinutes()) })); - } - - try { - jm.getPlugin().getPrisonerManager().prepareJail(j, c, p, pris); - } catch (Exception e) { - sender.sendMessage(ChatColor.RED + e.getMessage()); - return true; - } - - return true; - } -} +package com.graywolf336.jail.command.subcommands; + +import java.util.Arrays; +import java.util.LinkedList; +import java.util.List; + +import org.bukkit.ChatColor; +import org.bukkit.command.CommandSender; +import org.bukkit.entity.Player; + +import com.graywolf336.jail.JailManager; +import com.graywolf336.jail.Util; +import com.graywolf336.jail.beans.Cell; +import com.graywolf336.jail.beans.Jail; +import com.graywolf336.jail.beans.Prisoner; +import com.graywolf336.jail.command.Command; +import com.graywolf336.jail.command.CommandInfo; +import com.graywolf336.jail.command.commands.jewels.Jailing; +import com.graywolf336.jail.enums.LangString; +import com.graywolf336.jail.enums.Settings; +import com.graywolf336.jail.events.PrePrisonerJailedEvent; +import com.lexicalscope.jewel.cli.ArgumentValidationException; +import com.lexicalscope.jewel.cli.CliFactory; + +@CommandInfo( + maxArgs = -1, + minimumArgs = 0, + needsPlayer = false, + pattern = "jail|j", + permission = "jail.command.jail", + usage = "/jail [name] (-t time) (-j JailName) (-c CellName) (-m Muted) (-r A reason for jailing)" + ) +public class JailCommand implements Command { + + /* + * Executes the command. Checks the following: + * + * - If there are any jails. + * - If the command can be parsed correctly. + * - If the player is already jailed. + * - If the given time can be parsed correctly, defaults to what is defined in the config + * - If the jail is reasonable or not, else sets the one from the config + * - If the cell is not empty then checks to be sure that cell exists + * - If the prisoner is online or not. + */ + public boolean execute(JailManager jm, CommandSender sender, String... args) { + + if(jm.getJails().isEmpty()) { + sender.sendMessage(jm.getPlugin().getJailIO().getLanguageString(LangString.NOJAILS)); + return true; + } + + //This is just to add the -p param so CliFactory doesn't blow up + List arguments = new LinkedList(Arrays.asList(args)); + //Only add the "-p" if it doesn't already contain it, this way people can do `/jail -p check` in the event someone + //has a name which is one of our subcommands + if(!arguments.contains("-p")) arguments.add(0, "-p"); + + Jailing params = null; + + try { + params = CliFactory.parseArguments(Jailing.class, arguments.toArray(new String[arguments.size()])); + }catch(ArgumentValidationException e) { + sender.sendMessage(ChatColor.RED + e.getMessage()); + return true; + } + + //Check if they've actually given us a player to jail + if(params.getPlayer() == null) { + sender.sendMessage(jm.getPlugin().getJailIO().getLanguageString(LangString.PROVIDEAPLAYER, LangString.JAILING)); + return true; + }else { + jm.getPlugin().debug("We are getting ready to handle jailing: " + params.getPlayer()); + } + + //Check if the given player is already jailed or not + if(jm.isPlayerJailedByLastKnownUsername(params.getPlayer())) { + sender.sendMessage(jm.getPlugin().getJailIO().getLanguageString(LangString.ALREADYJAILED, params.getPlayer())); + return true; + } + + //Try to parse the time, if they give us nothing in the time parameter then we get the default time + //from the config and if that isn't there then we default to thirty minutes. + Long time = 10L; + try { + if(params.getTime() == null) { + time = Util.getTime(jm.getPlugin().getConfig().getString(Settings.JAILDEFAULTTIME.getPath(), "30m")); + }else if(params.getTime() == String.valueOf(-1)) { + time = -1L; + }else { + time = Util.getTime(params.getTime()); + } + }catch(Exception e) { + sender.sendMessage(jm.getPlugin().getJailIO().getLanguageString(LangString.NUMBERFORMATINCORRECT)); + return true; + } + + //Check the jail params. If it is empty, let's get the default jail + //from the config. If that is nearest, let's make a call to getting the nearest jail to + //the sender but otherwise if it isn't nearest then let's set it to the default jail + //which is defined in the config. + String jailName = ""; + if(params.getJail() == null) { + String dJail = jm.getPlugin().getConfig().getString(Settings.DEFAULTJAIL.getPath()); + + if(dJail.equalsIgnoreCase("nearest")) { + jailName = jm.getNearestJail(sender).getName(); + }else { + jailName = jm.getPlugin().getConfig().getString(Settings.DEFAULTJAIL.getPath()); + } + }else if(jm.getJail(params.getJail()) == null) { + sender.sendMessage(jm.getPlugin().getJailIO().getLanguageString(LangString.NOJAIL, params.getJail())); + return true; + }else { + jailName = params.getJail(); + } + + //Check if the cell is defined, and if so check to be sure it exists. + if(params.getCell() != null) { + if(jm.getJail(params.getJail()).getCell(params.getCell()) == null) { + //There is no cell by that name + sender.sendMessage(jm.getPlugin().getJailIO().getLanguageString(LangString.NOCELL, new String[] { params.getCell(), params.getJail() })); + return true; + }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 + sender.sendMessage(jm.getPlugin().getJailIO().getLanguageString(LangString.CELLNOTEMPTY, params.getCell())); + Cell suggestedCell = jm.getJail(params.getJail()).getFirstEmptyCell(); + if(suggestedCell != null) { + sender.sendMessage(jm.getPlugin().getJailIO().getLanguageString(LangString.SUGGESTEDCELL, new String[] { params.getJail(), suggestedCell.getName() })); + }else { + sender.sendMessage(jm.getPlugin().getJailIO().getLanguageString(LangString.NOEMPTYCELLS, params.getJail())); + } + + return true; + } + } + + //If the jailer gave no reason, then let's get the default reason + String reason = ""; + if(params.getReason() == null) { + reason = jm.getPlugin().getJailIO().getLanguageString(LangString.DEFAULTJAILEDREASON); + }else { + StringBuilder sb = new StringBuilder(); + for(String s : params.getReason()) { + sb.append(s).append(' '); + } + + sb.deleteCharAt(sb.length() - 1); + reason = sb.toString(); + } + + //If the config has automatic muting, then let's set them as muted + boolean muted = params.getMuted(); + if(jm.getPlugin().getConfig().getBoolean(Settings.AUTOMATICMUTE.getPath())) { + muted = true; + } + + Player p = jm.getPlugin().getServer().getPlayer(params.getPlayer()); + + //If the player instance is not null and the player has the permission + //'jail.cantbejailed' then don't allow this to happen + if(p != null && p.hasPermission("jail.cantbejailed")) { + sender.sendMessage(jm.getPlugin().getJailIO().getLanguageString(LangString.CANTBEJAILED)); + return true; + } + + String uuid = ""; + if(p == null) { + //TODO: Make this whole jail command non-blocking + uuid = jm.getPlugin().getServer().getOfflinePlayer(params.getPlayer()).getUniqueId().toString(); + }else { + uuid = p.getUniqueId().toString(); + } + + //Get the jail instance from the name of jail in the params. + Jail j = jm.getJail(jailName); + Cell c = j.getCell(params.getCell()); + Prisoner pris = new Prisoner(uuid, params.getPlayer(), muted, time, sender.getName(), reason); + + //call the event + PrePrisonerJailedEvent event = new PrePrisonerJailedEvent(j, c, pris, p, p == null, pris.getJailer()); + jm.getPlugin().getServer().getPluginManager().callEvent(event); + + //check if the event is cancelled + if(event.isCancelled()) { + if(event.getCancelledMessage().isEmpty()) + sender.sendMessage(jm.getPlugin().getJailIO().getLanguageString(LangString.CANCELLEDBYANOTHERPLUGIN, params.getPlayer())); + else + sender.sendMessage(event.getCancelledMessage()); + + return true; + } + + //recall data from the event + j = event.getJail(); + c = event.getCell(); + pris = event.getPrisoner(); + p = event.getPlayer(); + + //Player is not online + if(p == null) { + sender.sendMessage(jm.getPlugin().getJailIO().getLanguageString(LangString.OFFLINEJAIL, new String[] { pris.getLastKnownName(), String.valueOf(pris.getRemainingTimeInMinutes()) })); + }else { + //Player *is* online + sender.sendMessage(jm.getPlugin().getJailIO().getLanguageString(LangString.ONLINEJAIL, new String[] { pris.getLastKnownName(), String.valueOf(pris.getRemainingTimeInMinutes()) })); + } + + try { + jm.getPlugin().getPrisonerManager().prepareJail(j, c, p, pris); + } catch (Exception e) { + sender.sendMessage(ChatColor.RED + e.getMessage()); + return true; + } + + return true; + } +} diff --git a/src/main/java/com/graywolf336/jail/command/subcommands/JailDeleteCellCommand.java b/src/main/java/com/graywolf336/jail/command/subcommands/JailDeleteCellCommand.java index e0c8fc9..f8294df 100644 --- a/src/main/java/com/graywolf336/jail/command/subcommands/JailDeleteCellCommand.java +++ b/src/main/java/com/graywolf336/jail/command/subcommands/JailDeleteCellCommand.java @@ -1,31 +1,31 @@ -package com.graywolf336.jail.command.subcommands; - -import org.bukkit.command.CommandSender; - -import com.graywolf336.jail.JailManager; -import com.graywolf336.jail.beans.ConfirmPlayer; -import com.graywolf336.jail.command.Command; -import com.graywolf336.jail.command.CommandInfo; -import com.graywolf336.jail.enums.Confirmation; -import com.graywolf336.jail.enums.LangString; - -@CommandInfo( - maxArgs = 2, - minimumArgs = 2, - needsPlayer = false, - pattern = "deletecell|dc", - permission = "jail.command.jaildeletecell", - usage = "/jail deletecell " - ) -public class JailDeleteCellCommand implements Command { - public boolean execute(JailManager jm, CommandSender sender, String... args) throws Exception { - if(jm.isConfirming(sender.getName())) { - sender.sendMessage(jm.getPlugin().getJailIO().getLanguageString(LangString.ALREADY)); - }else { - jm.addConfirming(sender.getName(), new ConfirmPlayer(sender.getName(), args, Confirmation.DELETECELL)); - sender.sendMessage(jm.getPlugin().getJailIO().getLanguageString(LangString.START)); - } - - return true; - } -} +package com.graywolf336.jail.command.subcommands; + +import org.bukkit.command.CommandSender; + +import com.graywolf336.jail.JailManager; +import com.graywolf336.jail.beans.ConfirmPlayer; +import com.graywolf336.jail.command.Command; +import com.graywolf336.jail.command.CommandInfo; +import com.graywolf336.jail.enums.Confirmation; +import com.graywolf336.jail.enums.LangString; + +@CommandInfo( + maxArgs = 2, + minimumArgs = 2, + needsPlayer = false, + pattern = "deletecell|dc", + permission = "jail.command.jaildeletecell", + usage = "/jail deletecell " + ) +public class JailDeleteCellCommand implements Command { + public boolean execute(JailManager jm, CommandSender sender, String... args) throws Exception { + if(jm.isConfirming(sender.getName())) { + sender.sendMessage(jm.getPlugin().getJailIO().getLanguageString(LangString.ALREADY)); + }else { + jm.addConfirming(sender.getName(), new ConfirmPlayer(sender.getName(), args, Confirmation.DELETECELL)); + sender.sendMessage(jm.getPlugin().getJailIO().getLanguageString(LangString.START)); + } + + return true; + } +} diff --git a/src/main/java/com/graywolf336/jail/command/subcommands/JailDeleteCellsCommand.java b/src/main/java/com/graywolf336/jail/command/subcommands/JailDeleteCellsCommand.java index eae373b..2c4deb1 100644 --- a/src/main/java/com/graywolf336/jail/command/subcommands/JailDeleteCellsCommand.java +++ b/src/main/java/com/graywolf336/jail/command/subcommands/JailDeleteCellsCommand.java @@ -1,31 +1,31 @@ -package com.graywolf336.jail.command.subcommands; - -import org.bukkit.command.CommandSender; - -import com.graywolf336.jail.JailManager; -import com.graywolf336.jail.beans.ConfirmPlayer; -import com.graywolf336.jail.command.Command; -import com.graywolf336.jail.command.CommandInfo; -import com.graywolf336.jail.enums.Confirmation; -import com.graywolf336.jail.enums.LangString; - -@CommandInfo( - maxArgs = 1, - minimumArgs = 1, - needsPlayer = false, - pattern = "deletecells|dcs", - permission = "jail.command.jaildeletecell", - usage = "/jail deletecells " - ) -public class JailDeleteCellsCommand implements Command { - public boolean execute(JailManager jm, CommandSender sender, String... args) throws Exception { - if(jm.isConfirming(sender.getName())) { - sender.sendMessage(jm.getPlugin().getJailIO().getLanguageString(LangString.ALREADY)); - }else { - jm.addConfirming(sender.getName(), new ConfirmPlayer(sender.getName(), args, Confirmation.DELETECELLS)); - sender.sendMessage(jm.getPlugin().getJailIO().getLanguageString(LangString.START)); - } - - return true; - } -} +package com.graywolf336.jail.command.subcommands; + +import org.bukkit.command.CommandSender; + +import com.graywolf336.jail.JailManager; +import com.graywolf336.jail.beans.ConfirmPlayer; +import com.graywolf336.jail.command.Command; +import com.graywolf336.jail.command.CommandInfo; +import com.graywolf336.jail.enums.Confirmation; +import com.graywolf336.jail.enums.LangString; + +@CommandInfo( + maxArgs = 1, + minimumArgs = 1, + needsPlayer = false, + pattern = "deletecells|dcs", + permission = "jail.command.jaildeletecell", + usage = "/jail deletecells " + ) +public class JailDeleteCellsCommand implements Command { + public boolean execute(JailManager jm, CommandSender sender, String... args) throws Exception { + if(jm.isConfirming(sender.getName())) { + sender.sendMessage(jm.getPlugin().getJailIO().getLanguageString(LangString.ALREADY)); + }else { + jm.addConfirming(sender.getName(), new ConfirmPlayer(sender.getName(), args, Confirmation.DELETECELLS)); + sender.sendMessage(jm.getPlugin().getJailIO().getLanguageString(LangString.START)); + } + + return true; + } +} diff --git a/src/main/java/com/graywolf336/jail/command/subcommands/JailDeleteCommand.java b/src/main/java/com/graywolf336/jail/command/subcommands/JailDeleteCommand.java index e0c0ca1..6d417b8 100644 --- a/src/main/java/com/graywolf336/jail/command/subcommands/JailDeleteCommand.java +++ b/src/main/java/com/graywolf336/jail/command/subcommands/JailDeleteCommand.java @@ -1,31 +1,31 @@ -package com.graywolf336.jail.command.subcommands; - -import org.bukkit.command.CommandSender; - -import com.graywolf336.jail.JailManager; -import com.graywolf336.jail.beans.ConfirmPlayer; -import com.graywolf336.jail.command.Command; -import com.graywolf336.jail.command.CommandInfo; -import com.graywolf336.jail.enums.Confirmation; -import com.graywolf336.jail.enums.LangString; - -@CommandInfo( - maxArgs = 1, - minimumArgs = 1, - needsPlayer = false, - pattern = "delete|d", - permission = "jail.command.jaildelete", - usage = "/jail delete " - ) -public class JailDeleteCommand implements Command { - public boolean execute(JailManager jm, CommandSender sender, String... args) throws Exception { - if(jm.isConfirming(sender.getName())) { - sender.sendMessage(jm.getPlugin().getJailIO().getLanguageString(LangString.ALREADY)); - }else { - jm.addConfirming(sender.getName(), new ConfirmPlayer(sender.getName(), args, Confirmation.DELETE)); - sender.sendMessage(jm.getPlugin().getJailIO().getLanguageString(LangString.START)); - } - - return true; - } -} +package com.graywolf336.jail.command.subcommands; + +import org.bukkit.command.CommandSender; + +import com.graywolf336.jail.JailManager; +import com.graywolf336.jail.beans.ConfirmPlayer; +import com.graywolf336.jail.command.Command; +import com.graywolf336.jail.command.CommandInfo; +import com.graywolf336.jail.enums.Confirmation; +import com.graywolf336.jail.enums.LangString; + +@CommandInfo( + maxArgs = 1, + minimumArgs = 1, + needsPlayer = false, + pattern = "delete|d", + permission = "jail.command.jaildelete", + usage = "/jail delete " + ) +public class JailDeleteCommand implements Command { + public boolean execute(JailManager jm, CommandSender sender, String... args) throws Exception { + if(jm.isConfirming(sender.getName())) { + sender.sendMessage(jm.getPlugin().getJailIO().getLanguageString(LangString.ALREADY)); + }else { + jm.addConfirming(sender.getName(), new ConfirmPlayer(sender.getName(), args, Confirmation.DELETE)); + sender.sendMessage(jm.getPlugin().getJailIO().getLanguageString(LangString.START)); + } + + return true; + } +} diff --git a/src/main/java/com/graywolf336/jail/command/subcommands/JailListCellsCommand.java b/src/main/java/com/graywolf336/jail/command/subcommands/JailListCellsCommand.java index 5773876..5090205 100644 --- a/src/main/java/com/graywolf336/jail/command/subcommands/JailListCellsCommand.java +++ b/src/main/java/com/graywolf336/jail/command/subcommands/JailListCellsCommand.java @@ -1,54 +1,54 @@ -package com.graywolf336.jail.command.subcommands; - -import org.bukkit.ChatColor; -import org.bukkit.command.CommandSender; - -import com.graywolf336.jail.JailManager; -import com.graywolf336.jail.beans.Cell; -import com.graywolf336.jail.beans.Jail; -import com.graywolf336.jail.command.Command; -import com.graywolf336.jail.command.CommandInfo; -import com.graywolf336.jail.enums.LangString; - -@CommandInfo( - maxArgs = 1, - minimumArgs = 1, - needsPlayer = false, - pattern = "listcells|lc", - permission = "jail.command.jaillistcell", - usage = "/jail listcells " - ) -public class JailListCellsCommand implements Command { - @Override - public boolean execute(JailManager jm, CommandSender sender, String... args) { - sender.sendMessage(ChatColor.AQUA + "----------Cells----------"); - - if(!jm.getJails().isEmpty()) { - if(jm.getJail(args[1]) != null) { - Jail j = jm.getJail(args[1]); - - String message = ""; - for(Cell c : j.getCells()) { - if(message.isEmpty()) { - message = c.getName() + (c.getPrisoner() == null ? "" : " (" + c.getPrisoner().getLastKnownName() + ")"); - }else { - message += ", " + c.getName() + (c.getPrisoner() == null ? "" : " (" + c.getPrisoner().getLastKnownName() + ")"); - } - } - - if(message.isEmpty()) { - sender.sendMessage(jm.getPlugin().getJailIO().getLanguageString(LangString.NOCELLS, j.getName())); - }else { - sender.sendMessage(ChatColor.GREEN + message); - } - }else { - sender.sendMessage(jm.getPlugin().getJailIO().getLanguageString(LangString.NOJAIL, args[1])); - } - }else { - sender.sendMessage(jm.getPlugin().getJailIO().getLanguageString(LangString.NOJAILS)); - } - - sender.sendMessage(ChatColor.AQUA + "-------------------------"); - return true; - } -} +package com.graywolf336.jail.command.subcommands; + +import org.bukkit.ChatColor; +import org.bukkit.command.CommandSender; + +import com.graywolf336.jail.JailManager; +import com.graywolf336.jail.beans.Cell; +import com.graywolf336.jail.beans.Jail; +import com.graywolf336.jail.command.Command; +import com.graywolf336.jail.command.CommandInfo; +import com.graywolf336.jail.enums.LangString; + +@CommandInfo( + maxArgs = 1, + minimumArgs = 1, + needsPlayer = false, + pattern = "listcells|lc", + permission = "jail.command.jaillistcell", + usage = "/jail listcells " + ) +public class JailListCellsCommand implements Command { + @Override + public boolean execute(JailManager jm, CommandSender sender, String... args) { + sender.sendMessage(ChatColor.AQUA + "----------Cells----------"); + + if(!jm.getJails().isEmpty()) { + if(jm.getJail(args[1]) != null) { + Jail j = jm.getJail(args[1]); + + String message = ""; + for(Cell c : j.getCells()) { + if(message.isEmpty()) { + message = c.getName() + (c.getPrisoner() == null ? "" : " (" + c.getPrisoner().getLastKnownName() + ")"); + }else { + message += ", " + c.getName() + (c.getPrisoner() == null ? "" : " (" + c.getPrisoner().getLastKnownName() + ")"); + } + } + + if(message.isEmpty()) { + sender.sendMessage(jm.getPlugin().getJailIO().getLanguageString(LangString.NOCELLS, j.getName())); + }else { + sender.sendMessage(ChatColor.GREEN + message); + } + }else { + sender.sendMessage(jm.getPlugin().getJailIO().getLanguageString(LangString.NOJAIL, args[1])); + } + }else { + sender.sendMessage(jm.getPlugin().getJailIO().getLanguageString(LangString.NOJAILS)); + } + + sender.sendMessage(ChatColor.AQUA + "-------------------------"); + return true; + } +} diff --git a/src/main/java/com/graywolf336/jail/command/subcommands/JailListCommand.java b/src/main/java/com/graywolf336/jail/command/subcommands/JailListCommand.java index b1d33e8..1c9e4c0 100644 --- a/src/main/java/com/graywolf336/jail/command/subcommands/JailListCommand.java +++ b/src/main/java/com/graywolf336/jail/command/subcommands/JailListCommand.java @@ -1,63 +1,63 @@ -package com.graywolf336.jail.command.subcommands; - -import java.util.Collection; - -import org.bukkit.ChatColor; -import org.bukkit.command.CommandSender; - -import com.graywolf336.jail.JailManager; -import com.graywolf336.jail.beans.Jail; -import com.graywolf336.jail.beans.Prisoner; -import com.graywolf336.jail.command.Command; -import com.graywolf336.jail.command.CommandInfo; -import com.graywolf336.jail.enums.LangString; - -@CommandInfo( - maxArgs = 1, - minimumArgs = 0, - needsPlayer = false, - pattern = "list|l", - permission = "jail.command.jaillist", - usage = "/jail list " - ) -public class JailListCommand implements Command { - public boolean execute(JailManager jm, CommandSender sender, String... args) { - sender.sendMessage(ChatColor.AQUA + "----------" + (args.length == 1 ? "Jails" : "Prisoners") + "----------"); - - //Check if there are any jails - if(jm.getJails().isEmpty()) { - sender.sendMessage(" " + jm.getPlugin().getJailIO().getLanguageString(LangString.NOJAILS)); - }else { - //Check if they have provided a jail to list or not - if(args.length == 1) { - //No jail provided, so give them a list of the jails - for(Jail j : jm.getJails()) { - sender.sendMessage(ChatColor.BLUE + " " + j.getName() + " (" + j.getAllPrisoners().size() + ")"); - } - }else { - Jail j = jm.getJail(args[1]); - - if(j == null) { - //No jail was found - sender.sendMessage(" " + jm.getPlugin().getJailIO().getLanguageString(LangString.NOJAIL, args[1])); - }else { - Collection pris = j.getAllPrisoners().values(); - - if(pris.isEmpty()) { - //If there are no prisoners, then send that message - sender.sendMessage(" " + jm.getPlugin().getJailIO().getLanguageString(LangString.NOPRISONERS, j.getName())); - }else { - for(Prisoner p : pris) { - //graywolf663: Being gray's evil twin; CONSOLE (10) - //prisoner: reason; jailer (time in minutes) - sender.sendMessage(ChatColor.BLUE + " " + p.getLastKnownName() + ": " + p.getReason() + "; " + p.getJailer() + " (" + p.getRemainingTimeInMinutes() + " mins)"); - } - } - } - } - } - - sender.sendMessage(ChatColor.AQUA + "-------------------------"); - return true; - } -} +package com.graywolf336.jail.command.subcommands; + +import java.util.Collection; + +import org.bukkit.ChatColor; +import org.bukkit.command.CommandSender; + +import com.graywolf336.jail.JailManager; +import com.graywolf336.jail.beans.Jail; +import com.graywolf336.jail.beans.Prisoner; +import com.graywolf336.jail.command.Command; +import com.graywolf336.jail.command.CommandInfo; +import com.graywolf336.jail.enums.LangString; + +@CommandInfo( + maxArgs = 1, + minimumArgs = 0, + needsPlayer = false, + pattern = "list|l", + permission = "jail.command.jaillist", + usage = "/jail list " + ) +public class JailListCommand implements Command { + public boolean execute(JailManager jm, CommandSender sender, String... args) { + sender.sendMessage(ChatColor.AQUA + "----------" + (args.length == 1 ? "Jails" : "Prisoners") + "----------"); + + //Check if there are any jails + if(jm.getJails().isEmpty()) { + sender.sendMessage(" " + jm.getPlugin().getJailIO().getLanguageString(LangString.NOJAILS)); + }else { + //Check if they have provided a jail to list or not + if(args.length == 1) { + //No jail provided, so give them a list of the jails + for(Jail j : jm.getJails()) { + sender.sendMessage(ChatColor.BLUE + " " + j.getName() + " (" + j.getAllPrisoners().size() + ")"); + } + }else { + Jail j = jm.getJail(args[1]); + + if(j == null) { + //No jail was found + sender.sendMessage(" " + jm.getPlugin().getJailIO().getLanguageString(LangString.NOJAIL, args[1])); + }else { + Collection pris = j.getAllPrisoners().values(); + + if(pris.isEmpty()) { + //If there are no prisoners, then send that message + sender.sendMessage(" " + jm.getPlugin().getJailIO().getLanguageString(LangString.NOPRISONERS, j.getName())); + }else { + for(Prisoner p : pris) { + //graywolf663: Being gray's evil twin; CONSOLE (10) + //prisoner: reason; jailer (time in minutes) + sender.sendMessage(ChatColor.BLUE + " " + p.getLastKnownName() + ": " + p.getReason() + "; " + p.getJailer() + " (" + p.getRemainingTimeInMinutes() + " mins)"); + } + } + } + } + } + + sender.sendMessage(ChatColor.AQUA + "-------------------------"); + return true; + } +} diff --git a/src/main/java/com/graywolf336/jail/command/subcommands/JailMuteCommand.java b/src/main/java/com/graywolf336/jail/command/subcommands/JailMuteCommand.java index 067ea25..7745a82 100644 --- a/src/main/java/com/graywolf336/jail/command/subcommands/JailMuteCommand.java +++ b/src/main/java/com/graywolf336/jail/command/subcommands/JailMuteCommand.java @@ -1,38 +1,38 @@ -package com.graywolf336.jail.command.subcommands; - -import org.bukkit.command.CommandSender; - -import com.graywolf336.jail.JailManager; -import com.graywolf336.jail.command.Command; -import com.graywolf336.jail.command.CommandInfo; -import com.graywolf336.jail.enums.LangString; - -@CommandInfo( - maxArgs = 1, - minimumArgs = 1, - needsPlayer = false, - pattern = "mute|m", - permission = "jail.command.jailmute", - usage = "/jail mute " - ) -public class JailMuteCommand implements Command { - public boolean execute(JailManager jm, CommandSender sender, String... args) throws Exception { - //Let's check if the player they're sending us is jailed - if(jm.isPlayerJailedByLastKnownUsername(args[1])) { - //They are, so let's toggle whether they are muted or not - boolean muted = !jm.getPrisonerByLastKnownName(args[1]).isMuted(); - jm.getPrisonerByLastKnownName(args[1]).setMuted(muted); - - //Send the message to the sender based upon whether they are muted or unmuted - if(muted) - sender.sendMessage(jm.getPlugin().getJailIO().getLanguageString(LangString.NOWMUTED, args[1])); - else - sender.sendMessage(jm.getPlugin().getJailIO().getLanguageString(LangString.NOWUNMUTED, args[1])); - }else { - //The player provided is not jailed, so let's tell the sender that - sender.sendMessage(jm.getPlugin().getJailIO().getLanguageString(LangString.NOTJAILED, args[1])); - } - - return true; - } -} +package com.graywolf336.jail.command.subcommands; + +import org.bukkit.command.CommandSender; + +import com.graywolf336.jail.JailManager; +import com.graywolf336.jail.command.Command; +import com.graywolf336.jail.command.CommandInfo; +import com.graywolf336.jail.enums.LangString; + +@CommandInfo( + maxArgs = 1, + minimumArgs = 1, + needsPlayer = false, + pattern = "mute|m", + permission = "jail.command.jailmute", + usage = "/jail mute " + ) +public class JailMuteCommand implements Command { + public boolean execute(JailManager jm, CommandSender sender, String... args) throws Exception { + //Let's check if the player they're sending us is jailed + if(jm.isPlayerJailedByLastKnownUsername(args[1])) { + //They are, so let's toggle whether they are muted or not + boolean muted = !jm.getPrisonerByLastKnownName(args[1]).isMuted(); + jm.getPrisonerByLastKnownName(args[1]).setMuted(muted); + + //Send the message to the sender based upon whether they are muted or unmuted + if(muted) + sender.sendMessage(jm.getPlugin().getJailIO().getLanguageString(LangString.NOWMUTED, args[1])); + else + sender.sendMessage(jm.getPlugin().getJailIO().getLanguageString(LangString.NOWUNMUTED, args[1])); + }else { + //The player provided is not jailed, so let's tell the sender that + sender.sendMessage(jm.getPlugin().getJailIO().getLanguageString(LangString.NOTJAILED, args[1])); + } + + return true; + } +} diff --git a/src/main/java/com/graywolf336/jail/command/subcommands/JailPayCommand.java b/src/main/java/com/graywolf336/jail/command/subcommands/JailPayCommand.java index 9740939..08966f4 100644 --- a/src/main/java/com/graywolf336/jail/command/subcommands/JailPayCommand.java +++ b/src/main/java/com/graywolf336/jail/command/subcommands/JailPayCommand.java @@ -1,229 +1,229 @@ -package com.graywolf336.jail.command.subcommands; - -import java.util.concurrent.TimeUnit; - -import org.bukkit.ChatColor; -import org.bukkit.command.CommandSender; -import org.bukkit.entity.Player; - -import com.graywolf336.jail.JailManager; -import com.graywolf336.jail.JailPayManager; -import com.graywolf336.jail.beans.Prisoner; -import com.graywolf336.jail.command.Command; -import com.graywolf336.jail.command.CommandInfo; -import com.graywolf336.jail.enums.LangString; -import com.graywolf336.jail.enums.Settings; - -@CommandInfo( - maxArgs = 2, - minimumArgs = 0, - needsPlayer = true, - pattern = "pay", - permission = "jail.usercmd.jailpay", - usage = "/jail pay " - ) -public class JailPayCommand implements Command { - public boolean execute(JailManager jm, CommandSender sender, String... args) throws Exception { - if(jm.getPlugin().getConfig().getBoolean(Settings.JAILPAYENABLED.getPath())) { - JailPayManager pm = jm.getPlugin().getJailPayManager(); - - switch(args.length) { - case 1: - // `/jail pay` - //send how much it costs to get out - if(jm.isPlayerJailedByLastKnownUsername(sender.getName())) { - Prisoner p = jm.getPrisonerByLastKnownName(sender.getName()); - String amt = ""; - - if(pm.usingItemsForPayment()) { - amt = String.valueOf((int) Math.ceil(pm.calculateBill(p))); - }else { - amt = String.valueOf(pm.calculateBill(p)); - } - - if(p.getRemainingTime() > 0) { - if(pm.isTimedEnabled()) { - sender.sendMessage(jm.getPlugin().getJailIO().getLanguageString(LangString.PAYCOST, new String[] { pm.getCostPerMinute(), pm.getCurrencyName(), amt })); - }else { - sender.sendMessage(jm.getPlugin().getJailIO().getLanguageString(LangString.PAYNOTENABLED)); - jm.getPlugin().debug("Jail pay 'timed' paying is not enabled (config has 0 as the cost)."); - } - }else { - if(pm.isInfiniteEnabled()) { - sender.sendMessage(jm.getPlugin().getJailIO().getLanguageString(LangString.PAYCOST, new String[] { amt, pm.getCurrencyName() })); - }else { - sender.sendMessage(jm.getPlugin().getJailIO().getLanguageString(LangString.PAYNOTENABLED)); - jm.getPlugin().debug("Jail pay 'infinite' paying is not enabled (config has 0 as the cost)."); - } - } - }else { - sender.sendMessage(jm.getPlugin().getJailIO().getLanguageString(LangString.YOUARENOTJAILED)); - } - - break; - case 2: - // `/jail pay ` - //They are trying to pay for their self - if(jm.isPlayerJailedByLastKnownUsername(sender.getName())) { - Prisoner p = jm.getPrisonerByLastKnownName(sender.getName()); - - if(p.getRemainingTime() > 0) { - if(!pm.isTimedEnabled()) { - sender.sendMessage(jm.getPlugin().getJailIO().getLanguageString(LangString.PAYNOTENABLED)); - return true; - } - }else { - if(!pm.isInfiniteEnabled()) { - sender.sendMessage(jm.getPlugin().getJailIO().getLanguageString(LangString.PAYNOTENABLED)); - return true; - } - } - - if(args[1].startsWith("-")) { - sender.sendMessage(jm.getPlugin().getJailIO().getLanguageString(LangString.PAYNONEGATIVEAMOUNTS)); - }else { - double amt = 0; - - try { - amt = Double.parseDouble(args[1]); - }catch(NumberFormatException e) { - sender.sendMessage(ChatColor.RED + " must be a number."); - throw e; - } - - if(pm.hasEnoughToPay((Player) sender, amt)) { - double bill = pm.calculateBill(p); - - if(p.getRemainingTime() > 0) { - //timed sentence - if(amt >= bill) { - pm.pay((Player) sender, bill); - sender.sendMessage(jm.getPlugin().getJailIO().getLanguageString(LangString.PAYPAIDRELEASED, String.valueOf(bill))); - jm.getPlugin().getPrisonerManager().releasePrisoner((Player) sender, p); - }else { - long minutes = pm.getMinutesPayingFor(amt); - pm.pay((Player) sender, amt); - long remain = p.subtractTime(TimeUnit.MILLISECONDS.convert(minutes, TimeUnit.MINUTES)); - sender.sendMessage(jm.getPlugin().getJailIO().getLanguageString(LangString.PAYPAIDLOWEREDTIME, - new String[] { String.valueOf(amt), String.valueOf(TimeUnit.MINUTES.convert(remain, TimeUnit.MILLISECONDS)) })); - } - }else { - //infinite jailing - if(amt >= bill) { - pm.pay((Player) sender, bill); - sender.sendMessage(jm.getPlugin().getJailIO().getLanguageString(LangString.PAYPAIDRELEASED, String.valueOf(bill))); - jm.getPlugin().getPrisonerManager().releasePrisoner((Player) sender, p); - }else { - //You haven't provided enough money to get them out - sender.sendMessage(jm.getPlugin().getJailIO().getLanguageString(LangString.PAYNOTENOUGHMONEYPROVIDED)); - } - } - }else { - sender.sendMessage(jm.getPlugin().getJailIO().getLanguageString(LangString.PAYNOTENOUGHMONEY)); - } - } - }else { - sender.sendMessage(jm.getPlugin().getJailIO().getLanguageString(LangString.YOUARENOTJAILED)); - } - break; - case 3: - // `/jail pay - //they are trying to pay for someone else - if(jm.isPlayerJailedByLastKnownUsername(sender.getName())) { - //When they are jailed they can not pay for someone else - sender.sendMessage(jm.getPlugin().getJailIO().getLanguageString(LangString.PAYCANTPAYWHILEJAILED)); - }else { - if(jm.isPlayerJailedByLastKnownUsername(args[2])) { - Prisoner p = jm.getPrisonerByLastKnownName(args[2]); - - if(p.getRemainingTime() > 0) { - if(!pm.isTimedEnabled()) { - sender.sendMessage(jm.getPlugin().getJailIO().getLanguageString(LangString.PAYNOTENABLED)); - return true; - } - }else { - if(!pm.isInfiniteEnabled()) { - sender.sendMessage(jm.getPlugin().getJailIO().getLanguageString(LangString.PAYNOTENABLED)); - return true; - } - } - - if(args[1].startsWith("-")) { - sender.sendMessage(jm.getPlugin().getJailIO().getLanguageString(LangString.PAYNONEGATIVEAMOUNTS)); - }else { - double amt = 0; - - try { - amt = Double.parseDouble(args[1]); - }catch(NumberFormatException e) { - sender.sendMessage(ChatColor.RED + " must be a number."); - throw e; - } - - - if(pm.hasEnoughToPay((Player) sender, amt)) { - double bill = pm.calculateBill(p); - - if(p.getRemainingTime() > 0) { - //timed sentence - if(amt >= bill) { - pm.pay((Player) sender, bill); - sender.sendMessage(jm.getPlugin().getJailIO().getLanguageString(LangString.PAYPAIDRELEASEDELSE, new String[] { String.valueOf(bill), p.getLastKnownName() })); - jm.getPlugin().getPrisonerManager().releasePrisoner(jm.getPlugin().getServer().getPlayer(p.getUUID()), p); - }else { - long minutes = pm.getMinutesPayingFor(amt); - pm.pay((Player) sender, amt); - long remain = p.subtractTime(TimeUnit.MILLISECONDS.convert(minutes, TimeUnit.MINUTES)); - sender.sendMessage(jm.getPlugin().getJailIO().getLanguageString(LangString.PAYPAIDLOWEREDTIMEELSE, - new String[] { String.valueOf(amt), p.getLastKnownName(), String.valueOf(TimeUnit.MINUTES.convert(remain, TimeUnit.MILLISECONDS)) })); - } - }else { - //infinite jailing - if(amt >= bill) { - pm.pay((Player) sender, bill); - sender.sendMessage(jm.getPlugin().getJailIO().getLanguageString(LangString.PAYPAIDRELEASEDELSE, new String[] { String.valueOf(bill), p.getLastKnownName() })); - jm.getPlugin().getPrisonerManager().releasePrisoner(jm.getPlugin().getServer().getPlayer(p.getUUID()), p); - }else { - //You haven't provided enough money to get them out - sender.sendMessage(jm.getPlugin().getJailIO().getLanguageString(LangString.PAYNOTENOUGHMONEYPROVIDED)); - } - } - }else { - sender.sendMessage(jm.getPlugin().getJailIO().getLanguageString(LangString.PAYNOTENOUGHMONEY)); - } - } - }else { - //Person they're trying to pay for is not jailed - sender.sendMessage(jm.getPlugin().getJailIO().getLanguageString(LangString.NOTJAILED, args[2])); - } - } - break; - default: - return false; - } - }else { - jm.getPlugin().debug("Jail pay not enabled."); - sender.sendMessage(jm.getPlugin().getJailIO().getLanguageString(LangString.PAYNOTENABLED)); - } - - return true; - } -} - -/* - * -Messages: - MessageJailPayAmountForever: To get out of this mess, you will have to pay . - JailPayCannotPay: Sorry, money won't help you this time. - JailPayCannotPayHim: Sorry, money won't help him this time. - JailPayNotEnoughMoney: You don't have that much money! - JailPayCost: 1 minute of your sentence will cost you . That means that cost for releasing you out of the jail is . - JailPayPaidReleased: You have just payed and saved yourself from the jail! - JailPayPaidReleasedHim: You have just payed and saved from the jail! - JailPayLoweredTime: You have just payed and lowered your sentence to minutes! - JailPayLoweredTimeHim: You have just payed and lowered 's sentence to minutes! -JailPay: - PricePerMinute: 10 - PriceForInfiniteJail: 9999 - Currency: 0 +package com.graywolf336.jail.command.subcommands; + +import java.util.concurrent.TimeUnit; + +import org.bukkit.ChatColor; +import org.bukkit.command.CommandSender; +import org.bukkit.entity.Player; + +import com.graywolf336.jail.JailManager; +import com.graywolf336.jail.JailPayManager; +import com.graywolf336.jail.beans.Prisoner; +import com.graywolf336.jail.command.Command; +import com.graywolf336.jail.command.CommandInfo; +import com.graywolf336.jail.enums.LangString; +import com.graywolf336.jail.enums.Settings; + +@CommandInfo( + maxArgs = 2, + minimumArgs = 0, + needsPlayer = true, + pattern = "pay", + permission = "jail.usercmd.jailpay", + usage = "/jail pay " + ) +public class JailPayCommand implements Command { + public boolean execute(JailManager jm, CommandSender sender, String... args) throws Exception { + if(jm.getPlugin().getConfig().getBoolean(Settings.JAILPAYENABLED.getPath())) { + JailPayManager pm = jm.getPlugin().getJailPayManager(); + + switch(args.length) { + case 1: + // `/jail pay` + //send how much it costs to get out + if(jm.isPlayerJailedByLastKnownUsername(sender.getName())) { + Prisoner p = jm.getPrisonerByLastKnownName(sender.getName()); + String amt = ""; + + if(pm.usingItemsForPayment()) { + amt = String.valueOf((int) Math.ceil(pm.calculateBill(p))); + }else { + amt = String.valueOf(pm.calculateBill(p)); + } + + if(p.getRemainingTime() > 0) { + if(pm.isTimedEnabled()) { + sender.sendMessage(jm.getPlugin().getJailIO().getLanguageString(LangString.PAYCOST, new String[] { pm.getCostPerMinute(), pm.getCurrencyName(), amt })); + }else { + sender.sendMessage(jm.getPlugin().getJailIO().getLanguageString(LangString.PAYNOTENABLED)); + jm.getPlugin().debug("Jail pay 'timed' paying is not enabled (config has 0 as the cost)."); + } + }else { + if(pm.isInfiniteEnabled()) { + sender.sendMessage(jm.getPlugin().getJailIO().getLanguageString(LangString.PAYCOST, new String[] { amt, pm.getCurrencyName() })); + }else { + sender.sendMessage(jm.getPlugin().getJailIO().getLanguageString(LangString.PAYNOTENABLED)); + jm.getPlugin().debug("Jail pay 'infinite' paying is not enabled (config has 0 as the cost)."); + } + } + }else { + sender.sendMessage(jm.getPlugin().getJailIO().getLanguageString(LangString.YOUARENOTJAILED)); + } + + break; + case 2: + // `/jail pay ` + //They are trying to pay for their self + if(jm.isPlayerJailedByLastKnownUsername(sender.getName())) { + Prisoner p = jm.getPrisonerByLastKnownName(sender.getName()); + + if(p.getRemainingTime() > 0) { + if(!pm.isTimedEnabled()) { + sender.sendMessage(jm.getPlugin().getJailIO().getLanguageString(LangString.PAYNOTENABLED)); + return true; + } + }else { + if(!pm.isInfiniteEnabled()) { + sender.sendMessage(jm.getPlugin().getJailIO().getLanguageString(LangString.PAYNOTENABLED)); + return true; + } + } + + if(args[1].startsWith("-")) { + sender.sendMessage(jm.getPlugin().getJailIO().getLanguageString(LangString.PAYNONEGATIVEAMOUNTS)); + }else { + double amt = 0; + + try { + amt = Double.parseDouble(args[1]); + }catch(NumberFormatException e) { + sender.sendMessage(ChatColor.RED + " must be a number."); + throw e; + } + + if(pm.hasEnoughToPay((Player) sender, amt)) { + double bill = pm.calculateBill(p); + + if(p.getRemainingTime() > 0) { + //timed sentence + if(amt >= bill) { + pm.pay((Player) sender, bill); + sender.sendMessage(jm.getPlugin().getJailIO().getLanguageString(LangString.PAYPAIDRELEASED, String.valueOf(bill))); + jm.getPlugin().getPrisonerManager().releasePrisoner((Player) sender, p); + }else { + long minutes = pm.getMinutesPayingFor(amt); + pm.pay((Player) sender, amt); + long remain = p.subtractTime(TimeUnit.MILLISECONDS.convert(minutes, TimeUnit.MINUTES)); + sender.sendMessage(jm.getPlugin().getJailIO().getLanguageString(LangString.PAYPAIDLOWEREDTIME, + new String[] { String.valueOf(amt), String.valueOf(TimeUnit.MINUTES.convert(remain, TimeUnit.MILLISECONDS)) })); + } + }else { + //infinite jailing + if(amt >= bill) { + pm.pay((Player) sender, bill); + sender.sendMessage(jm.getPlugin().getJailIO().getLanguageString(LangString.PAYPAIDRELEASED, String.valueOf(bill))); + jm.getPlugin().getPrisonerManager().releasePrisoner((Player) sender, p); + }else { + //You haven't provided enough money to get them out + sender.sendMessage(jm.getPlugin().getJailIO().getLanguageString(LangString.PAYNOTENOUGHMONEYPROVIDED)); + } + } + }else { + sender.sendMessage(jm.getPlugin().getJailIO().getLanguageString(LangString.PAYNOTENOUGHMONEY)); + } + } + }else { + sender.sendMessage(jm.getPlugin().getJailIO().getLanguageString(LangString.YOUARENOTJAILED)); + } + break; + case 3: + // `/jail pay + //they are trying to pay for someone else + if(jm.isPlayerJailedByLastKnownUsername(sender.getName())) { + //When they are jailed they can not pay for someone else + sender.sendMessage(jm.getPlugin().getJailIO().getLanguageString(LangString.PAYCANTPAYWHILEJAILED)); + }else { + if(jm.isPlayerJailedByLastKnownUsername(args[2])) { + Prisoner p = jm.getPrisonerByLastKnownName(args[2]); + + if(p.getRemainingTime() > 0) { + if(!pm.isTimedEnabled()) { + sender.sendMessage(jm.getPlugin().getJailIO().getLanguageString(LangString.PAYNOTENABLED)); + return true; + } + }else { + if(!pm.isInfiniteEnabled()) { + sender.sendMessage(jm.getPlugin().getJailIO().getLanguageString(LangString.PAYNOTENABLED)); + return true; + } + } + + if(args[1].startsWith("-")) { + sender.sendMessage(jm.getPlugin().getJailIO().getLanguageString(LangString.PAYNONEGATIVEAMOUNTS)); + }else { + double amt = 0; + + try { + amt = Double.parseDouble(args[1]); + }catch(NumberFormatException e) { + sender.sendMessage(ChatColor.RED + " must be a number."); + throw e; + } + + + if(pm.hasEnoughToPay((Player) sender, amt)) { + double bill = pm.calculateBill(p); + + if(p.getRemainingTime() > 0) { + //timed sentence + if(amt >= bill) { + pm.pay((Player) sender, bill); + sender.sendMessage(jm.getPlugin().getJailIO().getLanguageString(LangString.PAYPAIDRELEASEDELSE, new String[] { String.valueOf(bill), p.getLastKnownName() })); + jm.getPlugin().getPrisonerManager().releasePrisoner(jm.getPlugin().getServer().getPlayer(p.getUUID()), p); + }else { + long minutes = pm.getMinutesPayingFor(amt); + pm.pay((Player) sender, amt); + long remain = p.subtractTime(TimeUnit.MILLISECONDS.convert(minutes, TimeUnit.MINUTES)); + sender.sendMessage(jm.getPlugin().getJailIO().getLanguageString(LangString.PAYPAIDLOWEREDTIMEELSE, + new String[] { String.valueOf(amt), p.getLastKnownName(), String.valueOf(TimeUnit.MINUTES.convert(remain, TimeUnit.MILLISECONDS)) })); + } + }else { + //infinite jailing + if(amt >= bill) { + pm.pay((Player) sender, bill); + sender.sendMessage(jm.getPlugin().getJailIO().getLanguageString(LangString.PAYPAIDRELEASEDELSE, new String[] { String.valueOf(bill), p.getLastKnownName() })); + jm.getPlugin().getPrisonerManager().releasePrisoner(jm.getPlugin().getServer().getPlayer(p.getUUID()), p); + }else { + //You haven't provided enough money to get them out + sender.sendMessage(jm.getPlugin().getJailIO().getLanguageString(LangString.PAYNOTENOUGHMONEYPROVIDED)); + } + } + }else { + sender.sendMessage(jm.getPlugin().getJailIO().getLanguageString(LangString.PAYNOTENOUGHMONEY)); + } + } + }else { + //Person they're trying to pay for is not jailed + sender.sendMessage(jm.getPlugin().getJailIO().getLanguageString(LangString.NOTJAILED, args[2])); + } + } + break; + default: + return false; + } + }else { + jm.getPlugin().debug("Jail pay not enabled."); + sender.sendMessage(jm.getPlugin().getJailIO().getLanguageString(LangString.PAYNOTENABLED)); + } + + return true; + } +} + +/* + * +Messages: + MessageJailPayAmountForever: To get out of this mess, you will have to pay . + JailPayCannotPay: Sorry, money won't help you this time. + JailPayCannotPayHim: Sorry, money won't help him this time. + JailPayNotEnoughMoney: You don't have that much money! + JailPayCost: 1 minute of your sentence will cost you . That means that cost for releasing you out of the jail is . + JailPayPaidReleased: You have just payed and saved yourself from the jail! + JailPayPaidReleasedHim: You have just payed and saved from the jail! + JailPayLoweredTime: You have just payed and lowered your sentence to minutes! + JailPayLoweredTimeHim: You have just payed and lowered 's sentence to minutes! +JailPay: + PricePerMinute: 10 + PriceForInfiniteJail: 9999 + Currency: 0 */ \ No newline at end of file diff --git a/src/main/java/com/graywolf336/jail/command/subcommands/JailRecordCommand.java b/src/main/java/com/graywolf336/jail/command/subcommands/JailRecordCommand.java index a0ca887..3e28b53 100644 --- a/src/main/java/com/graywolf336/jail/command/subcommands/JailRecordCommand.java +++ b/src/main/java/com/graywolf336/jail/command/subcommands/JailRecordCommand.java @@ -1,45 +1,45 @@ -package com.graywolf336.jail.command.subcommands; - -import java.util.List; - -import org.bukkit.command.CommandSender; - -import com.graywolf336.jail.JailManager; -import com.graywolf336.jail.command.Command; -import com.graywolf336.jail.command.CommandInfo; -import com.graywolf336.jail.enums.LangString; - -@CommandInfo( - maxArgs = 2, - minimumArgs = 1, - needsPlayer = false, - pattern = "reload|r", - permission = "jail.command.jailrecord", - usage = "/jail record " - ) -public class JailRecordCommand implements Command { - public boolean execute(JailManager jm, CommandSender sender, String... args) { - if(args.length == 2) { - // /jail record - List entries = jm.getPlugin().getJailIO().getRecordEntries(args[1]); - - sender.sendMessage(jm.getPlugin().getJailIO().getLanguageString(LangString.RECORDTIMESJAILED, new String[] { args[1], String.valueOf(entries.size()) })); - }else if(args.length == 3) { - // /jail record something - List entries = jm.getPlugin().getJailIO().getRecordEntries(args[1]); - - //Send all the record entries - for(String s : entries) { - sender.sendMessage(s); - } - - sender.sendMessage(jm.getPlugin().getJailIO().getLanguageString(LangString.RECORDTIMESJAILED, new String[] { args[1], String.valueOf(entries.size()) })); - }else { - //They didn't do the command right - //send them back to get the usage - return false; - } - - return true; - } -} +package com.graywolf336.jail.command.subcommands; + +import java.util.List; + +import org.bukkit.command.CommandSender; + +import com.graywolf336.jail.JailManager; +import com.graywolf336.jail.command.Command; +import com.graywolf336.jail.command.CommandInfo; +import com.graywolf336.jail.enums.LangString; + +@CommandInfo( + maxArgs = 2, + minimumArgs = 1, + needsPlayer = false, + pattern = "reload|r", + permission = "jail.command.jailrecord", + usage = "/jail record " + ) +public class JailRecordCommand implements Command { + public boolean execute(JailManager jm, CommandSender sender, String... args) { + if(args.length == 2) { + // /jail record + List entries = jm.getPlugin().getJailIO().getRecordEntries(args[1]); + + sender.sendMessage(jm.getPlugin().getJailIO().getLanguageString(LangString.RECORDTIMESJAILED, new String[] { args[1], String.valueOf(entries.size()) })); + }else if(args.length == 3) { + // /jail record something + List entries = jm.getPlugin().getJailIO().getRecordEntries(args[1]); + + //Send all the record entries + for(String s : entries) { + sender.sendMessage(s); + } + + sender.sendMessage(jm.getPlugin().getJailIO().getLanguageString(LangString.RECORDTIMESJAILED, new String[] { args[1], String.valueOf(entries.size()) })); + }else { + //They didn't do the command right + //send them back to get the usage + return false; + } + + return true; + } +} diff --git a/src/main/java/com/graywolf336/jail/command/subcommands/JailReloadCommand.java b/src/main/java/com/graywolf336/jail/command/subcommands/JailReloadCommand.java index f1e439d..cb214da 100644 --- a/src/main/java/com/graywolf336/jail/command/subcommands/JailReloadCommand.java +++ b/src/main/java/com/graywolf336/jail/command/subcommands/JailReloadCommand.java @@ -1,36 +1,36 @@ -package com.graywolf336.jail.command.subcommands; - -import org.bukkit.ChatColor; -import org.bukkit.command.CommandSender; - -import com.graywolf336.jail.JailManager; -import com.graywolf336.jail.command.Command; -import com.graywolf336.jail.command.CommandInfo; -import com.graywolf336.jail.enums.LangString; - -@CommandInfo( - maxArgs = 0, - minimumArgs = 0, - needsPlayer = false, - pattern = "reload|r", - permission = "jail.command.jailreload", - usage = "/jail reload" - ) -public class JailReloadCommand implements Command { - public boolean execute(JailManager jm, CommandSender sender, String... args) { - try { - jm.getPlugin().reloadConfig(); - jm.getPlugin().getJailIO().loadLanguage(); - jm.getPlugin().getJailIO().loadJails(); - jm.getPlugin().reloadScoreBoardManager(); - jm.getPlugin().reloadJailSticks(); - jm.getPlugin().reloadJailPayManager(); - - sender.sendMessage(jm.getPlugin().getJailIO().getLanguageString(LangString.PLUGINRELOADED)); - }catch (Exception e) { - sender.sendMessage(ChatColor.RED + e.getMessage()); - } - - return true; - } -} +package com.graywolf336.jail.command.subcommands; + +import org.bukkit.ChatColor; +import org.bukkit.command.CommandSender; + +import com.graywolf336.jail.JailManager; +import com.graywolf336.jail.command.Command; +import com.graywolf336.jail.command.CommandInfo; +import com.graywolf336.jail.enums.LangString; + +@CommandInfo( + maxArgs = 0, + minimumArgs = 0, + needsPlayer = false, + pattern = "reload|r", + permission = "jail.command.jailreload", + usage = "/jail reload" + ) +public class JailReloadCommand implements Command { + public boolean execute(JailManager jm, CommandSender sender, String... args) { + try { + jm.getPlugin().reloadConfig(); + jm.getPlugin().getJailIO().loadLanguage(); + jm.getPlugin().getJailIO().loadJails(); + jm.getPlugin().reloadScoreBoardManager(); + jm.getPlugin().reloadJailSticks(); + jm.getPlugin().reloadJailPayManager(); + + sender.sendMessage(jm.getPlugin().getJailIO().getLanguageString(LangString.PLUGINRELOADED)); + }catch (Exception e) { + sender.sendMessage(ChatColor.RED + e.getMessage()); + } + + return true; + } +} diff --git a/src/main/java/com/graywolf336/jail/command/subcommands/JailStickCommand.java b/src/main/java/com/graywolf336/jail/command/subcommands/JailStickCommand.java index 1557df0..8ca1eb2 100644 --- a/src/main/java/com/graywolf336/jail/command/subcommands/JailStickCommand.java +++ b/src/main/java/com/graywolf336/jail/command/subcommands/JailStickCommand.java @@ -1,35 +1,35 @@ -package com.graywolf336.jail.command.subcommands; - -import org.bukkit.command.CommandSender; - -import com.graywolf336.jail.JailManager; -import com.graywolf336.jail.command.Command; -import com.graywolf336.jail.command.CommandInfo; -import com.graywolf336.jail.enums.LangString; -import com.graywolf336.jail.enums.Settings; - -@CommandInfo( - maxArgs = 0, - minimumArgs = 0, - needsPlayer = true, - pattern = "stick", - permission = "jail.usercmd.jailstick", - usage = "/jail stick" - ) -public class JailStickCommand implements Command { - public boolean execute(JailManager jm, CommandSender sender, String... args) throws Exception { - if(jm.getPlugin().getConfig().getBoolean(Settings.JAILSTICKENABLED.getPath())) { - boolean using = jm.getPlugin().getJailStickManager().toggleUsingStick(sender.getName()); - - if(using) { - sender.sendMessage(jm.getPlugin().getJailIO().getLanguageString(LangString.JAILSTICKENABLED)); - }else { - sender.sendMessage(jm.getPlugin().getJailIO().getLanguageString(LangString.JAILSTICKDISABLED)); - } - }else { - sender.sendMessage(jm.getPlugin().getJailIO().getLanguageString(LangString.JAILSTICKUSAGEDISABLED)); - } - - return true; - } -} +package com.graywolf336.jail.command.subcommands; + +import org.bukkit.command.CommandSender; + +import com.graywolf336.jail.JailManager; +import com.graywolf336.jail.command.Command; +import com.graywolf336.jail.command.CommandInfo; +import com.graywolf336.jail.enums.LangString; +import com.graywolf336.jail.enums.Settings; + +@CommandInfo( + maxArgs = 0, + minimumArgs = 0, + needsPlayer = true, + pattern = "stick", + permission = "jail.usercmd.jailstick", + usage = "/jail stick" + ) +public class JailStickCommand implements Command { + public boolean execute(JailManager jm, CommandSender sender, String... args) throws Exception { + if(jm.getPlugin().getConfig().getBoolean(Settings.JAILSTICKENABLED.getPath())) { + boolean using = jm.getPlugin().getJailStickManager().toggleUsingStick(sender.getName()); + + if(using) { + sender.sendMessage(jm.getPlugin().getJailIO().getLanguageString(LangString.JAILSTICKENABLED)); + }else { + sender.sendMessage(jm.getPlugin().getJailIO().getLanguageString(LangString.JAILSTICKDISABLED)); + } + }else { + sender.sendMessage(jm.getPlugin().getJailIO().getLanguageString(LangString.JAILSTICKUSAGEDISABLED)); + } + + return true; + } +} diff --git a/src/main/java/com/graywolf336/jail/command/subcommands/JailTeleInCommand.java b/src/main/java/com/graywolf336/jail/command/subcommands/JailTeleInCommand.java index 96ccdcb..be3188f 100644 --- a/src/main/java/com/graywolf336/jail/command/subcommands/JailTeleInCommand.java +++ b/src/main/java/com/graywolf336/jail/command/subcommands/JailTeleInCommand.java @@ -1,54 +1,54 @@ -package com.graywolf336.jail.command.subcommands; - -import org.bukkit.command.CommandSender; -import org.bukkit.entity.Player; - -import com.graywolf336.jail.JailManager; -import com.graywolf336.jail.beans.Jail; -import com.graywolf336.jail.command.Command; -import com.graywolf336.jail.command.CommandInfo; -import com.graywolf336.jail.enums.LangString; - -@CommandInfo( - maxArgs = 2, - minimumArgs = 1, - needsPlayer = false, - pattern = "telein|teleportin", - permission = "jail.command.jailtelein", - usage = "/jail telein (player)" - ) -public class JailTeleInCommand implements Command { - public boolean execute(JailManager jm, CommandSender sender, String... args) throws Exception { - Jail j = jm.getJail(args[1]); - - //The jail doesn't exist - if(j == null) { - sender.sendMessage(jm.getPlugin().getJailIO().getLanguageString(LangString.NOJAIL, args[1])); - }else { - //The jail does exist - //now let's check the size of the command - //if it has two args then someone is sending someone else in - //otherwise it is just the sender going in - if(args.length == 3) { - Player p = jm.getPlugin().getServer().getPlayer(args[2]); - - //If the player they're trying to send is offline, don't do anything - if(p == null) { - sender.sendMessage(jm.getPlugin().getJailIO().getLanguageString(LangString.PLAYERNOTONLINE, args[2])); - }else { - p.teleport(j.getTeleportIn()); - sender.sendMessage(jm.getPlugin().getJailIO().getLanguageString(LangString.TELEIN, new String[] { args[2], args[1] })); - } - }else { - if(sender instanceof Player) { - ((Player) sender).teleport(j.getTeleportIn()); - sender.sendMessage(jm.getPlugin().getJailIO().getLanguageString(LangString.TELEIN, new String[] { sender.getName(), args[1] })); - }else { - sender.sendMessage(jm.getPlugin().getJailIO().getLanguageString(LangString.PLAYERCONTEXTREQUIRED)); - } - } - } - - return true; - } -} +package com.graywolf336.jail.command.subcommands; + +import org.bukkit.command.CommandSender; +import org.bukkit.entity.Player; + +import com.graywolf336.jail.JailManager; +import com.graywolf336.jail.beans.Jail; +import com.graywolf336.jail.command.Command; +import com.graywolf336.jail.command.CommandInfo; +import com.graywolf336.jail.enums.LangString; + +@CommandInfo( + maxArgs = 2, + minimumArgs = 1, + needsPlayer = false, + pattern = "telein|teleportin", + permission = "jail.command.jailtelein", + usage = "/jail telein (player)" + ) +public class JailTeleInCommand implements Command { + public boolean execute(JailManager jm, CommandSender sender, String... args) throws Exception { + Jail j = jm.getJail(args[1]); + + //The jail doesn't exist + if(j == null) { + sender.sendMessage(jm.getPlugin().getJailIO().getLanguageString(LangString.NOJAIL, args[1])); + }else { + //The jail does exist + //now let's check the size of the command + //if it has two args then someone is sending someone else in + //otherwise it is just the sender going in + if(args.length == 3) { + Player p = jm.getPlugin().getServer().getPlayer(args[2]); + + //If the player they're trying to send is offline, don't do anything + if(p == null) { + sender.sendMessage(jm.getPlugin().getJailIO().getLanguageString(LangString.PLAYERNOTONLINE, args[2])); + }else { + p.teleport(j.getTeleportIn()); + sender.sendMessage(jm.getPlugin().getJailIO().getLanguageString(LangString.TELEIN, new String[] { args[2], args[1] })); + } + }else { + if(sender instanceof Player) { + ((Player) sender).teleport(j.getTeleportIn()); + sender.sendMessage(jm.getPlugin().getJailIO().getLanguageString(LangString.TELEIN, new String[] { sender.getName(), args[1] })); + }else { + sender.sendMessage(jm.getPlugin().getJailIO().getLanguageString(LangString.PLAYERCONTEXTREQUIRED)); + } + } + } + + return true; + } +} diff --git a/src/main/java/com/graywolf336/jail/command/subcommands/JailTeleOutCommand.java b/src/main/java/com/graywolf336/jail/command/subcommands/JailTeleOutCommand.java index cf951d4..2215f9d 100644 --- a/src/main/java/com/graywolf336/jail/command/subcommands/JailTeleOutCommand.java +++ b/src/main/java/com/graywolf336/jail/command/subcommands/JailTeleOutCommand.java @@ -1,54 +1,54 @@ -package com.graywolf336.jail.command.subcommands; - -import org.bukkit.command.CommandSender; -import org.bukkit.entity.Player; - -import com.graywolf336.jail.JailManager; -import com.graywolf336.jail.beans.Jail; -import com.graywolf336.jail.command.Command; -import com.graywolf336.jail.command.CommandInfo; -import com.graywolf336.jail.enums.LangString; - -@CommandInfo( - maxArgs = 2, - minimumArgs = 1, - needsPlayer = false, - pattern = "teleout|teleportout", - permission = "jail.command.jailteleout", - usage = "/jail teleout (player)" - ) -public class JailTeleOutCommand implements Command { - public boolean execute(JailManager jm, CommandSender sender, String... args) throws Exception { - Jail j = jm.getJail(args[1]); - - //The jail doesn't exist - if(j == null) { - sender.sendMessage(jm.getPlugin().getJailIO().getLanguageString(LangString.NOJAIL, args[1])); - }else { - //The jail does exist - //now let's check the size of the command - //if it has two args then someone is sending someone else in - //otherwise it is just the sender going in - if(args.length == 3) { - Player p = jm.getPlugin().getServer().getPlayer(args[2]); - - //If the player they're trying to send is offline, don't do anything - if(p == null) { - sender.sendMessage(jm.getPlugin().getJailIO().getLanguageString(LangString.PLAYERNOTONLINE, args[2])); - }else { - p.teleport(j.getTeleportFree()); - sender.sendMessage(jm.getPlugin().getJailIO().getLanguageString(LangString.TELEOUT, new String[] { args[2], args[1] })); - } - }else { - if(sender instanceof Player) { - ((Player) sender).teleport(j.getTeleportFree()); - sender.sendMessage(jm.getPlugin().getJailIO().getLanguageString(LangString.TELEOUT, new String[] { sender.getName(), args[1] })); - }else { - sender.sendMessage(jm.getPlugin().getJailIO().getLanguageString(LangString.PLAYERCONTEXTREQUIRED)); - } - } - } - - return true; - } -} +package com.graywolf336.jail.command.subcommands; + +import org.bukkit.command.CommandSender; +import org.bukkit.entity.Player; + +import com.graywolf336.jail.JailManager; +import com.graywolf336.jail.beans.Jail; +import com.graywolf336.jail.command.Command; +import com.graywolf336.jail.command.CommandInfo; +import com.graywolf336.jail.enums.LangString; + +@CommandInfo( + maxArgs = 2, + minimumArgs = 1, + needsPlayer = false, + pattern = "teleout|teleportout", + permission = "jail.command.jailteleout", + usage = "/jail teleout (player)" + ) +public class JailTeleOutCommand implements Command { + public boolean execute(JailManager jm, CommandSender sender, String... args) throws Exception { + Jail j = jm.getJail(args[1]); + + //The jail doesn't exist + if(j == null) { + sender.sendMessage(jm.getPlugin().getJailIO().getLanguageString(LangString.NOJAIL, args[1])); + }else { + //The jail does exist + //now let's check the size of the command + //if it has two args then someone is sending someone else in + //otherwise it is just the sender going in + if(args.length == 3) { + Player p = jm.getPlugin().getServer().getPlayer(args[2]); + + //If the player they're trying to send is offline, don't do anything + if(p == null) { + sender.sendMessage(jm.getPlugin().getJailIO().getLanguageString(LangString.PLAYERNOTONLINE, args[2])); + }else { + p.teleport(j.getTeleportFree()); + sender.sendMessage(jm.getPlugin().getJailIO().getLanguageString(LangString.TELEOUT, new String[] { args[2], args[1] })); + } + }else { + if(sender instanceof Player) { + ((Player) sender).teleport(j.getTeleportFree()); + sender.sendMessage(jm.getPlugin().getJailIO().getLanguageString(LangString.TELEOUT, new String[] { sender.getName(), args[1] })); + }else { + sender.sendMessage(jm.getPlugin().getJailIO().getLanguageString(LangString.PLAYERCONTEXTREQUIRED)); + } + } + } + + return true; + } +} diff --git a/src/main/java/com/graywolf336/jail/command/subcommands/JailTimeCommand.java b/src/main/java/com/graywolf336/jail/command/subcommands/JailTimeCommand.java index bbeb82e..4053a5e 100644 --- a/src/main/java/com/graywolf336/jail/command/subcommands/JailTimeCommand.java +++ b/src/main/java/com/graywolf336/jail/command/subcommands/JailTimeCommand.java @@ -1,55 +1,55 @@ -package com.graywolf336.jail.command.subcommands; - -import org.bukkit.command.CommandSender; - -import com.graywolf336.jail.JailManager; -import com.graywolf336.jail.Util; -import com.graywolf336.jail.beans.Prisoner; -import com.graywolf336.jail.command.Command; -import com.graywolf336.jail.command.CommandInfo; -import com.graywolf336.jail.enums.LangString; - -@CommandInfo( - maxArgs = 3, - minimumArgs = 2, - needsPlayer = false, - pattern = "time|t", - permission = "jail.command.jailtime", - usage = "/jail time