Removed flat file stats and cooldowns; migrated to SQLite; other optimizations

This commit is contained in:
cervinakuy committed 2021-04-17 19:58:50 -07:00
1 parent 855749fc3d
commit 07dc0cc6b6
24 files changed
+1128 -846

No files matched your search

@@ -1,7 +1,8 @@
package com.planetgallium.kitpvp;
import com.cryptomorin.xseries.XMaterial;
import com.planetgallium.kitpvp.game.Infobase;
import org.bukkit.Bukkit;
import org.bukkit.World;
import org.bukkit.entity.Player;
import org.bukkit.event.EventHandler;
import org.bukkit.event.Listener;
@@ -25,11 +26,10 @@ public class Game extends JavaPlugin implements Listener {
private static String prefix;
private Arena arena;
private Database database;
private Infobase database;
private Resources resources = new Resources(this);
private String updateVersion = "Error";
public String storageType;
private boolean needsUpdate = false;
private boolean hasPlaceholderAPI = false;
private boolean hasWorldGuard = false;
@@ -38,10 +38,9 @@ public class Game extends JavaPlugin implements Listener {
public void onEnable() {
instance = this;
resources.load();
prefix = resources.getMessages().getString("Messages.General.Prefix");
database = new Database(this, "Storage.MySQL");
database = new Infobase(this);
arena = new Arena(this, resources);
PluginManager pm = Bukkit.getPluginManager();
@@ -69,16 +68,6 @@ public class Game extends JavaPlugin implements Listener {
Bukkit.getConsoleSender().sendMessage(Toolkit.translate("&7[&b&lKIT-PVP&7] &7Enabling &bKitPvP &7version &b" + this.getDescription().getVersion() + "&7..."));
if (resources.getConfig().getString("Storage.Type").equalsIgnoreCase("mysql")) {
storageType = "mysql";
database.setup();
database.holdConnection();
database.createData();
} else {
storageType = "yaml";
}
new Metrics(this);
new BukkitRunnable() {
@@ -107,13 +96,6 @@ public class Game extends JavaPlugin implements Listener {
}
@Override
public void onDisable() {
for (Player all : Bukkit.getOnlinePlayers()) {
database.saveAndRemovePlayer(all);
}
}
private void checkUpdate() {
Updater.of(this).resourceId(27107).handleResponse((versionResponse, version) -> {
@@ -159,6 +141,15 @@ public class Game extends JavaPlugin implements Listener {
out.writeUTF(server);
p.sendPluginMessage(this, "BungeeCord", out.toByteArray());
} else if (resources.getConfig().getBoolean("Items.Leave.Multiworld.Enabled")) {
String worldName = resources.getConfig().getString("Items.Leave.Multiworld.World");
World world = Bukkit.getWorld(worldName);
if (world != null) {
p.teleport(world.getSpawnLocation());
} else {
p.sendMessage(Toolkit.translate("&7[&b&lKIT-PVP&7] &cWorld %world% not found. Configure properly in the config.yml.").replace("%world%", worldName));
}
}
e.setCancelled(true);
@@ -182,8 +173,8 @@ public class Game extends JavaPlugin implements Listener {
public static Game getInstance() { return instance; }
public Arena getArena() { return arena; }
public Database getDatabase() { return database; }
public Infobase getDatabase() { return database; }
public static String getPrefix() { return prefix; }
@@ -14,21 +14,24 @@ import org.bukkit.command.CommandExecutor;
import org.bukkit.command.CommandSender;
import org.bukkit.entity.Player;
import org.bukkit.plugin.Plugin;
import org.bukkit.potion.Potion;
import org.bukkit.potion.PotionEffect;
import org.bukkit.potion.PotionType;
import org.bukkit.scheduler.BukkitRunnable;
import java.io.File;
import java.util.ArrayList;
import java.util.List;
public class MainCommand implements CommandExecutor {
private List<String> spawnUsers = new ArrayList<String>();
private List<String> spawnUsers = new ArrayList<>();
private Game plugin;
private Arena arena;
private Resources resources;
private Resource config;
private Resource messages;
private final Game plugin;
private final Arena arena;
private final Resources resources;
private final Resource config;
private final Resource messages;
public MainCommand(Game game) {
this.plugin = game;
@@ -75,8 +78,7 @@ public class MainCommand implements CommandExecutor {
sender.sendMessage(Toolkit.translate("&7- &b/kp stats &7View your stats."));
sender.sendMessage(Toolkit.translate("&7- &b/kp stats [player] &7View the stats of another player."));
sender.sendMessage(Toolkit.translate("&7- &b/kp menu &7Displays the kits menu."));
sender.sendMessage(Toolkit.translate("&7- &b/kp import &7Imports all stats from the MySQL database."));
sender.sendMessage(Toolkit.translate("&7- &b/kp export &7Exports all stats to the MySQL database."));
sender.sendMessage(Toolkit.translate("&7- &b/kp export &7Exports all stats to the database."));
sender.sendMessage(Toolkit.translate(" "));
sender.sendMessage(Toolkit.translate("&3&m "));
return true;
@@ -104,34 +106,21 @@ public class MainCommand implements CommandExecutor {
sender.sendMessage(Toolkit.translate("&7[&b&lKIT-PVP&7] &aSupport Discord: &7https://discord.gg/GtXQKZ6"));
sender.sendMessage(Toolkit.translate("&7[&b&lKIT-PVP&7] &aPlugin List: &7" + names));
} else if (args[0].equalsIgnoreCase("import") && hasPermission(sender, "kp.command.import")) {
if (plugin.getDatabase().isEnabled()) {
sender.sendMessage(Toolkit.translate("%prefix% &7Importing data, please wait..."));
plugin.getDatabase().importData(resources);
sender.sendMessage(Toolkit.translate("%prefix% &aDatabase data has successfully been exported to the stats.yml."));
} else {
sender.sendMessage(Toolkit.translate("%prefix% &cImporting is unnecessary, you can switch your storage type and import."));
}
return true;
} else if (args[0].equalsIgnoreCase("export") && hasPermission(sender, "kp.command.export")) {
if (plugin.getDatabase().isEnabled()) {
File statsFile = new File(plugin.getDataFolder().getAbsolutePath() + "/stats.yml");
sender.sendMessage(Toolkit.translate("%prefix% &7Exporting data, please wait..."));
plugin.getDatabase().exportData(resources);
if (statsFile.exists()) {
sender.sendMessage(Toolkit.translate("%prefix% &7Exporting data, this may take a while..."));
new BukkitRunnable() {
@Override
public void run() {
plugin.getDatabase().exportStats();
}
}.runTaskAsynchronously(plugin);
sender.sendMessage(Toolkit.translate("%prefix% &aStats successfully exported to database."));
} else {
sender.sendMessage(Toolkit.translate("%prefix% &cYou are using YAML storage, so exporting is not possible. Change your settings in the config.yml"));
sender.sendMessage(Toolkit.translate("%prefix% &cNo stats.yml was found to export from."));
}
return true;
@@ -140,7 +129,7 @@ public class MainCommand implements CommandExecutor {
String message = "";
for (String kitName : arena.getKits().getKitList()) {
for (String kitName : resources.getKitList(false)) {
String[] fileName = kitName.split(".yml", 2);
message += fileName[0] + ", ";
}
@@ -182,7 +171,7 @@ public class MainCommand implements CommandExecutor {
if (arena.getKits().isKit(kitName)) {
resources.removeResource(kitName + ".yml");
arena.getKits().deleteKit(kitName);
sender.sendMessage(messages.getString("Messages.Commands.Delete")
.replace("%kit%", kitName));
@@ -257,6 +246,11 @@ public class MainCommand implements CommandExecutor {
}
} else if (args[0].equalsIgnoreCase("test")) {
Potion test = new Potion(PotionType.JUMP, 2);
p.getInventory().addItem(test.toItemStack(1));
} else if (args[0].equalsIgnoreCase("menu") && hasPermission(sender, "kp.command.menu")) {
arena.getMenus().getKitMenu().open(p);
@@ -19,20 +19,20 @@ import me.clip.placeholderapi.PlaceholderAPI;
public class Arena {
private Game plugin;
private Random random;
private final Game plugin;
private final Random random;
private Resources resources;
private Resource config;
private final Resources resources;
private final Resource config;
private Map<String, String> hitCache;
private Stats stats;
private Kits kits;
private KillStreaks killstreaks;
private Levels levels;
private Cooldowns cooldowns;
private Menus menus;
private final Map<String, String> hitCache;
private final Stats stats;
private final Kits kits;
private final KillStreaks killstreaks;
private final Levels levels;
private final Cooldowns cooldowns;
private final Menus menus;
public Arena(Game plugin, Resources resources) {
this.plugin = plugin;
@@ -42,12 +42,12 @@ public class Arena {
this.config = resources.getConfig();
this.hitCache = new HashMap<>();
this.stats = new Stats(plugin, resources);
this.stats = new Stats(plugin);
this.kits = new Kits(plugin, this);
this.killstreaks = new KillStreaks(resources);
this.levels = new Levels(this, resources);
this.cooldowns = new Cooldowns(this, resources);
this.cooldowns = new Cooldowns(plugin);
this.menus = new Menus(resources);
}
@@ -117,9 +117,7 @@ public class Arena {
updateScoreboards(p, true);
}
if (hitCache.containsKey(p.getName())) {
hitCache.remove(p.getName());
}
hitCache.remove(p.getName());
}
@@ -132,9 +130,7 @@ public class Arena {
CacheManager.getPlayerAbilityCooldowns(p.getName()).clear();
if (hitCache.containsKey(p.getName())) {
hitCache.remove(p.getName());
}
hitCache.remove(p.getName());
}
@@ -201,37 +197,69 @@ public class Arena {
text = PlaceholderAPI.setPlaceholders(p, text);
}
text = text.replace("%streak%", String.valueOf(this.getKillStreaks().getStreak(p.getName())))
.replace("%player%", p.getName())
.replace("%xp%", String.valueOf(this.getLevels().getExperience(p.getUniqueId())))
.replace("%level%", String.valueOf(this.getLevels().getLevel(p.getUniqueId())))
.replace("%max_xp%", String.valueOf(resources.getLevels().getInt("Levels.Options.Experience-To-Level-Up")))
.replace("%max_level%", String.valueOf(resources.getLevels().getInt("Levels.Options.Maximum-Level")))
.replace("%kd%", String.valueOf(this.getStats().getKDRatio(p.getUniqueId())))
.replace("%deaths%", String.valueOf(this.getStats().getDeaths(p.getUniqueId())))
.replace("%kills%", String.valueOf(this.getStats().getKills(p.getUniqueId())));
return replacePlaceholderIfPresent(text, p);
if (getKits().getKitOfPlayer(p.getName()) != null) {
text = text.replace("%kit%", getKits().getKitOfPlayer(p.getName()).getName());
} else {
text = text.replace("%kit%", "None");
}
public String replacePlaceholderIfPresent(String s, Player p) {
// The reason I'm doing all these if statements rather than a more concise code solution is to reduce
// the amount of data that is unnecessarily fetched (ex by using .replace) to improve performance
// no longer constantly fetching stats from database for EACH line of scoreboard on update and player join
if (s.contains("%streak%")) {
s = s.replace("%streak%", String.valueOf(getKillStreaks().getStreak(p.getName())));
}
return text;
if (s.contains("%player%")) {
s = s.replace("%player%", p.getName());
}
if (s.contains("%xp%")) {
s = s.replace("%xp%", String.valueOf(getLevels().getExperience(p.getUniqueId())));
}
if (s.contains("%level%")) {
s = s.replace("%level%", String.valueOf(levels.getLevel(p.getUniqueId())));
}
if (s.contains("%max_xp%")) {
s = s.replace("%max_xp%", String.valueOf(resources.getLevels().getInt("Levels.Options.Experience-To-Level-Up")));
}
if (s.contains("%max_level%")) {
s = s.replace("%max_level%", String.valueOf(resources.getLevels().getInt("Levels.Options.Maximum-Level")));
}
if (s.contains("%kd%")) {
s = s.replace("%kd%", String.valueOf(getStats().getKDRatio(p.getUniqueId())));
}
if (s.contains("%kills%")) {
s = s.replace("%kills%", String.valueOf(getStats().getKills(p.getUniqueId())));
}
if (s.contains("%deaths%")) {
s = s.replace("%deaths%", String.valueOf(getStats().getDeaths(p.getUniqueId())));
}
if (s.contains("%kit%")) {
if (getKits().getKitOfPlayer(p.getName()) != null) {
s = s.replace("%kit%", getKits().getKitOfPlayer(p.getName()).getName());
} else {
s = s.replace("%kit%", "None");
}
}
return s;
}
public String generateRandomArenaSpawn(String arenaName) {
ConfigurationSection section = config.getConfigurationSection("Arenas." + arenaName);
List<String> spawnKeys = new ArrayList<String>();
for (String identifier : section.getKeys(false)) {
spawnKeys.add(identifier);
}
List<String> spawnKeys = new ArrayList<>(section.getKeys(false));
return spawnKeys.get(random.nextInt(spawnKeys.size()));
}
public boolean isCombatActionPermittedInRegion(Player p) {
@@ -252,7 +280,7 @@ public class Arena {
}
public Map<String, String> getHitCache() { return hitCache; }
public Stats getStats() { return stats; }
public Kits getKits() { return kits; }
@@ -2,97 +2,63 @@ package com.planetgallium.kitpvp.game;
import java.util.UUID;
import com.planetgallium.kitpvp.Game;
import com.planetgallium.kitpvp.api.Ability;
import com.planetgallium.kitpvp.api.Kit;
import com.planetgallium.kitpvp.util.CacheManager;
import com.planetgallium.kitpvp.util.Cooldown;
import com.planetgallium.kitpvp.util.Resource;
import com.planetgallium.kitpvp.util.Resources;
import com.zp4rker.localdb.DataType;
import org.bukkit.entity.Player;
public class Cooldowns {
private Arena arena;
private Resource stats;
private Infobase database;
public Cooldowns(Arena arena, Resources resources) {
this.arena = arena;
this.stats = resources.getStats();
public Cooldowns(Game plugin) {
this.database = plugin.getDatabase();
}
public void setAbilityCooldown(String playerName, String abilityName) {
CacheManager.getPlayerAbilityCooldowns(playerName).put(abilityName, (System.currentTimeMillis() / 1000));
}
public void setCooldown(UUID uuid, String kit) {
// TODO: MySQL storing
stats.set("Stats.Players." + uuid + ".Cooldowns." + kit, (System.currentTimeMillis() / 1000));
stats.save();
public void setKitCooldown(UUID uuid, String kitName) {
database.setData(kitName + "_cooldowns", "last_used", (System.currentTimeMillis() / 1000), DataType.INTEGER, uuid.toString());
System.out.println("Done");
}
public boolean isOnCooldown(Player p, Object type) {
public Cooldown getRemainingCooldown(Player p, Object type) {
long currentTimeSeconds = (System.currentTimeMillis() / 1000);
int timeLastUsedSeconds = 0;
int cooldownSeconds = 0;
int actionCooldownSeconds = 0;
Cooldown noCooldown = new Cooldown(0, 0, 0, 0);
if (type instanceof Kit) {
Kit kit = (Kit) type;
if (kit.getCooldown() == null) return false;
timeLastUsedSeconds = stats.getInt("Stats.Players." + p.getUniqueId() + ".Cooldowns." + kit.getName());
cooldownSeconds = kit.getCooldown().toSeconds();
if (kit.getCooldown() == null) return noCooldown;
Object timeLastUsedResult = database.getData(kit.getName() + "_cooldowns", "last_used", p.getUniqueId().toString());
if (timeLastUsedResult != null) {
timeLastUsedSeconds = (int) timeLastUsedResult;
}
actionCooldownSeconds = kit.getCooldown().toSeconds();
} else if (type instanceof Ability) {
Ability ability = (Ability) type;
if (ability.getCooldown() == null ||
!CacheManager.getPlayerAbilityCooldowns(p.getName()).containsKey(ability.getName()))
return false;
return noCooldown;
timeLastUsedSeconds = CacheManager.getPlayerAbilityCooldowns(p.getName()).get(ability.getName()).intValue();
cooldownSeconds = ability.getCooldown().toSeconds();
actionCooldownSeconds = ability.getCooldown().toSeconds();
} else {
return false;
}
return timeLastUsedSeconds + cooldownSeconds >= currentTimeSeconds;
}
public String getFormattedCooldown(int useTimeSeconds, int cooldownSeconds) {
int timeRemainingSeconds = (int) (useTimeSeconds + cooldownSeconds - (System.currentTimeMillis() / 1000));
int days = 0;
int hours = 0;
int minutes = 0;
int seconds = 0;
if (timeRemainingSeconds / 86400 > 0) {
days = timeRemainingSeconds / 86400;
timeRemainingSeconds -= (days * 86400);
}
if (timeRemainingSeconds / 3600 > 0) {
hours = timeRemainingSeconds / 3600;
timeRemainingSeconds -= (hours * 3600);
}
if (timeRemainingSeconds / 60 > 0) {
minutes = timeRemainingSeconds / 60;
timeRemainingSeconds -= (minutes * 60);
}
if (timeRemainingSeconds > 0) {
seconds = timeRemainingSeconds;
}
return new Cooldown(days, hours, minutes, seconds).formatted(false);
int cooldownRemainingSeconds = (int) (timeLastUsedSeconds + actionCooldownSeconds - currentTimeSeconds);
return new Cooldown(cooldownRemainingSeconds);
}
@@ -0,0 +1,231 @@
package com.planetgallium.kitpvp.game;
import com.planetgallium.kitpvp.Game;
import com.planetgallium.kitpvp.util.Resource;
import com.planetgallium.kitpvp.util.Resources;
import com.planetgallium.kitpvp.util.Toolkit;
import com.zp4rker.localdb.Column;
import com.zp4rker.localdb.DataType;
import com.zp4rker.localdb.Database;
import com.zp4rker.localdb.Table;
import org.bukkit.configuration.ConfigurationSection;
import org.bukkit.entity.Player;
import java.util.*;
public class Infobase {
private final Game plugin;
private final Resources resources;
private final Database database;
private final Map<String, Table> kitCooldownTables;
// TODO: add cooldown table when kit is created
// TODO: eventually fork localDB and add these helper methods ig?
// TODO: use this to make leaderboards (use table.search for a kills column for example)
public Infobase(Game plugin) {
this.plugin = plugin;
this.resources = plugin.getResources();
this.kitCooldownTables = new HashMap<>();
Column uuid = new Column("uuid", DataType.STRING, 0);
// Stats
Column username = new Column("username", DataType.STRING, 0);
Column kills = new Column("kills", DataType.INTEGER, 0);
Column deaths = new Column("deaths", DataType.INTEGER, 0);
Column experience = new Column("experience", DataType.INTEGER, 0);
Column level = new Column("level", DataType.INTEGER, 0);
Table statsTable = new Table("stats", uuid, username, kills, deaths, experience, level);
// Cooldowns
Column last_used = new Column("last_used", DataType.INTEGER, 0);
this.database = new Database(plugin, "storage", statsTable, "plugins/KitPvP");
for (String kitName : resources.getKitList(false)) {
kitCooldownTables.put(kitName, new Table(kitName + "_cooldowns", uuid, last_used));
}
for (String kitCooldownTableName : kitCooldownTables.keySet()) {
database.addTable(kitCooldownTables.get(kitCooldownTableName));
}
}
public void createPlayerStats(Player p) {
if (databaseTableContainsUUID("stats", p.getUniqueId().toString())) {
return;
}
Column uuid = new Column("uuid", DataType.STRING, 0);
Column username = new Column("username", DataType.STRING, 0);
Column kills = new Column("kills", DataType.INTEGER, 0);
Column deaths = new Column("deaths", DataType.INTEGER, 0);
Column experience = new Column("experience", DataType.INTEGER, 0);
Column level = new Column("level", DataType.INTEGER, 0);
uuid.setValue(p.getUniqueId().toString());
username.setValue(p.getName());
kills.setValue(0);
deaths.setValue(0);
experience.setValue(0);
level.setValue(resources.getLevels().getInt("Levels.Options.Minimum-Level"));
getTableByName("stats").insert(uuid, username, kills, deaths, experience, level);
}
public void exportStats() {
Resource statsResource = new Resource(plugin, "stats.yml");
statsResource.load();
ConfigurationSection statsSection = statsResource.getConfigurationSection("Stats.Players");
Column uuidColumn = new Column("uuid", DataType.STRING);
Column username = new Column("username", DataType.STRING);
Column kills = new Column("kills", DataType.INTEGER);
Column deaths = new Column("deaths", DataType.INTEGER);
Column experience = new Column("experience", DataType.INTEGER);
Column level = new Column("level", DataType.INTEGER);
Table statsTable = getTableByName("stats");
for (String uuid : statsSection.getKeys(false)) {
ConfigurationSection playerSection = statsSection.getConfigurationSection(uuid);
uuidColumn.setValue(uuid);
username.setValue(playerSection.getString("Username"));
kills.setValue(playerSection.getInt("Kills"));
deaths.setValue(playerSection.getInt("Deaths"));
experience.setValue(playerSection.getInt("Experience"));
level.setValue(playerSection.getInt("Level"));
statsTable.insert(uuidColumn, username, kills, deaths, experience, level);
}
statsResource.getFile().delete();
}
public void addKitCooldownTable(String kitName) {
Column uuid = new Column("uuid", DataType.STRING, 0);
Column last_used = new Column("last_used", DataType.INTEGER, 0);
kitCooldownTables.put(kitName, new Table(kitName + "_cooldowns", uuid, last_used));
database.addTable(kitCooldownTables.get(kitName));
}
public void deleteKitCooldownTable(String kitName) {
Table table = getTableByName(kitName + "_cooldowns");
if (table == null) return;
database.deleteTable(table);
cleanupUnusedKitCooldownTables();
}
public boolean databaseTableContainsUUID(String tableName, String uuid) {
Table table = getTableByName(tableName);
if (table == null) return false;
Column uuidColumn = new Column("uuid", DataType.STRING, 0);
uuidColumn.setValue(uuid);
return table.containsColumn(uuidColumn);
}
public void cleanupUnusedKitCooldownTables() {
for (Table table : database.getTables()) {
String tableName = table.getName();
if (tableName.contains("_cooldowns")) {
String kitName = tableName.split("_cooldowns")[0];
if (!plugin.getArena().getKits().isKit(kitName)) {
database.deleteTable(table);
}
}
}
}
public String getTopNStat(int n, String identifier) {
// update topN results when a player dies
Column numberColumn = new Column(identifier, DataType.INTEGER);
return getTableByName("stats").getTopN(numberColumn, n).get(n - 1);
}
public Table getTableByName(String name) {
for (Table table : database.getTables()) {
if (table.getName().equals(name)) {
return table;
}
}
Toolkit.printToConsole(String.format("&7[&b&lKIT-PVP&7] &cCould not find table with name [%s]", name));
return null;
}
public List<Column> getRowByUUID(String tableName, String uuid) {
Table table = getTableByName(tableName);
if (table == null) return null;
Column uuidColumn = new Column("uuid", DataType.STRING, 0);
uuidColumn.setValue(uuid);
if (table.containsColumn(uuidColumn)) {
return table.getExact(uuidColumn);
}
return null;
}
public Column getColumnByName(String tableName, String columnName, String uuid) {
Table table = getTableByName(tableName);
if (table == null) return null;
for (Column column : getRowByUUID(tableName, uuid)) {
if (column.getName().equals(columnName)) {
return column;
}
}
return null;
}
public void setData(String tableName, String identifier, Object data, DataType type, String uuid) {
Table table = getTableByName(tableName);
if (table == null) return;
Column dataColumn = new Column(identifier.toLowerCase(), type, 0);
dataColumn.setValue(data);
Column uuidColumn = new Column("uuid", DataType.STRING, 0);
uuidColumn.setValue(uuid);
if (databaseTableContainsUUID(tableName, uuid)) {
table.update(uuidColumn, dataColumn);
} else {
table.insert(uuidColumn, dataColumn);
}
}
public Object getData(String tableName, String identifier, String uuid) {
if (databaseTableContainsUUID(tableName, uuid)) {
return getColumnByName(tableName, identifier, uuid).getValue();
}
return null;
}
}
@@ -9,6 +9,7 @@ import com.planetgallium.kitpvp.api.Kit;
import com.planetgallium.kitpvp.api.PlayerSelectKitEvent;
import com.planetgallium.kitpvp.item.AttributeParser;
import com.planetgallium.kitpvp.util.*;
import com.zp4rker.localdb.Table;
import org.bukkit.Bukkit;
import org.bukkit.entity.Player;
import org.bukkit.inventory.ItemStack;
@@ -45,6 +46,7 @@ public class Kits {
kitToCreate.toResource(kitResource);
resources.addResource(kitToCreate.getName() + ".yml", kitResource);
plugin.getDatabase().addKitCooldownTable(kitName);
if (plugin.getConfig().getBoolean("Other.AutomaticallyAddKitToMenu")) {
@@ -198,11 +200,9 @@ public class Kits {
return;
}
// TODO: improve kit cooldown handling plugin-wide
if (!(p.hasPermission("kp.cooldownbypass") || !arena.getCooldowns().isOnCooldown(p, kit))) {
int timeLastUsedSeconds = resources.getStats().getInt("Stats.Players." + p.getUniqueId() + ".Cooldowns." + kit.getName());
int cooldownSeconds = kit.getCooldown().toSeconds();
p.sendMessage(messages.getString("Messages.Error.CooldownKit").replace("%cooldown%", arena.getCooldowns().getFormattedCooldown(timeLastUsedSeconds, cooldownSeconds)));
Cooldown cooldownRemaining = arena.getCooldowns().getRemainingCooldown(p, kit);
if (!p.hasPermission("kp.cooldownbypass") || cooldownRemaining.toSeconds() > 0) {
p.sendMessage(messages.getString("Messages.Error.CooldownKit").replace("%cooldown%", cooldownRemaining.formatted(false)));
return;
}
@@ -224,8 +224,9 @@ public class Kits {
Bukkit.getPluginManager().callEvent(new PlayerSelectKitEvent(player, kit));
setKit(p.getName(), kit.getName());
if (kit.getCooldown() != null && !p.hasPermission("kp.cooldownbypass")) {
arena.getCooldowns().setCooldown(p.getUniqueId(), kit.getName());
Cooldown kitCooldown = kit.getCooldown();
if (kitCooldown != null && kitCooldown.toSeconds() > 0 && !p.hasPermission("kp.cooldownbypass")) {
arena.getCooldowns().setKitCooldown(p.getUniqueId(), kit.getName());
}
Resource kitResource = resources.getKit(kit.getName());
@@ -236,6 +237,13 @@ public class Kits {
}
public void deleteKit(String kitName) {
resources.removeResource(kitName + ".yml");
plugin.getDatabase().deleteKitCooldownTable(kitName);
}
public Kit getKitByName(String kitName) {
return loadKitFromCacheOrCreate(kitName);
@@ -273,7 +281,7 @@ public class Kits {
private Kit loadKitFromCacheOrCreate(String kitName) {
if (!CacheManager.getKitCache().containsKey(kitName)) {
if (getKitList().contains(kitName)) {
if (resources.getKitList(false).contains(kitName)) {
Resource kit = resources.getKit(kitName);
try {
CacheManager.getKitCache().put(kitName, createKitFromResource(kit));
@@ -281,7 +289,7 @@ public class Kits {
e.printStackTrace();
}
} else {
Bukkit.getConsoleSender().sendMessage("&7[&b&lKIT-PVP&7] &cNo kit with name " + kitName + " found in the kits folder. Try reloading the server.");
Toolkit.printToConsole("&7[&b&lKIT-PVP&7] &cNo kit with name " + kitName + " found in the kits folder. Try reloading the server.");
}
}
@@ -297,20 +305,7 @@ public class Kits {
public boolean isKit(String kitName) {
return getKitList().contains(kitName);
}
public List<String> getKitList() {
File folder = new File(plugin.getDataFolder().getAbsolutePath() + "/kits");
List<String> list = new ArrayList<>();
for (String fileName : Objects.requireNonNull(folder.list())) {
list.add(fileName.split(".yml")[0]);
}
return list;
return resources.getKitList(false).contains(kitName);
}
@@ -1,54 +0,0 @@
package com.planetgallium.kitpvp.game;
public class PlayerData {
private String username;
private int level;
private int experience;
private int kills;
private int deaths;
public PlayerData(String username, int level, int experience, int kills, int deaths) {
this.username = username;
this.level = level;
this.experience = experience;
this.kills = kills;
this.deaths = deaths;
}
public void addKills(int amount) {
this.kills += amount;
}
public void addDeaths(int amount) {
this.deaths += amount;
}
public void setExperience(int amount) {
this.experience = amount;
}
public void setLevel(int level) {
this.level = level;
}
public int getKills() { return kills; }
public int getDeaths() { return deaths; }
public int getExperience() { return experience; }
public int getLevel() { return level; }
public String getUsername() { return username; }
}
@@ -1,277 +1,92 @@
package com.planetgallium.kitpvp.game;
import com.planetgallium.kitpvp.Game;
import com.planetgallium.kitpvp.util.Toolkit;
import com.zp4rker.localdb.DataType;
import org.bukkit.entity.Player;
import java.util.UUID;
import com.planetgallium.kitpvp.Game;
import com.planetgallium.kitpvp.util.Resource;
import com.planetgallium.kitpvp.util.Resources;
import com.planetgallium.kitpvp.util.Toolkit;
public class Stats {
private Game game;
private Resources resources;
private Resource stats;
public Stats(Game game, Resources resources) {
this.game = game;
this.resources = resources;
this.stats = resources.getStats();
}
public void createPlayer(String username, UUID uuid) {
if (!game.getDatabase().isEnabled()) {
if (!stats.contains("Stats.Players." + uuid + ".Username")) {
stats.set("Stats.Players." + uuid + ".Username", username);
stats.set("Stats.Players." + uuid + ".Level", resources.getLevels().getInt("Levels.Options.Minimum-Level"));
stats.set("Stats.Players." + uuid + ".Experience", 0);
stats.set("Stats.Players." + uuid + ".Kills", 0);
stats.set("Stats.Players." + uuid + ".Deaths", 0);
resources.save();
}
} else {
if (!game.getDatabase().getCache().containsKey(uuid) || game.getDatabase().getCache().get(uuid) == null) {
PlayerData playerData = new PlayerData(username, 0, 0, 0, 0);
game.getDatabase().getCache().put(uuid, playerData);
}
}
}
public void addKill(UUID uuid) {
if (!game.getDatabase().isEnabled()) {
if (stats.contains("Stats.Players." + uuid + ".Kills")) {
stats.set("Stats.Players." + uuid + ".Kills", getKills(uuid) + 1);
resources.save();
}
} else {
PlayerData playerData = game.getDatabase().getCache().get(uuid);
playerData.addKills(1);
}
}
public void addDeath(UUID uuid) {
if (!game.getDatabase().isEnabled()) {
if (stats.contains("Stats.Players." + uuid + ".Deaths")) {
stats.set("Stats.Players." + uuid + ".Deaths", getDeaths(uuid) + 1);
resources.save();
}
} else {
PlayerData playerData = game.getDatabase().getCache().get(uuid);
playerData.addDeaths(1);
}
}
public void addExperience(UUID uuid, int experience) {
if (!game.getDatabase().isEnabled()) {
if (stats.contains("Stats.Players." + uuid + ".Experience")) {
stats.set("Stats.Players." + uuid + ".Experience", getExperience(uuid) + experience);
resources.save();
}
} else {
PlayerData playerData = game.getDatabase().getCache().get(uuid);
playerData.setExperience(getExperience(uuid) + experience);
}
}
public void removeExperience(UUID uuid, int experience) {
if (!game.getDatabase().isEnabled()) {
if (stats.contains("Stats.Players." + uuid + ".Experience")) {
if (stats.getInt("Stats.Players." + uuid + ".Experience") > experience) {
stats.set("Stats.Players." + uuid + ".Experience", getExperience(uuid) - experience);
resources.save();
}
}
} else {
PlayerData playerData = game.getDatabase().getCache().get(uuid);
if (playerData.getExperience() > experience) {
playerData.setExperience(getExperience(uuid) - experience);
}
}
}
public void setLevel(UUID uuid, int level) {
if (!game.getDatabase().isEnabled()) {
if (stats.contains("Stats.Players." + uuid + ".Level")) {
stats.set("Stats.Players." + uuid + ".Level", level);
resources.save();
}
} else {
PlayerData playerData = game.getDatabase().getCache().get(uuid);
playerData.setLevel(level);
}
}
public void setExperience(UUID uuid, int experience) {
if (!game.getDatabase().isEnabled()) {
if (stats.contains("Stats.Players." + uuid + ".Experience")) {
stats.set("Stats.Players." + uuid + ".Experience", experience);
resources.save();
}
} else {
PlayerData playerData = game.getDatabase().getCache().get(uuid);
playerData.setExperience(experience);
}
}
public int getKills(UUID uuid) {
if (!game.getDatabase().isEnabled()) {
if (stats.contains("Stats.Players." + uuid + ".Kills")) {
return stats.getInt("Stats.Players." + uuid + ".Kills");
}
} else {
PlayerData playerData = game.getDatabase().getCache().get(uuid);
return playerData.getKills();
}
return 0;
}
public int getDeaths(UUID uuid) {
if (!game.getDatabase().isEnabled()) {
if (stats.contains("Stats.Players." + uuid + ".Deaths")) {
return stats.getInt("Stats.Players." + uuid + ".Deaths");
}
} else {
PlayerData playerData = game.getDatabase().getCache().get(uuid);
return playerData.getDeaths();
}
return 0;
}
public double getKDRatio(UUID uuid) {
if (getDeaths(uuid) != 0) {
double divided = (double) getKills(uuid) / getDeaths(uuid);
return Toolkit.round(divided, 2);
}
return 0.00;
}
public int getExperience(UUID uuid) {
if (!game.getDatabase().isEnabled()) {
if (stats.contains("Stats.Players." + uuid + ".Experience")) {
return stats.getInt("Stats.Players." + uuid + ".Experience");
}
} else {
PlayerData playerData = game.getDatabase().getCache().get(uuid);
return playerData.getExperience();
}
return 0;
}
public int getLevel(UUID uuid) {
if (!game.getDatabase().isEnabled()) {
if (stats.contains("Stats.Players." + uuid + ".Level")) {
return stats.getInt("Stats.Players." + uuid + ".Level");
}
} else {
PlayerData playerData = game.getDatabase().getCache().get(uuid);
return playerData.getLevel();
}
return 0;
}
private final Infobase database;
public Stats(Game plugin) {
this.database = plugin.getDatabase();
}
public void createPlayer(Player p) {
if (!isPlayerRegistered(p.getUniqueId())) {
database.createPlayerStats(p);
}
}
public boolean isPlayerRegistered(UUID uuid) {
return database.databaseTableContainsUUID("stats", uuid.toString());
}
public double getKDRatio(UUID uuid) {
if (getDeaths(uuid) != 0) {
double divided = (double) getKills(uuid) / getDeaths(uuid);
return Toolkit.round(divided, 2);
}
return 0.00;
}
public void addKills(UUID uuid, int amount) {
setKills(uuid, getKills(uuid) + amount);
}
public void addDeaths(UUID uuid, int amount) {
setDeaths(uuid, getDeaths(uuid) + amount);
}
public void addExperience(UUID uuid, int amount) {
setExperience(uuid, getExperience(uuid) + amount);
}
public void removeExperience(UUID uuid, int amount) {
if (isPlayerRegistered(uuid)) {
if (getExperience(uuid) > amount) {
setExperience(uuid, getExperience(uuid) - amount);
}
}
}
public void setKills(UUID uuid, int kills) {
if (!database.databaseTableContainsUUID("stats", uuid.toString())) return;
database.setData("stats", "kills", kills, DataType.INTEGER, uuid.toString());
}
public void setDeaths(UUID uuid, int deaths) {
if (!database.databaseTableContainsUUID("stats", uuid.toString())) return;
database.setData("stats", "deaths", deaths, DataType.INTEGER, uuid.toString());
}
public void setExperience(UUID uuid, int experience) {
if (!database.databaseTableContainsUUID("stats", uuid.toString())) return;
database.setData("stats", "experience", experience, DataType.INTEGER, uuid.toString());
}
public void setLevel(UUID uuid, int level) {
if (!database.databaseTableContainsUUID("stats", uuid.toString())) return;
database.setData("stats", "level", level, DataType.INTEGER, uuid.toString());
}
public int getKills(UUID uuid) {
return (int) database.getData("stats", "kills", uuid.toString());
}
public int getDeaths(UUID uuid) {
return (int) database.getData("stats", "deaths", uuid.toString());
}
public int getExperience(UUID uuid) {
return (int) database.getData("stats", "experience", uuid.toString());
}
public int getLevel(UUID uuid) {
return (int) database.getData("stats", "level", uuid.toString());
}
}
@@ -3,7 +3,7 @@ package com.planetgallium.kitpvp.listener;
import com.planetgallium.kitpvp.Game;
import com.planetgallium.kitpvp.api.Ability;
import com.planetgallium.kitpvp.api.Kit;
import com.planetgallium.kitpvp.util.CacheManager;
import com.planetgallium.kitpvp.util.Cooldown;
import org.bukkit.entity.Player;
import org.bukkit.event.EventHandler;
import org.bukkit.event.Listener;
@@ -15,12 +15,10 @@ import com.planetgallium.kitpvp.util.Toolkit;
public class AbilityListener implements Listener {
private Game plugin;
private Arena arena;
private Resources resources;
public AbilityListener(Game plugin) {
this.plugin = plugin;
this.arena = plugin.getArena();
this.resources = plugin.getResources();
}
@@ -43,11 +41,10 @@ public class AbilityListener implements Listener {
return;
}
if (arena.getCooldowns().isOnCooldown(p, ability)) {
int timeLastUsedSeconds = CacheManager.getPlayerAbilityCooldowns(p.getName()).get(ability.getName()).intValue();
int cooldownSeconds = ability.getCooldown().toSeconds();
Cooldown cooldownRemaining = arena.getCooldowns().getRemainingCooldown(p, ability);
if (cooldownRemaining.toSeconds() > 0) {
p.sendMessage(resources.getMessages().getString("Messages.Error.CooldownAbility")
.replace("%cooldown%", arena.getCooldowns().getFormattedCooldown(timeLastUsedSeconds, cooldownSeconds)));
.replace("%cooldown%", cooldownRemaining.formatted(false)));
return;
}
@@ -54,7 +54,7 @@ public class DeathListener implements Listener {
setDeathMessage(victim);
respawnPlayer(victim);
arena.getStats().addDeath(victim.getUniqueId());
arena.getStats().addDeaths(victim.getUniqueId(), 1);
arena.getLevels().removeExperience(victim, resources.getLevels().getInt("Levels.Options.Experience-Taken-On-Death"));
if (config.getBoolean("Arena.DeathParticle")) {
@@ -94,7 +94,11 @@ public class DeathListener implements Listener {
}
private void respawnPlayer(Player victim) {
if (!victim.isOnline()) {
return;
}
if (config.getBoolean("Arena.FancyDeath")) {
Location deathLocation = victim.getLocation();
@@ -263,7 +267,7 @@ public class DeathListener implements Listener {
if (!victim.getName().equals(killer.getName())) {
arena.getStats().addKill(killer.getUniqueId());
arena.getStats().addKills(killer.getUniqueId(), 1);
arena.getLevels().addExperience(killer, resources.getLevels().getInt("Levels.Options.Experience-Given-On-Kill"));
List<String> killCommands = config.getStringList("Kill.Commands");
@@ -43,8 +43,7 @@ public class JoinListener implements Listener {
}
plugin.getDatabase().addPlayer(p);
arena.getStats().createPlayer(p.getName(), p.getUniqueId());
arena.getStats().createPlayer(p);
if (Toolkit.inArena(p)) {
@@ -1,6 +1,5 @@
package com.planetgallium.kitpvp.listener;
import com.planetgallium.kitpvp.util.CacheManager;
import com.planetgallium.kitpvp.util.Toolkit;
import org.bukkit.entity.Player;
import org.bukkit.event.EventHandler;
@@ -12,11 +11,9 @@ import com.planetgallium.kitpvp.game.Arena;
public class LeaveListener implements Listener {
private Game plugin;
private Arena arena;
public LeaveListener(Game plugin) {
this.plugin = plugin;
this.arena = plugin.getArena();
}
@@ -26,10 +23,7 @@ public class LeaveListener implements Listener {
Player p = e.getPlayer();
if (Toolkit.inArena(p)) {
arena.deletePlayer(p);
plugin.getDatabase().saveAndRemovePlayer(p);
}
}
@@ -15,6 +15,29 @@ public class Cooldown {
this.seconds = seconds;
}
public Cooldown(int seconds) {
if (seconds / 86400 > 0) {
this.days = seconds / 86400;
seconds -= (days * 86400);
}
if (seconds / 3600 > 0) {
this.hours = seconds / 3600;
seconds -= (hours * 3600);
}
if (seconds / 60 > 0) {
this.minutes = seconds / 60;
seconds -= (minutes * 60);
}
if (seconds > 0) {
this.seconds = seconds;
}
}
public Cooldown(String formattedCooldown) {
@@ -1,291 +0,0 @@
package com.planetgallium.kitpvp.util;
import java.io.File;
import java.io.IOException;
import java.sql.*;
import java.util.HashMap;
import java.util.Map;
import java.util.UUID;
import org.bukkit.Bukkit;
import org.bukkit.configuration.ConfigurationSection;
import org.bukkit.entity.Player;
import com.planetgallium.kitpvp.Game;
import com.planetgallium.kitpvp.game.PlayerData;
public class Database {
private Game game;
private boolean isEnabled;
private Connection connection;
private Map<UUID, PlayerData> cache;
private String host;
private String database;
private String table;
private int port;
private String username;
private String password;
public Database(Game game, String path) {
this.game = game;
this.cache = new HashMap<>();
this.host = game.getConfig().getString(path + ".Host");
this.database = game.getConfig().getString(path + ".Database");
this.table = game.getConfig().getString(path + ".Table");
this.port = game.getConfig().getInt(path + ".Port");
this.username = game.getConfig().getString(path + ".Username");
this.password = game.getConfig().getString(path + ".Password");
}
public void setup() {
try {
synchronized (this) {
if (connection != null && !connection.isClosed()) {
return;
}
Class.forName("com.mysql.jdbc.Driver");
this.connection = DriverManager.getConnection("jdbc:mysql://" + host + ":" + port + "/" + database + "?autoReconnect=true", username, password);
Bukkit.getConsoleSender().sendMessage(Toolkit.translate("&7[&b&lKIT-PVP&7] &aMySQL was successfully connected on port " + port + "."));
isEnabled = true;
}
} catch (SQLException | ClassNotFoundException e) {
e.printStackTrace();
}
}
public void holdConnection() {
try {
PreparedStatement statement = connection.prepareStatement("SELECT ?");
statement.setInt(1, 1);
statement.executeQuery();
} catch (SQLException e) {
e.printStackTrace();
}
Bukkit.getScheduler().runTaskLaterAsynchronously(game, () -> holdConnection(), 24000L);
}
public void createData() {
boolean isTableCreated = false;
try {
DatabaseMetaData databaseMeta = connection.getMetaData();
ResultSet result = databaseMeta.getTables(null, null, table, null);
if (result.next()) {
isTableCreated = true;
}
String playerTable = "CREATE TABLE " + table + " (" +
"UUID VARCHAR(255)," +
"USERNAME VARCHAR(255)," +
"LEVEL INT(4)," +
"EXPERIENCE INT(10)," +
"KILLS INT(10)," +
"DEATHS INT(10)" +
")";
if (!isTableCreated) {
PreparedStatement statement = connection.prepareStatement(playerTable);
statement.executeUpdate();
}
} catch (SQLException e) {
e.printStackTrace();
}
}
public void addPlayer(Player p) {
if (this.isEnabled) {
try {
PreparedStatement statement = connection.prepareStatement("SELECT * FROM " + table + " WHERE UUID=?");
statement.setString(1, p.getUniqueId().toString());
ResultSet result = statement.executeQuery();
boolean hasPlayerData = false;
if (result.next()) {
hasPlayerData = true;
String username = result.getString("USERNAME");
int level = result.getInt("LEVEL");
int experience = result.getInt("EXPERIENCE");
int kills = result.getInt("KILLS");
int deaths = result.getInt("DEATHS");
PlayerData playerData = new PlayerData(username, level, experience, kills, deaths);
cache.put(p.getUniqueId(), playerData);
}
if (!hasPlayerData) {
game.getArena().getStats().createPlayer(p.getName(), p.getUniqueId());
PreparedStatement stmt = connection.prepareStatement("INSERT INTO " + table +
" (UUID, USERNAME, LEVEL, EXPERIENCE, KILLS, DEATHS) VALUES (?, ?, ?, ?, ?, ?)");
stmt.setString(1, p.getUniqueId().toString());
stmt.setString(2, p.getName());
stmt.setInt(3, 0);
stmt.setInt(4, 0);
stmt.setInt(5, 0);
stmt.setInt(6, 0);
stmt.executeUpdate();
}
} catch (SQLException e) {
e.printStackTrace();
}
}
}
public void saveAndRemovePlayer(Player p) {
if (isEnabled) {
PlayerData playerData = getCache().get(p.getUniqueId());
try {
PreparedStatement statement = connection.prepareStatement("UPDATE " + table +
" SET USERNAME=?, LEVEL=?, EXPERIENCE=?, KILLS=?, DEATHS=? WHERE UUID=?");
statement.setString(1, playerData.getUsername());
statement.setInt(2, playerData.getLevel());
statement.setInt(3, playerData.getExperience());
statement.setInt(4, playerData.getKills());
statement.setInt(5, playerData.getDeaths());
statement.setString(6, p.getUniqueId().toString());
statement.executeUpdate();
} catch (SQLException e) {
e.printStackTrace();
}
cache.remove(p.getUniqueId());
}
}
public void importData(Resources resources) {
File file = new File(game.getDataFolder(), "stats.yml");
if (file.exists()) {
file.delete();
}
try {
file.createNewFile();
} catch (IOException e) {
e.printStackTrace();
}
for (UUID uuid: game.getDatabase().getCache().keySet()) {
PlayerData playerData = game.getDatabase().getCache().get(uuid);
resources.getStats().set("Stats.Players." + uuid + ".Username", playerData.getUsername());
resources.getStats().set("Stats.Players." + uuid + ".Level", playerData.getLevel());
resources.getStats().set("Stats.Players." + uuid + ".Experience", playerData.getExperience());
resources.getStats().set("Stats.Players." + uuid + ".Kills", playerData.getKills());
resources.getStats().set("Stats.Players." + uuid + ".Deaths", playerData.getDeaths());
resources.save();
}
}
public void exportData(Resources resources) {
ConfigurationSection stats = resources.getStats().getConfigurationSection("Stats.Players");
PreparedStatement statement = null;
try {
statement = connection.prepareStatement("DELETE FROM " + table);
statement.executeUpdate();
} catch (SQLException e) {
e.printStackTrace();
}
for (String uuid: stats.getKeys(false)) {
String username = resources.getStats().getString("Stats.Players." + uuid + ".Username");
int level = resources.getStats().getInt("Stats.Players." + uuid + ".Level");
int experience = resources.getStats().getInt("Stats.Players." + uuid + ".Experience");
int kills = resources.getStats().getInt("Stats.Players." + uuid + ".Kills");
int deaths = resources.getStats().getInt("Stats.Players." + uuid + ".Deaths");
try {
PreparedStatement stmt = connection.prepareStatement("INSERT INTO " + table + " (UUID, USERNAME, LEVEL, EXPERIENCE, KILLS, DEATHS)" +
" VALUES (?, ?, ?, ?, ?, ?)");
stmt.setString(1, uuid);
stmt.setString(2, username);
stmt.setInt(3, level);
stmt.setInt(4, experience);
stmt.setInt(5, kills);
stmt.setInt(6, deaths);
stmt.executeUpdate();
} catch (SQLException e) {
e.printStackTrace();
}
}
}
public boolean isEnabled() { return isEnabled; }
public Map<UUID, PlayerData> getCache() { return cache; }
}
@@ -21,7 +21,6 @@ public class Resources {
private Resource menu;
private Resource messages;
private Resource scoreboard;
private Resource stats;
private Resource signs;
public Resources(Game plugin) {
@@ -53,10 +52,9 @@ public class Resources {
menu = new Resource(plugin, "menu.yml");
messages = new Resource(plugin, "messages.yml");
scoreboard = new Resource(plugin, "scoreboard.yml");
stats = new Resource(plugin, "stats.yml");
signs = new Resource(plugin, "signs.yml");
for (String fileName : this.getKitList()) {
for (String fileName : this.getKitList(true)) {
kits.put(fileName, new Resource(plugin, "kits/" + fileName));
}
@@ -71,7 +69,6 @@ public class Resources {
menu.load();
messages.load();
scoreboard.load();
stats.load();
signs.load();
messages.addCopyDefaultExemption("Messages.Stats.Message");
@@ -86,8 +83,8 @@ public class Resources {
scoreboard.addCopyDefaultExemption("Scoreboard.Lines");
scoreboard.copyDefaults();
config.addCopyDefaultExemption("Items.Kits");
config.addCopyDefaultExemption("Items.Leave");
config.addCopyDefaultExemption("Items.Kits.Commands");
config.addCopyDefaultExemption("Items.Leave.Commands");
config.copyDefaults();
abilities.copyDefaults();
@@ -98,7 +95,7 @@ public class Resources {
}
// load new kits that have been added through file system (when doing /kp reload)
for (String fileName : getKitList()) {
for (String fileName : getKitList(true)) {
if (!kits.containsKey(fileName)) {
kits.put(fileName, new Resource(plugin, "kits/" + fileName));
}
@@ -121,7 +118,6 @@ public class Resources {
menu.save();
messages.save();
scoreboard.save();
stats.save();
signs.save();
for (String key : kits.keySet()) {
@@ -154,14 +150,17 @@ public class Resources {
}
private List<String> getKitList() {
public List<String> getKitList(boolean withFileEndings) {
File folder = new File(plugin.getDataFolder().getAbsolutePath() + "/kits");
List<String> kitList = new ArrayList<>();
if (folder.exists()) {
return new ArrayList<String>(Arrays.asList(folder.list()));
if (folder.exists() && folder.list() != null) {
for (String fileName : folder.list()) {
kitList.add(withFileEndings ? fileName : fileName.split(".yml")[0]);
}
}
return new ArrayList<String>();
return kitList;
}
@@ -179,8 +178,6 @@ public class Resources {
public Resource getScoreboard() { return scoreboard; }
public Resource getStats() { return stats; }
public Resource getSigns() { return signs; }
}
@@ -0,0 +1,54 @@
package com.zp4rker.localdb;
public class Column {
public String name;
public DataType dataType;
public int limit = 0;
private Object value;
public Column(String name, DataType dataType, int limit) {
this.name = name;
this.dataType = dataType;
this.limit = limit;
}
public Column(String name, DataType dataType) {
this.name = name;
this.dataType = dataType;
this.limit = 0;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public DataType getDataType() {
return dataType;
}
public void setDataType(DataType dataType) {
this.dataType = dataType;
}
public int getLimit() {
return limit;
}
public void setLimit(int limit) {
this.limit = limit;
}
public Object getValue() {
return value;
}
public void setValue(Object value) {
this.value = value;
}
}
@@ -0,0 +1,7 @@
package com.zp4rker.localdb;
public enum DataType {
STRING, INTEGER, FLOAT
}
@@ -0,0 +1,71 @@
package com.zp4rker.localdb;
import org.bukkit.plugin.java.JavaPlugin;
import com.zp4rker.localdb.db.SQLite;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;
public class Database {
private List<Table> tables = new ArrayList<>();
private SQLite sqLite;
public Database(JavaPlugin plugin, String dbName, Table table) {
this.tables.add(table);
this.sqLite = new SQLite(plugin, dbName, this);
sqLite.load();
table.setSqLite(sqLite);
}
public Database(JavaPlugin plugin, String dbName, Table table, String file) {
this.tables.add(table);
this.sqLite = new SQLite(plugin, dbName, this, file);
sqLite.load();
table.setSqLite(sqLite);
}
public List<Table> getTables() {
return tables;
}
public String getTableQuery() {
return tables.get(0).getQuery();
}
public SQLite getDB() {
return this.sqLite;
}
public Connection getConnection() {
return this.sqLite.getSQLConnection();
}
public void addTable(Table table) {
tables.add(table);
table.setSqLite(sqLite);
try {
PreparedStatement statement = this.sqLite.getSQLConnection().prepareStatement(table.getQuery());
statement.executeUpdate();
statement.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
public void deleteTable(Table table) {
tables.remove(table);
try {
PreparedStatement statement = this.sqLite.getSQLConnection().prepareStatement(table.getDeleteQuery());
statement.executeUpdate();
statement.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
}
@@ -0,0 +1,342 @@
package com.zp4rker.localdb;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import com.zp4rker.localdb.db.SQLite;
public class Table {
private String name;
private List<Column> columns = new ArrayList<>();
private Column primaryKey;
private SQLite sqLite;
public Table(String name, Column... columns) {
this.name = name;
this.primaryKey = columns[0];
this.columns.addAll(Arrays.asList(columns));
this.primaryKey = this.columns.get(0);
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public List<Column> getColumns() {
return columns;
}
public void setColumns(List<Column> columns) {
this.columns = columns;
}
public Column getPrimaryKey() {
return primaryKey;
}
public void setPrimaryKey(Column primaryKey) {
this.primaryKey = primaryKey;
}
private static String getStringType(DataType dataType) {
switch(dataType) {
case STRING: return "VARCHAR";
case INTEGER: return "INT";
case FLOAT: return "FLOAT";
default: return null;
}
}
public void setSqLite(SQLite sqLite) {
this.sqLite = sqLite;
}
public String getQuery() {
String query = "CREATE TABLE IF NOT EXISTS " + getName() + " (";
for (Column column : getColumns()) {
query += "`" + column.name + "` ";
query += Table.getStringType(column.dataType);
query += (column.limit > 0 ? " (" + column.limit + "), " : ", ");
}
query += "PRIMARY KEY (`" + primaryKey.getName() + "`)";
query += ");";
return query;
}
public String getDeleteQuery() {
String query = "DROP TABLE IF EXISTS " + getName();
return query;
}
public void insert(Column... columns) {
List<Column> columnList = new ArrayList<>(Arrays.asList(columns));
insert(columnList);
}
private void insert(List<Column> columns) {
if (getExact(columns.get(0)) == null) {
String query = "INSERT INTO " + getName() + " (";
for (Column column : columns) {
if (columns.indexOf(column) < columns.size() - 1) {
query += "`" + column.getName() + "`, ";
} else {
query += "`" + column.getName() + "`) ";
}
}
query += "VALUES (";
for (int i = 0; i < columns.size(); i++) {
if (i < columns.size() - 1) {
query += "?, ";
} else {
query += "?)";
}
}
query += ";";
try {
PreparedStatement s = sqLite.getSQLConnection().prepareStatement(query);
for (int i = 0; i < columns.size(); i++) {
if (columns.get(i).dataType == DataType.STRING) {
s.setString(i + 1, columns.get(i).getValue().toString());
} else if (columns.get(i).dataType == DataType.INTEGER) {
s.setInt(i + 1, Integer.parseInt(columns.get(i).getValue().toString()));
} else {
s.setFloat(i + 1, Float.parseFloat(columns.get(i).getValue().toString()));
}
}
s.executeUpdate();
s.close();
} catch (SQLException e) {
e.printStackTrace();
}
} else {
System.out.println("A row with that name already exists!");
}
}
public List<Column> getExact(Column column) {
List<Column> result = new ArrayList<>();
String query = "SELECT * FROM " + getName() + " WHERE `" + column.getName() + "`=?";
try {
PreparedStatement s = sqLite.getSQLConnection().prepareStatement(query);
if (column.dataType == DataType.STRING) {
s.setString(1, column.getValue().toString());
} else if (column.dataType == DataType.INTEGER) {
s.setInt(1, Integer.parseInt(column.getValue().toString()));
} else {
s.setFloat(1, Float.parseFloat(column.getValue().toString()));
}
ResultSet rs = s.executeQuery();
try {
for (int i = 0; i < getColumns().size(); i++) {
Column rCol = new Column(getColumns().get(i).getName(), getColumns().get(i).dataType,
getColumns().get(i).limit);
if (rCol.dataType == DataType.STRING) {
rCol.setValue(rs.getString(i + 1));
} else if (rCol.dataType == DataType.INTEGER) {
rCol.setValue(rs.getInt(i + 1));
} else {
rCol.setValue(rs.getFloat(i + 1));
}
result.add(rCol);
}
sqLite.close(s, rs);
} catch (SQLException e) {
s.close();
return null;
}
} catch (SQLException e) {
e.printStackTrace();
}
return result;
}
public List<String> getTopN(Column column, int n) {
// will return an ordered list of usernames
// (0) Shredder72 - 700
// (1) cervinakuy - 600
// etc.
return null;
}
public List<List<Column>> search(Column column) {
List<List<Column>> results = new ArrayList<>();
if (!column.getName().equalsIgnoreCase(primaryKey.getName())) {
String query = "SELECT * FROM " + getName() + " WHERE `" + column.getName() + "`=?";
try {
PreparedStatement s = sqLite.getSQLConnection().prepareStatement(query);
// TODO: use setStatementType
if (column.dataType == DataType.STRING) {
s.setString(1, column.getValue().toString());
} else if (column.dataType == DataType.INTEGER) {
s.setInt(1, Integer.parseInt(column.getValue().toString()));
} else {
s.setFloat(1, Float.parseFloat(column.getValue().toString()));
}
ResultSet rs = s.executeQuery();
while (rs.next()) {
List<Column> result = new ArrayList<>();
for (int i = 0; i < getColumns().size(); i++) {
Column rCol = new Column(getColumns().get(i).getName(), getColumns().get(i).dataType,
getColumns().get(i).limit);
if (getColumns().get(i).dataType == DataType.STRING) {
rCol.setValue(rs.getString(i + 1));
} else if (getColumns().get(i).dataType == DataType.INTEGER) {
rCol.setValue(rs.getInt(i + 1));
} else {
rCol.setValue(rs.getFloat(i + 1));
}
result.add(rCol);
}
results.add(result);
}
sqLite.close(s, rs);
} catch (SQLException e) {
e.printStackTrace();
}
return results;
} else {
return null;
}
}
public boolean containsColumn(Column column) {
return getExact(column) != null;
}
private void setStatementType(PreparedStatement preparedStatement, Column column) {
Object value = column.getValue();
DataType type = column.getDataType();
try {
if (type == DataType.STRING) {
preparedStatement.setString(1, value.toString());
} else if (type == DataType.INTEGER) {
preparedStatement.setInt(1, Integer.parseInt(value.toString()));
} else if (type == DataType.FLOAT) {
preparedStatement.setFloat(1, Float.parseFloat(value.toString()));
}
} catch (SQLException e) {
e.printStackTrace();
}
}
public List<List<Column>> getAll() {
List<List<Column>> results = new ArrayList<>();
String query = "SELECT * FROM " + getName();
try {
PreparedStatement s = sqLite.getSQLConnection().prepareStatement(query);
ResultSet rs = s.executeQuery();
while (rs.next()) {
List<Column> result = new ArrayList<>();
for (int i = 0; i < getColumns().size(); i++) {
Column rCol = new Column(getColumns().get(i).getName(), getColumns().get(i).dataType,
getColumns().get(i).limit);
if (getColumns().get(i).dataType == DataType.STRING) {
s.setString(1, getColumns().get(i).getValue().toString());
} else if (getColumns().get(i).dataType == DataType.INTEGER) {
s.setInt(1, Integer.parseInt(getColumns().get(i).getValue().toString()));
} else {
s.setFloat(1, Float.parseFloat(getColumns().get(i).getValue().toString()));
}
result.add(rCol);
}
results.add(result);
}
sqLite.close(s, rs);
} catch (SQLException e) {
e.printStackTrace();
}
return results;
}
public void delete(Column column) {
if (column.getName().equalsIgnoreCase(primaryKey.getName())) {
String query = "DELETE FROM " + getName() + " WHERE `" + column.getName() + "`=?";
try {
PreparedStatement s = sqLite.getSQLConnection().prepareStatement(query);
if (column.dataType == DataType.STRING) {
s.setString(1, column.getValue().toString());
} else if (column.dataType == DataType.INTEGER) {
s.setInt(1, Integer.parseInt(column.getValue().toString()));
} else {
s.setFloat(1, Float.parseFloat(column.getValue().toString()));
}
s.executeUpdate();
s.close();
} catch (SQLException e) {
e.printStackTrace();
}
} else {
System.out.println("Primary key must be used!");
}
}
public void update(Column primaryKey, Column... columns) {
List<Column> columnList = new ArrayList<>(Arrays.asList(columns));
update(primaryKey, columnList);
}
private void update(Column primaryKey, List<Column> columns) {
if (!containsKey(columns)) {
String query = "UPDATE " + getName() + " SET ";
for (Column column : columns) {
if (column.dataType == DataType.STRING) {
query += "`" + column.getName() + "`='" + column.getValue().toString() + "'";
} else {
query += "`" + column.getName() + "`=" + column.getValue().toString();
}
if (columns.indexOf(column) == columns.size() - 1) {
query += " ";
} else {
query += ", ";
}
}
query += "WHERE `" + primaryKey.getName() + "`=";
if (primaryKey.dataType == DataType.STRING) {
query += "'" + primaryKey.getValue().toString() + "'";
} else {
query += primaryKey.getValue().toString();
}
try {
PreparedStatement s = sqLite.getSQLConnection().prepareStatement(query);
s.executeUpdate();
s.close();
} catch (SQLException e) {
e.printStackTrace();
}
} else {
List<Column> newColumns = getExact(primaryKey);
for (Column column : columns) {
if (column.getName().equalsIgnoreCase(primaryKey.getName())) {
newColumns.set(0, column);
} else {
newColumns.set(columns.indexOf(column), column);
}
}
delete(primaryKey);
insert(newColumns);
}
}
private boolean containsKey(List<Column> columns) {
for (Column column : columns) {
if (column.getName().equalsIgnoreCase(primaryKey.getName())) {
return true;
}
}
return false;
}
}
@@ -0,0 +1,14 @@
package com.zp4rker.localdb.db;
import org.bukkit.plugin.java.JavaPlugin;
import java.util.logging.Level;
public class Error {
public static void execute(JavaPlugin plugin, Exception ex){
plugin.getLogger().log(Level.SEVERE, "Couldn't execute MySQL statement: ", ex);
}
public static void close(JavaPlugin plugin, Exception ex){
plugin.getLogger().log(Level.SEVERE, "Failed to close MySQL connection: ", ex);
}
}
@@ -0,0 +1,16 @@
package com.zp4rker.localdb.db;
public class Errors {
public static String sqlConnectionExecute(){
return "Couldn't execute MySQL statement: ";
}
public static String sqlConnectionClose(){
return "Failed to close MySQL connection: ";
}
public static String noSQLConnection(){
return "Unable to retreive MYSQL connection: ";
}
public static String noTableFound(){
return "DB Error: No Table Found";
}
}
@@ -0,0 +1,104 @@
package com.zp4rker.localdb.db;
import org.bukkit.plugin.java.JavaPlugin;
import com.zp4rker.localdb.Database;
import java.io.File;
import java.io.IOException;
import java.sql.*;
import java.util.logging.Level;
public class SQLite {
private String dbName;
private String query;
private boolean inDF = true;
private String dir;
private JavaPlugin plugin;
private Connection connection;
public SQLite(JavaPlugin instance, String dbName, Database db) {
this.plugin = instance;
this.dbName = dbName;
query = db.getTableQuery();
this.connection = getSQLConnection();
}
public SQLite(JavaPlugin instance, String dbName, Database db, String directory) {
this.plugin = instance;
this.dbName = dbName;
query = db.getTableQuery();
this.inDF = false;
this.dir = directory;
this.connection = getSQLConnection();
}
public Connection getSQLConnection() {
File file;
if (inDF) {
file = new File(plugin.getDataFolder(), dbName + ".db");
plugin.getDataFolder().mkdirs();
} else {
new File(this.dir).mkdirs();
file = new File(this.dir + "/" + dbName + ".db");
}
if (!file.exists()) {
try {
file.createNewFile();
} catch (IOException e) {
plugin.getLogger().log(Level.SEVERE, "File write error: " + dbName + ".db");
}
}
try {
if (connection != null && !connection.isClosed()) {
return connection;
}
Class.forName("org.sqlite.JDBC");
connection = DriverManager.getConnection("jdbc:sqlite:" + file);
return connection;
} catch (SQLException ex) {
plugin.getLogger().log(Level.SEVERE, "SQLite exception on initialize", ex);
} catch (ClassNotFoundException ex) {
plugin.getLogger().log(Level.SEVERE, "You need the SQLite JBDC library. Google it. Put it in /lib folder.");
}
return null;
}
public void load() {
connection = getSQLConnection();
try {
PreparedStatement s = connection.prepareStatement(query);
s.executeUpdate();
s.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
public void close(PreparedStatement ps, ResultSet rs) {
try {
if (ps != null)
ps.close();
if (rs != null)
rs.close();
} catch (SQLException ex) {
Error.close(plugin, ex);
}
}
public void closeConnection() {
try {
if (!(connection.isClosed())) {
connection.close();
connection = null;
} else {
connection = null;
}
} catch(Exception e) {
Error.close(plugin, e);
}
}
}
+3 -10
View File
@@ -17,6 +17,9 @@ Items:
Slot: 8
BungeeCord:
Server: Hub
Enabled: false
Multiworld:
World: Hub
Enabled: true
Commands: []
Chat:
@@ -87,16 +90,6 @@ Commands:
Kit: false
Kits: false
Stats: false
#either put MySQl or YAML
Storage:
Type: YAML
MySQL:
Host: planetgallium.com
Database: kitpvp
Table: kitpvp_userdata
Port: 3306
Username: walrus
Password: supersecretpassword
Arena:
ClearPotionEffectsOnJoin: true
ClearInventoryOnJoin: true
-8
View File
@@ -1,8 +0,0 @@
Stats:
Players:
9d0a15ca-55fd-4fe0-8f73-28512b23d9f1:
Username: 'cervinakuy'
Level: 100
Experience: 0
Kills: 10000
Deaths: 0