From b07809939dab73aac7e24ebf7764af9c1750f401 Mon Sep 17 00:00:00 2001 From: GeorgH93 Date: Sun, 6 Nov 2016 18:09:23 +0100 Subject: [PATCH] Start the clean up for V2 --- README.md | 2 +- ToDo.txt | 3 + pom.xml | 38 +- resources/lang/de.yml | 32 +- resources/lang/en.yml | 32 +- src/at/pcgamingfreaks/MinePacks/Backpack.java | 10 +- .../MinePacks/Database/Config.java | 5 - .../MinePacks/Database/Database.java | 6 +- .../MinePacks/Database/Files.java | 63 ++-- .../Database/InventorySerializer.java | 4 +- .../MinePacks/Database/Language.java | 87 ++++- .../MinePacks/Database/MySQL.java | 36 +- .../MinePacks/Database/SQL.java | 118 +++--- .../MinePacks/Database/SQLite.java | 36 +- .../MinePacks/EventListener.java | 16 +- .../MinePacks/ItemsCollector.java | 12 +- .../pcgamingfreaks/MinePacks/MinePacks.java | 38 +- .../MinePacks/MinepacksV2IsOut.java | 71 ---- .../pcgamingfreaks/MinePacks/OnCommand.java | 18 +- .../Updater/BukkitUpdateProvider.java | 181 --------- .../MinePacks/Updater/UpdateResult.java | 60 --- .../MinePacks/Updater/Updater.java | 351 ------------------ 22 files changed, 295 insertions(+), 924 deletions(-) create mode 100644 ToDo.txt delete mode 100644 src/at/pcgamingfreaks/MinePacks/MinepacksV2IsOut.java delete mode 100644 src/at/pcgamingfreaks/MinePacks/Updater/BukkitUpdateProvider.java delete mode 100644 src/at/pcgamingfreaks/MinePacks/Updater/UpdateResult.java delete mode 100644 src/at/pcgamingfreaks/MinePacks/Updater/Updater.java diff --git a/README.md b/README.md index 3472926..3cf9594 100644 --- a/README.md +++ b/README.md @@ -7,4 +7,4 @@ [Spigot](https://www.spigotmc.org/resources/minepacks.19286/)
[Dev Bukkit](http://dev.bukkit.org/bukkit-plugins/minepacks/)
[Issue tracker](https://github.com/GeorgH93/Bukkit_Minepacks/issues)
-[Build Server ![Build Status](http://ci.pcgamingfreaks.at/job/Minepacks/badge/icon)](http://ci.pcgamingfreaks.at/job/Minepacks/) \ No newline at end of file +[Build Server ![Build Status](http://ci.pcgamingfreaks.at/job/Minepacks/badge/icon)](http://ci.pcgamingfreaks.at/job/Minepacks%20V2/) \ No newline at end of file diff --git a/ToDo.txt b/ToDo.txt new file mode 100644 index 0000000..5221f04 --- /dev/null +++ b/ToDo.txt @@ -0,0 +1,3 @@ +Multi Page +Port to message API +DB Migration \ No newline at end of file diff --git a/pom.xml b/pom.xml index 7ce3653..c47b304 100644 --- a/pom.xml +++ b/pom.xml @@ -3,7 +3,7 @@ 4.0.0 at.pcgamingfreaks MinePacks - 1.16.3 + 2.0-SNAPSHOT scm:git:git@github.com:GeorgH93/Bukkit_Minepacks.git @@ -31,27 +31,27 @@ - - spigot-repo - https://hub.spigotmc.org/nexus/content/groups/public/ - pcgf-repo http://repo.pcgamingfreaks.at/repository/everything/ + + spigot-nexus + https://hub.spigotmc.org/nexus/content/groups/public/ + org.bukkit bukkit - LATEST + 1.10.2-R0.1-SNAPSHOT provided at.pcgamingfreaks Bukkit_Bungee_PluginLib - LATEST + 1.0-SNAPSHOT com.zaxxer @@ -91,30 +91,6 @@ 1.7 - - org.apache.maven.plugins - maven-shade-plugin - 2.3 - - - package - - shade - - - false - true - - - at.pcgamingfreaks:Bukkit_Bungee_PluginLib - com.zaxxer:HikariCP - org.slf4j:* - - - - - - diff --git a/resources/lang/de.yml b/resources/lang/de.yml index db9ce07..27f5bff 100644 --- a/resources/lang/de.yml +++ b/resources/lang/de.yml @@ -1,24 +1,18 @@ Language: - Console: - Enabled: MinePacks wurde aktiviert. - Disabled: MinePacks wurde deaktiviert. - NotFromConsole: Dieser Befehl kann nicht in der Console ausgeführt werden. - LangUpdated: Die Sprachdatei wurde aktualisiert. - UpdateUUIDs: Beginne die Spielernamen in UUIDs umzuwandeln... - UpdatedUUIDs: 'Es wurden %d Spielernamen in UUIDs umgewandelt.' - MinecraftVersionNotCompatible: "Deine Minecraft Version (MC %1$s) ist mit der Version des Plugins (%2$s) nicht kompatibel! Bitte prüfe ob ein update verfügbar ist!" + NotFromConsole: "&cDieser Befehl kann nicht in der Console ausgeführt werden." Ingame: - NoPermission: 'Dir fehlen die Rechte dafür.' - OwnBackPackClose: 'Rucksack geschlossen.' + NoPermission: "Dir fehlen die Rechte dafür." + OwnBackPackClose: "Rucksack geschlossen." PlayerBackPackClose: "%s's Rucksack geschlossen." - InvalidBackpack: Rucksack fehlerhaft. - BackpackCleaned: Rucksack gelehrt. - Cooldown: 'Bitte warte kurz bis du deinen Rucksack wieder öffnest.' - Description: - Backpack: Öffent deinen Rucksack. - Clean: Leert deinen Rucksack. - CleanOther: Leert den Rucksack eines anderen Spielers. - View: Öffnet den Rucksack eines anderen Spielers. + InvalidBackpack: "Rucksack fehlerhaft." + BackpackCleaned: "Rucksack gelehrt." + Cooldown: "&2Bitte warte kurz bis du deinen Rucksack wieder öffnest." + Commands: + Description: + Backpack: "Öffent deinen Rucksack." + Clean: "Leert deinen Rucksack." + CleanOther: "Leert den Rucksack eines anderen Spielers." + View: "Öffnet den Rucksack eines anderen Spielers." # Language file version. Don't touch it! -Version: 4 \ No newline at end of file +Version: 10 \ No newline at end of file diff --git a/resources/lang/en.yml b/resources/lang/en.yml index 01b594c..cae7396 100644 --- a/resources/lang/en.yml +++ b/resources/lang/en.yml @@ -1,24 +1,18 @@ Language: - Console: - Enabled: MinePacks has been enabled! - Disabled: MinePacks has been disabled. - NotFromConsole: Command not useable from console. - LangUpdated: Language File has been updated. - UpdateUUIDs: Start updating database to UUIDs ... - UpdatedUUIDs: 'Updated %s accounts to UUIDs.' - MinecraftVersionNotCompatible: "Your minecraft version (MC %1$s) is currently not compatible with this plugins version (%2$s). Please check for updates!" + NotFromConsole: "&cCommand not useable from console." Ingame: - NoPermission: You don't have the Permission to do that. - OwnBackPackClose: 'Backpack closed!' + NoPermission: "&cYou don't have the Permission to do that." + OwnBackPackClose: "Backpack closed!" PlayerBackPackClose: "%s's backpack closed!" - InvalidBackpack: Invalid backpack. - BackpackCleaned: Backpack cleaned. - Cooldown: "Please wait till you reopen your backpack." - Description: - Backpack: Opens your backpack. - Clean: Cleans your backpack. - CleanOther: Cleans the backpack of other players. - View: Shows the backpack of other player. + InvalidBackpack: "Invalid backpack." + BackpackCleaned: "Backpack cleaned." + Cooldown: "&2Please wait till you reopen your backpack." + Commands: + Description: + Backpack: "Opens your backpack." + Clean: "Cleans your backpack." + CleanOther: "Cleans the backpack of other players." + View: "Shows the backpack of other player." # Language file version. Don't touch it! -Version: 4 \ No newline at end of file +Version: 10 \ No newline at end of file diff --git a/src/at/pcgamingfreaks/MinePacks/Backpack.java b/src/at/pcgamingfreaks/MinePacks/Backpack.java index 83ec9b5..b57f99a 100644 --- a/src/at/pcgamingfreaks/MinePacks/Backpack.java +++ b/src/at/pcgamingfreaks/MinePacks/Backpack.java @@ -1,5 +1,5 @@ /* - * Copyright (C) 2014-2015 GeorgH93 + * Copyright (C) 2014-2016 GeorgH93 * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by @@ -18,7 +18,7 @@ package at.pcgamingfreaks.MinePacks; import at.pcgamingfreaks.Bukkit.NMSReflection; -import at.pcgamingfreaks.Bukkit.Utils; +import at.pcgamingfreaks.StringUtils; import java.lang.reflect.Field; import java.lang.reflect.Method; @@ -59,7 +59,7 @@ public Backpack(OfflinePlayer owner, int size) public Backpack(OfflinePlayer owner, int Size, int ID) { this.owner = owner; - titleOther = Utils.limitLength(String.format(MinePacks.backpackTitleOther, owner.getName()), 32); + titleOther = StringUtils.limitLength(String.format(MinePacks.getInstance().backpackTitleOther, owner.getName()), 32); bp = Bukkit.createInventory(this, Size, titleOther); size = Size; ownerID = ID; @@ -94,7 +94,7 @@ public void open(Player p, boolean editable) Player player = owner.getPlayer(); if(player != null) { - int size = MinePacks.getBackpackPermSize(player); + int size = MinePacks.getInstance().getBackpackPermSize(player); if(size != bp.getSize()) { List items = setSize(size); @@ -117,7 +117,7 @@ public void open(Player p, boolean editable) try { FIELD_TITLE.setAccessible(true); - FIELD_TITLE.set(METHOD_GET_INVENTORY.invoke(bp), p.equals(owner) ? MinePacks.backpackTitle : titleOther); + FIELD_TITLE.set(METHOD_GET_INVENTORY.invoke(bp), p.equals(owner) ? MinePacks.getInstance().backpackTitle : titleOther); } catch(Exception e) { diff --git a/src/at/pcgamingfreaks/MinePacks/Database/Config.java b/src/at/pcgamingfreaks/MinePacks/Database/Config.java index 73f1af0..bf6846f 100644 --- a/src/at/pcgamingfreaks/MinePacks/Database/Config.java +++ b/src/at/pcgamingfreaks/MinePacks/Database/Config.java @@ -195,9 +195,4 @@ public double getFullInvRadius() { return config.getDouble("full_inventory.collect_radius", 1.5); // in blocks } - - public boolean isV2InfoDisabled() - { - return config.getBoolean("Misc.DisableV2Info", false); - } } \ No newline at end of file diff --git a/src/at/pcgamingfreaks/MinePacks/Database/Database.java b/src/at/pcgamingfreaks/MinePacks/Database/Database.java index ba33073..0e5706f 100644 --- a/src/at/pcgamingfreaks/MinePacks/Database/Database.java +++ b/src/at/pcgamingfreaks/MinePacks/Database/Database.java @@ -27,13 +27,13 @@ public class Database { - protected MinePacks plugin; + protected static final String START_UUID_UPDATE = "Start updating database to UUIDs ...", UUIDS_UPDATED = "Updated %d accounts to UUIDs."; + protected MinePacks plugin; protected boolean useUUIDs, useUUIDSeparators; protected long maxAge; - - private HashMap backpacks = new HashMap<>(); protected InventorySerializer itsSerializer = new InventorySerializer(); + private HashMap backpacks = new HashMap<>(); public Database(MinePacks mp) { diff --git a/src/at/pcgamingfreaks/MinePacks/Database/Files.java b/src/at/pcgamingfreaks/MinePacks/Database/Files.java index 55ebf11..db50a23 100644 --- a/src/at/pcgamingfreaks/MinePacks/Database/Files.java +++ b/src/at/pcgamingfreaks/MinePacks/Database/Files.java @@ -1,5 +1,5 @@ /* - * Copyright (C) 2014-2015 GeorgH93 + * Copyright (C) 2014-2016 GeorgH93 * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by @@ -33,43 +33,50 @@ public class Files extends Database { + private static final String EXT = ".backpack", EXT_REGEX = "\\.backpack"; + private File saveFolder; - private final String ext = ".backpack"; - public Files(MinePacks mp) + public Files(MinePacks plugin) { - super(mp); + super(plugin); maxAge *= 24 * 3600000L; - saveFolder = new File(plugin.getDataFolder(), "backpacks"); + saveFolder = new File(this.plugin.getDataFolder(), "backpacks"); if(!saveFolder.exists()) { - //noinspection ResultOfMethodCallIgnored - saveFolder.mkdirs(); + if(!saveFolder.mkdirs()) + { + plugin.getLogger().warning("Failed to create save folder (" + saveFolder.getAbsolutePath() + ")."); + } } else { - CheckFiles(); + checkFiles(); } } @SuppressWarnings("ResultOfMethodCallIgnored") - private void CheckFiles() + private void checkFiles() { File[] allFiles = saveFolder.listFiles(new BackpackFileFilter()); + if(allFiles == null) return; int len; for (File file : allFiles) { if(maxAge > 0 && (new Date()).getTime() - file.lastModified() > maxAge) // Check if the file is older then x days { - file.delete(); // Delete old files + if(!file.delete()) + { + plugin.getLogger().warning("Failed to delete file (" + file.getAbsolutePath() + ")."); + } continue; // We don't have to check if the file name is correct cause we have the deleted the file } - len = file.getName().length() - ext.length(); + len = file.getName().length() - EXT.length(); if(useUUIDs) // Use UUID-based saving { if(len <= 16) // It's a player name { - file.renameTo(new File(saveFolder, UUIDConverter.getUUIDFromName(file.getName().substring(0, len), true, useUUIDSeparators) + ext)); + file.renameTo(new File(saveFolder, UUIDConverter.getUUIDFromName(file.getName().substring(0, len), true, useUUIDSeparators) + EXT)); } else // It's an UUID { @@ -84,7 +91,7 @@ private void CheckFiles() { if(useUUIDSeparators) { - file.renameTo(new File(saveFolder, file.getName().replaceAll("(\\w{8})(\\w{4})(\\w{4})(\\w{4})(\\w{12})" + ext, "$1-$2-$3-$4-$5" + ext))); + file.renameTo(new File(saveFolder, file.getName().replaceAll("(\\w{8})(\\w{4})(\\w{4})(\\w{4})(\\w{12})" + EXT_REGEX, "$1-$2-$3-$4-$5" + EXT))); } } } @@ -93,7 +100,7 @@ private void CheckFiles() { if(len > 16) // We only have to rename it if it's name is more than 16 chars (minecraft max player name length) { - file.renameTo(new File(saveFolder, UUIDConverter.getNameFromUUID(file.getName().substring(0, len)) + ext)); + file.renameTo(new File(saveFolder, UUIDConverter.getNameFromUUID(file.getName().substring(0, len)) + EXT)); } } } @@ -101,7 +108,7 @@ private void CheckFiles() private String getFileName(OfflinePlayer player) { - return getPlayerNameOrUUID(player) + ext; + return getPlayerNameOrUUID(player) + EXT; } // DB Functions @@ -109,13 +116,11 @@ private String getFileName(OfflinePlayer player) public void saveBackpack(Backpack backpack) { File save = new File(saveFolder, getFileName(backpack.getOwner())); - try + try(FileOutputStream fos = new FileOutputStream(save)) { - FileOutputStream fos = new FileOutputStream(save); fos.write(itsSerializer.getUsedSerializer()); fos.write(itsSerializer.serialize(backpack.getInventory())); fos.flush(); - fos.close(); } catch(Exception e) { @@ -131,13 +136,17 @@ public Backpack loadBackpack(OfflinePlayer player) { if(save.exists()) { - FileInputStream fis = new FileInputStream(save); - int v = fis.read(); - byte[] out = new byte[(int)(save.length()-1)]; - //noinspection ResultOfMethodCallIgnored - fis.read(out); - fis.close(); - return new Backpack(player, itsSerializer.deserialize(out, v), -1); + try(FileInputStream fis = new FileInputStream(save)) + { + int v = fis.read(); + byte[] out = new byte[(int) (save.length() - 1)]; + int c = fis.read(out); + if(v != c) + { + plugin.getLogger().warning("Problem reading file, only read " + c + " of " + v + " bytes."); + } + return new Backpack(player, itsSerializer.deserialize(out, v), -1); + } } } catch(Exception e) @@ -147,14 +156,14 @@ public Backpack loadBackpack(OfflinePlayer player) return null; } - class BackpackFileFilter extends FileFilter implements FilenameFilter + private static class BackpackFileFilter extends FileFilter implements FilenameFilter { String description, extension; public BackpackFileFilter() { description = "Filters for Minepack backpack files."; - extension = "backpack"; + extension = EXT.substring(1); } @Override diff --git a/src/at/pcgamingfreaks/MinePacks/Database/InventorySerializer.java b/src/at/pcgamingfreaks/MinePacks/Database/InventorySerializer.java index 3c2fac4..32c0236 100644 --- a/src/at/pcgamingfreaks/MinePacks/Database/InventorySerializer.java +++ b/src/at/pcgamingfreaks/MinePacks/Database/InventorySerializer.java @@ -27,8 +27,8 @@ public class InventorySerializer { - ItemStackSerializer serializer, baseItemStackSerializer = new BukkitItemStackSerializer(); - int usedSerializer = 1; + private ItemStackSerializer serializer, baseItemStackSerializer = new BukkitItemStackSerializer(); + private int usedSerializer = 1; public InventorySerializer() { diff --git a/src/at/pcgamingfreaks/MinePacks/Database/Language.java b/src/at/pcgamingfreaks/MinePacks/Database/Language.java index c0cf1bc..523c1ab 100644 --- a/src/at/pcgamingfreaks/MinePacks/Database/Language.java +++ b/src/at/pcgamingfreaks/MinePacks/Database/Language.java @@ -17,27 +17,96 @@ package at.pcgamingfreaks.MinePacks.Database; +import at.pcgamingfreaks.yaml.YAML; + +import org.bukkit.ChatColor; import org.bukkit.plugin.java.JavaPlugin; +import java.util.LinkedHashMap; +import java.util.Map; + public class Language extends at.pcgamingfreaks.Bukkit.Language { - private static final int LANG_VERSION = 4; + private static final int LANG_VERSION = 10, UPGRADE_THRESHOLD = 10; public Language(JavaPlugin plugin) { - super(plugin, LANG_VERSION); + super(plugin, LANG_VERSION, UPGRADE_THRESHOLD); } - @SuppressWarnings("SpellCheckingInspection") @Override - protected void doUpdate() + protected void doUpdate() {} + + @Override + protected void doUpgrade(at.pcgamingfreaks.Language oldLang) { - switch(getVersion()) + if(oldLang.getVersion() < UPGRADE_THRESHOLD) { - case 1: lang.set("Language.Ingame.Cooldown", "Please wait till you reopen your backpack."); - case 2: lang.set("Language.Ingame.InvalidBackpack", lang.getString("Language.Ingame.IvalidBackpack", "Invalid backpack.")); - case 3: lang.set("Language.Console.MinecraftVersionNotCompatible", "Your minecraft version (MC %1$s) is currently not compatible with this plugins version (%2$s). Please check for updates!"); - break; + YAML oldYAML = oldLang.getLang(), newYAML = getLang(); + Map simpleConverter = new LinkedHashMap<>(), advancedConverter = new LinkedHashMap<>(); + String[] keys; + String helper; + for(String key : oldYAML.getKeys(true)) + { + try + { + keys = key.split("\\."); + if(keys.length == 3) + { + switch(keys[1]) + { + case "Console": + switch(keys[2]) + { + case "NotFromConsole": advancedConverter.put("Language.NotFromConsole", ChatColor.RED + oldYAML.getString(key)); break; + } + break; + case "Ingame": + switch(keys[3]) + { + case "NoPermission": advancedConverter.put(key, ChatColor.RED + oldYAML.getString(key)); break; + case "OwnBackPackClose": simpleConverter.put(key, key); break; + case "PlayerBackPackClose": simpleConverter.put(key, key); break; + case "InvalidBackpack": simpleConverter.put(key, key); break; + case "BackpackCleaned": simpleConverter.put(key, key); break; + case "Cooldown": advancedConverter.put(key, ChatColor.DARK_GREEN + oldYAML.getString(key)); break; + } + break; + case "Description": + helper = "Language.Commands.Description."; + simpleConverter.put(helper + keys[2], key); + break; + } + } + } + catch(Exception e) + { + plugin.getLogger().warning("Failed to convert the old \"" + key + "\" language value into the corresponding new one."); + e.printStackTrace(); + } + } + + // Patch them into the lang file + try + { + for(Map.Entry entry : advancedConverter.entrySet()) + { + newYAML.set(entry.getKey(), entry.getValue()); + } + for(Map.Entry entry : simpleConverter.entrySet()) + { + newYAML.set(entry.getKey(), oldYAML.getString(entry.getValue())); + } + } + catch(Exception e) + { + plugin.getLogger().warning("Failed to write the old language values into the new language file."); + e.printStackTrace(); + } + } + else + { + super.doUpgrade(oldLang); } } } \ No newline at end of file diff --git a/src/at/pcgamingfreaks/MinePacks/Database/MySQL.java b/src/at/pcgamingfreaks/MinePacks/Database/MySQL.java index 7f70679..9380c13 100644 --- a/src/at/pcgamingfreaks/MinePacks/Database/MySQL.java +++ b/src/at/pcgamingfreaks/MinePacks/Database/MySQL.java @@ -48,8 +48,8 @@ protected HikariConfig getPoolConfig() @Override protected void updateQuerysForDialect() { - Query_DeleteOldBackpacks = "DELETE FROM `{TableBackpacks}` WHERE `{FieldBPLastUpdate}` + INTERVAL {VarMaxAge} day < NOW()"; - Query_UpdateBP = Query_UpdateBP.replaceAll("\\{NOW\\}", "NOW()"); + queryDeleteOldBackpacks = "DELETE FROM `{TableBackpacks}` WHERE `{FieldBPLastUpdate}` + INTERVAL {VarMaxAge} day < NOW()"; + queryUpdateBP = queryUpdateBP.replaceAll("\\{NOW\\}", "NOW()"); } @Override @@ -60,52 +60,52 @@ protected void checkDB() ResultSet res; if(useUUIDs) { - stmt.execute("CREATE TABLE IF NOT EXISTS `" + Table_Players + "` (`" + Field_PlayerID + "` INT UNSIGNED NOT NULL AUTO_INCREMENT,`" + Field_Name + "` CHAR(16) NOT NULL,`" + Field_UUID + "` CHAR(36) UNIQUE, PRIMARY KEY (`" + Field_PlayerID + "`));"); - res = stmt.executeQuery("SELECT * FROM INFORMATION_SCHEMA.COLUMNS WHERE table_name = '" + Table_Players + "' AND COLUMN_NAME = '" + Field_UUID + "';"); + stmt.execute("CREATE TABLE IF NOT EXISTS `" + tablePlayers + "` (`" + fieldPlayerID + "` INT UNSIGNED NOT NULL AUTO_INCREMENT,`" + fieldName + "` CHAR(16) NOT NULL,`" + fieldUUID + "` CHAR(36) UNIQUE, PRIMARY KEY (`" + fieldPlayerID + "`));"); + res = stmt.executeQuery("SELECT * FROM INFORMATION_SCHEMA.COLUMNS WHERE table_name = '" + tablePlayers + "' AND COLUMN_NAME = '" + fieldUUID + "';"); if(!res.next()) { - stmt.execute("ALTER TABLE `" + Table_Players + "` ADD COLUMN `" + Field_UUID + "` CHAR(36) UNIQUE;"); + stmt.execute("ALTER TABLE `" + tablePlayers + "` ADD COLUMN `" + fieldUUID + "` CHAR(36) UNIQUE;"); } res.close(); - res = stmt.executeQuery("SELECT * FROM INFORMATION_SCHEMA.COLUMNS WHERE table_name = '" + Table_Players + "' AND COLUMN_NAME = '" + Field_Name + "' AND COLUMN_KEY='UNI';"); + res = stmt.executeQuery("SELECT * FROM INFORMATION_SCHEMA.COLUMNS WHERE table_name = '" + tablePlayers + "' AND COLUMN_NAME = '" + fieldName + "' AND COLUMN_KEY='UNI';"); if(res.next()) { - stmt.execute("ALTER TABLE `" + Table_Players + "` DROP INDEX `" + Field_Name + "_UNIQUE`;"); + stmt.execute("ALTER TABLE `" + tablePlayers + "` DROP INDEX `" + fieldName + "_UNIQUE`;"); } res.close(); if(useUUIDSeparators) { - res = stmt.executeQuery("SELECT CHARACTER_MAXIMUM_LENGTH FROM INFORMATION_SCHEMA.COLUMNS WHERE table_name = '" + Table_Players + "' AND COLUMN_NAME = '" + Field_UUID + "';"); + res = stmt.executeQuery("SELECT CHARACTER_MAXIMUM_LENGTH FROM INFORMATION_SCHEMA.COLUMNS WHERE table_name = '" + tablePlayers + "' AND COLUMN_NAME = '" + fieldUUID + "';"); if(res.next() && res.getInt(1) < 36) { - stmt.execute("ALTER TABLE `" + Table_Players + "` MODIFY `" + Field_UUID + "` CHAR(36) UNIQUE;"); + stmt.execute("ALTER TABLE `" + tablePlayers + "` MODIFY `" + fieldUUID + "` CHAR(36) UNIQUE;"); } res.close(); } } else { - stmt.execute("CREATE TABLE IF NOT EXISTS `" + Table_Players + "` (`" + Field_PlayerID + "` INT UNSIGNED NOT NULL AUTO_INCREMENT,`" + Field_Name + "` CHAR(16) NOT NULL, PRIMARY KEY (`" + Field_PlayerID + "`));"); - res = stmt.executeQuery("SELECT * FROM INFORMATION_SCHEMA.COLUMNS WHERE table_name = '" + Table_Players + "' AND COLUMN_NAME = '" + Field_Name + "' AND COLUMN_KEY='UNI';"); + stmt.execute("CREATE TABLE IF NOT EXISTS `" + tablePlayers + "` (`" + fieldPlayerID + "` INT UNSIGNED NOT NULL AUTO_INCREMENT,`" + fieldName + "` CHAR(16) NOT NULL, PRIMARY KEY (`" + fieldPlayerID + "`));"); + res = stmt.executeQuery("SELECT * FROM INFORMATION_SCHEMA.COLUMNS WHERE table_name = '" + tablePlayers + "' AND COLUMN_NAME = '" + fieldName + "' AND COLUMN_KEY='UNI';"); if(!res.next()) { - stmt.execute("ALTER TABLE `" + Table_Players + "` ADD UNIQUE INDEX `" + Field_Name + "_UNIQUE` (`" + Field_Name + "` ASC);"); + stmt.execute("ALTER TABLE `" + tablePlayers + "` ADD UNIQUE INDEX `" + fieldName + "_UNIQUE` (`" + fieldName + "` ASC);"); } res.close(); } - stmt.execute("CREATE TABLE IF NOT EXISTS `" + Table_Backpacks + "` (`" + Field_BPOwner + "` INT UNSIGNED NOT NULL, `" + Field_BPITS + "` BLOB, `" - + Field_BPVersion + "` INT DEFAULT 0, " + ((maxAge > 0) ? "`" + Field_BPLastUpdate + "` TIMESTAMP DEFAULT CURRENT_TIMESTAMP, " : "") + "PRIMARY KEY (`" + Field_BPOwner + "`));"); - res = stmt.executeQuery("SELECT * FROM INFORMATION_SCHEMA.COLUMNS WHERE table_name = '" + Table_Backpacks + "' AND COLUMN_NAME = '" + Field_BPVersion + "';"); + stmt.execute("CREATE TABLE IF NOT EXISTS `" + tableBackpacks + "` (`" + fieldBpOwner + "` INT UNSIGNED NOT NULL, `" + fieldBpIts + "` BLOB, `" + + fieldBpVersion + "` INT DEFAULT 0, " + ((maxAge > 0) ? "`" + fieldBpLastUpdate + "` TIMESTAMP DEFAULT CURRENT_TIMESTAMP, " : "") + "PRIMARY KEY (`" + fieldBpOwner + "`));"); + res = stmt.executeQuery("SELECT * FROM INFORMATION_SCHEMA.COLUMNS WHERE table_name = '" + tableBackpacks + "' AND COLUMN_NAME = '" + fieldBpVersion + "';"); if(!res.next()) { - stmt.execute("ALTER TABLE `" + Table_Backpacks + "` ADD COLUMN `" + Field_BPVersion + "` INT DEFAULT 0;"); + stmt.execute("ALTER TABLE `" + tableBackpacks + "` ADD COLUMN `" + fieldBpVersion + "` INT DEFAULT 0;"); } if(maxAge > 0) { - res = stmt.executeQuery("SELECT * FROM INFORMATION_SCHEMA.COLUMNS WHERE table_name = '" + Table_Backpacks + "' AND COLUMN_NAME = '" + Field_BPLastUpdate + "';"); + res = stmt.executeQuery("SELECT * FROM INFORMATION_SCHEMA.COLUMNS WHERE table_name = '" + tableBackpacks + "' AND COLUMN_NAME = '" + fieldBpLastUpdate + "';"); if(!res.next()) { - stmt.execute("ALTER TABLE `" + Table_Backpacks + "` ADD COLUMN `" + Field_BPLastUpdate + "` TIMESTAMP DEFAULT CURRENT_TIMESTAMP;"); + stmt.execute("ALTER TABLE `" + tableBackpacks + "` ADD COLUMN `" + fieldBpLastUpdate + "` TIMESTAMP DEFAULT CURRENT_TIMESTAMP;"); } res.close(); } diff --git a/src/at/pcgamingfreaks/MinePacks/Database/SQL.java b/src/at/pcgamingfreaks/MinePacks/Database/SQL.java index d624476..0f91a1c 100644 --- a/src/at/pcgamingfreaks/MinePacks/Database/SQL.java +++ b/src/at/pcgamingfreaks/MinePacks/Database/SQL.java @@ -36,10 +36,10 @@ public abstract class SQL extends Database { private HikariDataSource dataSource; - protected String Table_Players, Table_Backpacks; // Table Names - protected String Field_Name, Field_PlayerID, Field_UUID, Field_BPOwner, Field_BPITS, Field_BPVersion, Field_BPLastUpdate; // Table Fields - protected String Query_UpdatePlayerAdd, Query_GetPlayerID, Query_InsertBP, Query_UpdateBP, Query_GetBP, Query_DeleteOldBackpacks, Query_GetUnsetOrInvalidUUIDs, Query_FixUUIDs; // DB Querys - protected boolean UpdatePlayer; + protected String tablePlayers, tableBackpacks; // Table Names + protected String fieldName, fieldPlayerID, fieldUUID, fieldBpOwner, fieldBpIts, fieldBpVersion, fieldBpLastUpdate; // Table Fields + protected String queryUpdatePlayerAdd, queryGetPlayerID, queryInsertBP, queryUpdateBP, queryGetBP, queryDeleteOldBackpacks, queryGetUnsetOrInvalidUUIDs, queryFixUUIDs; // DB Querys + protected boolean updatePlayer; public SQL(MinePacks mp) { @@ -50,7 +50,7 @@ public SQL(MinePacks mp) loadSettings(); buildQuerys(); checkDB(); - if(useUUIDs && UpdatePlayer) + if(useUUIDs && updatePlayer) { checkUUIDs(); // Check if there are user accounts without UUID } @@ -60,7 +60,10 @@ public SQL(MinePacks mp) { try { - getConnection().createStatement().execute(Query_DeleteOldBackpacks); + try(Connection connection = getConnection(); Statement statement = connection.createStatement()) + { + statement.execute(queryDeleteOldBackpacks); + } } catch(SQLException e) { @@ -74,16 +77,16 @@ public SQL(MinePacks mp) protected void loadSettings() { // Load table and field names - Table_Players = plugin.config.getUserTable(); - Table_Backpacks = plugin.config.getBackpackTable(); - Field_PlayerID = plugin.config.getDBFields("User.Player_ID"); - Field_Name = plugin.config.getDBFields("User.Name"); - Field_UUID = plugin.config.getDBFields("User.UUID"); - Field_BPOwner = plugin.config.getDBFields("Backpack.Owner_ID"); - Field_BPITS = plugin.config.getDBFields("Backpack.ItemStacks"); - Field_BPVersion = plugin.config.getDBFields("Backpack.Version"); - Field_BPLastUpdate = plugin.config.getDBFields("Backpack.LastUpdate"); - UpdatePlayer = plugin.config.getUpdatePlayer(); + tablePlayers = plugin.config.getUserTable(); + tableBackpacks = plugin.config.getBackpackTable(); + fieldPlayerID = plugin.config.getDBFields("User.Player_ID"); + fieldName = plugin.config.getDBFields("User.Name"); + fieldUUID = plugin.config.getDBFields("User.UUID"); + fieldBpOwner = plugin.config.getDBFields("Backpack.Owner_ID"); + fieldBpIts = plugin.config.getDBFields("Backpack.ItemStacks"); + fieldBpVersion = plugin.config.getDBFields("Backpack.Version"); + fieldBpLastUpdate = plugin.config.getDBFields("Backpack.LastUpdate"); + updatePlayer = plugin.config.getUpdatePlayer(); } @Override @@ -97,12 +100,11 @@ protected void checkUUIDs() class UpdateData // Helper class for fixing UUIDs { int id; - String name, uuid; + String uuid; - public UpdateData(String name, String uuid, int id) + public UpdateData(String uuid, int id) { this.id = id; - this.name = name; this.uuid = uuid; } } @@ -110,23 +112,23 @@ public UpdateData(String name, String uuid, int id) { Map toConvert = new HashMap<>(); List toUpdate = new LinkedList<>(); - try(Statement stmt = connection.createStatement(); ResultSet res = stmt.executeQuery(Query_GetUnsetOrInvalidUUIDs)) + try(Statement stmt = connection.createStatement(); ResultSet res = stmt.executeQuery(queryGetUnsetOrInvalidUUIDs)) { while(res.next()) { if(res.isFirst()) { - plugin.log.info(plugin.lang.get("Console.UpdateUUIDs")); + plugin.log.info(START_UUID_UPDATE); } - String uuid = res.getString(Field_UUID); + String uuid = res.getString(fieldUUID); if(uuid == null) { - toConvert.put(res.getString(Field_Name).toLowerCase(), new UpdateData(res.getString(Field_Name), null, res.getInt(Field_PlayerID))); + toConvert.put(res.getString(fieldName).toLowerCase(), new UpdateData(null, res.getInt(fieldPlayerID))); } else { uuid = (useUUIDSeparators) ? uuid.replaceAll("(\\w{8})(\\w{4})(\\w{4})(\\w{4})(\\w{12})", "$1-$2-$3-$4-$5") : uuid.replaceAll("-", ""); - toUpdate.add(new UpdateData(res.getString(Field_Name), uuid, res.getInt(Field_PlayerID))); + toUpdate.add(new UpdateData(uuid, res.getInt(fieldPlayerID))); } } } @@ -142,7 +144,7 @@ public UpdateData(String name, String uuid, int id) toUpdate.add(updateData); } } - try(PreparedStatement ps = connection.prepareStatement(Query_FixUUIDs)) + try(PreparedStatement ps = connection.prepareStatement(queryFixUUIDs)) { for(UpdateData updateData : toUpdate) { @@ -152,7 +154,7 @@ public UpdateData(String name, String uuid, int id) ps.executeBatch(); } } - plugin.log.info(String.format(plugin.lang.get("Console.UpdatedUUIDs"), toUpdate.size())); + plugin.log.info(String.format(UUIDS_UPDATED, toUpdate.size())); } } catch(SQLException e) @@ -171,48 +173,48 @@ protected Connection getConnection() throws SQLException protected final void buildQuerys() { // Build the SQL querys with placeholders for the table and field names - Query_GetBP = "SELECT `{FieldBPOwner}`,`{FieldBPITS}`,`{FieldBPVersion}` FROM `{TableBackpacks}` INNER JOIN `{TablePlayers}` ON `{TableBackpacks}`.`{FieldBPOwner}`=`{TablePlayers}`.`{FieldPlayerID}` WHERE "; + queryGetBP = "SELECT `{FieldBPOwner}`,`{FieldBPITS}`,`{FieldBPVersion}` FROM `{TableBackpacks}` INNER JOIN `{TablePlayers}` ON `{TableBackpacks}`.`{FieldBPOwner}`=`{TablePlayers}`.`{FieldPlayerID}` WHERE "; if(useUUIDs) { - Query_UpdatePlayerAdd = "INSERT INTO `{TablePlayers}` (`{FieldName}`,`{FieldUUID}`) VALUES (?,?) ON DUPLICATE KEY UPDATE `{FieldName}`=?;"; - Query_GetPlayerID = "SELECT `{FieldPlayerID}` FROM `{TablePlayers}` WHERE `{FieldUUID}`=?;"; - Query_GetBP += "`{FieldUUID}`=?;"; + queryUpdatePlayerAdd = "INSERT INTO `{TablePlayers}` (`{FieldName}`,`{FieldUUID}`) VALUES (?,?) ON DUPLICATE KEY UPDATE `{FieldName}`=?;"; + queryGetPlayerID = "SELECT `{FieldPlayerID}` FROM `{TablePlayers}` WHERE `{FieldUUID}`=?;"; + queryGetBP += "`{FieldUUID}`=?;"; } else { - Query_UpdatePlayerAdd = "INSERT IGNORE INTO `{TablePlayers}` (`{FieldName}`) VALUES (?);"; - Query_GetPlayerID = "SELECT `{FieldPlayerID}` FROM `{TablePlayers}` WHERE `{FieldName}`=?;"; - Query_GetBP += "`{FieldName}`=?;"; + queryUpdatePlayerAdd = "INSERT IGNORE INTO `{TablePlayers}` (`{FieldName}`) VALUES (?);"; + queryGetPlayerID = "SELECT `{FieldPlayerID}` FROM `{TablePlayers}` WHERE `{FieldName}`=?;"; + queryGetBP += "`{FieldName}`=?;"; } - Query_InsertBP = "INSERT INTO `{TableBackpacks}` (`{FieldBPOwner}`,`{FieldBPITS}`,`{FieldBPVersion}`) VALUES (?,?,?);"; - Query_UpdateBP = "UPDATE `{TableBackpacks}` SET `{FieldBPITS}`=?,`{FieldBPVersion}`=?"; + queryInsertBP = "INSERT INTO `{TableBackpacks}` (`{FieldBPOwner}`,`{FieldBPITS}`,`{FieldBPVersion}`) VALUES (?,?,?);"; + queryUpdateBP = "UPDATE `{TableBackpacks}` SET `{FieldBPITS}`=?,`{FieldBPVersion}`=?"; if(maxAge > 0) { - Query_UpdateBP += ",`{FieldBPLastUpdate}`={NOW}"; + queryUpdateBP += ",`{FieldBPLastUpdate}`={NOW}"; } - Query_UpdateBP += " WHERE `{FieldBPOwner}`=?;"; - Query_DeleteOldBackpacks = "DELETE FROM `{TableBackpacks}` WHERE `{FieldBPLastUpdate}` < DATE('now', '-{VarMaxAge} days')"; + queryUpdateBP += " WHERE `{FieldBPOwner}`=?;"; + queryDeleteOldBackpacks = "DELETE FROM `{TableBackpacks}` WHERE `{FieldBPLastUpdate}` < DATE('now', '-{VarMaxAge} days')"; if(useUUIDSeparators) { - Query_GetUnsetOrInvalidUUIDs = "SELECT `{FieldPlayerID}`,`{FieldName}`,`{FieldUUID}` FROM `{TablePlayers}` WHERE `{FieldUUID}` IS NULL OR `{FieldUUID}` NOT LIKE '%-%-%-%-%';"; + queryGetUnsetOrInvalidUUIDs = "SELECT `{FieldPlayerID}`,`{FieldName}`,`{FieldUUID}` FROM `{TablePlayers}` WHERE `{FieldUUID}` IS NULL OR `{FieldUUID}` NOT LIKE '%-%-%-%-%';"; } else { - Query_GetUnsetOrInvalidUUIDs = "SELECT `{FieldPlayerID}`,`{FieldName}`,`{FieldUUID}` FROM `{TablePlayers}` WHERE `{FieldUUID}` IS NULL OR `{FieldUUID}` LIKE '%-%';"; + queryGetUnsetOrInvalidUUIDs = "SELECT `{FieldPlayerID}`,`{FieldName}`,`{FieldUUID}` FROM `{TablePlayers}` WHERE `{FieldUUID}` IS NULL OR `{FieldUUID}` LIKE '%-%';"; } - Query_FixUUIDs = "UPDATE `{TablePlayers}` SET `{FieldUUID}`=? WHERE `{FieldPlayerID}`=?;"; + queryFixUUIDs = "UPDATE `{TablePlayers}` SET `{FieldUUID}`=? WHERE `{FieldPlayerID}`=?;"; updateQuerysForDialect(); // Replace the table and filed names with the names from the config - Query_UpdatePlayerAdd = Query_UpdatePlayerAdd.replaceAll("\\{TablePlayers\\}", Table_Players).replaceAll("\\{FieldName\\}", Field_Name).replaceAll("\\{FieldUUID\\}", Field_UUID).replaceAll("\\{FieldPlayerID\\}", Field_PlayerID); - Query_GetPlayerID = Query_GetPlayerID.replaceAll("\\{TablePlayers\\}", Table_Players).replaceAll("\\{FieldName\\}", Field_Name).replaceAll("\\{FieldUUID\\}", Field_UUID).replaceAll("\\{FieldPlayerID\\}", Field_PlayerID); - Query_GetBP = Query_GetBP.replaceAll("\\{FieldBPOwner\\}", Field_BPOwner).replaceAll("\\{FieldBPITS\\}", Field_BPITS).replaceAll("\\{FieldBPVersion\\}", Field_BPVersion).replaceAll("\\{TableBackpacks\\}", Table_Backpacks).replaceAll("\\{TablePlayers\\}", Table_Players).replaceAll("\\{FieldPlayerID\\}", Field_PlayerID).replaceAll("\\{FieldName\\}", Field_Name).replaceAll("\\{FieldUUID\\}", Field_UUID); - Query_InsertBP = Query_InsertBP.replaceAll("\\{TableBackpacks\\}", Table_Backpacks).replaceAll("\\{FieldBPOwner\\}", Field_BPOwner).replaceAll("\\{FieldBPITS\\}", Field_BPITS).replaceAll("\\{FieldBPVersion\\}", Field_BPVersion).replaceAll("\\{FieldBPLastUpdate\\}", Field_BPLastUpdate); - Query_UpdateBP = Query_UpdateBP.replaceAll("\\{TableBackpacks\\}", Table_Backpacks).replaceAll("\\{FieldBPOwner\\}", Field_BPOwner).replaceAll("\\{FieldBPITS\\}", Field_BPITS).replaceAll("\\{FieldBPVersion\\}", Field_BPVersion).replaceAll("\\{FieldBPLastUpdate\\}", Field_BPLastUpdate); - Query_DeleteOldBackpacks = Query_DeleteOldBackpacks.replaceAll("\\{TableBackpacks\\}", Table_Backpacks).replaceAll("\\{FieldBPLastUpdate\\}", Field_BPLastUpdate).replaceAll("\\{VarMaxAge\\}", maxAge + ""); - Query_GetUnsetOrInvalidUUIDs = Query_GetUnsetOrInvalidUUIDs.replaceAll("\\{TablePlayers\\}", Table_Players).replaceAll("\\{FieldName\\}", Field_Name).replaceAll("\\{FieldUUID\\}", Field_UUID).replaceAll("\\{FieldPlayerID\\}", Field_PlayerID); - Query_FixUUIDs = Query_FixUUIDs.replaceAll("\\{TablePlayers\\}", Table_Players).replaceAll("\\{FieldUUID\\}", Field_UUID).replaceAll("\\{FieldPlayerID\\}", Field_PlayerID); + queryUpdatePlayerAdd = queryUpdatePlayerAdd.replaceAll("\\{TablePlayers\\}", tablePlayers).replaceAll("\\{FieldName\\}", fieldName).replaceAll("\\{FieldUUID\\}", fieldUUID).replaceAll("\\{FieldPlayerID\\}", fieldPlayerID); + queryGetPlayerID = queryGetPlayerID.replaceAll("\\{TablePlayers\\}", tablePlayers).replaceAll("\\{FieldName\\}", fieldName).replaceAll("\\{FieldUUID\\}", fieldUUID).replaceAll("\\{FieldPlayerID\\}", fieldPlayerID); + queryGetBP = queryGetBP.replaceAll("\\{FieldBPOwner\\}", fieldBpOwner).replaceAll("\\{FieldBPITS\\}", fieldBpIts).replaceAll("\\{FieldBPVersion\\}", fieldBpVersion).replaceAll("\\{TableBackpacks\\}", tableBackpacks).replaceAll("\\{TablePlayers\\}", tablePlayers).replaceAll("\\{FieldPlayerID\\}", fieldPlayerID).replaceAll("\\{FieldName\\}", fieldName).replaceAll("\\{FieldUUID\\}", fieldUUID); + queryInsertBP = queryInsertBP.replaceAll("\\{TableBackpacks\\}", tableBackpacks).replaceAll("\\{FieldBPOwner\\}", fieldBpOwner).replaceAll("\\{FieldBPITS\\}", fieldBpIts).replaceAll("\\{FieldBPVersion\\}", fieldBpVersion).replaceAll("\\{FieldBPLastUpdate\\}", fieldBpLastUpdate); + queryUpdateBP = queryUpdateBP.replaceAll("\\{TableBackpacks\\}", tableBackpacks).replaceAll("\\{FieldBPOwner\\}", fieldBpOwner).replaceAll("\\{FieldBPITS\\}", fieldBpIts).replaceAll("\\{FieldBPVersion\\}", fieldBpVersion).replaceAll("\\{FieldBPLastUpdate\\}", fieldBpLastUpdate); + queryDeleteOldBackpacks = queryDeleteOldBackpacks.replaceAll("\\{TableBackpacks\\}", tableBackpacks).replaceAll("\\{FieldBPLastUpdate\\}", fieldBpLastUpdate).replaceAll("\\{VarMaxAge\\}", maxAge + ""); + queryGetUnsetOrInvalidUUIDs = queryGetUnsetOrInvalidUUIDs.replaceAll("\\{TablePlayers\\}", tablePlayers).replaceAll("\\{FieldName\\}", fieldName).replaceAll("\\{FieldUUID\\}", fieldUUID).replaceAll("\\{FieldPlayerID\\}", fieldPlayerID); + queryFixUUIDs = queryFixUUIDs.replaceAll("\\{TablePlayers\\}", tablePlayers).replaceAll("\\{FieldUUID\\}", fieldUUID).replaceAll("\\{FieldPlayerID\\}", fieldPlayerID); } protected abstract void updateQuerysForDialect(); @@ -252,11 +254,11 @@ public void updatePlayer(final Player player) { if(useUUIDs) { - runStatementAsync(Query_UpdatePlayerAdd, player.getName(), getPlayerFormattedUUID(player), player.getName()); + runStatementAsync(queryUpdatePlayerAdd, player.getName(), getPlayerFormattedUUID(player), player.getName()); } else { - runStatementAsync(Query_UpdatePlayerAdd, player.getName()); + runStatementAsync(queryUpdatePlayerAdd, player.getName()); } } @@ -277,7 +279,7 @@ public void run() if(id <= 0) { final int newID; - try(PreparedStatement ps = connection.prepareStatement(Query_GetPlayerID)) + try(PreparedStatement ps = connection.prepareStatement(queryGetPlayerID)) { ps.setString(1, nameOrUUID); try(ResultSet rs = ps.executeQuery()) @@ -305,7 +307,7 @@ public void run() plugin.log.warning("Failed saving backpack for: " + name + " (Unable to get players ID from database)"); return; } - try(PreparedStatement ps = connection.prepareStatement(Query_InsertBP)) + try(PreparedStatement ps = connection.prepareStatement(queryInsertBP)) { ps.setInt(1, newID); ps.setBytes(2, data); @@ -315,7 +317,7 @@ public void run() } else { - try(PreparedStatement ps = connection.prepareStatement(Query_UpdateBP)) + try(PreparedStatement ps = connection.prepareStatement(queryUpdateBP)) { ps.setBytes(1, data); ps.setInt(2, usedSerializer); @@ -324,7 +326,7 @@ public void run() } } } - catch(Exception e) + catch(SQLException e) { e.printStackTrace(); } @@ -340,7 +342,7 @@ protected void loadBackpack(final OfflinePlayer player, final Callback @Override public void run() { - try(Connection conn = getConnection(); PreparedStatement ps = conn.prepareStatement(Query_GetBP)) + try(Connection conn = getConnection(); PreparedStatement ps = conn.prepareStatement(queryGetBP)) { ps.setString(1, getPlayerNameOrUUID(player)); final int bpID, version; @@ -377,7 +379,7 @@ public void run() } }); } - catch(Exception e) + catch(SQLException e) { e.printStackTrace(); callback.onFail(); @@ -389,7 +391,7 @@ public void run() @Override public Backpack loadBackpack(OfflinePlayer player) // The sync function shouldn't be called at all { - try(Connection connection = getConnection(); PreparedStatement ps = connection.prepareStatement(Query_GetBP)) + try(Connection connection = getConnection(); PreparedStatement ps = connection.prepareStatement(queryGetBP)) { ps.setString(1, getPlayerNameOrUUID(player)); try(ResultSet rs = ps.executeQuery()) diff --git a/src/at/pcgamingfreaks/MinePacks/Database/SQLite.java b/src/at/pcgamingfreaks/MinePacks/Database/SQLite.java index 17c2010..1e1b96e 100644 --- a/src/at/pcgamingfreaks/MinePacks/Database/SQLite.java +++ b/src/at/pcgamingfreaks/MinePacks/Database/SQLite.java @@ -41,20 +41,20 @@ public SQLite(MinePacks mp) protected void loadSettings() { // Set table and field names to fixed values to prevent users from destroying old databases. - Field_PlayerID = "player_id"; - Field_Name = "name"; - Field_UUID = "uuid"; - Field_BPOwner = "owner"; + fieldPlayerID = "player_id"; + fieldName = "name"; + fieldUUID = "uuid"; + fieldBpOwner = "owner"; //noinspection SpellCheckingInspection - Field_BPITS = "itemstacks"; - Field_BPVersion = "version"; + fieldBpIts = "itemstacks"; + fieldBpVersion = "version"; //noinspection SpellCheckingInspection - Field_BPLastUpdate = "lastupdate"; - Table_Players = "backpack_players"; - Table_Backpacks = "backpacks"; + fieldBpLastUpdate = "lastupdate"; + tablePlayers = "backpack_players"; + tableBackpacks = "backpacks"; // Set fixed settings useUUIDSeparators = false; - UpdatePlayer = true; + updatePlayer = true; } @Override @@ -80,17 +80,17 @@ protected void updateQuerysForDialect() { if(maxAge > 0) { - Query_InsertBP = Query_InsertBP.replaceAll("\\) VALUES \\(\\?,\\?,\\?", "{FieldBPLastUpdate}) VALUES (?,?,?,DATE('now')"); + queryInsertBP = queryInsertBP.replaceAll("\\) VALUES \\(\\?,\\?,\\?", "{FieldBPLastUpdate}) VALUES (?,?,?,DATE('now')"); } - Query_DeleteOldBackpacks = "DELETE FROM `{TableBackpacks}` WHERE `{FieldBPLastUpdate}` < DATE('now', '-{VarMaxAge} days')"; - Query_UpdateBP = Query_UpdateBP.replaceAll("\\{NOW\\}", "DATE('now')"); + queryDeleteOldBackpacks = "DELETE FROM `{TableBackpacks}` WHERE `{FieldBPLastUpdate}` < DATE('now', '-{VarMaxAge} days')"; + queryUpdateBP = queryUpdateBP.replaceAll("\\{NOW\\}", "DATE('now')"); if(useUUIDs) { - Query_UpdatePlayerAdd = "INSERT OR IGNORE INTO `{TablePlayers}` (`{FieldName}`,`{FieldUUID}`) VALUES (?,?);"; + queryUpdatePlayerAdd = "INSERT OR IGNORE INTO `{TablePlayers}` (`{FieldName}`,`{FieldUUID}`) VALUES (?,?);"; } else { - Query_UpdatePlayerAdd = Query_UpdatePlayerAdd.replaceAll("INSERT IGNORE INTO", "INSERT OR IGNORE INTO"); + queryUpdatePlayerAdd = queryUpdatePlayerAdd.replaceAll("INSERT IGNORE INTO", "INSERT OR IGNORE INTO"); } } @@ -142,14 +142,14 @@ public void updatePlayer(final Player player) @Override public void run() { - runStatement(Query_UpdatePlayerAdd, player.getName(), getPlayerFormattedUUID(player)); - runStatement("UPDATE `" + Table_Players + "` SET `" + Field_Name + "`=? WHERE `" + Field_UUID + "`=?;", player.getName(), getPlayerFormattedUUID(player)); + runStatement(queryUpdatePlayerAdd, player.getName(), getPlayerFormattedUUID(player)); + runStatement("UPDATE `" + tablePlayers + "` SET `" + fieldName + "`=? WHERE `" + fieldUUID + "`=?;", player.getName(), getPlayerFormattedUUID(player)); } }); } else { - runStatementAsync(Query_UpdatePlayerAdd, player.getName()); + runStatementAsync(queryUpdatePlayerAdd, player.getName()); } } } \ No newline at end of file diff --git a/src/at/pcgamingfreaks/MinePacks/EventListener.java b/src/at/pcgamingfreaks/MinePacks/EventListener.java index a9177ba..1b59250 100644 --- a/src/at/pcgamingfreaks/MinePacks/EventListener.java +++ b/src/at/pcgamingfreaks/MinePacks/EventListener.java @@ -1,5 +1,5 @@ /* - * Copyright (C) 2014-2015 GeorgH93 + * Copyright (C) 2014-2016 GeorgH93 * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by @@ -34,16 +34,16 @@ public class EventListener implements Listener private MinePacks plugin; private boolean drop_on_death, showCloseMessageOwn, showCloseMessageOther; - private String message_OwnBPClose, message_PlayerBPClose; + private String messageOwnBPClose, messagePlayerBPClose; public EventListener(MinePacks mp) { plugin = mp; drop_on_death = plugin.config.getDropOnDeath(); - message_OwnBPClose = plugin.lang.getTranslated("Ingame.OwnBackPackClose"); - message_PlayerBPClose = plugin.lang.getTranslated("Ingame.PlayerBackPackClose"); - showCloseMessageOther = message_PlayerBPClose != null && plugin.config.getShowCloseMessage(); - showCloseMessageOwn = message_OwnBPClose != null && plugin.config.getShowCloseMessage(); + messageOwnBPClose = plugin.lang.getTranslated("Ingame.OwnBackPackClose"); + messagePlayerBPClose = plugin.lang.getTranslated("Ingame.PlayerBackPackClose"); + showCloseMessageOther = messagePlayerBPClose != null && plugin.config.getShowCloseMessage(); + showCloseMessageOwn = messageOwnBPClose != null && plugin.config.getShowCloseMessage(); } @EventHandler @@ -97,14 +97,14 @@ public void onClose(InventoryCloseEvent event) { if(showCloseMessageOwn) { - closer.sendMessage(message_OwnBPClose); + closer.sendMessage(messageOwnBPClose); } } else { if(showCloseMessageOther) { - closer.sendMessage(String.format(message_PlayerBPClose, backpack.getOwner().getName())); + closer.sendMessage(String.format(messagePlayerBPClose, backpack.getOwner().getName())); } } } diff --git a/src/at/pcgamingfreaks/MinePacks/ItemsCollector.java b/src/at/pcgamingfreaks/MinePacks/ItemsCollector.java index a750336..0b649f6 100644 --- a/src/at/pcgamingfreaks/MinePacks/ItemsCollector.java +++ b/src/at/pcgamingfreaks/MinePacks/ItemsCollector.java @@ -1,5 +1,5 @@ /* - * Copyright (C) 2014-2015 GeorgH93 + * Copyright (C) 2014-2016 GeorgH93 * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by @@ -29,13 +29,13 @@ public class ItemsCollector extends BukkitRunnable { - private double radius = 1.5; - private MinePacks plugin; + private final MinePacks plugin; + private final double radius; - public ItemsCollector(MinePacks mp) + public ItemsCollector(MinePacks plugin) { - plugin = mp; - radius = plugin.config.getFullInvRadius(); + this.plugin = plugin; + radius = this.plugin.config.getFullInvRadius(); } @Override diff --git a/src/at/pcgamingfreaks/MinePacks/MinePacks.java b/src/at/pcgamingfreaks/MinePacks/MinePacks.java index 4fdf48e..8436dda 100644 --- a/src/at/pcgamingfreaks/MinePacks/MinePacks.java +++ b/src/at/pcgamingfreaks/MinePacks/MinePacks.java @@ -17,13 +17,14 @@ package at.pcgamingfreaks.MinePacks; +import at.pcgamingfreaks.Bukkit.MCVersion; +import at.pcgamingfreaks.Bukkit.Updater; import at.pcgamingfreaks.Bukkit.Utils; import at.pcgamingfreaks.ConsoleColor; import at.pcgamingfreaks.MinePacks.Database.Config; import at.pcgamingfreaks.MinePacks.Database.Database; import at.pcgamingfreaks.MinePacks.Database.Language; -import at.pcgamingfreaks.MinePacks.Updater.UpdateResult; -import at.pcgamingfreaks.MinePacks.Updater.Updater; +import at.pcgamingfreaks.StringUtils; import org.bukkit.Bukkit; import org.bukkit.OfflinePlayer; @@ -45,10 +46,10 @@ public class MinePacks extends JavaPlugin public HashMap cooldowns = new HashMap<>(); - public static String backpackTitleOther, backpackTitle; + public String backpackTitleOther, backpackTitle; public String messageInvalidBackpack; - private static int maxSize; + private int maxSize; public static MinePacks getInstance() { @@ -62,11 +63,11 @@ public void onEnable() Utils.warnOnJava_1_7(log); instance = this; //region Check compatibility with used minecraft version - String name = Bukkit.getServer().getClass().getPackage().getName(); - String[] version = name.substring(name.lastIndexOf('.') + 2).split("_"); - if((version[0].equals("1") && Integer.valueOf(version[1]) > 10) || Integer.valueOf(version[0]) > 1) + if(MCVersion.is(MCVersion.UNKNOWN) || MCVersion.isNewerThan(MCVersion.MC_NMS_1_10_R1)) { - MinePacks.getInstance().warnOnVersionIncompatibility(version[0] + "." + version[1]); + String name = Bukkit.getServer().getClass().getPackage().getName(); + String[] version = name.substring(name.lastIndexOf('.') + 2).split("_"); + this.warnOnVersionIncompatibility(version[0] + "." + version[1]); this.setEnabled(false); return; } @@ -85,7 +86,7 @@ public void onEnable() maxSize = config.getBackpackMaxSize(); backpackTitleOther = config.getBPTitleOther(); - backpackTitle = Utils.limitLength(config.getBPTitle(), 32); + backpackTitle = StringUtils.limitLength(config.getBPTitle(), 32); messageInvalidBackpack = lang.getTranslated("Ingame.InvalidBackpack"); getServer().getServicesManager().register(MinePacks.class, this, this, ServicePriority.Normal); @@ -93,19 +94,10 @@ public void onEnable() { log.info("Checking for updates ..."); Updater updater = new Updater(this, this.getFile(), true, 83445); // Create a new updater with dev.bukkit.org as update provider - updater.update(new at.pcgamingfreaks.MinePacks.Updater.Updater.UpdaterResponse() { - @Override - public void onDone(UpdateResult updateResult) - { - if(updateResult == UpdateResult.UPDATE_AVAILABLE_V2) - { - new MinepacksV2IsOut(MinePacks.this); - } - } - }); // Starts the update, if there is a new update available it will download while we close the rest + updater.update(); // Starts the update } - log.info(lang.get("Console.Enabled")); + log.info(lang.get(ConsoleColor.GREEN + "MinePacks has been enabled! " + ConsoleColor.YELLOW + ":)")); } @Override @@ -122,13 +114,13 @@ public void onDisable() DB.close(); // Close the DB connection, we won't need them any longer if(updater != null) updater.waitForAsyncOperation(); // The update can download while we kill the listeners and close the DB connections instance = null; - log.info(lang.get("Console.Disabled")); + log.info(lang.get(ConsoleColor.RED + "MinePacks has been disabled. " + ConsoleColor.YELLOW + ":)")); } public void warnOnVersionIncompatibility(String version) { log.warning(ConsoleColor.RED + "################################" + ConsoleColor.RESET); - log.warning(ConsoleColor.RED + String.format(lang.getTranslated("Console.MinecraftVersionNotCompatible"), version, getDescription().getVersion()) + ConsoleColor.RESET); + log.warning(ConsoleColor.RED + String.format("Your minecraft version (MC %1$s) is currently not compatible with this plugins version (%2$s). Please check for updates!", version, getDescription().getVersion()) + ConsoleColor.RESET); log.warning(ConsoleColor.RED + "################################" + ConsoleColor.RESET); Utils.blockThread(5); } @@ -162,7 +154,7 @@ public void openBackpack(Player opener, Backpack backpack, boolean editable) backpack.open(opener, editable); } - public static int getBackpackPermSize(Player player) + public int getBackpackPermSize(Player player) { for(int i = maxSize; i > 1; i--) { diff --git a/src/at/pcgamingfreaks/MinePacks/MinepacksV2IsOut.java b/src/at/pcgamingfreaks/MinePacks/MinepacksV2IsOut.java deleted file mode 100644 index 19043b0..0000000 --- a/src/at/pcgamingfreaks/MinePacks/MinepacksV2IsOut.java +++ /dev/null @@ -1,71 +0,0 @@ -/* - * Copyright (C) 2016 GeorgH93 - * - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU General Public License as published by - * the Free Software Foundation, either version 3 of the License, or - * (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public License - * along with this program. If not, see . - */ - -package at.pcgamingfreaks.MinePacks; - -import org.bukkit.Bukkit; -import org.bukkit.ChatColor; -import org.bukkit.entity.Player; -import org.bukkit.event.EventHandler; -import org.bukkit.event.Listener; -import org.bukkit.event.player.PlayerJoinEvent; - -public class MinepacksV2IsOut implements Listener -{ - public static MinepacksV2IsOut instance = null; - private MinePacks plugin; - - public MinepacksV2IsOut(MinePacks plugin) - { - if(plugin.config.isV2InfoDisabled()) return; - instance = this; - this.plugin = plugin; - plugin.getServer().getPluginManager().registerEvents(this, plugin); - Bukkit.getConsoleSender().sendMessage(ChatColor.GRAY + "#####################################"); - Bukkit.getConsoleSender().sendMessage(ChatColor.GOLD + "Minepacks V2 has been released! " + ChatColor.YELLOW + ":)"); - Bukkit.getConsoleSender().sendMessage("Please download it form here:" + ChatColor.AQUA + " https://www.spigotmc.org/resources/19286/"); - Bukkit.getConsoleSender().sendMessage(ChatColor.GRAY + "#####################################"); - } - - public void announce(Player player) - { - if(player != null && player.isOnline()) - { - player.sendMessage(ChatColor.GRAY + "#####################################"); - player.sendMessage(ChatColor.GOLD + "Minepacks V2 has been released! " + ChatColor.YELLOW + ":)"); - player.sendMessage("Please download it form here:" + ChatColor.AQUA + " https://www.spigotmc.org/resources/19286/"); - player.sendMessage(ChatColor.GRAY + "#####################################"); - } - } - - @EventHandler - public void onJoin(PlayerJoinEvent event) - { - final Player player = event.getPlayer(); - if(player.isOp()) - { - plugin.getServer().getScheduler().runTaskLater(plugin, new Runnable() - { - @Override - public void run() - { - announce(player); - } - }, 100L); - } - } -} \ No newline at end of file diff --git a/src/at/pcgamingfreaks/MinePacks/OnCommand.java b/src/at/pcgamingfreaks/MinePacks/OnCommand.java index 9d1ac69..0d657a9 100644 --- a/src/at/pcgamingfreaks/MinePacks/OnCommand.java +++ b/src/at/pcgamingfreaks/MinePacks/OnCommand.java @@ -1,5 +1,5 @@ /* - * Copyright (C) 2014-2015 GeorgH93 + * Copyright (C) 2014-2016 GeorgH93 * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by @@ -39,10 +39,10 @@ public class OnCommand implements CommandExecutor public OnCommand(MinePacks mp) { plugin = mp; - Message_NotFromConsole = plugin.lang.getTranslated("Console.NotFromConsole"); - Message_NoPermission = ChatColor.RED + plugin.lang.getTranslated("Ingame.NoPermission"); - Message_BackpackCleaned = ChatColor.DARK_GREEN + plugin.lang.getTranslated("Ingame.BackpackCleaned"); - Message_Cooldown = ChatColor.DARK_GREEN + plugin.lang.getTranslated("Ingame.Cooldown"); + Message_NotFromConsole = plugin.lang.getTranslated("NotFromConsole"); + Message_NoPermission = plugin.lang.getTranslated("Ingame.NoPermission"); + Message_BackpackCleaned = plugin.lang.getTranslated("Ingame.BackpackCleaned"); + Message_Cooldown = plugin.lang.getTranslated("Ingame.Cooldown"); cooldown = plugin.config.getCommandCooldown(); } @@ -95,18 +95,18 @@ public boolean onCommand(CommandSender sender, Command cmd, String arg, String[] if(player.hasPermission("backpack")) { player.sendMessage(ChatColor.GOLD + "Minepacks Help:"); - player.sendMessage(ChatColor.AQUA + "/backpack" + ChatColor.WHITE + " - " + plugin.lang.getTranslated("Description.Backpack")); + player.sendMessage(ChatColor.AQUA + "/backpack" + ChatColor.WHITE + " - " + plugin.lang.getTranslated("Commands.Description.Backpack")); if(player.hasPermission("backpack.clean")) { - player.sendMessage(ChatColor.AQUA + "/backpack clean" + ChatColor.WHITE + " - " + plugin.lang.getTranslated("Description.Clean")); + player.sendMessage(ChatColor.AQUA + "/backpack clean" + ChatColor.WHITE + " - " + plugin.lang.getTranslated("Commands.Description.Clean")); } if(player.hasPermission("backpack.clean.other")) { - player.sendMessage(ChatColor.AQUA + "/backpack clean " + ChatColor.WHITE + " - " + plugin.lang.getTranslated("Description.CleanOther")); + player.sendMessage(ChatColor.AQUA + "/backpack clean " + ChatColor.WHITE + " - " + plugin.lang.getTranslated("Commands.Description.CleanOther")); } if(player.hasPermission("backpack.other")) { - player.sendMessage(ChatColor.AQUA + "/backpack " + ChatColor.WHITE + " - " + plugin.lang.getTranslated("Description.View")); + player.sendMessage(ChatColor.AQUA + "/backpack " + ChatColor.WHITE + " - " + plugin.lang.getTranslated("Commands.Description.View")); } } else diff --git a/src/at/pcgamingfreaks/MinePacks/Updater/BukkitUpdateProvider.java b/src/at/pcgamingfreaks/MinePacks/Updater/BukkitUpdateProvider.java deleted file mode 100644 index 183ecdf..0000000 --- a/src/at/pcgamingfreaks/MinePacks/Updater/BukkitUpdateProvider.java +++ /dev/null @@ -1,181 +0,0 @@ -/* - * Copyright (C) 2016 GeorgH93 - * - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU General Public License as published by - * the Free Software Foundation, either version 3 of the License, or - * (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public License - * along with this program. If not, see . - */ - -package at.pcgamingfreaks.MinePacks.Updater; - -import at.pcgamingfreaks.ConsoleColor; -import at.pcgamingfreaks.Updater.UpdateProviders.NotSuccessfullyQueriedException; - -import com.google.gson.Gson; - -import java.io.BufferedReader; -import java.io.IOException; -import java.io.InputStreamReader; -import java.net.MalformedURLException; -import java.net.URL; -import java.net.URLConnection; -import java.util.logging.Level; -import java.util.logging.Logger; - -public class BukkitUpdateProvider -{ - //region static stuff - private static final String USER_AGENT = "Plugin-Updater"; - private static final String HOST = "https://api.curseforge.com/servermods/files?projectIds="; - private static final String VERSION_DELIMITER = "^[vV]|[\\s_-][vV]"; // Used for locating version numbers in file names, bukkit doesn't provide the version on it's own :( - //endregion - - private final int projectID; - private final String apiKey; - private URL url = null; - - private Version[] versions = null; - - public BukkitUpdateProvider(int projectID) - { - this(projectID, null); - } - - public BukkitUpdateProvider(int projectID, String apiKey) - { - this.projectID = projectID; - this.apiKey = apiKey; - - try - { - url = new URL(HOST + projectID); - } - catch(MalformedURLException ignored) {} - } - - public UpdateResult query(Logger logger) - { - if(url == null) return UpdateResult.FAIL_FILE_NOT_FOUND; - try - { - URLConnection connection = url.openConnection(); - connection.setConnectTimeout(5000); - if(apiKey != null) connection.addRequestProperty("X-API-Key", apiKey); - connection.addRequestProperty("User-Agent", USER_AGENT); - connection.setDoOutput(true); - - try(BufferedReader reader = new BufferedReader(new InputStreamReader(connection.getInputStream()))) - { - versions = new Gson().fromJson(reader, Version[].class); - if(versions == null || versions.length == 0) - { - logger.warning(ConsoleColor.RED + "The updater could not find any files for the project id " + projectID + " " + ConsoleColor.RESET); - return UpdateResult.FAIL_FILE_NOT_FOUND; - } - } - } - catch(final IOException e) - { - if(e.getMessage().contains("HTTP response code: 403")) - { - logger.severe(ConsoleColor.RED + "dev.bukkit.org rejected the provided API key!" + ConsoleColor.RESET); - logger.severe(ConsoleColor.RED + "Please double-check your configuration to ensure it is correct." + ConsoleColor.RESET); - logger.log(Level.SEVERE, null, e); - return UpdateResult.FAIL_API_KEY; - } - else - { - logger.severe(ConsoleColor.RED + "The updater could not contact dev.bukkit.org for updating!" + ConsoleColor.RESET); - logger.severe(ConsoleColor.RED + "If this is the first time you are seeing this message, the site may be experiencing temporary downtime." + ConsoleColor.RESET); - logger.log(Level.SEVERE, null, e); - return UpdateResult.FAIL_SERVER_OFFLINE; - } - } - return UpdateResult.SUCCESS; - } - - private class Version - { - @SuppressWarnings("unused") - public String name, downloadUrl, fileName, fileUrl, releaseType, gameVersion, md5, projectId; - } - - //region provider property's - public boolean provideDownloadURL() - { - return true; - } - - public boolean provideMD5Checksum() - { - return true; - } - //endregion - - //region getter for the latest version - public String getLatestVersion() throws NotSuccessfullyQueriedException - { - String name = getLatestName(); - String[] help = name.split(VERSION_DELIMITER); - if(help.length == 2) - { - return help[1].split("\\s+")[0]; - } - return null; - } - - public String getLatestVersionFileName() throws NotSuccessfullyQueriedException - { - if(versions == null) - { - throw new NotSuccessfullyQueriedException(); - } - return versions[versions.length - 1].fileName; - } - - public URL getLatestFileURL() throws NotSuccessfullyQueriedException - { - if(versions == null) - { - throw new NotSuccessfullyQueriedException(); - } - try - { - return new URL(versions[versions.length - 1].downloadUrl); - } - catch(MalformedURLException e) - { - System.out.println(ConsoleColor.RED + "Failed to interpret download url \"" + versions[versions.length - 1].downloadUrl + "\"!" + ConsoleColor.RESET); - e.printStackTrace(); - } - return null; - } - - public String getLatestName() throws NotSuccessfullyQueriedException - { - if(versions == null) - { - throw new NotSuccessfullyQueriedException(); - } - return versions[versions.length - 1].name; - } - - public String getLatestChecksum() throws NotSuccessfullyQueriedException - { - if(versions == null) - { - throw new NotSuccessfullyQueriedException(); - } - return versions[versions.length - 1].md5; - } - //endregion -} \ No newline at end of file diff --git a/src/at/pcgamingfreaks/MinePacks/Updater/UpdateResult.java b/src/at/pcgamingfreaks/MinePacks/Updater/UpdateResult.java deleted file mode 100644 index f85dcc0..0000000 --- a/src/at/pcgamingfreaks/MinePacks/Updater/UpdateResult.java +++ /dev/null @@ -1,60 +0,0 @@ -/* - * Copyright (C) 2016 GeorgH93 - * - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU General Public License as published by - * the Free Software Foundation, either version 3 of the License, or - * (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public License - * along with this program. If not, see . - */package at.pcgamingfreaks.MinePacks.Updater; - -/** - * Gives the developer the result of the update process. - */ -public enum UpdateResult -{ - /** - * The updater found an update, and has readied it to be loaded the next time the server restarts/reloads. - */ - SUCCESS, - /** - * The updater did not find an update, and nothing was downloaded. - */ - NO_UPDATE, - /** - * The server administrator has disabled the updating system. - */ - DISABLED, - /** - * The updater found an update, but was unable to download it. - */ - FAIL_DOWNLOAD, - /** - * For some reason, the updater was unable to contact the server to download the file. - */ - FAIL_SERVER_OFFLINE, - /** - * When running the version check, the file did not contain a recognizable version. - */ - FAIL_NO_VERSION_FOUND, - /** - * The update provider was unable to find the file. - */ - FAIL_FILE_NOT_FOUND, - /** - * The server administrator has improperly configured their API key in the configuration. - */ - FAIL_API_KEY, - /** - * The updater found an update, but the used provider doesn't provide us with a download link. - */ - UPDATE_AVAILABLE, - UPDATE_AVAILABLE_V2 -} \ No newline at end of file diff --git a/src/at/pcgamingfreaks/MinePacks/Updater/Updater.java b/src/at/pcgamingfreaks/MinePacks/Updater/Updater.java deleted file mode 100644 index c961460..0000000 --- a/src/at/pcgamingfreaks/MinePacks/Updater/Updater.java +++ /dev/null @@ -1,351 +0,0 @@ -/* - * Copyright (C) 2016 GeorgH93 - * - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU General Public License as published by - * the Free Software Foundation, either version 3 of the License, or - * (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public License - * along with this program. If not, see . - */ - -package at.pcgamingfreaks.MinePacks.Updater; - -import at.pcgamingfreaks.Updater.UpdateProviders.NotSuccessfullyQueriedException; - -import org.bukkit.Bukkit; -import org.bukkit.plugin.java.JavaPlugin; - -import java.io.BufferedInputStream; -import java.io.File; -import java.io.FileOutputStream; -import java.io.InputStream; -import java.net.HttpURLConnection; -import java.net.URL; -import java.security.DigestInputStream; -import java.security.MessageDigest; -import java.util.logging.Level; -import java.util.logging.Logger; -import java.util.regex.Pattern; - -public class Updater -{ - private final static int BUFFER_SIZE = 1024; - - private final File updateFolder; - private final BukkitUpdateProvider updateProvider; - private final boolean announceDownloadProgress; - private final Logger logger; - private final String localVersion, targetFileName; - private final JavaPlugin plugin; - - private Thread thread; - private UpdateResult result; - - public Updater(JavaPlugin plugin, File file, boolean announceDownloadProgress, int bukkitPluginID) - { - this(plugin, file, announceDownloadProgress, new BukkitUpdateProvider(bukkitPluginID)); - } - - public Updater(JavaPlugin plugin, File file, boolean announceDownloadProgress, BukkitUpdateProvider updateProvider) - { - this.updateFolder = Bukkit.getUpdateFolderFile(); - this.updateProvider = updateProvider; - this.announceDownloadProgress = announceDownloadProgress; - this.logger = plugin.getLogger(); - this.localVersion = plugin.getDescription().getVersion(); - this.targetFileName = file.getName(); - this.plugin = plugin; - } - - protected void runSync(Runnable runnable) - { - plugin.getServer().getScheduler().runTask(plugin, runnable); - } - - protected void runAsync(Runnable runnable) - { - thread = new Thread(runnable); - thread.start(); - } - - protected String getAuthor() - { - return plugin.getDescription().getAuthors().size() > 0 ? plugin.getDescription().getAuthors().get(0) : ""; - } - - public void waitForAsyncOperation() - { - if (thread != null && thread.isAlive()) - { - try - { - thread.join(); - } - catch (InterruptedException e) - { - plugin.getLogger().log(Level.SEVERE, null, e); - } - } - } - - //region version checking logic - protected String[] prepareVersion(String version) - { - String[] v = version.toLowerCase().split("-")[0].split(Pattern.quote(".")); - try - { - if(version.contains("snapshot") || version.contains("alpha") || version.contains("beta")) - { - if(v.length == 1) - { - v = new String[] { Integer.toString(Integer.parseInt(v[0]) - 1), Integer.toString(Integer.MAX_VALUE) }; - } - else - { - for(int i = v.length - 1; i > 0; i--) - { - if(Integer.parseInt(v[i]) > 0) - { - v[i] = Integer.toString(Integer.parseInt(v[i]) - 1); - break; - } - } - } - } - } - catch(Exception ignored) {} - return v; - } - - protected boolean shouldUpdate(String remoteVersion) - { - String[] locVersion = prepareVersion(localVersion), remVersion = prepareVersion(remoteVersion); - try - { - int c = Math.min(locVersion.length, remVersion.length); - for(int i = 0; i < c; i++) - { - int r = Integer.parseInt(remVersion[i]), l = Integer.parseInt(locVersion[i]); - if(r > l) - { - return true; - } - else if(r < l) - { - return false; - } - } - // If both version are the same for the length of the shorter version the version that has more digits probably is the newer one. - if(remVersion.length > locVersion.length) - { - return true; - } - } - catch(Exception e) - { - // There was a problem parsing the version. Use the fallback (if they don't match the remote version is the newer one) - logger.warning("Failed to determine the newer version between local version \"" + localVersion + - "\" and remote version \"" + remoteVersion + "\"! Using fallback method (if they don't match the remote version is the newer one)!"); - return !localVersion.equalsIgnoreCase(remoteVersion); - } - return false; - } - - protected boolean versionCheck(String remoteVersion) - { - if(remoteVersion != null) - { - if(!this.shouldUpdate(remoteVersion)) - { - // We already have the latest version, or this build is tagged for no-update - result = UpdateResult.NO_UPDATE; - return false; - } - } - else - { - // OMG!!! We have no version to work with! - logger.warning("There was a problem retrieving the remote version of the plugin!"); - logger.warning("You should contact the plugin author (" + getAuthor() + ") about this!"); - result = UpdateResult.FAIL_NO_VERSION_FOUND; - return false; - } - return true; - } - //endregion - - protected void download(URL url, String fileName) // Saves file into servers update directory - { - download(url, fileName, 0); - } - - protected void download(URL url, String fileName, int movedCount) // Saves file into servers update directory - { - if(!updateFolder.exists()) - { - //noinspection ResultOfMethodCallIgnored - updateFolder.mkdirs(); - } - try - { - HttpURLConnection connection = (HttpURLConnection) url.openConnection(); - connection.setInstanceFollowRedirects(false); - connection.setConnectTimeout(15000); - connection.setReadTimeout(15000); - switch (connection.getResponseCode()) - { - case HttpURLConnection.HTTP_MOVED_PERM: - case HttpURLConnection.HTTP_MOVED_TEMP: - if(movedCount == 5) - { - logger.warning("Target url moved more than 5 times. Abort."); - result = UpdateResult.FAIL_DOWNLOAD; - return; - } - download(new URL(url, connection.getHeaderField("Location")), fileName, ++movedCount); - return; - } - //endregion - long fileLength = connection.getContentLengthLong(); - int count, percent, percentHelper = -1; - File downloadFile = new File(updateFolder.getAbsolutePath() + File.separator + fileName); - MessageDigest md5HashGenerator = updateProvider.provideMD5Checksum() ? MessageDigest.getInstance("MD5") : null; - try(InputStream inputStream = (md5HashGenerator != null) ? new DigestInputStream(new BufferedInputStream(connection.getInputStream()), md5HashGenerator) : new BufferedInputStream(url.openStream()); - FileOutputStream outputStream = new FileOutputStream(downloadFile)) - { - byte[] buffer = new byte[BUFFER_SIZE]; - if(announceDownloadProgress) - { - logger.info("Start downloading update: " + updateProvider.getLatestVersion()); - } - long downloaded = 0; - while((count = inputStream.read(buffer, 0, BUFFER_SIZE)) != -1) - { - downloaded += count; - outputStream.write(buffer, 0, count); - percent = (int) ((downloaded * 100) / fileLength); - if(announceDownloadProgress && percent % 10 == 0 && percent / 10 > percentHelper) - { - percentHelper++; - logger.info("Downloading update: " + percent + "% of " + fileLength + " bytes."); - } - } - outputStream.flush(); - } - connection.disconnect(); - if(md5HashGenerator != null) - { - String MD5Download = byteArrayToHex(md5HashGenerator.digest()).toLowerCase(), MD5Target = updateProvider.getLatestChecksum().toLowerCase(); - if(!MD5Download.equals(MD5Target)) - { - logger.warning("The auto-updater was able to download the file, but the checksum did not match! Delete file."); - logger.warning("Checksum expected: " + MD5Target + " Checksum download: " + MD5Download); - result = UpdateResult.FAIL_DOWNLOAD; - //noinspection ResultOfMethodCallIgnored - downloadFile.delete(); - return; - } - } - if(result != UpdateResult.FAIL_DOWNLOAD && announceDownloadProgress) - { - result = UpdateResult.SUCCESS; - logger.info("Finished updating."); - } - } - catch(Exception ignored) - { - logger.warning("The auto-updater tried to download a new update, but was unsuccessful."); - ignored.printStackTrace(); - result = UpdateResult.FAIL_DOWNLOAD; - } - } - - private static String byteArrayToHex(byte[] bytes) - { - if(bytes == null || bytes.length == 0) return ""; - StringBuilder hexBuilder = new StringBuilder(bytes.length * 2); - for(byte b: bytes) - { - hexBuilder.append(String.format("%02x", b)); - } - return hexBuilder.toString(); - } - - protected String getRemoteVersion() - { - try - { - return updateProvider.getLatestVersion(); - } - catch(NotSuccessfullyQueriedException ignored) {} - return null; - } - - public void update() - { - update(null); - } - - public void update(final UpdaterResponse response) - { - if(result == UpdateResult.DISABLED) return; - runAsync(new Runnable() - { - @Override - public void run() - { - result = updateProvider.query(logger); - if(result == UpdateResult.SUCCESS) - { - if(getRemoteVersion().startsWith("2")) - { - result = UpdateResult.UPDATE_AVAILABLE_V2; - if(response != null) runSync(new Runnable() - { - @Override - public void run() - { - response.onDone(result); - } - }); - } - else if(versionCheck(getRemoteVersion())) - { - result = UpdateResult.UPDATE_AVAILABLE; - try - { - if(updateProvider.provideDownloadURL() && updateProvider.getLatestFileURL() != null) - { - download(updateProvider.getLatestFileURL(), (updateProvider.getLatestVersionFileName().toLowerCase().endsWith(".zip")) ? updateProvider.getLatestVersionFileName() : targetFileName); - if(response != null) runSync(new Runnable() - { - @Override - public void run() - { - response.onDone(result); - } - }); - } - } - catch(Exception e) - { - e.printStackTrace(); - } - } - } - } - }); - } - - public interface UpdaterResponse - { - void onDone(UpdateResult result); - } -} \ No newline at end of file