From 19ff0e661d1eabbab7ab33b82eec617db2144053 Mon Sep 17 00:00:00 2001 From: KingFaris10 Date: Thu, 1 Mar 2018 17:27:17 +0000 Subject: [PATCH] KingKits v5.3.2 KingKits v5.3.2 update. --- pom.xml | 28 +- .../com/comphenix/attributes/Attributes.java | 26 +- .../com/comphenix/attributes/NbtFactory.java | 30 +- .../faris/easysql/main/databases/SQLite.java | 2 +- .../com/faris/easysql/mysql/MySQLDetails.java | 5 +- .../mysql/helper/StatementCreateTable.java | 3 +- .../java/com/faris/kingkits/KingKits.java | 202 +++++---- src/main/java/com/faris/kingkits/Kit.java | 40 +- .../java/com/faris/kingkits/Messages.java | 2 +- .../java/com/faris/kingkits/Permissions.java | 5 +- .../kingkits/api/event/PlayerPreKitEvent.java | 9 +- .../kingkits/config/CustomConfiguration.java | 32 +- .../controller/CompassController.java | 5 +- .../kingkits/controller/ConfigController.java | 40 +- .../kingkits/controller/GuiController.java | 134 ++++-- .../kingkits/controller/KitController.java | 28 +- .../com/faris/kingkits/helper/CacheMap.java | 4 +- .../com/faris/kingkits/helper/Debugger.java | 2 +- .../java/com/faris/kingkits/helper/Time.java | 2 +- .../kingkits/helper/api/ActionBarAPI.java | 102 ----- .../faris/kingkits/helper/api/TitleAPI.java | 136 ------ .../helper/json/JsonKitSerializer.java | 2 +- .../kingkits/helper/util/BukkitUtilities.java | 16 +- .../kingkits/helper/util/ChatUtilities.java | 5 +- .../kingkits/helper/util/FileUtilities.java | 4 +- .../kingkits/helper/util/JsonUtilities.java | 5 +- .../kingkits/helper/util/KitUtilities.java | 27 +- .../kingkits/helper/util/ObjectUtilities.java | 4 +- .../kingkits/helper/util/PlayerUtilities.java | 3 +- .../helper/util/ReflectionUtilities.java | 4 +- .../kingkits/helper/util/StringUtilities.java | 3 +- .../faris/kingkits/helper/util/Utilities.java | 10 +- .../kingkits/listener/CommandListener.java | 268 ++++++++++-- .../kingkits/listener/EventListener.java | 217 ++++------ .../listener/commands/CommandCreateKit.java | 7 +- .../commands/CommandCreateUserKit.java | 7 +- .../listener/commands/CommandDeleteKit.java | 2 +- .../commands/CommandDeleteUserKit.java | 2 +- .../listener/commands/CommandPreviewKit.java | 2 +- .../listener/commands/CommandPvPKit.java | 6 +- .../listener/commands/CommandRefill.java | 2 +- .../listener/commands/CommandRenameKit.java | 2 +- .../commands/CommandRenameUserKit.java | 2 +- .../java/com/faris/kingkits/old/OldKit.java | 6 +- .../com/faris/kingkits/player/KitPlayer.java | 4 +- .../kingkits/player/OfflineKitPlayer.java | 16 +- .../faris/kingkits/storage/DataStorage.java | 8 +- .../kingkits/storage/FlatFileStorage.java | 7 +- .../faris/kingkits/storage/SQLStorage.java | 406 +++++++++--------- .../faris/kingkits/updater/BukkitUpdater.java | 15 +- .../faris/kingkits/updater/SpigotUpdater.java | 19 +- .../java/mkremins/fanciful/FancyMessage.java | 2 +- .../fanciful/JsonRepresentedObject.java | 2 +- .../java/mkremins/fanciful/JsonString.java | 3 +- .../java/mkremins/fanciful/MessagePart.java | 6 +- .../mkremins/fanciful/TextualComponent.java | 7 +- .../java/net/amoebaman/util/ArrayWrapper.java | 3 +- 57 files changed, 943 insertions(+), 998 deletions(-) delete mode 100644 src/main/java/com/faris/kingkits/helper/api/ActionBarAPI.java delete mode 100644 src/main/java/com/faris/kingkits/helper/api/TitleAPI.java diff --git a/pom.xml b/pom.xml index e91f015..619a1a4 100644 --- a/pom.xml +++ b/pom.xml @@ -40,28 +40,28 @@ org.apache.maven.plugins - maven-javadoc-plugin - 2.10.3 + maven-compiler-plugin + 3.7.0 - true - ${project.basedir} - gh-pages - private + 1.8 + 1.8 org.apache.maven.plugins - maven-compiler-plugin - 3.5.1 + maven-javadoc-plugin + 3.0.0 - 1.7 - 1.7 + true + ${project.basedir} + gh-pages + private org.apache.maven.plugins maven-shade-plugin - 2.4.3 + 3.1.0 false @@ -140,13 +140,13 @@ org.bukkit bukkit - 1.11.2-R0.1-SNAPSHOT + 1.12.2-R0.1-SNAPSHOT provided com.google.code.gson gson - 2.6.2 + 2.8.2 compile @@ -158,7 +158,7 @@ net.milkbowl.vault VaultAPI - 1.5 + 1.6 provided diff --git a/src/main/java/com/comphenix/attributes/Attributes.java b/src/main/java/com/comphenix/attributes/Attributes.java index 084cd79..6ecc54d 100644 --- a/src/main/java/com/comphenix/attributes/Attributes.java +++ b/src/main/java/com/comphenix/attributes/Attributes.java @@ -21,7 +21,6 @@ import com.comphenix.attributes.NbtFactory.NbtList; import com.faris.kingkits.helper.util.ObjectUtilities; import com.faris.kingkits.helper.util.Utilities; -import com.google.common.base.Function; import com.google.common.base.Objects; import com.google.common.base.Preconditions; import com.google.common.collect.Iterators; @@ -31,7 +30,7 @@ import java.lang.reflect.Field; import java.util.*; -import java.util.concurrent.ConcurrentMap; +import java.util.concurrent.*; public class Attributes { public enum Operation { @@ -40,7 +39,7 @@ public enum Operation { ADD_PERCENTAGE(2); private int id; - private Operation(int id) { + Operation(int id) { this.id = id; } @@ -473,21 +472,12 @@ public List getAll() { // We can't make Attributes itself iterable without splitting it up into separate classes public Iterable values() { - return new Iterable() { - @Override - public Iterator iterator() { - // Handle the empty case - if (size() == 0) - return Collections.emptyList().iterator(); - - return Iterators.transform(attributes.iterator(), - new Function() { - @Override - public Attribute apply(Object element) { - return new Attribute((NbtCompound) element); - } - }); - } + return () -> { + // Handle the empty case + if (size() == 0) + return Collections.emptyList().iterator(); + + return Iterators.transform(attributes.iterator(), element -> new Attribute((NbtCompound) element)); }; } } \ No newline at end of file diff --git a/src/main/java/com/comphenix/attributes/NbtFactory.java b/src/main/java/com/comphenix/attributes/NbtFactory.java index d6d80fd..638c19e 100644 --- a/src/main/java/com/comphenix/attributes/NbtFactory.java +++ b/src/main/java/com/comphenix/attributes/NbtFactory.java @@ -22,10 +22,7 @@ import com.google.common.collect.HashBiMap; import com.google.common.collect.Lists; import com.google.common.collect.MapMaker; -import com.google.common.io.Closeables; -import com.google.common.io.Files; -import com.google.common.io.InputSupplier; -import com.google.common.io.OutputSupplier; +import com.google.common.io.*; import com.google.common.primitives.Primitives; import org.bukkit.Bukkit; import org.bukkit.Material; @@ -38,9 +35,8 @@ import java.lang.reflect.Method; import java.lang.reflect.Modifier; import java.util.*; -import java.util.concurrent.ConcurrentMap; -import java.util.zip.GZIPInputStream; -import java.util.zip.GZIPOutputStream; +import java.util.concurrent.*; +import java.util.zip.*; public class NbtFactory { // Convert between NBT id and the equivalent class in java @@ -260,13 +256,13 @@ public T getPath(String path) { /** * Save the content of a NBT compound to a stream. *

- * Use {@link Files#newOutputStreamSupplier(java.io.File)} to provide a stream supplier to a file. + * Use {@link Files#asByteSink(File, FileWriteMode...)} to provide a stream supplier to a file. * * @param stream - the output stream. * @param option - whether or not to compress the output. * @throws IOException If anything went wrong. */ - public void saveTo(OutputSupplier stream, StreamOptions option) throws IOException { + public void saveTo(ByteSink stream, StreamOptions option) throws IOException { saveStream(this, stream, option); } @@ -431,7 +427,7 @@ public static NbtList createList(Object... content) { * * @return The NBT list. */ - public static NbtList createList(Iterable iterable) { + public static NbtList createList(Iterable iterable) { NbtList list = get().new NbtList( INSTANCE.createNbtTag(NbtType.TAG_LIST, null) ); @@ -466,20 +462,20 @@ public static NbtList fromList(Object nmsList) { /** * Load the content of a file from a stream. *

- * Use {@link Files#newInputStreamSupplier(java.io.File)} to provide a stream from a file. + * Use {@link Files#asByteSource(File)} to provide a stream from a file. * * @param stream - the stream supplier. * @param option - whether or not to decompress the input stream. * @return The decoded NBT compound. * @throws IOException If anything went wrong. */ - public static NbtCompound fromStream(InputSupplier stream, StreamOptions option) throws IOException { + public static NbtCompound fromStream(ByteSource stream, StreamOptions option) throws IOException { InputStream input = null; DataInputStream data = null; boolean suppress = true; try { - input = stream.getInput(); + input = stream.openStream(); data = new DataInputStream(new BufferedInputStream( option == StreamOptions.GZIP_COMPRESSION ? new GZIPInputStream(input) : input )); @@ -499,20 +495,20 @@ else if (input != null) /** * Save the content of a NBT compound to a stream. *

- * Use {@link Files#newOutputStreamSupplier(java.io.File)} to provide a stream supplier to a file. + * Use {@link Files#asByteSink(File, FileWriteMode...)} to provide a stream supplier to a file. * * @param source - the NBT compound to save. * @param stream - the stream. * @param option - whether or not to compress the output. * @throws IOException If anything went wrong. */ - public static void saveStream(NbtCompound source, OutputSupplier stream, StreamOptions option) throws IOException { + public static void saveStream(NbtCompound source, ByteSink stream, StreamOptions option) throws IOException { OutputStream output = null; DataOutputStream data = null; boolean suppress = true; try { - output = stream.getOutput(); + output = stream.openStream(); data = new DataOutputStream( option == StreamOptions.GZIP_COMPRESSION ? new GZIPOutputStream(output) : output ); @@ -922,7 +918,7 @@ public boolean hasNext() { public Entry next() { Entry entry = proxy.next(); - return new SimpleEntry( + return new SimpleEntry<>( entry.getKey(), wrapOutgoing(entry.getValue()) ); } diff --git a/src/main/java/com/faris/easysql/main/databases/SQLite.java b/src/main/java/com/faris/easysql/main/databases/SQLite.java index 86a3f31..613fbc2 100644 --- a/src/main/java/com/faris/easysql/main/databases/SQLite.java +++ b/src/main/java/com/faris/easysql/main/databases/SQLite.java @@ -8,7 +8,7 @@ import java.sql.Connection; import java.sql.DriverManager; import java.sql.SQLException; -import java.util.logging.Level; +import java.util.logging.*; /** * Connects to and uses a SQLite database diff --git a/src/main/java/com/faris/easysql/mysql/MySQLDetails.java b/src/main/java/com/faris/easysql/mysql/MySQLDetails.java index afc2eae..22092d6 100644 --- a/src/main/java/com/faris/easysql/mysql/MySQLDetails.java +++ b/src/main/java/com/faris/easysql/mysql/MySQLDetails.java @@ -4,9 +4,8 @@ import org.bukkit.Bukkit; import org.bukkit.configuration.serialization.ConfigurationSerializable; -import java.util.LinkedHashMap; -import java.util.Map; -import java.util.logging.Level; +import java.util.*; +import java.util.logging.*; public class MySQLDetails implements ConfigurationSerializable { diff --git a/src/main/java/com/faris/easysql/mysql/helper/StatementCreateTable.java b/src/main/java/com/faris/easysql/mysql/helper/StatementCreateTable.java index a71f1a5..60880cd 100644 --- a/src/main/java/com/faris/easysql/mysql/helper/StatementCreateTable.java +++ b/src/main/java/com/faris/easysql/mysql/helper/StatementCreateTable.java @@ -6,8 +6,7 @@ import java.sql.Connection; import java.sql.PreparedStatement; import java.sql.SQLException; -import java.util.ArrayList; -import java.util.List; +import java.util.*; public class StatementCreateTable extends StatementBuilder { diff --git a/src/main/java/com/faris/kingkits/KingKits.java b/src/main/java/com/faris/kingkits/KingKits.java index b50ad9c..3c1cc68 100644 --- a/src/main/java/com/faris/kingkits/KingKits.java +++ b/src/main/java/com/faris/kingkits/KingKits.java @@ -28,9 +28,8 @@ import java.io.FileOutputStream; import java.io.IOException; import java.io.InputStream; -import java.util.HashMap; -import java.util.Map; -import java.util.logging.Level; +import java.util.*; +import java.util.logging.*; public class KingKits extends JavaPlugin { @@ -46,7 +45,6 @@ public void onEnable() { Attributes.AttributeType.initialiseNameMap(); final boolean isSpigot = this.getServer().getVersion().contains("Spigot"); - try { String packageName = this.getServer().getClass().getPackage().getName(); SERVER_VERSION = packageName.substring(packageName.lastIndexOf('.') + 1); @@ -73,9 +71,11 @@ public void onEnable() { ConfigurationSerialization.registerClass(Attribute.class); ConfigurationSerialization.registerClass(MySQLDetails.class); - if (new File(this.getDataFolder(), "config.yml").exists() && (!ConfigController.getInstance().getConfig().contains("Version") || !ConfigController.getInstance().getConfig().getString("Version").equals(ConfigController.CURRENT_CONFIG_VERSION))) + if (new File(this.getDataFolder(), "config.yml").exists() && (!ConfigController.getInstance().getConfig().contains("Version") || !ConfigController.getInstance().getConfig().getString("Version").equals(ConfigController.CURRENT_CONFIG_VERSION))) { ConfigController.getInstance().migrateOldConfigs(); - else ConfigController.getInstance().loadConfiguration(); + } else { + ConfigController.getInstance().loadConfiguration(); + } try { Messages.initMessages(this); } catch (Exception ex) { @@ -88,111 +88,116 @@ public void onEnable() { CompassController.getInstance(); try { - if (Messages.KIT_NOT_ENOUGH_MONEY.getRawMessage().contains("%d")) + if (Messages.KIT_NOT_ENOUGH_MONEY.getRawMessage().contains("%d")) { Messages.KIT_NOT_ENOUGH_MONEY.setMessage(Messages.KIT_NOT_ENOUGH_MONEY.getRawMessage().replace("%d", "%.2f")); + } } catch (Exception ex) { ex.printStackTrace(); } this.getServer().getPluginManager().registerEvents((this.eventListener = new EventListener(this)), this); - if (ConfigController.getInstance().shouldCheckForUpdates()) { - this.getLogger().info("Checking for updates..."); - if (this.getServer().getVersion().contains("Spigot")) { - final int pluginID = 2209; - SpigotUpdater updater = new SpigotUpdater(this, pluginID, false); - if (updater.getResult() == SpigotUpdater.UpdateResult.UPDATE_AVAILABLE) { - String title = "============================================"; - String titleSpace = " "; - this.getLogger().info(title); - try { - this.getLogger().info(titleSpace.substring(0, titleSpace.length() / 2 - "KingKits".length() + 3) + "KingKits" + titleSpace.substring(0, titleSpace.length() / 2 - "KingKits".length())); - } catch (Exception ex) { - this.getLogger().info("KingKits"); - } - this.getLogger().info(title); - this.getLogger().info("A new version is available: KingKits v" + updater.getVersion()); - this.getLogger().info("Your current version: KingKits v" + updater.getCurrentVersion()); - this.getLogger().info((ConfigController.getInstance().shouldAutomaticallyUpdate() ? "KingKits auto-updater does not work for Spigot. " : "") + "Download it from: http://www.spigotmc.org/threads/kingkits.37947"); - } else { - switch (updater.getResult()) { - case UPDATE_AVAILABLE: - break; - case DISABLED: - this.getLogger().warning("Plugin updater disabled in the updater's configuration."); - break; - case BAD_RESOURCE_ID: - this.getLogger().warning("Check failed: Bad resource ID."); - break; - case FAIL_SPIGOT: - this.getLogger().warning("Check failed: Could not connect to Spigot."); - break; - case FAIL_NO_VERSION: - this.getLogger().warning("Check failed: The latest version has an incorrect title."); - break; - default: - this.getLogger().info("No new update found."); - break; - } - } - } else { - final int pluginID = 56371; - BukkitUpdater updater = new BukkitUpdater(this, pluginID, this.getFile(), BukkitUpdater.UpdateType.NO_DOWNLOAD, false); - if (updater.getResult() == BukkitUpdater.UpdateResult.UPDATE_AVAILABLE) { - String header = "============================================"; - String titleSpace = " "; - this.getLogger().info(header); - try { - this.getLogger().info(titleSpace.substring(0, titleSpace.length() / 2 - "KingKits".length() + 3) + "KingKits" + titleSpace.substring(0, titleSpace.length() / 2 - "KingKits".length())); - } catch (Exception ex) { - this.getLogger().info("== KingKits =="); - } - this.getLogger().info(header); - this.getLogger().info("A new version is available: " + updater.getLatestName()); - this.getLogger().info("Your current version: KingKits v" + this.getDescription().getVersion()); - if (ConfigController.getInstance().shouldAutomaticallyUpdate()) { - this.getLogger().info("Downloading " + updater.getLatestName() + "..."); - updater = new BukkitUpdater(this, pluginID, this.getFile(), BukkitUpdater.UpdateType.NO_VERSION_CHECK, false); - BukkitUpdater.UpdateResult updateResult = updater.getResult(); - switch (updateResult) { + try { + if (ConfigController.getInstance().shouldCheckForUpdates()) { + this.getLogger().info("Checking for updates..."); + if (this.getServer().getVersion().contains("Spigot")) { + final int pluginID = 2209; + SpigotUpdater updater = new SpigotUpdater(this, pluginID, false); + if (updater.getResult() == SpigotUpdater.UpdateResult.UPDATE_AVAILABLE) { + String title = "============================================"; + String titleSpace = " "; + this.getLogger().info(title); + try { + this.getLogger().info(titleSpace.substring(0, titleSpace.length() / 2 - "KingKits".length() + 3) + "KingKits" + titleSpace.substring(0, titleSpace.length() / 2 - "KingKits".length())); + } catch (Exception ex) { + this.getLogger().info("KingKits"); + } + this.getLogger().info(title); + this.getLogger().info("A new version is available: KingKits v" + updater.getVersion()); + this.getLogger().info("Your current version: KingKits v" + updater.getCurrentVersion()); + this.getLogger().info((ConfigController.getInstance().shouldAutomaticallyUpdate() ? "KingKits auto-updater does not work for Spigot. " : "") + "Download it from: http://www.spigotmc.org/threads/kingkits.37947"); + } else { + switch (updater.getResult()) { + case UPDATE_AVAILABLE: + break; case DISABLED: this.getLogger().warning("Plugin updater disabled in the updater's configuration."); break; - case FAIL_APIKEY: - this.getLogger().warning("Download failed: Improperly configured the server's API key in the configuration"); + case BAD_RESOURCE_ID: + this.getLogger().warning("Check failed: Bad resource ID."); break; - case FAIL_DBO: - this.getLogger().warning("Download failed: Could not connect to BukkitDev."); + case FAIL_SPIGOT: + this.getLogger().warning("Check failed: Could not connect to Spigot."); break; - case FAIL_DOWNLOAD: - this.getLogger().warning("Download failed: Could not download the file."); - break; - case FAIL_NOVERSION: - this.getLogger().warning("Download failed: The latest version has an incorrect title."); + case FAIL_NO_VERSION: + this.getLogger().warning("Check failed: The latest version has an incorrect title."); break; default: - this.getLogger().info("The latest version of KingKits has been downloaded."); + this.getLogger().info("No new update found."); break; } - } else { - this.getLogger().info("Download it from: " + updater.getLatestFileLink()); + } + } else { + final int pluginID = 56371; + BukkitUpdater updater = new BukkitUpdater(this, pluginID, this.getFile(), BukkitUpdater.UpdateType.NO_DOWNLOAD, false); + if (updater.getResult() == BukkitUpdater.UpdateResult.UPDATE_AVAILABLE) { + String header = "============================================"; + String titleSpace = " "; + this.getLogger().info(header); + try { + this.getLogger().info(titleSpace.substring(0, titleSpace.length() / 2 - "KingKits".length() + 3) + "KingKits" + titleSpace.substring(0, titleSpace.length() / 2 - "KingKits".length())); + } catch (Exception ex) { + this.getLogger().info("== KingKits =="); + } + this.getLogger().info(header); + this.getLogger().info("A new version is available: " + updater.getLatestName()); + this.getLogger().info("Your current version: KingKits v" + this.getDescription().getVersion()); + if (ConfigController.getInstance().shouldAutomaticallyUpdate()) { + this.getLogger().info("Downloading " + updater.getLatestName() + "..."); + updater = new BukkitUpdater(this, pluginID, this.getFile(), BukkitUpdater.UpdateType.NO_VERSION_CHECK, false); + BukkitUpdater.UpdateResult updateResult = updater.getResult(); + switch (updateResult) { + case DISABLED: + this.getLogger().warning("Plugin updater disabled in the updater's configuration."); + break; + case FAIL_APIKEY: + this.getLogger().warning("Download failed: Improperly configured the server's API key in the configuration"); + break; + case FAIL_DBO: + this.getLogger().warning("Download failed: Could not connect to BukkitDev."); + break; + case FAIL_DOWNLOAD: + this.getLogger().warning("Download failed: Could not download the file."); + break; + case FAIL_NOVERSION: + this.getLogger().warning("Download failed: The latest version has an incorrect title."); + break; + default: + this.getLogger().info("The latest version of KingKits has been downloaded."); + break; + } + } else { + this.getLogger().info("Download it from: " + updater.getLatestFileLink()); + } } } } + } catch (Exception ex) { + this.getLogger().log(Level.WARNING, "Failed to check for updates", ex); } try { if (DataStorage.getInstance() == null) { if (ConfigController.getInstance().getSQLDetails().isEnabled()) { - DataStorage.setInstance(DataStorage.DataStorageType.SQL); + DataStorage.createInstance(DataStorage.DataStorageType.SQL); } else { - DataStorage.setInstance(DataStorage.DataStorageType.FILE); + DataStorage.createInstance(DataStorage.DataStorageType.FILE); } } this.startAutoSaveTask(); } catch (Exception ex) { - ex.printStackTrace(); + this.getLogger().log(Level.SEVERE, "Failed to create data storage instance", ex); } if (!ConfigController.getInstance().getPlayersConfig().getValues(false).isEmpty()) { @@ -208,16 +213,13 @@ public void onEnable() { try { OfflineKitPlayer deserializedPlayer = OfflineKitPlayer.deserialize(ObjectUtilities.getMap(playerEntry.getValue())); deserializedPlayer.setModified(true); - DataStorage.getInstance().savePlayer(deserializedPlayer, new Runnable() { - @Override - public void run() { - ConfigController.getInstance().getPlayersConfig().set(playerEntry.getKey(), null); - ConfigController.getInstance().savePlayersConfig(); - - if (ConfigController.getInstance().getPlayersConfig().getValues(false).isEmpty()) { - allowJoining = true; - ConfigController.getInstance().deletePlayersConfig(); - } + DataStorage.getInstance().savePlayer(deserializedPlayer, () -> { + ConfigController.getInstance().getPlayersConfig().set(playerEntry.getKey(), null); + ConfigController.getInstance().savePlayersConfig(); + + if (ConfigController.getInstance().getPlayersConfig().getValues(false).isEmpty()) { + this.allowJoining = true; + ConfigController.getInstance().deletePlayersConfig(); } }); } catch (Exception ex) { @@ -244,7 +246,7 @@ public void run() { this.eventListener.handleJoinEvent(player); } } catch (Exception ex) { - ex.printStackTrace(); + this.getLogger().log(Level.SEVERE, "Failed to handle join event", ex); } try { @@ -319,12 +321,9 @@ public boolean allowJoining() { private void disablePlugin() { final KingKits pluginInstance = this; - this.getServer().getScheduler().runTaskLater(this, new Runnable() { - @Override - public void run() { - if (getServer().getPluginManager().isPluginEnabled(pluginInstance)) { - getServer().getPluginManager().disablePlugin(pluginInstance); - } + this.getServer().getScheduler().runTaskLater(this, () -> { + if (this.getServer().getPluginManager().isPluginEnabled(pluginInstance)) { + this.getServer().getPluginManager().disablePlugin(pluginInstance); } }, 20L); } @@ -369,12 +368,7 @@ public void saveResource(String resourcePath, boolean replace, File outFile) { public void startAutoSaveTask() { if (ConfigController.getInstance().getAutoSavePlayerDataTime() != -1D) { this.stopAutoSaveTask(); - this.autoSaveTaskID = this.getServer().getScheduler().runTaskTimer(this, new Runnable() { - @Override - public void run() { - PlayerController.getInstance().saveAllPlayers(); - } - }, (long) (ConfigController.getInstance().getAutoSavePlayerDataTime() * 60D * 20D), (long) (ConfigController.getInstance().getAutoSavePlayerDataTime() * 60D * 20D)).getTaskId(); + this.autoSaveTaskID = this.getServer().getScheduler().runTaskTimer(this, () -> PlayerController.getInstance().saveAllPlayers(), (long) (ConfigController.getInstance().getAutoSavePlayerDataTime() * 60D * 20D), (long) (ConfigController.getInstance().getAutoSavePlayerDataTime() * 60D * 20D)).getTaskId(); } } diff --git a/src/main/java/com/faris/kingkits/Kit.java b/src/main/java/com/faris/kingkits/Kit.java index 8c35705..59a60ab 100644 --- a/src/main/java/com/faris/kingkits/Kit.java +++ b/src/main/java/com/faris/kingkits/Kit.java @@ -17,7 +17,7 @@ public class Kit implements Cloneable, ConfigurationSerializable, JsonSerializab // Kit variables private String kitName = ""; - private String kitDisplayName = ""; // TODO: Add this. It is the name displayed on the GUI. + private String kitDisplayName = ""; private List kitDescription = new ArrayList<>(); private double kitCost = ConfigController.getInstance().getKitDefaultCost(); private double kitCooldown = ConfigController.getInstance().getKitDefaultCooldown(); @@ -137,7 +137,6 @@ public Kit clone() { return (Kit) super.clone(); } catch (Exception ex) { ex.printStackTrace(); - Kit kit = new Kit(this.kitName); kit.setDisplayName(this.getDisplayName()); kit.setUserKit(this.isUserKit()); @@ -158,7 +157,6 @@ public Kit clone() { kit.setHeldItemSlot(this.getHeldItemSlot()); kit.setArmour(this.getArmour()); kit.setPotionEffects(this.getPotionEffects()); - return kit; } } @@ -407,26 +405,36 @@ public static Kit deserialize(final Map serializedKit) { final Kit deserializedKit; if (serializedKit != null && serializedKit.get("Name") != null) { deserializedKit = new Kit(ObjectUtilities.getObject(serializedKit, String.class, "Name")); - if (serializedKit.containsKey("Display name")) + if (serializedKit.containsKey("Display name")) { deserializedKit.setDisplayName(ObjectUtilities.getObject(serializedKit, String.class, "Display name", deserializedKit.getName())); - if (serializedKit.containsKey("Command alias")) + } + if (serializedKit.containsKey("Command alias")) { deserializedKit.setAlias(ObjectUtilities.getObject(serializedKit, Boolean.class, "Command alias", false)); - if (serializedKit.containsKey("Description")) + } + if (serializedKit.containsKey("Description")) { deserializedKit.setDescription(Utilities.toStringList(ObjectUtilities.getObject(serializedKit, List.class, "Description"))); - if (serializedKit.containsKey("Cost")) + } + if (serializedKit.containsKey("Cost")) { deserializedKit.setCost(ObjectUtilities.getObject(serializedKit, Number.class, "Cost", 0D).doubleValue()); - if (serializedKit.containsKey("Cooldown")) + } + if (serializedKit.containsKey("Cooldown")) { deserializedKit.setCooldown(ObjectUtilities.getObject(serializedKit, Number.class, "Cooldown", 0D).doubleValue()); - if (serializedKit.containsKey("Max health")) + } + if (serializedKit.containsKey("Max health")) { deserializedKit.setMaxHealth(ObjectUtilities.getObject(serializedKit, Number.class, "Max health", PlayerUtilities.getDefaultMaxHealth()).doubleValue()); - if (serializedKit.containsKey("Walk speed")) + } + if (serializedKit.containsKey("Walk speed")) { deserializedKit.setWalkSpeed(ObjectUtilities.getObject(serializedKit, Number.class, "Walk speed", PlayerUtilities.getDefaultWalkSpeed()).floatValue()); - if (serializedKit.containsKey("Auto-unlock score")) + } + if (serializedKit.containsKey("Auto-unlock score")) { deserializedKit.setAutoUnlockScore(ObjectUtilities.getObject(serializedKit, Number.class, "Auto-unlock score", -1).intValue()); - if (serializedKit.containsKey("Breakable items")) + } + if (serializedKit.containsKey("Breakable items")) { deserializedKit.setItemsBreakable(ObjectUtilities.getObject(serializedKit, Boolean.class, "Breakable items", true)); - if (serializedKit.containsKey("Commands")) + } + if (serializedKit.containsKey("Commands")) { deserializedKit.setCommands(Utilities.toStringList(ObjectUtilities.getObject(serializedKit, List.class, "Commands", new ArrayList()))); + } if (serializedKit.containsKey("Killstreak commands")) { Map> killstreaksCommands = new HashMap<>(); Map killstreakMap = ObjectUtilities.getMap(serializedKit.get("Killstreak commands")); @@ -458,8 +466,9 @@ public static Kit deserialize(final Map serializedKit) { } if (serializedKit.containsKey("GUI")) { Map guiSection = ObjectUtilities.getMap(serializedKit.get("GUI")); - if (guiSection.containsKey("Position")) + if (guiSection.containsKey("Position")) { deserializedKit.setGuiPosition(ObjectUtilities.getObject(guiSection, Integer.class, "Position", -1)); + } if (guiSection.containsKey("Item")) { ItemStack guiItem = ItemUtilities.deserializeItem(ObjectUtilities.getMap(guiSection.get("Item"))); if (guiItem == null) guiItem = new ItemStack(Material.DIAMOND_SWORD); @@ -501,8 +510,9 @@ public static Kit deserialize(final Map serializedKit) { } deserializedKit.setItems(kitItems); } - if (serializedKit.containsKey("Held item slot")) + if (serializedKit.containsKey("Held item slot")) { deserializedKit.setHeldItemSlot(ObjectUtilities.getObject(serializedKit, Number.class, "Held item slot", -1).intValue()); + } if (serializedKit.containsKey("Armour")) { ItemStack[] kitArmour = new ItemStack[4]; Map armourSection = ObjectUtilities.getMap(serializedKit.get("Armour")); diff --git a/src/main/java/com/faris/kingkits/Messages.java b/src/main/java/com/faris/kingkits/Messages.java index a7dca9d..820a7e0 100644 --- a/src/main/java/com/faris/kingkits/Messages.java +++ b/src/main/java/com/faris/kingkits/Messages.java @@ -8,7 +8,7 @@ import java.io.File; import java.io.IOException; -import java.util.logging.Level; +import java.util.logging.*; public enum Messages { GENERAL_COMMAND_ERROR("General.Command error", "&cA(n) %s error occurred whilst trying to execute that command. Please contact a server administrator."), diff --git a/src/main/java/com/faris/kingkits/Permissions.java b/src/main/java/com/faris/kingkits/Permissions.java index 51f75d4..4ef0426 100644 --- a/src/main/java/com/faris/kingkits/Permissions.java +++ b/src/main/java/com/faris/kingkits/Permissions.java @@ -4,8 +4,7 @@ import org.bukkit.Bukkit; import org.bukkit.permissions.Permission; -import java.util.HashMap; -import java.util.Map; +import java.util.*; public class Permissions { @@ -17,6 +16,7 @@ public class Permissions { public static Permission COMMAND_CONFIG = null; public static Permission COMMAND_KILLSTREAK = null; public static Permission COMMAND_KILLSTREAK_OTHER = null; + public static Permission COMMAND_SET = null; public static Permission COMMAND_KIT = null; public static Permission COMMAND_KIT_OTHER = null; @@ -52,6 +52,7 @@ public static void initialisePermissions() { registerPermission("COMMAND_CONFIG", "kingkits.command.config"); registerPermission("COMMAND_KILLSTREAK", "kingkits.command.killstreak"); registerPermission("COMMAND_KILLSTREAK_OTHER", "kingkits.command.killstreak.other"); + registerPermission("COMMAND_SET", "kingkits.command.set"); registerPermission("COMMAND_KIT", "kingkits.command.kit"); registerPermission("COMMAND_KIT_OTHER", "kingkits.command.kit.other"); diff --git a/src/main/java/com/faris/kingkits/api/event/PlayerPreKitEvent.java b/src/main/java/com/faris/kingkits/api/event/PlayerPreKitEvent.java index 763a664..0a0f3fa 100644 --- a/src/main/java/com/faris/kingkits/api/event/PlayerPreKitEvent.java +++ b/src/main/java/com/faris/kingkits/api/event/PlayerPreKitEvent.java @@ -9,10 +9,7 @@ import org.bukkit.inventory.ItemStack; import org.bukkit.potion.PotionEffect; -import java.util.ArrayList; -import java.util.HashMap; -import java.util.List; -import java.util.Map; +import java.util.*; public class PlayerPreKitEvent extends Event implements Cancellable { @@ -66,7 +63,7 @@ public void setArmour(ItemStack[] armour) { */ public void setItems(Map items) { if (this.kit != null) { - this.kit.setItems(items != null ? items : new HashMap()); + this.kit.setItems(items != null ? items : new HashMap<>()); } } @@ -88,7 +85,7 @@ public void setOffHand(ItemStack offHand) { */ public void setPotionEffects(List potionEffects) { if (this.kit != null) { - this.kit.setPotionEffects(potionEffects != null ? potionEffects : new ArrayList()); + this.kit.setPotionEffects(potionEffects != null ? potionEffects : new ArrayList<>()); } } diff --git a/src/main/java/com/faris/kingkits/config/CustomConfiguration.java b/src/main/java/com/faris/kingkits/config/CustomConfiguration.java index dc789d9..f065834 100644 --- a/src/main/java/com/faris/kingkits/config/CustomConfiguration.java +++ b/src/main/java/com/faris/kingkits/config/CustomConfiguration.java @@ -9,11 +9,8 @@ import java.io.*; import java.nio.file.Files; import java.nio.file.StandardCopyOption; -import java.util.ArrayList; -import java.util.LinkedHashMap; -import java.util.List; -import java.util.Map; -import java.util.logging.Level; +import java.util.*; +import java.util.logging.*; public class CustomConfiguration extends YamlConfiguration { @@ -55,7 +52,7 @@ public Map> getComments() { } public List getComments(String path) { - return this.comments.containsKey(path) ? new ArrayList<>(this.comments.get(path)) : new ArrayList(); + return this.comments.containsKey(path) ? new ArrayList<>(this.comments.get(path)) : new ArrayList<>(); } @Override @@ -88,6 +85,8 @@ public void load(File file) throws IOException, InvalidConfigurationException { } } } + this.comments.clear(); + this.comments.putAll(configComments); } public void load(File file, boolean loadComments) throws IOException, InvalidConfigurationException { @@ -97,6 +96,10 @@ public void load(File file, boolean loadComments) throws IOException, InvalidCon @Override public void save(File file) throws IOException { + this.save(file, true); + } + + public void save(File file, boolean saveComments) throws IOException { super.save(file); List configContent = new ArrayList<>(); @@ -113,23 +116,30 @@ public void save(File file) throws IOException { try { configWriter = new BufferedWriter(new FileWriter(file)); configWriter.write(""); + boolean hitKey = false; for (int lineIndex = 0; lineIndex < configContent.size(); lineIndex++) { String configLine = configContent.get(lineIndex); String configKey = null; - if (!configLine.startsWith("#") && configLine.contains(":")) + if (!configLine.startsWith("#") && configLine.contains(":")) { + hitKey = true; configKey = getPathToKey(configContent, lineIndex, configLine); - if (configKey != null && this.comments.containsKey(configKey)) { + } + if (configKey != null && saveComments && this.comments.containsKey(configKey)) { int numOfSpaces = getPrefixSpaceCount(configLine); String spacePrefix = ""; for (int i = 0; i < numOfSpaces; i++) spacePrefix += " "; List configComments = this.comments.get(configKey); if (configComments != null) { for (String comment : configComments) { + if (comment.isEmpty()) continue; configWriter.append(spacePrefix).append("# ").append(comment); configWriter.newLine(); } } } + if (!saveComments && !hitKey && lineIndex != 0 && (configLine.startsWith("#") || configLine.isEmpty())) { + continue; + } configWriter.append(configLine); configWriter.newLine(); boolean isComment = configLine.startsWith("#"); @@ -195,9 +205,13 @@ public static CustomConfiguration loadConfiguration(File file) { } public static CustomConfiguration loadConfigurationSafely(File file) { + return loadConfigurationSafely(file, true); + } + + public static CustomConfiguration loadConfigurationSafely(File file, boolean loadComments) { CustomConfiguration config = new CustomConfiguration(); try { - config.load(file); + config.load(file, loadComments); } catch (Exception ex) { if (ex.getClass() != FileNotFoundException.class) { Bukkit.getServer().getLogger().log(Level.SEVERE, "Cannot load " + file, ex); diff --git a/src/main/java/com/faris/kingkits/controller/CompassController.java b/src/main/java/com/faris/kingkits/controller/CompassController.java index 33a7750..4923b3f 100644 --- a/src/main/java/com/faris/kingkits/controller/CompassController.java +++ b/src/main/java/com/faris/kingkits/controller/CompassController.java @@ -1,9 +1,6 @@ package com.faris.kingkits.controller; -import java.util.ArrayList; -import java.util.HashMap; -import java.util.Map; -import java.util.UUID; +import java.util.*; public class CompassController implements Controller { diff --git a/src/main/java/com/faris/kingkits/controller/ConfigController.java b/src/main/java/com/faris/kingkits/controller/ConfigController.java index 5d91d40..72d1ce9 100644 --- a/src/main/java/com/faris/kingkits/controller/ConfigController.java +++ b/src/main/java/com/faris/kingkits/controller/ConfigController.java @@ -22,7 +22,7 @@ import java.io.File; import java.io.IOException; import java.util.*; -import java.util.logging.Level; +import java.util.logging.*; public class ConfigController implements Controller { @@ -99,6 +99,7 @@ public class ConfigController implements Controller { private boolean shouldRemovePotionEffectsOnLeave = true; private boolean shouldRemovePotionEffectsOnReload = true; private boolean shouldShowKitPreview = true; + private boolean shouldShowKitMenuOnPreviewClose = true; private boolean shouldSortKitsAlphanumerically = false; private boolean shouldSetCompassToNearestPlayer = false; private boolean shouldSetDefaultGamemodeOnKitSelection = true; @@ -143,8 +144,9 @@ private void saveDefaultConfig() { this.getConfig().addDefault("MySQL", new MySQLDetails().serialize(), "MySQL authentication information and details."); this.getConfig().addDefault("Admin bypass", true, "Set to 'true' if you want OPs or players with 'kingkits.admin' node to be able to drop/pickup items and do other activities even if disabled in the config."); this.getConfig().addDefault("Auto-save player data", -1D, "Every time the set number of minutes passes, player data is saved asynchronously.", "Set to -1 to disable auto-save."); - if (!this.getConfig().contains("Allow")) + if (!this.getConfig().contains("Allow")) { this.getConfig().createSection("Allow", "Allow/disallow (enable/disable) various things."); + } this.getConfig().addDefault("Allow.Block modification", true, "Set to 'false' if you want players to not be able to break/place blocks."); this.getConfig().addDefault("Allow.Death messages", true, "Set to 'false' if you want to disable vanilla death messages."); this.getConfig().addDefault("Allow.Item dropping", true, "Set to 'false' if you want to ban players from dropping items."); @@ -167,14 +169,16 @@ private void saveDefaultConfig() { this.put("Refill", true); }}, "Enable/disable commands."); } - if (!this.getConfig().contains("Economy")) + if (!this.getConfig().contains("Economy")) { this.getConfig().createSection("Economy", "Economy settings", "Note: Vault is required if economy is enabled."); + } this.getConfig().addDefault("Economy.Enabled", false); this.getConfig().addDefault("Economy.Cost per refill", 2.5D, "The cost of refilling each empty bowl."); this.getConfig().addDefault("Economy.Money per kill", 5D, "The amount of money to give to a player when they kill another player."); this.getConfig().addDefault("Economy.Money per death", 7.5D, "The amount of money to take when a player dies"); - if (!this.getConfig().contains("Kit defaults")) + if (!this.getConfig().contains("Kit defaults")) { this.getConfig().createSection("Kit defaults", "Default kit options"); + } this.getConfig().addDefault("Kit defaults.Breakable items", true, "The value of this is the default value for \"Breakable items\" of a new kit."); this.getConfig().addDefault("Kit defaults.Command alias", false, "The value of this is the default value for \"Command alias\" of a new kit."); this.getConfig().addDefault("Kit defaults.Commands", new ArrayList<>(), "The value of this is the default value for \"Commands\" of a new kit."); @@ -215,6 +219,7 @@ private void saveDefaultConfig() { this.getConfig().addDefault("Should.Set max health to kit max health", true, "If this plugin should set the player's max health to the max health set in the kit config."); this.getConfig().addDefault("Should.Set to default gamemode on kit selection", true, "Whether or not to set the player's gamemode to the server's default when they choose a kit."); this.getConfig().addDefault("Should.Show kit preview", true, "If a GUI opens up with a list of all the items in a kit when a player chooses a kit that they do not have permission to use."); + this.getConfig().addDefault("Should.Show kit menu on preview close", true, "Show the kit menu the player previously had open if they click the close button in the kit preview GUI."); this.getConfig().addDefault("Should.Sort kits alphanumerically", false, "If the list of kits should be sorted alphanumerically."); this.getConfig().addDefault("Should.Use permissions for kit list", false, "Whether or not to list kits players don't have access to."); this.getConfig().addDefault("Sign.Kit.Unregistered", "[Kit]", "The text on the first line of a kit sign.", "Set to '' to disable kit signs."); @@ -312,6 +317,7 @@ public void loadConfiguration() { this.shouldSetDefaultGamemodeOnKitSelection = this.getConfig().getBoolean("Should.Set to default gamemode on kit selection", true); this.shouldSetMaxHealth = this.getConfig().getBoolean("Should.Set max health to kit max health", true); this.shouldShowKitPreview = this.getConfig().getBoolean("Should.Show kit preview", true); + this.shouldShowKitMenuOnPreviewClose = this.getConfig().getBoolean("Should.Show kit menu on preview close", true); this.shouldSortKitsAlphanumerically = this.getConfig().getBoolean("Should.Sort kits alphanumerically", false); this.shouldUsePermissionsForKitList = this.getConfig().getBoolean("Should.Use permissions for kit list", true); this.signKit = ChatUtilities.replaceChatCodes(this.getConfig().getString("Sign.Kit.Unregistered", "[Kit]"), this.getConfig().getString("Sign.Kit.Valid", "[&1Kit&0]"), this.getConfig().getString("Sign.Kit.Invalid", "[&cKit&0]")); @@ -467,7 +473,7 @@ public double getAutoSavePlayerDataTime() { } public String getChatPlaceholder(String configKey, String defaultValue) { - return this.chatPlaceholders.containsKey(configKey) ? this.chatPlaceholders.get(configKey) : defaultValue; + return this.chatPlaceholders.getOrDefault(configKey, defaultValue); } public boolean[] getCommands(World world) { @@ -730,6 +736,10 @@ public boolean shouldShowKitPreview() { return this.shouldShowKitPreview; } + public boolean shouldShowKitMenuOnPreviewClose() { + return this.shouldShowKitMenuOnPreviewClose; + } + public boolean shouldSortKitsAlphanumerically() { return this.shouldSortKitsAlphanumerically; } @@ -1087,9 +1097,9 @@ else if (strArmourType.endsWith("boots")) this.loadConfiguration(); if (ConfigController.getInstance().getSQLDetails().isEnabled()) { SQLController.getInstance(); - DataStorage.setInstance(DataStorage.DataStorageType.SQL); + DataStorage.createInstance(DataStorage.DataStorageType.SQL); } else { - DataStorage.setInstance(DataStorage.DataStorageType.FILE); + DataStorage.createInstance(DataStorage.DataStorageType.FILE); } try { @@ -1293,9 +1303,9 @@ else if (strArmourType.endsWith("boots")) try { if (ConfigController.getInstance().getSQLDetails().isEnabled()) { SQLController.getInstance(); - DataStorage.setInstance(DataStorage.DataStorageType.SQL); + DataStorage.createInstance(DataStorage.DataStorageType.SQL); } else { - DataStorage.setInstance(DataStorage.DataStorageType.FILE); + DataStorage.createInstance(DataStorage.DataStorageType.FILE); } } catch (Exception ex) { ex.printStackTrace(); @@ -1638,9 +1648,9 @@ else if (strArmourType.endsWith("boots")) try { if (ConfigController.getInstance().getSQLDetails().isEnabled()) { SQLController.getInstance(); - DataStorage.setInstance(DataStorage.DataStorageType.SQL); + DataStorage.createInstance(DataStorage.DataStorageType.SQL); } else { - DataStorage.setInstance(DataStorage.DataStorageType.FILE); + DataStorage.createInstance(DataStorage.DataStorageType.FILE); } } catch (Exception ex) { ex.printStackTrace(); @@ -1807,9 +1817,9 @@ else if (strArmourType.endsWith("boots")) try { if (ConfigController.getInstance().getSQLDetails().isEnabled()) { SQLController.getInstance(); - DataStorage.setInstance(DataStorage.DataStorageType.SQL); + DataStorage.createInstance(DataStorage.DataStorageType.SQL); } else { - DataStorage.setInstance(DataStorage.DataStorageType.FILE); + DataStorage.createInstance(DataStorage.DataStorageType.FILE); } } catch (Exception ex) { ex.printStackTrace(); @@ -1895,9 +1905,9 @@ else if (strArmourType.endsWith("boots")) try { if (ConfigController.getInstance().getSQLDetails().isEnabled()) { SQLController.getInstance(); - DataStorage.setInstance(DataStorage.DataStorageType.SQL); + DataStorage.createInstance(DataStorage.DataStorageType.SQL); } else { - DataStorage.setInstance(DataStorage.DataStorageType.FILE); + DataStorage.createInstance(DataStorage.DataStorageType.FILE); } } catch (Exception ex) { ex.printStackTrace(); diff --git a/src/main/java/com/faris/kingkits/controller/GuiController.java b/src/main/java/com/faris/kingkits/controller/GuiController.java index 41cbde9..a00cea9 100644 --- a/src/main/java/com/faris/kingkits/controller/GuiController.java +++ b/src/main/java/com/faris/kingkits/controller/GuiController.java @@ -119,7 +119,7 @@ public Inventory createKitsInventory(Player player) { } guiKits = new GuiKits(filteredKitList); } else { - guiKits = new GuiKits(new ArrayList()); + guiKits = new GuiKits(new ArrayList<>()); } } else { guiKits = new GuiKits(kitList); @@ -134,6 +134,40 @@ public Inventory createKitsInventory(Player player) { return kitsInv; } + public Inventory createKitsInventory(Player player, int page) { + Inventory kitsInv = null; + if (player != null) { + kitsInv = Bukkit.getServer().createInventory(player, this.kitsInventory.getSize(), this.kitsInventory.getTitle()); + kitsInv.setContents(this.kitsInventory.getContents()); + + Collection kitList = ConfigController.getInstance().shouldSortKitsAlphanumerically() ? KitUtilities.sortAlphabetically(KitController.getInstance().getKits().values()) : KitController.getInstance().getKits().values(); + GuiKits guiKits = null; + if (ConfigController.getInstance().shouldUsePermissionsForKitList()) { + KitPlayer kitPlayer = PlayerController.getInstance().getPlayer(player); + if (kitPlayer != null && kitPlayer.isLoaded()) { + List filteredKitList = new ArrayList<>(); + for (Kit kit : kitList) { + if (kitPlayer.hasPermission(kit) || kitPlayer.hasUnlocked(kit)) { + filteredKitList.add(kit); + } + } + guiKits = new GuiKits(filteredKitList); + } else { + guiKits = new GuiKits(new ArrayList<>()); + } + } else { + guiKits = new GuiKits(kitList); + } + if (page >= 1 && page <= guiKits.maxPage) guiKits.page = page; + guiKits.fillInventory(player, kitsInv); + this.guiKits.put(player.getUniqueId(), guiKits); + } else { + kitsInv = Bukkit.getServer().createInventory(null, InventoryType.CHEST); + kitsInv.setContents(this.kitsInventory.getContents()); + } + return kitsInv; + } + public Inventory createKitPreviewInventory(Player player, Kit kit) { Inventory kitPreviewInv = null; if (player != null) { @@ -185,7 +219,7 @@ public void openKitsMenu(Player player) { if (player != null && !this.guiViewers.containsKey(player.getUniqueId())) { player.closeInventory(); KitPlayer kitPlayer = PlayerController.getInstance().getPlayer(player); - if (kitPlayer != null && kitPlayer.getKits().isEmpty()) { + if (kitPlayer == null || kitPlayer.getKits().isEmpty()) { Inventory inventory = this.createKitsInventory(player); if (inventory != null) { this.guiViewers.put(player.getUniqueId(), GuiType.GUI_KITS); @@ -233,37 +267,31 @@ public void onInventoryClick(InventoryClickEvent event) { player.closeInventory(); final UUID playerUUID = player.getUniqueId(); final Inventory kitsInventory = createKitsInventory(player); - player.getServer().getScheduler().runTask(KingKits.getInstance(), new Runnable() { - @Override - public void run() { - if (player.isOnline()) { - player.openInventory(kitsInventory); - guiViewers.put(player.getUniqueId(), GuiType.GUI_KITS); - } else { - guiKits.remove(playerUUID); - } + player.getServer().getScheduler().runTask(KingKits.getInstance(), () -> { + if (player.isOnline()) { + player.openInventory(kitsInventory); + guiViewers.put(player.getUniqueId(), GuiType.GUI_KITS); + } else { + guiKits.remove(playerUUID); } }); } else if (event.getRawSlot() == 5) { player.closeInventory(); final UUID playerUUID = player.getUniqueId(); final Inventory userKitsInventory = createUserKitsInventory(player); - player.getServer().getScheduler().runTask(KingKits.getInstance(), new Runnable() { - @Override - public void run() { - if (player.isOnline()) { - player.openInventory(userKitsInventory); - guiViewers.put(player.getUniqueId(), GuiType.GUI_USER_KITS); - } else { - guiKits.remove(playerUUID); - } + player.getServer().getScheduler().runTask(KingKits.getInstance(), () -> { + if (player.isOnline()) { + player.openInventory(userKitsInventory); + guiViewers.put(player.getUniqueId(), GuiType.GUI_USER_KITS); + } else { + guiKits.remove(playerUUID); } }); } } else if (guiType == GuiType.GUI_KITS) { event.setCancelled(true); if (guiKits.containsKey(player.getUniqueId())) { - GuiKits guiKit = guiKits.get(player.getUniqueId()); + final GuiKits guiKit = guiKits.get(player.getUniqueId()); Kit clickedKit = guiKit.getKit(event.getRawSlot()); if (clickedKit != null) { KitPlayer kitPlayer = PlayerController.getInstance().getPlayer(player); @@ -276,16 +304,13 @@ public void run() { final UUID playerUUID = player.getUniqueId(); final Inventory previewKitInventory = createKitPreviewInventory(player, clickedKit); final Kit finalKit = clickedKit; - player.getServer().getScheduler().runTask(KingKits.getInstance(), new Runnable() { - @Override - public void run() { - if (player.isOnline()) { - player.openInventory(previewKitInventory); - guiViewers.put(player.getUniqueId(), GuiType.GUI_PREVIEW_KIT); - guiKitPreview.put(player.getUniqueId(), new GuiKitPreview(finalKit.getName())); - } else { - guiKits.remove(playerUUID); - } + player.getServer().getScheduler().runTask(KingKits.getInstance(), () -> { + if (player.isOnline()) { + player.openInventory(previewKitInventory); + guiViewers.put(player.getUniqueId(), GuiType.GUI_PREVIEW_KIT); + guiKitPreview.put(player.getUniqueId(), new GuiKitPreview(finalKit.getName(), guiKit)); + } else { + guiKits.remove(playerUUID); } }); } @@ -350,7 +375,25 @@ public void run() { } } } else if (event.getRawSlot() == event.getInventory().getSize() - 4) { - player.closeInventory(); + if (ConfigController.getInstance().shouldShowKitMenuOnPreviewClose()) { + final GuiKitPreview guiKitP = guiKitPreview.get(player.getUniqueId()); + player.closeInventory(); + if (guiKitP != null && guiKitP.getPreviousPage() != -1) { + player.getServer().getScheduler().runTask(KingKits.getInstance(), () -> { + if (player.isOnline()) { + Inventory inventory = createKitsInventory(player, guiKitP.getPreviousPage()); + if (inventory != null) { + guiViewers.put(player.getUniqueId(), GuiType.GUI_KITS); + player.openInventory(inventory); + } + } else { + guiKits.remove(player.getUniqueId()); + } + }); + } + } else { + player.closeInventory(); + } } } } catch (Exception ex) { @@ -512,16 +555,13 @@ private void setKit(Kit selectedKit, final Player player, final KitPlayer kitPla final UUID playerUUID = player.getUniqueId(); final Inventory previewKitInventory = this.createKitPreviewInventory(player, selectedKit); final Kit finalKit = selectedKit; - player.getServer().getScheduler().runTask(KingKits.getInstance(), new Runnable() { - @Override - public void run() { - if (player.isOnline()) { - player.openInventory(previewKitInventory); - guiViewers.put(player.getUniqueId(), GuiType.GUI_PREVIEW_KIT); - guiKitPreview.put(player.getUniqueId(), new GuiKitPreview(finalKit.getName())); - } else { - guiKits.remove(playerUUID); - } + player.getServer().getScheduler().runTask(KingKits.getInstance(), () -> { + if (player.isOnline()) { + player.openInventory(previewKitInventory); + guiViewers.put(player.getUniqueId(), GuiType.GUI_PREVIEW_KIT); + guiKitPreview.put(player.getUniqueId(), new GuiKitPreview(finalKit.getName())); + } else { + guiKits.remove(playerUUID); } }); } else { @@ -708,14 +748,24 @@ public void previous() { private static class GuiKitPreview { private String kitName = ""; + private int previousPage = -1; public GuiKitPreview(String kit) { this.kitName = kit; } + public GuiKitPreview(String kit, GuiKits previousGUI) { + this.kitName = kit; + this.previousPage = previousGUI.page; + } + public Kit getKit() { return KitController.getInstance().getKit(this.kitName); } + + public int getPreviousPage() { + return this.previousPage; + } } } diff --git a/src/main/java/com/faris/kingkits/controller/KitController.java b/src/main/java/com/faris/kingkits/controller/KitController.java index 16d21d7..1649afc 100644 --- a/src/main/java/com/faris/kingkits/controller/KitController.java +++ b/src/main/java/com/faris/kingkits/controller/KitController.java @@ -13,10 +13,8 @@ import java.io.File; import java.io.IOException; -import java.util.LinkedHashMap; -import java.util.Map; -import java.util.UUID; -import java.util.logging.Level; +import java.util.*; +import java.util.logging.*; public class KitController implements Controller { @@ -164,6 +162,28 @@ public void saveKit(Kit kit, UUID playerUUID) { } } + public void saveKit(Kit kit, String path, Object value) throws Exception { + if (kit != null && !kit.isUserKit()) { + String kitName = kit.getName(); + File kitFile = new File(this.kitsFolder, kitName + ".yml"); + if (!kitFile.exists()) { + saveKit(kit); + return; + } + CustomConfiguration configKit = CustomConfiguration.loadConfigurationSafely(kitFile, false); + configKit.setNewLinePerKey(true); + if (configKit.getValues(false).isEmpty()) { + Map serializedKit = kit.serialize(); + for (Map.Entry serializationEntry : serializedKit.entrySet()) { + configKit.set(serializationEntry.getKey(), serializationEntry.getValue()); + } + } else { + configKit.set(path, value); + } + configKit.save(kitFile, false); + } + } + public static KitController getInstance() { if (instance == null) instance = new KitController(); return instance; diff --git a/src/main/java/com/faris/kingkits/helper/CacheMap.java b/src/main/java/com/faris/kingkits/helper/CacheMap.java index b9d7d74..40dfc6c 100644 --- a/src/main/java/com/faris/kingkits/helper/CacheMap.java +++ b/src/main/java/com/faris/kingkits/helper/CacheMap.java @@ -1,9 +1,7 @@ package com.faris.kingkits.helper; import java.lang.ref.SoftReference; -import java.util.HashMap; -import java.util.Map; -import java.util.Set; +import java.util.*; public class CacheMap { diff --git a/src/main/java/com/faris/kingkits/helper/Debugger.java b/src/main/java/com/faris/kingkits/helper/Debugger.java index 1ad3fdf..93dd99f 100644 --- a/src/main/java/com/faris/kingkits/helper/Debugger.java +++ b/src/main/java/com/faris/kingkits/helper/Debugger.java @@ -2,7 +2,7 @@ import com.faris.kingkits.KingKits; -import java.util.logging.Level; +import java.util.logging.*; /** * Solely for plugin debugging only diff --git a/src/main/java/com/faris/kingkits/helper/Time.java b/src/main/java/com/faris/kingkits/helper/Time.java index e8b5bef..88f9cea 100644 --- a/src/main/java/com/faris/kingkits/helper/Time.java +++ b/src/main/java/com/faris/kingkits/helper/Time.java @@ -1,6 +1,6 @@ package com.faris.kingkits.helper; -import java.util.concurrent.TimeUnit; +import java.util.concurrent.*; public class Time { diff --git a/src/main/java/com/faris/kingkits/helper/api/ActionBarAPI.java b/src/main/java/com/faris/kingkits/helper/api/ActionBarAPI.java deleted file mode 100644 index ff8c7cd..0000000 --- a/src/main/java/com/faris/kingkits/helper/api/ActionBarAPI.java +++ /dev/null @@ -1,102 +0,0 @@ -package com.faris.kingkits.helper.api; - -import com.faris.kingkits.helper.util.ReflectionUtilities; -import org.apache.commons.lang.Validate; -import org.bukkit.ChatColor; -import org.bukkit.entity.Player; - -public class ActionBarAPI { - - private static boolean initialised = false; - - private static Class classCraftPlayer = null; - private static Class classEntityPlayer = null; - - private static Class classPacket = null; - private static Class classPacketPlayOutChat = null; - - private static Class classIChatBaseComponent = null; - private static Class classChatSerializer = null; - private static Class classPlayerConnection = null; - - private ActionBarAPI() { - } - - public static void deinitialiseReflection() { - classCraftPlayer = null; - classEntityPlayer = null; - classPacket = null; - classPacketPlayOutChat = null; - classIChatBaseComponent = null; - classChatSerializer = null; - classPlayerConnection = null; - - initialised = false; - } - - public static void initialiseReflection() { - try { - classCraftPlayer = ReflectionUtilities.getBukkitClass("entity.CraftPlayer"); - Validate.notNull(classCraftPlayer); - classEntityPlayer = ReflectionUtilities.getMinecraftClass("EntityPlayer"); - Validate.notNull(classEntityPlayer); - - classPacket = ReflectionUtilities.getMinecraftClass("Packet"); - Validate.notNull(classPacket); - classPacketPlayOutChat = ReflectionUtilities.getMinecraftClass("PacketPlayOutChat"); - Validate.notNull(classPacketPlayOutChat); - - classIChatBaseComponent = ReflectionUtilities.getMinecraftClass("IChatBaseComponent"); - Validate.notNull(classIChatBaseComponent); - classChatSerializer = ReflectionUtilities.getClass(classIChatBaseComponent, "ChatSerializer"); - Validate.notNull(classChatSerializer); - classPlayerConnection = ReflectionUtilities.getMinecraftClass("PlayerConnection"); - Validate.notNull(classPlayerConnection); - - initialised = true; - } catch (Exception ex) { - ex.printStackTrace(); - initialised = false; - } - } - - public static boolean isInitialised() { - return initialised; - } - - public static void sendActionBar(Player player, String message) throws Exception { - if (player == null || message == null) return; - message = message.replaceAll("%name%", player.getName()); - message = message.replaceAll("%player%", player.getDisplayName()); - message = ChatColor.translateAlternateColorCodes('&', message); - if (initialised) { - try { - ReflectionUtilities.MethodInvoker methodGetHandle = ReflectionUtilities.getMethod(classCraftPlayer, "getHandle"); - Object objCraftPlayer = classCraftPlayer.cast(player); - Object entityPlayer = methodGetHandle.invoke(objCraftPlayer); - - ReflectionUtilities.FieldAccess fieldPlayerConnection = ReflectionUtilities.getField(classEntityPlayer, "playerConnection"); - Object playerConnection = fieldPlayerConnection.getObject(entityPlayer); - ReflectionUtilities.MethodInvoker methodSendPacket = ReflectionUtilities.getMethod(classPlayerConnection, "sendPacket", classPacket); - - ReflectionUtilities.ConstructorInvoker constructorClassPacketPlayOutChat = ReflectionUtilities.getConstructor(classPacketPlayOutChat, classIChatBaseComponent, byte.class); - ReflectionUtilities.FieldAccess fieldGson = ReflectionUtilities.getFieldByClass(classChatSerializer, "Gson", 0); - if (fieldGson != null) { - ReflectionUtilities.MethodInvoker methodFromJson = ReflectionUtilities.getMethod(fieldGson.getField().getType(), "fromJson", String.class, Class.class); - - Object objJsonTitleMain = methodFromJson.invoke(fieldGson.getObject(null), "{\"text\": \"" + message + "\"}", classIChatBaseComponent); - Object objTitleMain = classIChatBaseComponent.cast(objJsonTitleMain); - - Object objPacketPlayOutTimes = constructorClassPacketPlayOutChat.newInstance(objTitleMain, (byte) 2); - methodSendPacket.invoke(playerConnection, objPacketPlayOutTimes); - } else { - initialised = false; - } - } catch (Exception ex) { - initialised = false; - throw ex; - } - } - } - -} diff --git a/src/main/java/com/faris/kingkits/helper/api/TitleAPI.java b/src/main/java/com/faris/kingkits/helper/api/TitleAPI.java deleted file mode 100644 index cc72dbf..0000000 --- a/src/main/java/com/faris/kingkits/helper/api/TitleAPI.java +++ /dev/null @@ -1,136 +0,0 @@ -package com.faris.kingkits.helper.api; - -import com.faris.kingkits.helper.util.ChatUtilities; -import com.faris.kingkits.helper.util.ReflectionUtilities; -import org.apache.commons.lang.Validate; -import org.bukkit.ChatColor; -import org.bukkit.entity.Player; - -public class TitleAPI { - - private static boolean initialised = false; - - private static Class classCraftPlayer = null; - private static Class classEntityPlayer = null; - - private static Class classEnumTitleAction = null; - - private static Class classPacket = null; - private static Class classPacketPlayOutTitle = null; - - private static Class classIChatBaseComponent = null; - private static Class classChatSerializer = null; - private static Class classPlayerConnection = null; - - private TitleAPI() { - } - - public static void deinitialiseReflection() { - classCraftPlayer = null; - classEntityPlayer = null; - classEnumTitleAction = null; - classPacket = null; - classPacketPlayOutTitle = null; - classIChatBaseComponent = null; - classChatSerializer = null; - classPlayerConnection = null; - - initialised = false; - } - - public static void initialiseReflection() { - try { - classCraftPlayer = ReflectionUtilities.getBukkitClass("entity.CraftPlayer"); - Validate.notNull(classCraftPlayer); - classEntityPlayer = ReflectionUtilities.getMinecraftClass("EntityPlayer"); - Validate.notNull(classEntityPlayer); - - classPacket = ReflectionUtilities.getMinecraftClass("Packet"); - Validate.notNull(classPacket); - classPacketPlayOutTitle = ReflectionUtilities.getMinecraftClass("PacketPlayOutTitle"); - Validate.notNull(classPacketPlayOutTitle); - - classEnumTitleAction = ReflectionUtilities.getClass(classPacketPlayOutTitle, "EnumTitleAction"); - Validate.notNull(classEnumTitleAction); - - classIChatBaseComponent = ReflectionUtilities.getMinecraftClass("IChatBaseComponent"); - Validate.notNull(classIChatBaseComponent); - classChatSerializer = ReflectionUtilities.getClass(classIChatBaseComponent, "ChatSerializer"); - Validate.notNull(classChatSerializer); - classPlayerConnection = ReflectionUtilities.getMinecraftClass("PlayerConnection"); - Validate.notNull(classPlayerConnection); - - initialised = true; - } catch (Exception ex) { - ex.printStackTrace(); - initialised = false; - } - } - - public static boolean isInitialised() { - return initialised; - } - - public static void sendTitle(Player player, double fadeInTime, double durationTime, double fadeOutTime, String title) throws Exception { - sendTitle(player, fadeInTime, durationTime, fadeOutTime, title, null); - } - - public static void sendTitle(Player player, double fadeInTime, double durationTime, double fadeOutTime, String title, String subtitle) throws Exception { - if (player == null) return; - if (initialised) { - try { - ReflectionUtilities.MethodInvoker methodGetHandle = ReflectionUtilities.getMethod(classCraftPlayer, "getHandle"); - Object objCraftPlayer = classCraftPlayer.cast(player); - Object entityPlayer = methodGetHandle.invoke(objCraftPlayer); - - ReflectionUtilities.FieldAccess fieldPlayerConnection = ReflectionUtilities.getField(classEntityPlayer, "playerConnection"); - Object playerConnection = fieldPlayerConnection.getObject(entityPlayer); - ReflectionUtilities.MethodInvoker methodSendPacket = ReflectionUtilities.getMethod(classPlayerConnection, "sendPacket", classPacket); - - ReflectionUtilities.ConstructorInvoker constructorClassPacketPlayOutTitle1 = ReflectionUtilities.getConstructor(classPacketPlayOutTitle, classEnumTitleAction, classIChatBaseComponent, int.class, int.class, int.class); - ReflectionUtilities.ConstructorInvoker constructorClassPacketPlayOutTitle2 = ReflectionUtilities.getConstructor(classPacketPlayOutTitle, classEnumTitleAction, classIChatBaseComponent); - - Object objPacketPlayOutTimes = constructorClassPacketPlayOutTitle1.newInstance(Enum.valueOf(classEnumTitleAction, "TIMES"), null, (int) (fadeInTime * 10), (int) (durationTime * 10), (int) (fadeOutTime * 10)); - methodSendPacket.invoke(playerConnection, objPacketPlayOutTimes); - - ReflectionUtilities.FieldAccess fieldGson = ReflectionUtilities.getFieldByClass(classChatSerializer, "Gson", 0); - if (fieldGson != null) { - ReflectionUtilities.MethodInvoker methodFromJson = ReflectionUtilities.getMethod(fieldGson.getField().getType(), "fromJson", String.class, Class.class); - - if (subtitle != null) { - subtitle = subtitle.replaceAll("%name%", player.getName()); - subtitle = subtitle.replaceAll("%player%", player.getDisplayName()); - subtitle = ChatColor.translateAlternateColorCodes('&', subtitle); - - Object objJsonTitleSub = methodFromJson.invoke(fieldGson.getObject(null), "{\"text\": \"" + subtitle + "\"}", classIChatBaseComponent); - Object objTitleSub = classIChatBaseComponent.cast(objJsonTitleSub); - - objPacketPlayOutTimes = constructorClassPacketPlayOutTitle2.newInstance(Enum.valueOf(classEnumTitleAction, "SUBTITLE"), objTitleSub); - methodSendPacket.invoke(playerConnection, objPacketPlayOutTimes); - } - - if (title != null) { - title = title.replaceAll("%name%", player.getName()); - title = title.replaceAll("%player%", player.getDisplayName()); - title = ChatColor.translateAlternateColorCodes('&', title); - - Object objJsonTitleMain = methodFromJson.invoke(fieldGson.getObject(null), "{\"text\": \"" + title + "\"}", classIChatBaseComponent); - Object objTitleMain = classIChatBaseComponent.cast(objJsonTitleMain); - - objPacketPlayOutTimes = constructorClassPacketPlayOutTitle2.newInstance(Enum.valueOf(classEnumTitleAction, "TITLE"), objTitleMain); - methodSendPacket.invoke(playerConnection, objPacketPlayOutTimes); - } - } else { - initialised = false; - - if (title != null) player.sendMessage(ChatUtilities.replaceChatCodes(title)); - if (subtitle != null) player.sendMessage(ChatUtilities.replaceChatCodes(subtitle)); - } - } catch (Exception ex) { - initialised = false; - throw ex; - } - } - } - -} diff --git a/src/main/java/com/faris/kingkits/helper/json/JsonKitSerializer.java b/src/main/java/com/faris/kingkits/helper/json/JsonKitSerializer.java index f7a637e..69e0dec 100644 --- a/src/main/java/com/faris/kingkits/helper/json/JsonKitSerializer.java +++ b/src/main/java/com/faris/kingkits/helper/json/JsonKitSerializer.java @@ -6,7 +6,7 @@ import com.google.gson.*; import java.lang.reflect.Type; -import java.util.Map; +import java.util.*; public class JsonKitSerializer implements JsonSerializer, JsonDeserializer { diff --git a/src/main/java/com/faris/kingkits/helper/util/BukkitUtilities.java b/src/main/java/com/faris/kingkits/helper/util/BukkitUtilities.java index 6a6a2e5..e7e9a0c 100644 --- a/src/main/java/com/faris/kingkits/helper/util/BukkitUtilities.java +++ b/src/main/java/com/faris/kingkits/helper/util/BukkitUtilities.java @@ -25,21 +25,17 @@ public static boolean performCommand(String command) { } public static void sendMessageSync(final CommandSender sender, final String message) { - Bukkit.getServer().getScheduler().runTask(KingKits.getInstance(), new Runnable() { - @Override - public void run() { - if (!(sender instanceof Player) || ((Player) sender).isOnline()) - sender.sendMessage(ChatUtilities.replaceChatCodes(message)); + Bukkit.getServer().getScheduler().runTask(KingKits.getInstance(), () -> { + if (!(sender instanceof Player) || ((Player) sender).isOnline()) { + sender.sendMessage(ChatUtilities.replaceChatCodes(message)); } }); } public static void sendMessageSync(final CommandSender sender, final Messages message, final Object... format) { - Bukkit.getServer().getScheduler().runTask(KingKits.getInstance(), new Runnable() { - @Override - public void run() { - if (!(sender instanceof Player) || ((Player) sender).isOnline()) - Messages.sendMessage(sender, message, format); + Bukkit.getServer().getScheduler().runTask(KingKits.getInstance(), () -> { + if (!(sender instanceof Player) || ((Player) sender).isOnline()) { + Messages.sendMessage(sender, message, format); } }); } diff --git a/src/main/java/com/faris/kingkits/helper/util/ChatUtilities.java b/src/main/java/com/faris/kingkits/helper/util/ChatUtilities.java index 3e6b582..60f7179 100644 --- a/src/main/java/com/faris/kingkits/helper/util/ChatUtilities.java +++ b/src/main/java/com/faris/kingkits/helper/util/ChatUtilities.java @@ -3,8 +3,7 @@ import org.bukkit.Bukkit; import org.bukkit.ChatColor; -import java.util.ArrayList; -import java.util.List; +import java.util.*; public class ChatUtilities { @@ -28,7 +27,7 @@ public static List replaceChatCodes(List someStrings) { for (int i = 0; i < someStrings.size(); i++) someStrings.set(i, replaceChatCodes(someStrings.get(i))); } - return someStrings != null ? someStrings : new ArrayList(); + return someStrings != null ? someStrings : new ArrayList<>(); } public static List replaceChatColours(List someStrings) { diff --git a/src/main/java/com/faris/kingkits/helper/util/FileUtilities.java b/src/main/java/com/faris/kingkits/helper/util/FileUtilities.java index 58b93a8..eb83a0b 100644 --- a/src/main/java/com/faris/kingkits/helper/util/FileUtilities.java +++ b/src/main/java/com/faris/kingkits/helper/util/FileUtilities.java @@ -7,9 +7,7 @@ import java.nio.ByteBuffer; import java.nio.file.*; import java.nio.file.attribute.*; -import java.util.ArrayList; -import java.util.EnumSet; -import java.util.List; +import java.util.*; public class FileUtilities { diff --git a/src/main/java/com/faris/kingkits/helper/util/JsonUtilities.java b/src/main/java/com/faris/kingkits/helper/util/JsonUtilities.java index e1a739a..6606545 100644 --- a/src/main/java/com/faris/kingkits/helper/util/JsonUtilities.java +++ b/src/main/java/com/faris/kingkits/helper/util/JsonUtilities.java @@ -6,10 +6,7 @@ import com.google.gson.JsonObject; import com.google.gson.JsonPrimitive; -import java.util.ArrayList; -import java.util.LinkedHashMap; -import java.util.List; -import java.util.Map; +import java.util.*; public class JsonUtilities { diff --git a/src/main/java/com/faris/kingkits/helper/util/KitUtilities.java b/src/main/java/com/faris/kingkits/helper/util/KitUtilities.java index 23ddbbf..48bf195 100644 --- a/src/main/java/com/faris/kingkits/helper/util/KitUtilities.java +++ b/src/main/java/com/faris/kingkits/helper/util/KitUtilities.java @@ -26,11 +26,15 @@ private KitUtilities() { public static KitSearchResult getKits(String kitName) { Kit exactKit = null; - List kitList = new ArrayList<>(); + List kitList = null; if (kitName != null) { for (Map.Entry kitEntry : KitController.getInstance().getKits().entrySet()) { - if (kitName.equals(kitEntry.getKey())) exactKit = kitEntry.getValue(); - else if (kitName.equalsIgnoreCase(kitEntry.getKey())) kitList.add(kitEntry.getValue()); + if (kitName.equals(kitEntry.getKey())) { + exactKit = kitEntry.getValue(); + } else if (kitName.equalsIgnoreCase(kitEntry.getKey())) { + if (kitList == null) kitList = new ArrayList<>(); + kitList.add(kitEntry.getValue()); + } } } return new KitSearchResult(exactKit, kitList); @@ -38,12 +42,15 @@ public static KitSearchResult getKits(String kitName) { public static KitSearchResult getKits(String kitName, KitPlayer kitPlayer) { Kit exactKit = null; - List kitList = new ArrayList<>(); - + List kitList = null; if (kitName != null && kitPlayer != null) { for (Map.Entry kitEntry : kitPlayer.getKits().entrySet()) { - if (kitName.equals(kitEntry.getValue().getName())) exactKit = kitEntry.getValue(); - else if (kitName.equalsIgnoreCase(kitEntry.getValue().getName())) kitList.add(kitEntry.getValue()); + if (kitName.equals(kitEntry.getValue().getName())) { + exactKit = kitEntry.getValue(); + } else if (kitName.equalsIgnoreCase(kitEntry.getValue().getName())) { + if (kitList == null) kitList = new ArrayList<>(); + kitList.add(kitEntry.getValue()); + } } } return new KitSearchResult(exactKit, kitList); @@ -294,7 +301,7 @@ public static List sortAlphabetically(Collection kitList) { if (kit != null) kitMap.put(kit.getName(), kit); } List sortedKitNames = new ArrayList<>(kitMap.keySet()); - Collections.sort(sortedKitNames, Utilities.getAlphanumericalComparator()); + sortedKitNames.sort(Utilities.getAlphanumericalComparator()); for (String sortedKitName : sortedKitNames) { Kit sortedKit = kitMap.get(sortedKitName); if (sortedKit != null) sortedKits.add(sortedKit); @@ -324,7 +331,7 @@ public Kit getKit() { /** * Get other kits with the same name as the search name. (ignores character casing) * - * @return The kit. + * @return The kits. Returns null if there are no other kits. */ public List getOtherKits() { return this.otherKits; @@ -345,7 +352,7 @@ public boolean hasKit() { * @return True if so, false if not. */ public boolean hasOtherKits() { - return !this.otherKits.isEmpty(); + return this.otherKits != null && !this.otherKits.isEmpty(); } } diff --git a/src/main/java/com/faris/kingkits/helper/util/ObjectUtilities.java b/src/main/java/com/faris/kingkits/helper/util/ObjectUtilities.java index 16e293b..f8465ba 100644 --- a/src/main/java/com/faris/kingkits/helper/util/ObjectUtilities.java +++ b/src/main/java/com/faris/kingkits/helper/util/ObjectUtilities.java @@ -3,9 +3,7 @@ import com.google.gson.JsonObject; import org.bukkit.configuration.ConfigurationSection; -import java.util.HashMap; -import java.util.Map; -import java.util.Objects; +import java.util.*; public class ObjectUtilities { diff --git a/src/main/java/com/faris/kingkits/helper/util/PlayerUtilities.java b/src/main/java/com/faris/kingkits/helper/util/PlayerUtilities.java index 246a5b3..19becab 100644 --- a/src/main/java/com/faris/kingkits/helper/util/PlayerUtilities.java +++ b/src/main/java/com/faris/kingkits/helper/util/PlayerUtilities.java @@ -23,8 +23,9 @@ private PlayerUtilities() { public static boolean checkPlayer(CommandSender sender, KitPlayer kitPlayer) { if (sender == null) return false; if (kitPlayer == null) { - if (!(sender instanceof Player) || ((Player) sender).isOnline()) + if (!(sender instanceof Player) || ((Player) sender).isOnline()) { Messages.sendMessage(sender, Messages.GENERAL_COMMAND_ERROR, NullPointerException.class.getName()); + } return false; } return true; diff --git a/src/main/java/com/faris/kingkits/helper/util/ReflectionUtilities.java b/src/main/java/com/faris/kingkits/helper/util/ReflectionUtilities.java index 222965c..b39a697 100644 --- a/src/main/java/com/faris/kingkits/helper/util/ReflectionUtilities.java +++ b/src/main/java/com/faris/kingkits/helper/util/ReflectionUtilities.java @@ -6,9 +6,7 @@ import java.lang.reflect.Field; import java.lang.reflect.Method; import java.lang.reflect.Modifier; -import java.util.ArrayList; -import java.util.LinkedList; -import java.util.List; +import java.util.*; /** * @author KingFaris10 diff --git a/src/main/java/com/faris/kingkits/helper/util/StringUtilities.java b/src/main/java/com/faris/kingkits/helper/util/StringUtilities.java index d209370..e16a5ad 100644 --- a/src/main/java/com/faris/kingkits/helper/util/StringUtilities.java +++ b/src/main/java/com/faris/kingkits/helper/util/StringUtilities.java @@ -1,7 +1,6 @@ package com.faris.kingkits.helper.util; -import java.util.ArrayList; -import java.util.List; +import java.util.*; public class StringUtilities { diff --git a/src/main/java/com/faris/kingkits/helper/util/Utilities.java b/src/main/java/com/faris/kingkits/helper/util/Utilities.java index eb5b5d2..bd1eb4b 100644 --- a/src/main/java/com/faris/kingkits/helper/util/Utilities.java +++ b/src/main/java/com/faris/kingkits/helper/util/Utilities.java @@ -18,12 +18,10 @@ public class Utilities { private static Gson gson = null; - private static Comparator ALPHANUMERICAL_ORDER = new Comparator() { - public int compare(String str1, String str2) { - int res = String.CASE_INSENSITIVE_ORDER.compare(str1, str2); - if (res == 0) res = str1.compareTo(str2); - return res; - } + private static final Comparator ALPHANUMERICAL_ORDER = (str1, str2) -> { + int res = String.CASE_INSENSITIVE_ORDER.compare(str1, str2); + if (res == 0) res = str1.compareTo(str2); + return res; }; private Utilities() { diff --git a/src/main/java/com/faris/kingkits/listener/CommandListener.java b/src/main/java/com/faris/kingkits/listener/CommandListener.java index 1e4af59..8fae9da 100644 --- a/src/main/java/com/faris/kingkits/listener/CommandListener.java +++ b/src/main/java/com/faris/kingkits/listener/CommandListener.java @@ -37,7 +37,7 @@ import java.lang.reflect.InvocationTargetException; import java.sql.PreparedStatement; import java.util.*; -import java.util.logging.Level; +import java.util.logging.*; public class CommandListener implements CommandExecutor { @@ -74,9 +74,9 @@ public boolean onCommand(final CommandSender sender, Command cmd, String label, } if (DataStorage.getInstance() == null) { if (ConfigController.getInstance().getSQLDetails().isEnabled()) { - DataStorage.setInstance(DataStorage.DataStorageType.SQL); + DataStorage.createInstance(DataStorage.DataStorageType.SQL); } else { - DataStorage.setInstance(DataStorage.DataStorageType.FILE); + DataStorage.createInstance(DataStorage.DataStorageType.FILE); } } @@ -128,22 +128,26 @@ public void run() { if (Utilities.isUUID(strUUID)) { UUID uuid = UUID.fromString(strUUID); File playerDataFile = new File(playerDataFolder, uuid.toString() + ".yml"); - if (playerDataFile.exists()) + if (playerDataFile.exists()) { playerDataFile.delete(); + } FileConfiguration playerDataConfig = YamlConfiguration.loadConfiguration(playerDataFile); StatementSelectTable.Table.Column columnUsername = selectResult.getColumn(row, "username"); - if (!columnUsername.isNull() && !columnUsername.asString().trim().isEmpty()) + if (!columnUsername.isNull() && !columnUsername.asString().trim().isEmpty()) { playerDataConfig.set("Username", columnUsername.asString()); + } StatementSelectTable.Table.Column columnScore = selectResult.getColumn(row, "score"); - if (!columnUsername.isNull()) + if (!columnUsername.isNull()) { playerDataConfig.set("Score", columnScore.asInteger()); + } StatementSelectTable.Table.Column columnUnlockedKits = selectResult.getColumn(row, "unlocked"); - if (!columnUnlockedKits.isNull() && !columnUnlockedKits.asString().trim().isEmpty()) + if (!columnUnlockedKits.isNull() && !columnUnlockedKits.asString().trim().isEmpty()) { playerDataConfig.set("Unlocked kits", columnUnlockedKits.asString()); + } StatementSelectTable.Table.Column columnKits = selectResult.getColumn(row, "kits"); if (!columnKits.isNull() && !columnKits.asString().trim().isEmpty()) { @@ -152,12 +156,14 @@ public void run() { for (Map.Entry jsonKit : jsonKits.entrySet()) { if (jsonKit.getValue().isJsonPrimitive()) { Kit playerKit = Utilities.getGsonParser().fromJson(jsonKit.getValue().getAsJsonPrimitive(), Kit.class); - if (playerKit != null) + if (playerKit != null) { playerKitsSerialized.put(playerKit.getName(), playerKit.serialize()); + } } } - if (!playerKitsSerialized.isEmpty()) + if (!playerKitsSerialized.isEmpty()) { playerDataConfig.set("Kits", playerKitsSerialized); + } } playerDataConfig.save(playerDataFile); @@ -177,8 +183,9 @@ public void run() { } catch (Exception ex) { ex.printStackTrace(); } finally { - if (!SQLController.getInstance().isEnabled()) + if (!SQLController.getInstance().isEnabled()) { SQLController.getInstance().closeConnection(); + } } } }); @@ -200,8 +207,9 @@ public void run() { public void run() { try { final List sqlQueries = new ArrayList<>(); - if (SQLController.getInstance().getHandler().doesTableExist(SQLController.getInstance().getPlayersTable())) + if (SQLController.getInstance().getHandler().doesTableExist(SQLController.getInstance().getPlayersTable())) { sqlQueries.add(new StatementDropTable(SQLController.getInstance().getHandler()).setTable(SQLController.getInstance().getPlayersTable()).toSQLString()); + } sqlQueries.add(SQLStorage.getDefaultTableCreateQuery().toSQLString()); for (File playerDataFile : playerDataFiles) { if (playerDataFile.getName().endsWith(".yml")) { @@ -216,22 +224,27 @@ public void run() { for (Map.Entry kitEntry : kitsSection.entrySet()) { try { Kit playerKit = Kit.deserialize(ObjectUtilities.getMap(kitEntry.getValue())); - if (playerKit != null) + if (playerKit != null) { playerKits.put(playerKit.getName(), playerKit.setUserKit(true)); + } } catch (Exception ignored) { } } } StatementInsertTable statementInsertTable = new StatementInsertTable(SQLController.getInstance().getHandler()).setTable(SQLController.getInstance().getPlayersTable()).setColumns(new StatementInsertTable.Column("uuid", playerUUID.toString())); - if (playerDataConfig.contains("Username")) + if (playerDataConfig.contains("Username")) { statementInsertTable.addColumns(new StatementInsertTable.Column("username", playerDataConfig.getString("Username"))); - if (playerDataConfig.getInt("Score", 0) != 0) + } + if (playerDataConfig.getInt("Score", 0) != 0) { statementInsertTable.addColumns(new StatementInsertTable.Column("score", playerDataConfig.getInt("Score"))); - if (playerDataConfig.contains("Unlocked kits") && !playerDataConfig.getStringList("Unlocked kits").isEmpty()) + } + if (playerDataConfig.contains("Unlocked kits") && !playerDataConfig.getStringList("Unlocked kits").isEmpty()) { statementInsertTable.addColumns(new StatementInsertTable.Column("unlocked", playerDataConfig.getStringList("Unlocked kits"))); - if (!playerKits.isEmpty()) + } + if (!playerKits.isEmpty()) { statementInsertTable.addColumns(new StatementInsertTable.Column("kits", JSONObject.escape(Utilities.getGsonParser().toJson(JsonUtilities.fromMap(playerKits))))); + } String insertQuery = statementInsertTable.toSQLString(); if (insertQuery != null) sqlQueries.add(insertQuery); } @@ -248,8 +261,9 @@ public void run() { preparedStatement.executeUpdate(); if (sqlQuery.startsWith("INSERT ")) this.success++; } finally { - if (preparedStatement != null) + if (preparedStatement != null) { Utilities.silentlyClose(preparedStatement); + } } } } catch (Exception ex) { @@ -261,8 +275,9 @@ public void run() { ex.printStackTrace(); BukkitUtilities.sendMessageSync(sender, Messages.GENERAL_COMMAND_ERROR, ex.getClass().getName()); } finally { - if (!SQLController.getInstance().isEnabled()) + if (!SQLController.getInstance().isEnabled()) { SQLController.getInstance().closeConnection(); + } } } }); @@ -346,8 +361,9 @@ public void run() { StringBuilder pageContent = new StringBuilder(); for (int i = 0; i < configPage.getValue().size(); i++) { pageContent.append(configPage.getValue().get(i)); - if (i < configPage.getValue().size() - 1) + if (i < configPage.getValue().size() - 1) { pageContent.append('\n'); + } } bookMeta.addPage(pageContent.toString()); } @@ -404,10 +420,11 @@ public void run() { Player player = (Player) sender; KitPlayer kitPlayer = PlayerController.getInstance().getPlayer(player); if (!PlayerUtilities.checkPlayer(player, kitPlayer)) return true; - if (kitPlayer.hasKit()) + if (kitPlayer.hasKit()) { Messages.sendMessage(sender, Messages.COMMAND_VIEW_KIT_SELF_KIT, kitPlayer.getKit().getName() + (kitPlayer.getKit().isUserKit() ? " (User)" : "")); - else + } else { Messages.sendMessage(sender, Messages.COMMAND_VIEW_KIT_SELF_NO_KIT); + } } else { Messages.sendMessage(sender, Messages.GENERAL_PLAYER_COMMAND); } @@ -416,10 +433,11 @@ public void run() { if (target != null) { KitPlayer targetKitPlayer = PlayerController.getInstance().getPlayer(target); if (!PlayerUtilities.checkPlayer(sender, targetKitPlayer)) return true; - if (targetKitPlayer.hasKit()) + if (targetKitPlayer.hasKit()) { Messages.sendMessage(sender, Messages.COMMAND_VIEW_KIT_OTHER_KIT, target.getName(), targetKitPlayer.getKit().getName() + (targetKitPlayer.getKit().isUserKit() ? " (User)" : "")); - else + } else { Messages.sendMessage(sender, Messages.COMMAND_VIEW_KIT_OTHER_NO_KIT, target.getName()); + } } else { Messages.sendMessage(sender, Messages.GENERAL_PLAYER_NOT_FOUND, args[1]); } @@ -448,21 +466,16 @@ public void run() { OfflineKitPlayer offlineKitPlayer = DataStorage.getInstance().loadOfflinePlayer(args[1]); Messages.sendMessage(sender, Messages.COMMAND_SCORE_OTHER, offlineKitPlayer.getUsername(), offlineKitPlayer.getScore()); } else { - sender.getServer().getScheduler().runTaskAsynchronously(this.plugin, new Runnable() { - @Override - public void run() { - OfflineKitPlayer offlineKitPlayer = DataStorage.getInstance().loadOfflinePlayer(args[1]); - long startTime = System.currentTimeMillis(); - while (true) { - if (offlineKitPlayer.isLoaded()) { - break; - } else if (System.currentTimeMillis() - startTime > 5_000L) { - BukkitUtilities.sendMessageSync(sender, "&cServer took too long to respond."); - return; - } + sender.getServer().getScheduler().runTaskAsynchronously(this.plugin, () -> { + OfflineKitPlayer offlineKitPlayer = DataStorage.getInstance().loadOfflinePlayer(args[1]); + long startTime = System.currentTimeMillis(); + while (!offlineKitPlayer.isLoaded()) { + if (System.currentTimeMillis() - startTime > 5_000L) { + BukkitUtilities.sendMessageSync(sender, "&cServer took too long to respond."); + return; } - BukkitUtilities.sendMessageSync(sender, Messages.COMMAND_SCORE_OTHER, offlineKitPlayer.getUsername(), offlineKitPlayer.getScore()); } + BukkitUtilities.sendMessageSync(sender, Messages.COMMAND_SCORE_OTHER, offlineKitPlayer.getUsername(), offlineKitPlayer.getScore()); }); } } @@ -470,6 +483,189 @@ public void run() { Messages.sendMessage(sender, Messages.GENERAL_COMMAND_USAGE, label.toLowerCase(), subCommand.toLowerCase() + " " + (sender instanceof Player ? "[" : "") + "" + (sender instanceof Player ? "]" : "")); } return true; + } else if (subCommand.equalsIgnoreCase("set")) { + if (sender.hasPermission(Permissions.COMMAND_SET)) { + if (args.length > 3) { + KitUtilities.KitSearchResult kitSearchResult = KitUtilities.getKits(args[1]); + Kit targetKit = null; + if (kitSearchResult.hasKit()) { + targetKit = kitSearchResult.getKit(); + } else if (kitSearchResult.hasOtherKits()) { + if (kitSearchResult.getOtherKits().size() == 1) { + targetKit = kitSearchResult.getOtherKits().get(0); + } else { + StringBuilder sbKits = new StringBuilder(); + for (int i = 0; i < kitSearchResult.getOtherKits().size(); i++) { + sbKits.append(kitSearchResult.getOtherKits().get(i)); + if (i != kitSearchResult.getOtherKits().size() - 1) { + sbKits.append(ChatColor.RED).append(", ").append(ChatColor.GREEN); + } + } + sender.sendMessage(ChatColor.GOLD + "Select a kit from: " + ChatColor.GREEN + sbKits); + return true; + } + } else { + sender.sendMessage(ChatColor.RED + "Unknown kit: " + ChatColor.DARK_RED + args[1]); + return true; + } + String key = args[2]; + String strValue = StringUtilities.joinString(args, 3); + Object value = strValue; + if (key.equalsIgnoreCase("displayname")) { + key = "Display name"; + targetKit.setDisplayName(strValue); + } else if (key.equalsIgnoreCase("commandalias") || key.equalsIgnoreCase("alias") || key.equalsIgnoreCase("breakableitems") || key.equalsIgnoreCase("breakitems")) { + int keyType = -1; + if (key.equalsIgnoreCase("commandalias") || key.equalsIgnoreCase("alias")) { + key = "Command alias"; + keyType = 1; + } else if (key.equalsIgnoreCase("breakableitems") || key.equalsIgnoreCase("breakitems")) { + key = "Breakable items"; + keyType = 2; + } + if (strValue.equalsIgnoreCase("true")) { + value = true; + } else if (strValue.equalsIgnoreCase("false")) { + value = false; + } else { + sender.sendMessage(ChatColor.RED + "Valid values: true, false"); + return true; + } + switch (keyType) { + case 1: + targetKit.setAlias((Boolean) value); + break; + case 2: + targetKit.setItemsBreakable((Boolean) value); + break; + } + } else if (key.equalsIgnoreCase("description") || key.equalsIgnoreCase("commands")) { + int keyType = -1; + if (key.equalsIgnoreCase("description")) { + key = "Description"; + keyType = 1; + } else if (key.equalsIgnoreCase("commands")) { + key = "Commands"; + keyType = 2; + } + if (strValue.startsWith("[") && strValue.endsWith("]")) { + strValue = strValue.substring(1, strValue.length() - 1); + if (!strValue.trim().isEmpty()) { + List description = new ArrayList<>(); + Collections.addAll(description, strValue.split(", ")); + value = description; + } else { + value = new ArrayList(); + } + } else { + value = new ArrayList(); + } + switch (keyType) { + case 1: + targetKit.setDescription((List) value); + break; + case 2: + targetKit.setCommands((List) value); + break; + } + sender.sendMessage(ChatColor.DARK_RED + "Warning: " + ChatColor.RED + "It is not recommended you use commands to set lists."); + } else if (key.equalsIgnoreCase("cost") || key.equalsIgnoreCase("cooldown") || key.equalsIgnoreCase("maxhealth")) { + int keyType = -1; + if (key.equalsIgnoreCase("cost")) { + key = "Cost"; + keyType = 1; + } else if (key.equalsIgnoreCase("cooldown")) { + key = "Cooldown"; + keyType = 2; + } else if (key.equalsIgnoreCase("maxhealth")) { + key = "Max health"; + keyType = 3; + } + if (Utilities.isNumber(Double.class, strValue)) { + value = Double.parseDouble(strValue); + } else if (Utilities.isNumber(Integer.class, strValue)) { + value = (double) Integer.parseInt(strValue); + } else { + sender.sendMessage(ChatColor.RED + "Valid values: Positive numbers"); + return true; + } + if ((Double) value < 0D) { + sender.sendMessage(ChatColor.RED + "Valid values: Positive numbers"); + return true; + } + switch (keyType) { + case 1: + targetKit.setCost((Double) value); + break; + case 2: + targetKit.setCooldown((Double) value); + break; + case 3: + targetKit.setMaxHealth((Double) value); + break; + } + } else if (key.equalsIgnoreCase("walkspeed")) { + key = "Walk speed"; + if (Utilities.isNumber(Float.class, strValue)) { + value = Float.parseFloat(strValue); + } else if (Utilities.isNumber(Integer.class, strValue)) { + value = (Integer.valueOf(strValue)).floatValue(); + } else if (Utilities.isNumber(Double.class, strValue)) { + value = (Double.valueOf(strValue)).floatValue(); + } else { + sender.sendMessage(ChatColor.RED + "Valid values: 0.0 - 1.0"); + return true; + } + if ((Float) value < 0F || (Float) value > 1F) { + sender.sendMessage(ChatColor.RED + "Valid values: 0.0 - 1.0"); + return true; + } + targetKit.setWalkSpeed((Float) value); + } else if (key.equalsIgnoreCase("autounlock") || key.equalsIgnoreCase("autounlockscore") || key.equalsIgnoreCase("helditemslot")) { + int keyType = -1; + if (key.equalsIgnoreCase("autounlock") || key.equalsIgnoreCase("autounlockscore")) { + key = "Auto-unlock score"; + keyType = 1; + } else if (key.equalsIgnoreCase("helditemslot")) { + key = "Held item slot"; + keyType = 2; + } + if (Utilities.isNumber(Integer.class, strValue)) { + value = Integer.parseInt(strValue); + } else { + sender.sendMessage(ChatColor.RED + "Valid values: Positive integers"); + return true; + } + if ((Integer) value < 0) { + sender.sendMessage(ChatColor.RED + "Valid values: Positive integers"); + return true; + } + switch (keyType) { + case 1: + targetKit.setAutoUnlockScore((Integer) value); + break; + case 2: + targetKit.setHeldItemSlot((Integer) value); + break; + } + } else { + sender.sendMessage(ChatColor.RED + "Unknown key: " + ChatColor.DARK_RED + key); + return true; + } + try { + KitController.getInstance().saveKit(targetKit, key, value); + sender.sendMessage(ChatColor.GOLD + "Successfully set the value of key '" + key + "' to '" + String.valueOf(value) + "'."); + } catch (Exception ex) { + ex.printStackTrace(); + Messages.sendMessage(sender, Messages.GENERAL_COMMAND_ERROR, ex instanceof InvocationTargetException ? ((InvocationTargetException) ex).getTargetException().getClass().getName() : ex.getClass().getName()); + } + } else { + Messages.sendMessage(sender, Messages.GENERAL_COMMAND_USAGE, label.toLowerCase(), subCommand.toLowerCase() + " "); + } + } else { + Messages.sendMessage(sender, Messages.GENERAL_COMMAND_NO_PERMISSION); + } + return true; } } sender.sendMessage(ChatColor.GOLD + "KingKits v" + this.plugin.getDescription().getVersion() + " by " + ChatColor.RED.toString() + ChatColor.BOLD.toString() + "KingFaris10"); diff --git a/src/main/java/com/faris/kingkits/listener/EventListener.java b/src/main/java/com/faris/kingkits/listener/EventListener.java index 33a69a5..4b52a35 100644 --- a/src/main/java/com/faris/kingkits/listener/EventListener.java +++ b/src/main/java/com/faris/kingkits/listener/EventListener.java @@ -27,11 +27,8 @@ import org.bukkit.inventory.ItemStack; import org.bukkit.potion.PotionEffect; -import java.util.HashMap; -import java.util.List; -import java.util.Map; -import java.util.UUID; -import java.util.logging.Level; +import java.util.*; +import java.util.logging.*; public class EventListener implements Listener { @@ -402,15 +399,12 @@ public void onPlayerDeath(PlayerDeathEvent event) { } } if (ConfigController.getInstance().shouldAutoRespawn()) { - player.getServer().getScheduler().runTaskLater(this.plugin, new Runnable() { - @Override - public void run() { - if (player.isOnline() && player.isDead()) { - try { - PlayerUtilities.respawnPlayer(player); - } catch (Exception ex) { - ex.printStackTrace(); - } + player.getServer().getScheduler().runTaskLater(this.plugin, () -> { + if (player.isOnline() && player.isDead()) { + try { + PlayerUtilities.respawnPlayer(player); + } catch (Exception ex) { + ex.printStackTrace(); } } }, 1L); @@ -435,12 +429,9 @@ public void onPlayerRespawn(PlayerRespawnEvent event) { } if (showGUI && ConfigController.getInstance().shouldShowGuiOnRespawn()) { kitPlayer.setKit(null); - player.getServer().getScheduler().runTaskLater(this.plugin, new Runnable() { - @Override - public void run() { - if (player.isOnline() && Utilities.isPvPWorld(player.getWorld())) { - GuiController.getInstance().openKitsMenu(player); - } + player.getServer().getScheduler().runTaskLater(this.plugin, () -> { + if (player.isOnline() && Utilities.isPvPWorld(player.getWorld())) { + GuiController.getInstance().openKitsMenu(player); } }, 5L); } @@ -523,13 +514,10 @@ public void onPlayerDropItem(PlayerDropItemEvent event) { if (this.updateInventoryTasks.containsKey(playerUUID)) { BukkitUtilities.cancelTask(this.updateInventoryTasks.remove(playerUUID)); } - this.updateInventoryTasks.put(playerUUID, player.getServer().getScheduler().runTaskLater(this.plugin, new Runnable() { - @Override - public void run() { - updateInventoryTasks.remove(playerUUID); - if (player.isOnline()) { - player.updateInventory(); - } + this.updateInventoryTasks.put(playerUUID, player.getServer().getScheduler().runTaskLater(this.plugin, () -> { + updateInventoryTasks.remove(playerUUID); + if (player.isOnline()) { + player.updateInventory(); } }, 2L).getTaskId()); } else { @@ -645,23 +633,17 @@ public void onPlayerChangeWorld(PlayerChangedWorldEvent event) { player.removePotionEffect(activePotionEffect.getType()); } if (ConfigController.getInstance().shouldShowGuiOnJoin()) { - player.getServer().getScheduler().runTaskLater(this.plugin, new Runnable() { - @Override - public void run() { - if (player.isOnline() && Utilities.isPvPWorld(player.getWorld())) { - Runnable openMenuRunnable = new Runnable() { - @Override - public void run() { - if (player.isOnline() && Utilities.isPvPWorld(player.getWorld())) - GuiController.getInstance().openKitsMenu(player); - } - }; - if (player.getOpenInventory() != null) { - player.closeInventory(); - Bukkit.getServer().getScheduler().runTask(plugin, openMenuRunnable); - } else { - openMenuRunnable.run(); - } + player.getServer().getScheduler().runTaskLater(this.plugin, () -> { + if (player.isOnline() && Utilities.isPvPWorld(player.getWorld())) { + Runnable openMenuRunnable = () -> { + if (player.isOnline() && Utilities.isPvPWorld(player.getWorld())) + GuiController.getInstance().openKitsMenu(player); + }; + if (player.getOpenInventory() != null) { + player.closeInventory(); + Bukkit.getServer().getScheduler().runTask(plugin, openMenuRunnable); + } else { + openMenuRunnable.run(); } } }, 5L); @@ -780,18 +762,15 @@ public void onEntityDamage(EntityDamageEvent event) { } if (updateHelmet || updateChestplate || updateLeggings || updateBoots || updateOffhand) { final boolean finalUpdateHelmet = updateHelmet, finalUpdateChestplate = updateChestplate, finalUpdateLeggings = updateLeggings, finalUpdateBoots = updateBoots, finalUpdateOffhand = updateOffhand; - damaged.getServer().getScheduler().runTask(this.plugin, new Runnable() { - @Override - public void run() { - if (damaged.isOnline() && kitPlayer.hasKit() && !kitPlayer.getKit().canItemsBreak()) { - if (finalUpdateHelmet) damaged.getInventory().setHelmet(helmet); - if (finalUpdateChestplate) - damaged.getInventory().setChestplate(chestplate); - if (finalUpdateLeggings) damaged.getInventory().setLeggings(leggings); - if (finalUpdateBoots) damaged.getInventory().setBoots(boots); - if (finalUpdateOffhand) - damaged.getInventory().setItemInOffHand(offhand); - } + damaged.getServer().getScheduler().runTask(this.plugin, () -> { + if (damaged.isOnline() && kitPlayer.hasKit() && !kitPlayer.getKit().canItemsBreak()) { + if (finalUpdateHelmet) damaged.getInventory().setHelmet(helmet); + if (finalUpdateChestplate) + damaged.getInventory().setChestplate(chestplate); + if (finalUpdateLeggings) damaged.getInventory().setLeggings(leggings); + if (finalUpdateBoots) damaged.getInventory().setBoots(boots); + if (finalUpdateOffhand) + damaged.getInventory().setItemInOffHand(offhand); } }); } @@ -816,30 +795,24 @@ public void onEntityDamageByEntity(EntityDamageByEntityEvent event) { if (damagerKitPlayer != null && damagerKitPlayer.hasKit() && !damagerKitPlayer.getKit().canItemsBreak()) { if (damager.getInventory().getItemInMainHand() != null) { if (ItemUtilities.getDamageableMaterials().contains(damager.getInventory().getItemInMainHand().getType())) { - damager.getServer().getScheduler().runTask(this.plugin, new Runnable() { - @Override - public void run() { - if (damager.isOnline() && damagerKitPlayer.hasKit() && damager.getInventory().getItemInMainHand() != null && ItemUtilities.getDamageableMaterials().contains(damager.getInventory().getItemInMainHand().getType())) { - ItemStack itemInHand = damager.getInventory().getItemInMainHand(); - itemInHand.setDurability((short) 0); - damager.getInventory().setItemInMainHand(itemInHand); - damager.updateInventory(); - } + damager.getServer().getScheduler().runTask(this.plugin, () -> { + if (damager.isOnline() && damagerKitPlayer.hasKit() && damager.getInventory().getItemInMainHand() != null && ItemUtilities.getDamageableMaterials().contains(damager.getInventory().getItemInMainHand().getType())) { + ItemStack itemInHand = damager.getInventory().getItemInMainHand(); + itemInHand.setDurability((short) 0); + damager.getInventory().setItemInMainHand(itemInHand); + damager.updateInventory(); } }); } } if (damager.getInventory().getItemInOffHand() != null) { if (ItemUtilities.getDamageableMaterials().contains(damager.getInventory().getItemInOffHand().getType())) { - damager.getServer().getScheduler().runTask(this.plugin, new Runnable() { - @Override - public void run() { - if (damager.isOnline() && damagerKitPlayer.hasKit() && damager.getInventory().getItemInOffHand() != null && ItemUtilities.getDamageableMaterials().contains(damager.getInventory().getItemInOffHand().getType())) { - ItemStack itemInHand = damager.getInventory().getItemInOffHand(); - itemInHand.setDurability((short) 0); - damager.getInventory().setItemInOffHand(itemInHand); - damager.updateInventory(); - } + damager.getServer().getScheduler().runTask(this.plugin, () -> { + if (damager.isOnline() && damagerKitPlayer.hasKit() && damager.getInventory().getItemInOffHand() != null && ItemUtilities.getDamageableMaterials().contains(damager.getInventory().getItemInOffHand().getType())) { + ItemStack itemInHand = damager.getInventory().getItemInOffHand(); + itemInHand.setDurability((short) 0); + damager.getInventory().setItemInOffHand(itemInHand); + damager.updateInventory(); } }); } @@ -878,16 +851,13 @@ public void run() { } if (updateHelmet || updateChestplate || updateLeggings || updateBoots || updateOffhand) { final boolean finalUpdateHelmet = updateHelmet, finalUpdateChestplate = updateChestplate, finalUpdateLeggings = updateLeggings, finalUpdateBoots = updateBoots, finalUpdateOffhand = updateOffhand; - damaged.getServer().getScheduler().runTask(this.plugin, new Runnable() { - @Override - public void run() { - if (damaged.isOnline() && kitPlayer.hasKit() && !kitPlayer.getKit().canItemsBreak()) { - if (finalUpdateHelmet) damaged.getInventory().setHelmet(helmet); - if (finalUpdateChestplate) damaged.getInventory().setChestplate(chestplate); - if (finalUpdateLeggings) damaged.getInventory().setLeggings(leggings); - if (finalUpdateBoots) damaged.getInventory().setBoots(boots); - if (finalUpdateOffhand) damaged.getInventory().setItemInOffHand(offhand); - } + damaged.getServer().getScheduler().runTask(this.plugin, () -> { + if (damaged.isOnline() && kitPlayer.hasKit() && !kitPlayer.getKit().canItemsBreak()) { + if (finalUpdateHelmet) damaged.getInventory().setHelmet(helmet); + if (finalUpdateChestplate) damaged.getInventory().setChestplate(chestplate); + if (finalUpdateLeggings) damaged.getInventory().setLeggings(leggings); + if (finalUpdateBoots) damaged.getInventory().setBoots(boots); + if (finalUpdateOffhand) damaged.getInventory().setItemInOffHand(offhand); } }); } @@ -908,61 +878,46 @@ public void handleJoinEvent(final Player player, final boolean onlyReload) throw final KitPlayer kitPlayer = PlayerController.getInstance().registerPlayer(player); final long currentTime = System.currentTimeMillis(); - final Runnable joinTask = new Runnable() { - @Override - public void run() { - if (player.isOnline()) { - try { - if (ConfigController.getInstance().shouldShowGuiOnJoin() && Utilities.isPvPWorld(player.getWorld())) { - EventListener.this.joinTasks.put(player.getUniqueId(), player.getServer().getScheduler().runTaskLater(plugin, new Runnable() { - @SuppressWarnings("deprecation") - public void run() { - if (player.isOnline()) GuiController.getInstance().openKitsMenu(player); - } - }, System.currentTimeMillis() - currentTime > 1_000L ? 0L : 15L).getTaskId()); - } - } catch (Exception ex) { - Bukkit.getServer().getLogger().log(Level.SEVERE, "Failed to show the kit menu on join.", ex); + final Runnable joinTask = () -> { + if (player.isOnline()) { + try { + if (ConfigController.getInstance().shouldShowGuiOnJoin() && Utilities.isPvPWorld(player.getWorld())) { + EventListener.this.joinTasks.put(player.getUniqueId(), player.getServer().getScheduler().runTaskLater(plugin, () -> { + if (player.isOnline()) GuiController.getInstance().openKitsMenu(player); + }, System.currentTimeMillis() - currentTime > 1_000L ? 0L : 15L).getTaskId()); } + } catch (Exception ex) { + Bukkit.getServer().getLogger().log(Level.SEVERE, "Failed to show the kit menu on join.", ex); } } }; - kitPlayer.setLoadTaskID(player.getServer().getScheduler().runTaskAsynchronously(this.plugin, new Runnable() { - @Override - public void run() { - try { - DataStorage.getInstance().loadPlayer(PlayerController.getInstance().getPlayer(kitPlayer.getUniqueId())); - while (true) { - if (PlayerController.getInstance().getPlayer(kitPlayer.getUniqueId()).isLoaded()) { - break; - } else if (System.currentTimeMillis() - currentTime > 7_500L) { - Bukkit.getServer().getScheduler().runTask(plugin, new Runnable() { - @Override - public void run() { - if (player.isOnline()) { - player.getServer().broadcast(ChatColor.GOLD + "[" + ChatColor.BOLD + ChatColor.AQUA + "KingKits" + ChatColor.GOLD + "] " + ChatColor.RED + "The server took too long to load " + player.getName() + "'s data. They have been kicked from the server.", Permissions.ADMIN.getName()); - player.kickPlayer(ChatColor.RED + "[KingKits] Server took too long to respond!\n" + ChatColor.RED + "Could not load your data."); - } - } - }); - return; - } - } - if (!onlyReload) Bukkit.getServer().getScheduler().runTask(plugin, joinTask); - } catch (Exception ex) { - ex.printStackTrace(); - - Bukkit.getServer().getScheduler().runTask(plugin, new Runnable() { - @Override - public void run() { + kitPlayer.setLoadTaskID(player.getServer().getScheduler().runTaskAsynchronously(this.plugin, () -> { + try { + DataStorage.getInstance().loadPlayer(PlayerController.getInstance().getPlayer(kitPlayer.getUniqueId())); + while (true) { + if (PlayerController.getInstance().getPlayer(kitPlayer.getUniqueId()).isLoaded()) { + break; + } else if (System.currentTimeMillis() - currentTime > 7_500L) { + Bukkit.getServer().getScheduler().runTask(plugin, () -> { if (player.isOnline()) { - player.getServer().broadcast(ChatColor.GOLD + "[" + ChatColor.BOLD + ChatColor.AQUA + "KingKits" + ChatColor.GOLD + "] " + ChatColor.RED + "An error occurred whilst loading " + player.getName() + "'s data. They have been kicked from the server.", Permissions.ADMIN.getName()); - player.kickPlayer(ChatColor.RED + "[KingKits] An error occurred!\n" + ChatColor.RED + "Could not load your data."); + player.getServer().broadcast(ChatColor.GOLD + "[" + ChatColor.BOLD + ChatColor.AQUA + "KingKits" + ChatColor.GOLD + "] " + ChatColor.RED + "The server took too long to load " + player.getName() + "'s data. They have been kicked from the server.", Permissions.ADMIN.getName()); + player.kickPlayer(ChatColor.RED + "[KingKits] Server took too long to respond!\n" + ChatColor.RED + "Could not load your data."); } - } - }); + }); + return; + } } + if (!onlyReload) Bukkit.getServer().getScheduler().runTask(plugin, joinTask); + } catch (Exception ex) { + ex.printStackTrace(); + + Bukkit.getServer().getScheduler().runTask(plugin, () -> { + if (player.isOnline()) { + player.getServer().broadcast(ChatColor.GOLD + "[" + ChatColor.BOLD + ChatColor.AQUA + "KingKits" + ChatColor.GOLD + "] " + ChatColor.RED + "An error occurred whilst loading " + player.getName() + "'s data. They have been kicked from the server.", Permissions.ADMIN.getName()); + player.kickPlayer(ChatColor.RED + "[KingKits] An error occurred!\n" + ChatColor.RED + "Could not load your data."); + } + }); } }).getTaskId()); } diff --git a/src/main/java/com/faris/kingkits/listener/commands/CommandCreateKit.java b/src/main/java/com/faris/kingkits/listener/commands/CommandCreateKit.java index 8ca18da..401dfaf 100644 --- a/src/main/java/com/faris/kingkits/listener/commands/CommandCreateKit.java +++ b/src/main/java/com/faris/kingkits/listener/commands/CommandCreateKit.java @@ -18,11 +18,8 @@ import org.bukkit.permissions.Permission; import org.bukkit.potion.PotionEffect; -import java.util.ArrayList; -import java.util.List; -import java.util.Map; -import java.util.TreeMap; -import java.util.logging.Level; +import java.util.*; +import java.util.logging.*; public class CommandCreateKit extends KingKitsCommand { diff --git a/src/main/java/com/faris/kingkits/listener/commands/CommandCreateUserKit.java b/src/main/java/com/faris/kingkits/listener/commands/CommandCreateUserKit.java index 076d543..df1e9f5 100644 --- a/src/main/java/com/faris/kingkits/listener/commands/CommandCreateUserKit.java +++ b/src/main/java/com/faris/kingkits/listener/commands/CommandCreateUserKit.java @@ -17,11 +17,8 @@ import org.bukkit.inventory.ItemStack; import org.bukkit.potion.PotionEffect; -import java.util.ArrayList; -import java.util.List; -import java.util.Map; -import java.util.TreeMap; -import java.util.logging.Level; +import java.util.*; +import java.util.logging.*; public class CommandCreateUserKit extends KingKitsCommand { diff --git a/src/main/java/com/faris/kingkits/listener/commands/CommandDeleteKit.java b/src/main/java/com/faris/kingkits/listener/commands/CommandDeleteKit.java index d0f0047..97e99d8 100644 --- a/src/main/java/com/faris/kingkits/listener/commands/CommandDeleteKit.java +++ b/src/main/java/com/faris/kingkits/listener/commands/CommandDeleteKit.java @@ -14,7 +14,7 @@ import org.bukkit.command.CommandSender; import org.bukkit.entity.Player; -import java.util.logging.Level; +import java.util.logging.*; public class CommandDeleteKit extends KingKitsCommand { diff --git a/src/main/java/com/faris/kingkits/listener/commands/CommandDeleteUserKit.java b/src/main/java/com/faris/kingkits/listener/commands/CommandDeleteUserKit.java index cab99d6..6dd9a61 100644 --- a/src/main/java/com/faris/kingkits/listener/commands/CommandDeleteUserKit.java +++ b/src/main/java/com/faris/kingkits/listener/commands/CommandDeleteUserKit.java @@ -16,7 +16,7 @@ import org.bukkit.command.CommandSender; import org.bukkit.entity.Player; -import java.util.logging.Level; +import java.util.logging.*; public class CommandDeleteUserKit extends KingKitsCommand { diff --git a/src/main/java/com/faris/kingkits/listener/commands/CommandPreviewKit.java b/src/main/java/com/faris/kingkits/listener/commands/CommandPreviewKit.java index 32a2412..ce47486 100644 --- a/src/main/java/com/faris/kingkits/listener/commands/CommandPreviewKit.java +++ b/src/main/java/com/faris/kingkits/listener/commands/CommandPreviewKit.java @@ -14,7 +14,7 @@ import org.bukkit.command.CommandSender; import org.bukkit.entity.Player; -import java.util.logging.Level; +import java.util.logging.*; public class CommandPreviewKit extends KingKitsCommand { diff --git a/src/main/java/com/faris/kingkits/listener/commands/CommandPvPKit.java b/src/main/java/com/faris/kingkits/listener/commands/CommandPvPKit.java index fa4e2d3..626c520 100644 --- a/src/main/java/com/faris/kingkits/listener/commands/CommandPvPKit.java +++ b/src/main/java/com/faris/kingkits/listener/commands/CommandPvPKit.java @@ -19,10 +19,8 @@ import org.bukkit.inventory.ItemStack; import org.bukkit.potion.PotionEffect; -import java.util.ArrayList; -import java.util.List; -import java.util.Map; -import java.util.logging.Level; +import java.util.*; +import java.util.logging.*; public class CommandPvPKit extends KingKitsCommand { diff --git a/src/main/java/com/faris/kingkits/listener/commands/CommandRefill.java b/src/main/java/com/faris/kingkits/listener/commands/CommandRefill.java index cde5859..7e5123f 100644 --- a/src/main/java/com/faris/kingkits/listener/commands/CommandRefill.java +++ b/src/main/java/com/faris/kingkits/listener/commands/CommandRefill.java @@ -15,7 +15,7 @@ import org.bukkit.entity.Player; import org.bukkit.inventory.ItemStack; -import java.util.logging.Level; +import java.util.logging.*; public class CommandRefill extends KingKitsCommand { diff --git a/src/main/java/com/faris/kingkits/listener/commands/CommandRenameKit.java b/src/main/java/com/faris/kingkits/listener/commands/CommandRenameKit.java index 2cebde2..5a1726a 100644 --- a/src/main/java/com/faris/kingkits/listener/commands/CommandRenameKit.java +++ b/src/main/java/com/faris/kingkits/listener/commands/CommandRenameKit.java @@ -15,7 +15,7 @@ import org.bukkit.entity.Player; import org.bukkit.permissions.Permission; -import java.util.logging.Level; +import java.util.logging.*; public class CommandRenameKit extends KingKitsCommand { diff --git a/src/main/java/com/faris/kingkits/listener/commands/CommandRenameUserKit.java b/src/main/java/com/faris/kingkits/listener/commands/CommandRenameUserKit.java index c3e4db8..dd6e595 100644 --- a/src/main/java/com/faris/kingkits/listener/commands/CommandRenameUserKit.java +++ b/src/main/java/com/faris/kingkits/listener/commands/CommandRenameUserKit.java @@ -16,7 +16,7 @@ import org.bukkit.command.CommandSender; import org.bukkit.entity.Player; -import java.util.logging.Level; +import java.util.logging.*; public class CommandRenameUserKit extends KingKitsCommand { diff --git a/src/main/java/com/faris/kingkits/old/OldKit.java b/src/main/java/com/faris/kingkits/old/OldKit.java index 8779ba4..a3c79de 100644 --- a/src/main/java/com/faris/kingkits/old/OldKit.java +++ b/src/main/java/com/faris/kingkits/old/OldKit.java @@ -681,17 +681,17 @@ public static T getObject(Map map, String key, Class unus } public static T getObject(Map map, String key, Class unused, T defaultValue) throws ClassCastException { - Object value = map.containsKey(key) ? map.get(key) : null; + Object value = map.getOrDefault(key, null); return value != null ? (unused == Long.class ? (T) ((Long) Long.parseLong(value.toString())) : (unused == Integer.class ? (T) ((Integer) Integer.parseInt(value.toString())) : (unused == Short.class ? (T) ((Short) Short.parseShort(value.toString())) : (unused == Double.class ? (T) ((Double) Double.parseDouble(value.toString())) : (unused.isInstance(value) ? (T) value : defaultValue))))) : defaultValue; } public static Map getValues(Map mainMap, String key) { Object object = mainMap != null ? mainMap.get(key) : null; - return object instanceof ConfigurationSection ? ((ConfigurationSection) object).getValues(false) : (object instanceof Map ? (Map) object : new HashMap()); + return object instanceof ConfigurationSection ? ((ConfigurationSection) object).getValues(false) : (object instanceof Map ? (Map) object : new HashMap<>()); } public static Map getValues(Object object) { - return object instanceof ConfigurationSection ? ((ConfigurationSection) object).getValues(false) : (object instanceof Map ? (Map) object : new HashMap()); + return object instanceof ConfigurationSection ? ((ConfigurationSection) object).getValues(false) : (object instanceof Map ? (Map) object : new HashMap<>()); } public static Map getValues(Map.Entry entrySet) { diff --git a/src/main/java/com/faris/kingkits/player/KitPlayer.java b/src/main/java/com/faris/kingkits/player/KitPlayer.java index c01694c..883e090 100644 --- a/src/main/java/com/faris/kingkits/player/KitPlayer.java +++ b/src/main/java/com/faris/kingkits/player/KitPlayer.java @@ -5,9 +5,7 @@ import com.faris.kingkits.controller.PlayerController; import org.bukkit.entity.Player; -import java.util.HashMap; -import java.util.Map; -import java.util.UUID; +import java.util.*; public class KitPlayer extends OfflineKitPlayer { diff --git a/src/main/java/com/faris/kingkits/player/OfflineKitPlayer.java b/src/main/java/com/faris/kingkits/player/OfflineKitPlayer.java index 4eac0b8..dac3d0a 100644 --- a/src/main/java/com/faris/kingkits/player/OfflineKitPlayer.java +++ b/src/main/java/com/faris/kingkits/player/OfflineKitPlayer.java @@ -53,7 +53,7 @@ public Map getKits() { } public long getKitTimestamp(Kit kit) { - return kit != null ? (this.kitTimestamps.containsKey(kit.getName()) ? this.kitTimestamps.get(kit.getName()) : -1L) : 0L; + return kit != null ? this.kitTimestamps.getOrDefault(kit.getName(), -1L) : 0L; } public Map getKitTimestamps() { @@ -97,7 +97,7 @@ public void removeKit(Kit kit) { public void setKits(Map kits) { if (this.loaded && !this.playerKits.equals(kits)) this.modified = true; - this.playerKits = kits == null ? new HashMap() : kits; + this.playerKits = kits == null ? new HashMap<>() : kits; } public void setKitTimestamp(Kit kit, Long timestamp) { @@ -199,23 +199,27 @@ public static OfflineKitPlayer deserialize(Map serializedPlayer) try { if (serializedPlayer.containsKey("UUID")) { deserializedPlayer = new OfflineKitPlayer(UUID.fromString(ObjectUtilities.getObject(serializedPlayer, String.class, "UUID"))); - if (serializedPlayer.containsKey("Username")) + if (serializedPlayer.containsKey("Username")) { deserializedPlayer.setUsername(ObjectUtilities.getObject(serializedPlayer, String.class, "Username")); + } } else if (serializedPlayer.containsKey("Username")) { deserializedPlayer = new OfflineKitPlayer(ObjectUtilities.getObject(serializedPlayer, String.class, "Username")); } if (deserializedPlayer != null) { - if (serializedPlayer.containsKey("Score")) + if (serializedPlayer.containsKey("Score")) { deserializedPlayer.setScore(ObjectUtilities.getObject(serializedPlayer, Integer.class, "Score")); + } if (serializedPlayer.containsKey("Kit timestamps")) { Map serializedKitTimestamps = ObjectUtilities.getMap(serializedPlayer.get("Kit timestamps")); Map deserializedKitTimestamps = new HashMap<>(); for (Map.Entry serializedKitTimestamp : serializedKitTimestamps.entrySet()) { - if (Utilities.isNumber(Long.class, serializedKitTimestamp.getValue())) + if (Utilities.isNumber(Long.class, serializedKitTimestamp.getValue())) { deserializedKitTimestamps.put(serializedKitTimestamp.getKey(), Long.parseLong(serializedKitTimestamp.getValue().toString())); + } } - if (!deserializedKitTimestamps.isEmpty()) + if (!deserializedKitTimestamps.isEmpty()) { deserializedPlayer.setKitTimestamps(deserializedKitTimestamps); + } } if (serializedPlayer.containsKey("Player kits")) { Map serializedPlayerKits = ObjectUtilities.getMap(serializedPlayer.get("Player kits")); diff --git a/src/main/java/com/faris/kingkits/storage/DataStorage.java b/src/main/java/com/faris/kingkits/storage/DataStorage.java index 50a17d2..7242909 100644 --- a/src/main/java/com/faris/kingkits/storage/DataStorage.java +++ b/src/main/java/com/faris/kingkits/storage/DataStorage.java @@ -4,7 +4,7 @@ import com.faris.kingkits.player.OfflineKitPlayer; import org.bukkit.Bukkit; -import java.util.UUID; +import java.util.*; public abstract class DataStorage { @@ -24,7 +24,7 @@ public static DataStorage getInstance() { return instance; } - public static void setInstance(DataStorageType storageType) { + public static void createInstance(DataStorageType storageType) { if (storageType != null) { switch (storageType) { case FILE: @@ -35,12 +35,12 @@ public static void setInstance(DataStorageType storageType) { break; default: instance = new FlatFileStorage(); - Bukkit.getServer().getLogger().warning("An invalid storage type was provided! Using default storage type: Flat"); + Bukkit.getServer().getLogger().warning("An invalid storage type was provided! Using default storage type: Flat file"); break; } } else { instance = new FlatFileStorage(); - Bukkit.getServer().getLogger().warning("An invalid storage type was provided! Using default storage type: Flat"); + Bukkit.getServer().getLogger().warning("An invalid storage type was provided! Using default storage type: Flat file"); } } diff --git a/src/main/java/com/faris/kingkits/storage/FlatFileStorage.java b/src/main/java/com/faris/kingkits/storage/FlatFileStorage.java index eca38fb..122697b 100644 --- a/src/main/java/com/faris/kingkits/storage/FlatFileStorage.java +++ b/src/main/java/com/faris/kingkits/storage/FlatFileStorage.java @@ -13,11 +13,8 @@ import org.bukkit.util.FileUtil; import java.io.File; -import java.util.HashMap; -import java.util.LinkedHashMap; -import java.util.Map; -import java.util.UUID; -import java.util.logging.Level; +import java.util.*; +import java.util.logging.*; public class FlatFileStorage extends DataStorage { diff --git a/src/main/java/com/faris/kingkits/storage/SQLStorage.java b/src/main/java/com/faris/kingkits/storage/SQLStorage.java index dfcd57c..aea1849 100644 --- a/src/main/java/com/faris/kingkits/storage/SQLStorage.java +++ b/src/main/java/com/faris/kingkits/storage/SQLStorage.java @@ -18,7 +18,7 @@ import org.json.simple.JSONObject; import java.util.*; -import java.util.logging.Level; +import java.util.logging.*; public class SQLStorage extends DataStorage { @@ -26,82 +26,79 @@ public class SQLStorage extends DataStorage { public KitPlayer loadPlayer(final KitPlayer kitPlayer) { if (kitPlayer == null) throw new IllegalArgumentException("Kit player cannot be null!"); try { - Bukkit.getServer().getScheduler().runTaskAsynchronously(KingKits.getInstance(), new Runnable() { - @Override - public void run() { - try { - if (SQLController.getInstance().isEnabled()) { - SQLController.getInstance().openConnection(); + Bukkit.getServer().getScheduler().runTaskAsynchronously(KingKits.getInstance(), () -> { + try { + if (SQLController.getInstance().isEnabled()) { + SQLController.getInstance().openConnection(); - createDefaultTable(); + createDefaultTable(); - StatementSelectTable.Table table = new StatementSelectTable(SQLController.getInstance().getHandler()).setTable(SQLController.getInstance().getPlayersTable()).setWhere("uuid", kitPlayer.getUniqueId()).setRowLimit(1).executeAsTable(); - if (!table.isEmpty()) { - StatementSelectTable.Table.Column columnScore = table.getColumn(0, "score"); - if (columnScore.getValue() instanceof Number) - kitPlayer.setScore(columnScore.asNumber().intValue()); + StatementSelectTable.Table table = new StatementSelectTable(SQLController.getInstance().getHandler()).setTable(SQLController.getInstance().getPlayersTable()).setWhere("uuid", kitPlayer.getUniqueId()).setRowLimit(1).executeAsTable(); + if (!table.isEmpty()) { + StatementSelectTable.Table.Column columnScore = table.getColumn(0, "score"); + if (columnScore.getValue() instanceof Number) + kitPlayer.setScore(columnScore.asNumber().intValue()); - try { - StatementSelectTable.Table.Column columnUnlockedKits = table.getColumn(0, "unlocked"); - if (!columnUnlockedKits.isNull() && !columnUnlockedKits.asString().trim().isEmpty()) { - List unlockedKits = new ArrayList<>(); - JsonArray jsonUnlockedKits = Utilities.getGsonParser().fromJson(columnUnlockedKits.asString(), JsonArray.class); - for (JsonElement jsonUnlockedKit : jsonUnlockedKits) - unlockedKits.add(jsonUnlockedKit.getAsString()); - kitPlayer.setUnlockedKits(unlockedKits); - } - } catch (Exception ex) { - Bukkit.getServer().getLogger().log(Level.WARNING, "Failed to load player " + kitPlayer + "'s unlocked kits", ex); + try { + StatementSelectTable.Table.Column columnUnlockedKits = table.getColumn(0, "unlocked"); + if (!columnUnlockedKits.isNull() && !columnUnlockedKits.asString().trim().isEmpty()) { + List unlockedKits = new ArrayList<>(); + JsonArray jsonUnlockedKits = Utilities.getGsonParser().fromJson(columnUnlockedKits.asString(), JsonArray.class); + for (JsonElement jsonUnlockedKit : jsonUnlockedKits) + unlockedKits.add(jsonUnlockedKit.getAsString()); + kitPlayer.setUnlockedKits(unlockedKits); } + } catch (Exception ex) { + Bukkit.getServer().getLogger().log(Level.WARNING, "Failed to load player " + kitPlayer + "'s unlocked kits", ex); + } - try { - StatementSelectTable.Table.Column columnTimestamps = table.getColumn(0, "timestamps"); - if (!columnTimestamps.isNull() && !columnTimestamps.asString().trim().isEmpty()) { - String strTimestamps = columnTimestamps.asString(); - Map kitTimestamps = new HashMap<>(); - JsonObject jsonTimestamps = Utilities.getGsonParser().fromJson(strTimestamps, JsonObject.class); - for (Map.Entry jsonKit : jsonTimestamps.entrySet()) { - if (jsonKit.getValue().isJsonPrimitive()) { - kitTimestamps.put(jsonKit.getKey(), jsonKit.getValue().getAsLong()); - } + try { + StatementSelectTable.Table.Column columnTimestamps = table.getColumn(0, "timestamps"); + if (!columnTimestamps.isNull() && !columnTimestamps.asString().trim().isEmpty()) { + String strTimestamps = columnTimestamps.asString(); + Map kitTimestamps = new HashMap<>(); + JsonObject jsonTimestamps = Utilities.getGsonParser().fromJson(strTimestamps, JsonObject.class); + for (Map.Entry jsonKit : jsonTimestamps.entrySet()) { + if (jsonKit.getValue().isJsonPrimitive()) { + kitTimestamps.put(jsonKit.getKey(), jsonKit.getValue().getAsLong()); } - kitPlayer.setKitTimestamps(kitTimestamps); } - } catch (Exception ex) { - Bukkit.getServer().getLogger().log(Level.WARNING, "Failed to load player " + kitPlayer + "'s kit timestamps", ex); + kitPlayer.setKitTimestamps(kitTimestamps); } + } catch (Exception ex) { + Bukkit.getServer().getLogger().log(Level.WARNING, "Failed to load player " + kitPlayer + "'s kit timestamps", ex); + } - try { - StatementSelectTable.Table.Column columnKits = table.getColumn(0, "kits"); - if (!columnKits.isNull() && !columnKits.asString().trim().isEmpty()) { - String strColumnKits = columnKits.asString(); - Map playerKits = new LinkedHashMap<>(); - JsonObject jsonKits = Utilities.getGsonParser().fromJson(strColumnKits, JsonObject.class); - for (Map.Entry jsonKit : jsonKits.entrySet()) { - if (jsonKit.getValue().isJsonPrimitive()) { - // JsonObject jsonPlayerKit = Utilities.getGsonParser().fromJson(jsonKit.getValue().getAsJsonPrimitive().getAsString(), JsonObject.class); - // Kit playerKit = Kit.deserialize(JsonUtilities.toMap(jsonPlayerKit)); // Utilities.getGsonParser().fromJson(jsonKit.getValue().getAsJsonPrimitive(), Kit.class); - Kit playerKit = Kit.deserializeFromJson(jsonKit.getValue().getAsJsonPrimitive().getAsString()); - if (playerKit != null) playerKits.put(playerKit.getName(), playerKit); - } + try { + StatementSelectTable.Table.Column columnKits = table.getColumn(0, "kits"); + if (!columnKits.isNull() && !columnKits.asString().trim().isEmpty()) { + String strColumnKits = columnKits.asString(); + Map playerKits = new LinkedHashMap<>(); + JsonObject jsonKits = Utilities.getGsonParser().fromJson(strColumnKits, JsonObject.class); + for (Map.Entry jsonKit : jsonKits.entrySet()) { + if (jsonKit.getValue().isJsonPrimitive()) { + // JsonObject jsonPlayerKit = Utilities.getGsonParser().fromJson(jsonKit.getValue().getAsJsonPrimitive().getAsString(), JsonObject.class); + // Kit playerKit = Kit.deserialize(JsonUtilities.toMap(jsonPlayerKit)); // Utilities.getGsonParser().fromJson(jsonKit.getValue().getAsJsonPrimitive(), Kit.class); + Kit playerKit = Kit.deserializeFromJson(jsonKit.getValue().getAsJsonPrimitive().getAsString()); + if (playerKit != null) playerKits.put(playerKit.getName(), playerKit); } - kitPlayer.setKits(playerKits); } - } catch (Exception ex) { - Bukkit.getServer().getLogger().log(Level.WARNING, "Failed to load player " + kitPlayer + "'s kits", ex); + kitPlayer.setKits(playerKits); } + } catch (Exception ex) { + Bukkit.getServer().getLogger().log(Level.WARNING, "Failed to load player " + kitPlayer + "'s kits", ex); } - kitPlayer.setLoaded(true); - kitPlayer.update(); - } else { - setInstance(DataStorageType.FILE); - getInstance().loadPlayer(kitPlayer); } - } catch (Exception ex) { - Bukkit.getServer().getLogger().log(Level.WARNING, "Failed to load player " + kitPlayer, ex); kitPlayer.setLoaded(true); kitPlayer.update(); + } else { + createInstance(DataStorageType.FILE); + getInstance().loadPlayer(kitPlayer); } + } catch (Exception ex) { + Bukkit.getServer().getLogger().log(Level.WARNING, "Failed to load player " + kitPlayer, ex); + kitPlayer.setLoaded(true); + kitPlayer.update(); } }); } catch (Exception ex) { @@ -117,70 +114,67 @@ public OfflineKitPlayer loadOfflinePlayer(final String playerName) { if (playerName == null) throw new IllegalArgumentException("Player username cannot be null!"); final OfflineKitPlayer offlineKitPlayer = new OfflineKitPlayer(playerName); try { - Bukkit.getServer().getScheduler().runTaskAsynchronously(KingKits.getInstance(), new Runnable() { - @Override - public void run() { - try { - if (SQLController.getInstance().isEnabled()) { - SQLController.getInstance().openConnection(); + Bukkit.getServer().getScheduler().runTaskAsynchronously(KingKits.getInstance(), () -> { + try { + if (SQLController.getInstance().isEnabled()) { + SQLController.getInstance().openConnection(); - createDefaultTable(); - StatementSelectTable.Table table = new StatementSelectTable(SQLController.getInstance().getHandler()).setTable(SQLController.getInstance().getPlayersTable()).setWhere("username", offlineKitPlayer.getUsername(), true).setRowLimit(1).executeAsTable(); - if (!table.isEmpty()) { - StatementSelectTable.Table.Column columnUUID = table.getColumn(0, "uuid"); - if (Utilities.isUUID(columnUUID.getValue())) - offlineKitPlayer.setUniqueId(UUID.fromString(columnUUID.asString())); + createDefaultTable(); + StatementSelectTable.Table table = new StatementSelectTable(SQLController.getInstance().getHandler()).setTable(SQLController.getInstance().getPlayersTable()).setWhere("username", offlineKitPlayer.getUsername(), true).setRowLimit(1).executeAsTable(); + if (!table.isEmpty()) { + StatementSelectTable.Table.Column columnUUID = table.getColumn(0, "uuid"); + if (Utilities.isUUID(columnUUID.getValue())) + offlineKitPlayer.setUniqueId(UUID.fromString(columnUUID.asString())); - StatementSelectTable.Table.Column columnScore = table.getColumn(0, "score"); - if (columnScore.getValue() instanceof Number) - offlineKitPlayer.setScore(columnScore.asNumber().intValue()); + StatementSelectTable.Table.Column columnScore = table.getColumn(0, "score"); + if (columnScore.getValue() instanceof Number) + offlineKitPlayer.setScore(columnScore.asNumber().intValue()); - StatementSelectTable.Table.Column columnUnlockedKits = table.getColumn(0, "unlocked"); - if (!columnUnlockedKits.isNull() && !columnUnlockedKits.asString().trim().isEmpty()) { - List unlockedKits = new ArrayList<>(); - JsonArray jsonUnlockedKits = Utilities.getGsonParser().fromJson(columnUnlockedKits.asString(), JsonArray.class); - for (JsonElement jsonUnlockedKit : jsonUnlockedKits) - unlockedKits.add(jsonUnlockedKit.getAsString()); - offlineKitPlayer.setUnlockedKits(unlockedKits); - } + StatementSelectTable.Table.Column columnUnlockedKits = table.getColumn(0, "unlocked"); + if (!columnUnlockedKits.isNull() && !columnUnlockedKits.asString().trim().isEmpty()) { + List unlockedKits = new ArrayList<>(); + JsonArray jsonUnlockedKits = Utilities.getGsonParser().fromJson(columnUnlockedKits.asString(), JsonArray.class); + for (JsonElement jsonUnlockedKit : jsonUnlockedKits) + unlockedKits.add(jsonUnlockedKit.getAsString()); + offlineKitPlayer.setUnlockedKits(unlockedKits); + } - StatementSelectTable.Table.Column columnTimestamps = table.getColumn(0, "timestamps"); - if (!columnTimestamps.isNull() && !columnTimestamps.asString().trim().isEmpty()) { - String strTimestamps = columnTimestamps.asString(); - Map kitTimestamps = new HashMap<>(); - JsonObject jsonTimestamps = Utilities.getGsonParser().fromJson(strTimestamps, JsonObject.class); - for (Map.Entry jsonKit : jsonTimestamps.entrySet()) { - if (jsonKit.getValue().isJsonPrimitive()) { - kitTimestamps.put(jsonKit.getKey(), jsonKit.getValue().getAsLong()); - } + StatementSelectTable.Table.Column columnTimestamps = table.getColumn(0, "timestamps"); + if (!columnTimestamps.isNull() && !columnTimestamps.asString().trim().isEmpty()) { + String strTimestamps = columnTimestamps.asString(); + Map kitTimestamps = new HashMap<>(); + JsonObject jsonTimestamps = Utilities.getGsonParser().fromJson(strTimestamps, JsonObject.class); + for (Map.Entry jsonKit : jsonTimestamps.entrySet()) { + if (jsonKit.getValue().isJsonPrimitive()) { + kitTimestamps.put(jsonKit.getKey(), jsonKit.getValue().getAsLong()); } - offlineKitPlayer.setKitTimestamps(kitTimestamps); } + offlineKitPlayer.setKitTimestamps(kitTimestamps); + } - StatementSelectTable.Table.Column columnKits = table.getColumn(0, "kits"); - if (!columnKits.isNull() && !columnKits.asString().trim().isEmpty()) { - String strColumnKits = columnKits.asString(); - Map playerKits = new LinkedHashMap<>(); - JsonObject jsonKits = Utilities.getGsonParser().fromJson(strColumnKits, JsonObject.class); - for (Map.Entry jsonKit : jsonKits.entrySet()) { - if (jsonKit.getValue().isJsonPrimitive()) { - JsonObject jsonPlayerKit = Utilities.getGsonParser().fromJson(jsonKit.getValue().getAsJsonPrimitive().getAsString(), JsonObject.class); - Kit playerKit = Kit.deserialize(JsonUtilities.toMap(jsonPlayerKit)); - if (playerKit != null) playerKits.put(playerKit.getName(), playerKit); - } + StatementSelectTable.Table.Column columnKits = table.getColumn(0, "kits"); + if (!columnKits.isNull() && !columnKits.asString().trim().isEmpty()) { + String strColumnKits = columnKits.asString(); + Map playerKits = new LinkedHashMap<>(); + JsonObject jsonKits = Utilities.getGsonParser().fromJson(strColumnKits, JsonObject.class); + for (Map.Entry jsonKit : jsonKits.entrySet()) { + if (jsonKit.getValue().isJsonPrimitive()) { + JsonObject jsonPlayerKit = Utilities.getGsonParser().fromJson(jsonKit.getValue().getAsJsonPrimitive().getAsString(), JsonObject.class); + Kit playerKit = Kit.deserialize(JsonUtilities.toMap(jsonPlayerKit)); + if (playerKit != null) playerKits.put(playerKit.getName(), playerKit); } - offlineKitPlayer.setKits(playerKits); } + offlineKitPlayer.setKits(playerKits); } - offlineKitPlayer.setLoaded(true); - } else { - setInstance(DataStorageType.FILE); - getInstance().loadOfflinePlayer(playerName); } - } catch (Exception ex) { - Bukkit.getServer().getLogger().log(Level.WARNING, "Failed to load offline player " + offlineKitPlayer, ex); offlineKitPlayer.setLoaded(true); + } else { + createInstance(DataStorageType.FILE); + getInstance().loadOfflinePlayer(playerName); } + } catch (Exception ex) { + Bukkit.getServer().getLogger().log(Level.WARNING, "Failed to load offline player " + offlineKitPlayer, ex); + offlineKitPlayer.setLoaded(true); } }); } catch (Exception ex) { @@ -195,70 +189,67 @@ public OfflineKitPlayer loadOfflinePlayer(final UUID playerUUID) { if (playerUUID == null) throw new IllegalArgumentException("Player UUID cannot be null!"); final OfflineKitPlayer offlineKitPlayer = new OfflineKitPlayer(playerUUID); try { - Bukkit.getServer().getScheduler().runTaskAsynchronously(KingKits.getInstance(), new Runnable() { - @Override - public void run() { - try { - if (SQLController.getInstance().isEnabled()) { - SQLController.getInstance().openConnection(); + Bukkit.getServer().getScheduler().runTaskAsynchronously(KingKits.getInstance(), () -> { + try { + if (SQLController.getInstance().isEnabled()) { + SQLController.getInstance().openConnection(); - createDefaultTable(); - StatementSelectTable.Table table = new StatementSelectTable(SQLController.getInstance().getHandler()).setTable(SQLController.getInstance().getPlayersTable()).setWhere("uuid", offlineKitPlayer.getUniqueId()).setRowLimit(1).executeAsTable(); - if (!table.isEmpty()) { - StatementSelectTable.Table.Column columnUsername = table.getColumn(0, "username"); - if (!columnUsername.isNull()) - offlineKitPlayer.setUsername(columnUsername.asString()); + createDefaultTable(); + StatementSelectTable.Table table = new StatementSelectTable(SQLController.getInstance().getHandler()).setTable(SQLController.getInstance().getPlayersTable()).setWhere("uuid", offlineKitPlayer.getUniqueId()).setRowLimit(1).executeAsTable(); + if (!table.isEmpty()) { + StatementSelectTable.Table.Column columnUsername = table.getColumn(0, "username"); + if (!columnUsername.isNull()) + offlineKitPlayer.setUsername(columnUsername.asString()); - StatementSelectTable.Table.Column columnScore = table.getColumn(0, "score"); - if (columnScore.getValue() instanceof Number) - offlineKitPlayer.setScore(columnScore.asNumber().intValue()); + StatementSelectTable.Table.Column columnScore = table.getColumn(0, "score"); + if (columnScore.getValue() instanceof Number) + offlineKitPlayer.setScore(columnScore.asNumber().intValue()); - StatementSelectTable.Table.Column columnUnlockedKits = table.getColumn(0, "unlocked"); - if (!columnUnlockedKits.isNull() && !columnUnlockedKits.asString().trim().isEmpty()) { - List unlockedKits = new ArrayList<>(); - JsonArray jsonUnlockedKits = Utilities.getGsonParser().fromJson(columnUnlockedKits.asString(), JsonArray.class); - for (JsonElement jsonUnlockedKit : jsonUnlockedKits) - unlockedKits.add(jsonUnlockedKit.getAsString()); - offlineKitPlayer.setUnlockedKits(unlockedKits); - } + StatementSelectTable.Table.Column columnUnlockedKits = table.getColumn(0, "unlocked"); + if (!columnUnlockedKits.isNull() && !columnUnlockedKits.asString().trim().isEmpty()) { + List unlockedKits = new ArrayList<>(); + JsonArray jsonUnlockedKits = Utilities.getGsonParser().fromJson(columnUnlockedKits.asString(), JsonArray.class); + for (JsonElement jsonUnlockedKit : jsonUnlockedKits) + unlockedKits.add(jsonUnlockedKit.getAsString()); + offlineKitPlayer.setUnlockedKits(unlockedKits); + } - StatementSelectTable.Table.Column columnTimestamps = table.getColumn(0, "timestamps"); - if (!columnTimestamps.isNull() && !columnTimestamps.asString().trim().isEmpty()) { - String strTimestamps = columnTimestamps.asString(); - Map kitTimestamps = new HashMap<>(); - JsonObject jsonTimestamps = Utilities.getGsonParser().fromJson(strTimestamps, JsonObject.class); - for (Map.Entry jsonKit : jsonTimestamps.entrySet()) { - if (jsonKit.getValue().isJsonPrimitive()) { - kitTimestamps.put(jsonKit.getKey(), jsonKit.getValue().getAsLong()); - } + StatementSelectTable.Table.Column columnTimestamps = table.getColumn(0, "timestamps"); + if (!columnTimestamps.isNull() && !columnTimestamps.asString().trim().isEmpty()) { + String strTimestamps = columnTimestamps.asString(); + Map kitTimestamps = new HashMap<>(); + JsonObject jsonTimestamps = Utilities.getGsonParser().fromJson(strTimestamps, JsonObject.class); + for (Map.Entry jsonKit : jsonTimestamps.entrySet()) { + if (jsonKit.getValue().isJsonPrimitive()) { + kitTimestamps.put(jsonKit.getKey(), jsonKit.getValue().getAsLong()); } - offlineKitPlayer.setKitTimestamps(kitTimestamps); } + offlineKitPlayer.setKitTimestamps(kitTimestamps); + } - StatementSelectTable.Table.Column columnKits = table.getColumn(0, "kits"); - if (!columnKits.isNull() && !columnKits.asString().trim().isEmpty()) { - String strColumnKits = columnKits.asString(); - Map playerKits = new LinkedHashMap<>(); - JsonObject jsonKits = Utilities.getGsonParser().fromJson(strColumnKits, JsonObject.class); - for (Map.Entry jsonKit : jsonKits.entrySet()) { - if (jsonKit.getValue().isJsonPrimitive()) { - JsonObject jsonPlayerKit = Utilities.getGsonParser().fromJson(jsonKit.getValue().getAsJsonPrimitive().getAsString(), JsonObject.class); - Kit playerKit = Kit.deserialize(JsonUtilities.toMap(jsonPlayerKit)); - if (playerKit != null) playerKits.put(playerKit.getName(), playerKit); - } + StatementSelectTable.Table.Column columnKits = table.getColumn(0, "kits"); + if (!columnKits.isNull() && !columnKits.asString().trim().isEmpty()) { + String strColumnKits = columnKits.asString(); + Map playerKits = new LinkedHashMap<>(); + JsonObject jsonKits = Utilities.getGsonParser().fromJson(strColumnKits, JsonObject.class); + for (Map.Entry jsonKit : jsonKits.entrySet()) { + if (jsonKit.getValue().isJsonPrimitive()) { + JsonObject jsonPlayerKit = Utilities.getGsonParser().fromJson(jsonKit.getValue().getAsJsonPrimitive().getAsString(), JsonObject.class); + Kit playerKit = Kit.deserialize(JsonUtilities.toMap(jsonPlayerKit)); + if (playerKit != null) playerKits.put(playerKit.getName(), playerKit); } - offlineKitPlayer.setKits(playerKits); } + offlineKitPlayer.setKits(playerKits); } - offlineKitPlayer.setLoaded(true); - } else { - setInstance(DataStorageType.FILE); - getInstance().loadOfflinePlayer(playerUUID); } - } catch (Exception ex) { - Bukkit.getServer().getLogger().log(Level.WARNING, "Failed to load offline player " + offlineKitPlayer, ex); offlineKitPlayer.setLoaded(true); + } else { + createInstance(DataStorageType.FILE); + getInstance().loadOfflinePlayer(playerUUID); } + } catch (Exception ex) { + Bukkit.getServer().getLogger().log(Level.WARNING, "Failed to load offline player " + offlineKitPlayer, ex); + offlineKitPlayer.setLoaded(true); } }); } catch (Exception ex) { @@ -279,61 +270,58 @@ public void savePlayer(final OfflineKitPlayer offlineKitPlayer, final Runnable r if (!offlineKitPlayer.hasBeenModified()) return; final KitPlayer kitPlayer = offlineKitPlayer instanceof KitPlayer ? (KitPlayer) offlineKitPlayer : null; try { - Bukkit.getServer().getScheduler().runTaskAsynchronously(KingKits.getInstance(), new Runnable() { - @Override - public void run() { - try { - if (SQLController.getInstance().isEnabled()) { - SQLController.getInstance().openConnection(); + Bukkit.getServer().getScheduler().runTaskAsynchronously(KingKits.getInstance(), () -> { + try { + if (SQLController.getInstance().isEnabled()) { + SQLController.getInstance().openConnection(); - createDefaultTable(); + createDefaultTable(); - String strUUID = offlineKitPlayer.getUniqueId().toString(); - String strUsername = offlineKitPlayer.getUsername() != null ? offlineKitPlayer.getUsername() : ""; - int score = offlineKitPlayer.getScore(); - List unlockedKits = offlineKitPlayer.getUnlockedKits(); - Map kitTimestamps = offlineKitPlayer.getKitTimestamps(); - Map playerKits = offlineKitPlayer.getKits(); + String strUUID = offlineKitPlayer.getUniqueId().toString(); + String strUsername = offlineKitPlayer.getUsername() != null ? offlineKitPlayer.getUsername() : ""; + int score = offlineKitPlayer.getScore(); + List unlockedKits = offlineKitPlayer.getUnlockedKits(); + Map kitTimestamps = offlineKitPlayer.getKitTimestamps(); + Map playerKits = offlineKitPlayer.getKits(); - if (offlineKitPlayer.getUniqueId() != null && new StatementSelectTable(SQLController.getInstance().getHandler()).setTable(SQLController.getInstance().getPlayersTable()).setWhere("uuid", offlineKitPlayer.getUniqueId()).setRowLimit(1).executeAsTable().isEmpty()) { - StatementInsertTable statementInsertTable = new StatementInsertTable(SQLController.getInstance().getHandler()).setTable(SQLController.getInstance().getPlayersTable()).setColumns(new StatementInsertTable.Column("uuid", strUUID), new StatementInsertTable.Column("username", strUsername)); - statementInsertTable.addColumns(new StatementInsertTable.Column("score", score)); - if (!unlockedKits.isEmpty()) - statementInsertTable.addColumns(new StatementInsertTable.Column("unlocked", JSONObject.escape(Utilities.getGsonParser().toJson(JsonUtilities.fromArray(unlockedKits))))); - if (!kitTimestamps.isEmpty()) - statementInsertTable.addColumns(new StatementInsertTable.Column("timestamps", JSONObject.escape(Utilities.getGsonParser().toJson(JsonUtilities.fromMap(kitTimestamps))))); - if (!playerKits.isEmpty()) - statementInsertTable.addColumns(new StatementInsertTable.Column("kits", JSONObject.escape(Utilities.getGsonParser().toJson(JsonUtilities.fromMap(playerKits))))); - statementInsertTable.execute(); + if (offlineKitPlayer.getUniqueId() != null && new StatementSelectTable(SQLController.getInstance().getHandler()).setTable(SQLController.getInstance().getPlayersTable()).setWhere("uuid", offlineKitPlayer.getUniqueId()).setRowLimit(1).executeAsTable().isEmpty()) { + StatementInsertTable statementInsertTable = new StatementInsertTable(SQLController.getInstance().getHandler()).setTable(SQLController.getInstance().getPlayersTable()).setColumns(new StatementInsertTable.Column("uuid", strUUID), new StatementInsertTable.Column("username", strUsername)); + statementInsertTable.addColumns(new StatementInsertTable.Column("score", score)); + if (!unlockedKits.isEmpty()) + statementInsertTable.addColumns(new StatementInsertTable.Column("unlocked", JSONObject.escape(Utilities.getGsonParser().toJson(JsonUtilities.fromArray(unlockedKits))))); + if (!kitTimestamps.isEmpty()) + statementInsertTable.addColumns(new StatementInsertTable.Column("timestamps", JSONObject.escape(Utilities.getGsonParser().toJson(JsonUtilities.fromMap(kitTimestamps))))); + if (!playerKits.isEmpty()) + statementInsertTable.addColumns(new StatementInsertTable.Column("kits", JSONObject.escape(Utilities.getGsonParser().toJson(JsonUtilities.fromMap(playerKits))))); + statementInsertTable.execute(); + } else { + StatementUpdateTable statementUpdateTable = new StatementUpdateTable(SQLController.getInstance().getHandler()).setTable(SQLController.getInstance().getPlayersTable()); + if (offlineKitPlayer.getUniqueId() != null) { + statementUpdateTable.setWhere("uuid", strUUID); + if (offlineKitPlayer.getUsername() != null) + statementUpdateTable.setColumns(new StatementUpdateTable.Column("username", offlineKitPlayer.getUsername())); + } else if (offlineKitPlayer.getUsername() != null) { + statementUpdateTable.setWhere("username", strUsername); } else { - StatementUpdateTable statementUpdateTable = new StatementUpdateTable(SQLController.getInstance().getHandler()).setTable(SQLController.getInstance().getPlayersTable()); - if (offlineKitPlayer.getUniqueId() != null) { - statementUpdateTable.setWhere("uuid", strUUID); - if (offlineKitPlayer.getUsername() != null) - statementUpdateTable.setColumns(new StatementUpdateTable.Column("username", offlineKitPlayer.getUsername())); - } else if (offlineKitPlayer.getUsername() != null) { - statementUpdateTable.setWhere("username", strUsername); - } else { - return; - } - statementUpdateTable.addColumns(new StatementUpdateTable.Column("score", score)); - statementUpdateTable.addColumns(new StatementUpdateTable.Column("unlocked", !unlockedKits.isEmpty() ? JSONObject.escape(Utilities.getGsonParser().toJson(JsonUtilities.fromArray(unlockedKits))) : "")); - statementUpdateTable.addColumns(new StatementUpdateTable.Column("timestamps", !kitTimestamps.isEmpty() ? JSONObject.escape(Utilities.getGsonParser().toJson(JsonUtilities.fromMap(kitTimestamps))) : "")); - statementUpdateTable.addColumns(new StatementUpdateTable.Column("kits", !playerKits.isEmpty() ? JSONObject.escape(Utilities.getGsonParser().toJson(JsonUtilities.fromMap(playerKits))) : "")); - statementUpdateTable.execute(); + return; } - if (runOnComplete != null) runOnComplete.run(); - } else { - setInstance(DataStorageType.FILE); - getInstance().savePlayer(offlineKitPlayer); - if (runOnComplete != null) runOnComplete.run(); + statementUpdateTable.addColumns(new StatementUpdateTable.Column("score", score)); + statementUpdateTable.addColumns(new StatementUpdateTable.Column("unlocked", !unlockedKits.isEmpty() ? JSONObject.escape(Utilities.getGsonParser().toJson(JsonUtilities.fromArray(unlockedKits))) : "")); + statementUpdateTable.addColumns(new StatementUpdateTable.Column("timestamps", !kitTimestamps.isEmpty() ? JSONObject.escape(Utilities.getGsonParser().toJson(JsonUtilities.fromMap(kitTimestamps))) : "")); + statementUpdateTable.addColumns(new StatementUpdateTable.Column("kits", !playerKits.isEmpty() ? JSONObject.escape(Utilities.getGsonParser().toJson(JsonUtilities.fromMap(playerKits))) : "")); + statementUpdateTable.execute(); } - } catch (Exception ex) { - Bukkit.getServer().getLogger().log(Level.WARNING, "Failed to save" + (offlineKitPlayer instanceof KitPlayer ? " " : " offline ") + "player " + offlineKitPlayer, ex); if (runOnComplete != null) runOnComplete.run(); - } finally { - if (SQLController.getInstance().isEnabled()) SQLController.getInstance().closeConnection(); + } else { + createInstance(DataStorageType.FILE); + getInstance().savePlayer(offlineKitPlayer); + if (runOnComplete != null) runOnComplete.run(); } + } catch (Exception ex) { + Bukkit.getServer().getLogger().log(Level.WARNING, "Failed to save" + (offlineKitPlayer instanceof KitPlayer ? " " : " offline ") + "player " + offlineKitPlayer, ex); + if (runOnComplete != null) runOnComplete.run(); + } finally { + if (SQLController.getInstance().isEnabled()) SQLController.getInstance().closeConnection(); } }); } catch (Exception ex) { diff --git a/src/main/java/com/faris/kingkits/updater/BukkitUpdater.java b/src/main/java/com/faris/kingkits/updater/BukkitUpdater.java index 92df8fb..31f5c44 100644 --- a/src/main/java/com/faris/kingkits/updater/BukkitUpdater.java +++ b/src/main/java/com/faris/kingkits/updater/BukkitUpdater.java @@ -11,10 +11,9 @@ import java.net.MalformedURLException; import java.net.URL; import java.net.URLConnection; -import java.util.Enumeration; -import java.util.logging.Level; -import java.util.zip.ZipEntry; -import java.util.zip.ZipFile; +import java.util.*; +import java.util.logging.*; +import java.util.zip.*; /** * Check dev.bukkit.org to find updates for a given plugin, and download the updates if needed. @@ -24,7 +23,7 @@ */ public class BukkitUpdater { - /* Constants */ + /* Constants */ // Remote file's title private static final String TITLE_VALUE = "name"; @@ -57,7 +56,7 @@ public class BukkitUpdater { // Default disable value in config private static final boolean DISABLE_DEFAULT = false; - /* User-provided variables */ + /* User-provided variables */ // Plugin running Updater private final Plugin plugin; @@ -76,14 +75,14 @@ public class BukkitUpdater { // BukkitDev ServerMods API key private String apiKey = null; - /* Collected from Curse API */ + /* Collected from Curse API */ private String versionName; private String versionLink; private String versionType; private String versionGameVersion; - /* Update process variables */ + /* Update process variables */ // Connection to RSS private URL url; diff --git a/src/main/java/com/faris/kingkits/updater/SpigotUpdater.java b/src/main/java/com/faris/kingkits/updater/SpigotUpdater.java index 7626c1b..8810f06 100644 --- a/src/main/java/com/faris/kingkits/updater/SpigotUpdater.java +++ b/src/main/java/com/faris/kingkits/updater/SpigotUpdater.java @@ -8,17 +8,12 @@ import java.net.HttpURLConnection; import java.net.URL; -/** - * @author PatoTheBest - */ public class SpigotUpdater { - private final String API_KEY = "98BE0FE67F88AB82B4C197FAF1DC3B69206EFDCC4D3B80FC83A00037510B99B4"; - private final String REQUEST_METHOD = "POST"; + private final String REQUEST_METHOD = "GET"; private String RESOURCE_ID = ""; - private final String HOST = "http://www.spigotmc.org"; - private final String QUERY = "/api/general.php"; - private String WRITE_STRING; + private final String HOST = "https://api.spigotmc.org"; + private final String QUERY = "/legacy/update.php"; private String version; private String oldVersion; @@ -37,7 +32,7 @@ public enum UpdateResult { } public SpigotUpdater(JavaPlugin plugin, Integer resourceId, boolean disabled) { - RESOURCE_ID = resourceId + ""; + RESOURCE_ID = String.valueOf(resourceId); this.oldVersion = plugin.getDescription().getVersion(); if (disabled) { @@ -46,13 +41,12 @@ public SpigotUpdater(JavaPlugin plugin, Integer resourceId, boolean disabled) { } try { - this.connection = (HttpURLConnection) new URL(HOST + QUERY).openConnection(); - } catch (IOException e) { + this.connection = (HttpURLConnection) new URL(HOST + QUERY + "?resource=" + RESOURCE_ID).openConnection(); + } catch (Exception e) { this.result = UpdateResult.FAIL_SPIGOT; return; } - WRITE_STRING = "key=" + API_KEY + "&resource=" + RESOURCE_ID; this.run(); } @@ -72,7 +66,6 @@ private void run() { this.connection.setDoOutput(true); try { this.connection.setRequestMethod(REQUEST_METHOD); - this.connection.getOutputStream().write(WRITE_STRING.getBytes("UTF-8")); } catch (IOException e) { this.result = UpdateResult.FAIL_SPIGOT; } diff --git a/src/main/java/mkremins/fanciful/FancyMessage.java b/src/main/java/mkremins/fanciful/FancyMessage.java index 4830b09..21d5438 100644 --- a/src/main/java/mkremins/fanciful/FancyMessage.java +++ b/src/main/java/mkremins/fanciful/FancyMessage.java @@ -16,7 +16,7 @@ import java.io.IOException; import java.io.StringWriter; import java.util.*; -import java.util.logging.Level; +import java.util.logging.*; import static mkremins.fanciful.TextualComponent.rawText; diff --git a/src/main/java/mkremins/fanciful/JsonRepresentedObject.java b/src/main/java/mkremins/fanciful/JsonRepresentedObject.java index e32a479..4d8c672 100644 --- a/src/main/java/mkremins/fanciful/JsonRepresentedObject.java +++ b/src/main/java/mkremins/fanciful/JsonRepresentedObject.java @@ -15,6 +15,6 @@ interface JsonRepresentedObject { * @param writer The JSON writer which will receive the object. * @throws IOException If an error occurs writing to the stream. */ - public void writeJson(JsonWriter writer) throws IOException; + void writeJson(JsonWriter writer) throws IOException; } diff --git a/src/main/java/mkremins/fanciful/JsonString.java b/src/main/java/mkremins/fanciful/JsonString.java index dd42e71..c97a0de 100644 --- a/src/main/java/mkremins/fanciful/JsonString.java +++ b/src/main/java/mkremins/fanciful/JsonString.java @@ -4,8 +4,7 @@ import org.bukkit.configuration.serialization.ConfigurationSerializable; import java.io.IOException; -import java.util.HashMap; -import java.util.Map; +import java.util.*; /** * Represents a JSON string value. diff --git a/src/main/java/mkremins/fanciful/MessagePart.java b/src/main/java/mkremins/fanciful/MessagePart.java index d8afece..845914a 100644 --- a/src/main/java/mkremins/fanciful/MessagePart.java +++ b/src/main/java/mkremins/fanciful/MessagePart.java @@ -9,10 +9,8 @@ import org.bukkit.configuration.serialization.ConfigurationSerialization; import java.io.IOException; -import java.util.ArrayList; -import java.util.HashMap; -import java.util.Map; -import java.util.logging.Level; +import java.util.*; +import java.util.logging.*; /** * Internal class: Represents a component of a JSON-serializable {@link FancyMessage}. diff --git a/src/main/java/mkremins/fanciful/TextualComponent.java b/src/main/java/mkremins/fanciful/TextualComponent.java index 035abd9..5c13f19 100644 --- a/src/main/java/mkremins/fanciful/TextualComponent.java +++ b/src/main/java/mkremins/fanciful/TextualComponent.java @@ -7,8 +7,7 @@ import org.bukkit.configuration.serialization.ConfigurationSerialization; import java.io.IOException; -import java.util.HashMap; -import java.util.Map; +import java.util.*; /** * Represents a textual component of a message part. @@ -71,7 +70,7 @@ static boolean isTextKey(String key) { } static boolean isTranslatableText(TextualComponent component) { - return component instanceof ComplexTextTypeComponent && ((ComplexTextTypeComponent) component).getKey().equals("translate"); + return component instanceof ComplexTextTypeComponent && component.getKey().equals("translate"); } /** @@ -202,7 +201,7 @@ public static ComplexTextTypeComponent deserialize(Map map) { if (valEntry.getKey().equals("key")) { key = (String) valEntry.getValue(); } else if (valEntry.getKey().startsWith("value.")) { - value.put(((String) valEntry.getKey()).substring(6) /* Strips out the value prefix */, valEntry.getValue().toString()); + value.put(valEntry.getKey().substring(6) /* Strips out the value prefix */, valEntry.getValue().toString()); } } return new ComplexTextTypeComponent(key, value); diff --git a/src/main/java/net/amoebaman/util/ArrayWrapper.java b/src/main/java/net/amoebaman/util/ArrayWrapper.java index d080c24..d76bc82 100644 --- a/src/main/java/net/amoebaman/util/ArrayWrapper.java +++ b/src/main/java/net/amoebaman/util/ArrayWrapper.java @@ -3,8 +3,7 @@ import org.apache.commons.lang.Validate; import java.lang.reflect.Array; -import java.util.Arrays; -import java.util.Collection; +import java.util.*; /** * Represents a wrapper around an array class of an arbitrary reference type,