Initial commit.
This commit is contained in:
@@ -0,0 +1,24 @@
|
||||
package org.mobarena.stats;
|
||||
|
||||
import org.mobarena.stats.store.StatsStore;
|
||||
import org.mobarena.stats.store.StatsStoreRegistry;
|
||||
|
||||
import java.io.File;
|
||||
import java.util.concurrent.Executor;
|
||||
import java.util.logging.Logger;
|
||||
|
||||
public interface MobArenaStats {
|
||||
|
||||
Logger getLogger();
|
||||
|
||||
Executor getSyncExecutor();
|
||||
|
||||
Executor getAsyncExecutor();
|
||||
|
||||
StatsStore getStatsStore();
|
||||
|
||||
StatsStoreRegistry getStatsStoreRegistry();
|
||||
|
||||
File getDataFolder();
|
||||
|
||||
}
|
||||
@@ -0,0 +1,193 @@
|
||||
package org.mobarena.stats;
|
||||
|
||||
import com.garbagemule.MobArena.MobArena;
|
||||
import com.garbagemule.MobArena.commands.CommandHandler;
|
||||
import org.bukkit.command.PluginCommand;
|
||||
import org.bukkit.configuration.ConfigurationSection;
|
||||
import org.bukkit.event.HandlerList;
|
||||
import org.bukkit.plugin.PluginManager;
|
||||
import org.mobarena.stats.command.ArenaStatsCommand;
|
||||
import org.mobarena.stats.command.DeleteSessionStatsCommand;
|
||||
import org.mobarena.stats.command.ExportCommand;
|
||||
import org.mobarena.stats.command.GlobalStatsCommand;
|
||||
import org.mobarena.stats.command.ImportCommand;
|
||||
import org.mobarena.stats.command.PlayerStatsCommand;
|
||||
import org.mobarena.stats.platform.AsyncBukkitExecutor;
|
||||
import org.mobarena.stats.platform.SyncBukkitExecutor;
|
||||
import org.mobarena.stats.session.SessionListener;
|
||||
import org.mobarena.stats.session.SessionStore;
|
||||
import org.mobarena.stats.store.StatsStore;
|
||||
import org.bukkit.plugin.java.JavaPlugin;
|
||||
import org.bukkit.scheduler.BukkitScheduler;
|
||||
import org.mobarena.stats.store.StatsStoreRegistry;
|
||||
import org.mobarena.stats.store.csv.CsvStatsStore;
|
||||
import org.mobarena.stats.store.jdbc.JdbcStatsStore;
|
||||
import org.mobarena.stats.store.mariadb.MariadbStatsStore;
|
||||
import org.mobarena.stats.store.mysql.MysqlStatsStore;
|
||||
import org.mobarena.stats.store.sqlite.SqliteStatsStore;
|
||||
|
||||
import java.io.File;
|
||||
import java.util.concurrent.Executor;
|
||||
import java.util.logging.Level;
|
||||
|
||||
public class MobArenaStatsPlugin extends JavaPlugin implements MobArenaStats {
|
||||
|
||||
// The sad state of affairs is that MobArena's command framework has no
|
||||
// support for registering commands by instance, but only by class, which
|
||||
// means that we can't properly inject dependencies and have to resort to
|
||||
// the Singleton Pattern.
|
||||
private static MobArenaStats instance;
|
||||
|
||||
private StatsStoreRegistry statsStoreRegistry;
|
||||
|
||||
private Executor syncExecutor;
|
||||
private Executor asyncExecutor;
|
||||
|
||||
private SessionStore sessionStore;
|
||||
private StatsStore statsStore;
|
||||
private SessionListener sessionListener;
|
||||
|
||||
@Override
|
||||
public void onLoad() {
|
||||
createStatsStoreRegistry();
|
||||
registerStatsStoreFactories();
|
||||
}
|
||||
|
||||
private void createStatsStoreRegistry() {
|
||||
statsStoreRegistry = StatsStoreRegistry.create(this);
|
||||
}
|
||||
|
||||
private void registerStatsStoreFactories() {
|
||||
statsStoreRegistry.register("csv", CsvStatsStore::create);
|
||||
statsStoreRegistry.register("jdbc", JdbcStatsStore::create);
|
||||
statsStoreRegistry.register("sqlite", SqliteStatsStore::create);
|
||||
statsStoreRegistry.register("mysql", MysqlStatsStore::create);
|
||||
statsStoreRegistry.register("mariadb", MariadbStatsStore::create);
|
||||
}
|
||||
|
||||
@Override
|
||||
public void onEnable() {
|
||||
setup();
|
||||
reload();
|
||||
}
|
||||
|
||||
private void setup() {
|
||||
try {
|
||||
instance = this;
|
||||
|
||||
createDataFolder();
|
||||
createConfigFile();
|
||||
setupExecutors();
|
||||
setupCommands();
|
||||
} catch (Exception up) {
|
||||
// If setup fails, we can't recover, so throw up
|
||||
throw new RuntimeException(up);
|
||||
}
|
||||
}
|
||||
|
||||
private void createDataFolder() {
|
||||
File dir = getDataFolder();
|
||||
if (!dir.exists()) {
|
||||
if (!dir.mkdir()) {
|
||||
throw new IllegalStateException("Failed to create plugin data folder!");
|
||||
}
|
||||
getLogger().info("Data folder created.");
|
||||
}
|
||||
}
|
||||
|
||||
private void createConfigFile() {
|
||||
File file = new File(getDataFolder(), "config.yml");
|
||||
if (!file.exists()) {
|
||||
saveResource("config.yml", false);
|
||||
getLogger().info("config.yml created.");
|
||||
}
|
||||
}
|
||||
|
||||
private void setupExecutors() {
|
||||
BukkitScheduler scheduler = getServer().getScheduler();
|
||||
if (syncExecutor == null) {
|
||||
syncExecutor = new SyncBukkitExecutor(this, scheduler);
|
||||
}
|
||||
if (asyncExecutor == null) {
|
||||
asyncExecutor = new AsyncBukkitExecutor(this, scheduler);
|
||||
}
|
||||
}
|
||||
|
||||
private void setupCommands() {
|
||||
PluginManager manager = getServer().getPluginManager();
|
||||
MobArena mobarena = (MobArena) manager.getPlugin("MobArena");
|
||||
|
||||
PluginCommand command = mobarena.getCommand("ma");
|
||||
CommandHandler handler = (CommandHandler) command.getExecutor();
|
||||
|
||||
// User commands
|
||||
handler.register(ArenaStatsCommand.class);
|
||||
handler.register(GlobalStatsCommand.class);
|
||||
handler.register(PlayerStatsCommand.class);
|
||||
|
||||
// Admin commands
|
||||
handler.register(DeleteSessionStatsCommand.class);
|
||||
handler.register(ExportCommand.class);
|
||||
handler.register(ImportCommand.class);
|
||||
}
|
||||
|
||||
private void reload() {
|
||||
try {
|
||||
createSessionStore();
|
||||
loadStatsStore();
|
||||
registerSessionListener();
|
||||
} catch (Exception e) {
|
||||
getLogger().log(Level.SEVERE, "Load failure", e);
|
||||
}
|
||||
}
|
||||
|
||||
private void createSessionStore() {
|
||||
if (sessionStore != null) {
|
||||
sessionStore.clear();
|
||||
}
|
||||
|
||||
sessionStore = SessionStore.createNew();
|
||||
getLogger().info("Session store created.");
|
||||
}
|
||||
|
||||
private void loadStatsStore() throws Exception {
|
||||
ConfigurationSection config = getConfig();
|
||||
ConfigurationSection section = config.getConfigurationSection("store");
|
||||
if (section == null) {
|
||||
throw new IllegalArgumentException("No store section in config-file.");
|
||||
}
|
||||
|
||||
statsStore = statsStoreRegistry.create(section);
|
||||
}
|
||||
|
||||
private void registerSessionListener() {
|
||||
if (sessionListener != null) {
|
||||
HandlerList.unregisterAll(sessionListener);
|
||||
}
|
||||
|
||||
sessionListener = new SessionListener(sessionStore, statsStore, asyncExecutor, getLogger());
|
||||
getServer().getPluginManager().registerEvents(sessionListener, this);
|
||||
getLogger().info("Session listener registered.");
|
||||
}
|
||||
|
||||
public StatsStoreRegistry getStatsStoreRegistry() {
|
||||
return statsStoreRegistry;
|
||||
}
|
||||
|
||||
public Executor getSyncExecutor() {
|
||||
return syncExecutor;
|
||||
}
|
||||
|
||||
public Executor getAsyncExecutor() {
|
||||
return asyncExecutor;
|
||||
}
|
||||
|
||||
public StatsStore getStatsStore() {
|
||||
return statsStore;
|
||||
}
|
||||
|
||||
public static MobArenaStats getInstance() {
|
||||
return instance;
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,57 @@
|
||||
package org.mobarena.stats.command;
|
||||
|
||||
import com.garbagemule.MobArena.commands.Command;
|
||||
import com.garbagemule.MobArena.commands.CommandInfo;
|
||||
import com.garbagemule.MobArena.framework.ArenaMaster;
|
||||
import com.garbagemule.MobArena.util.Slugs;
|
||||
import org.bukkit.command.CommandSender;
|
||||
import org.bukkit.entity.Player;
|
||||
import org.mobarena.stats.MobArenaStats;
|
||||
import org.mobarena.stats.MobArenaStatsPlugin;
|
||||
import org.mobarena.stats.store.ArenaStats;
|
||||
import org.mobarena.stats.store.StatsStore;
|
||||
|
||||
import java.util.List;
|
||||
|
||||
@CommandInfo(
|
||||
name = "arena-stats",
|
||||
pattern = "arena-stats",
|
||||
usage = "/ma arena-stats <arena>",
|
||||
desc = "show overall stats for the given arena",
|
||||
permission = "mobarenastats.command.arena-stats"
|
||||
)
|
||||
public class ArenaStatsCommand implements Command {
|
||||
|
||||
@Override
|
||||
public boolean execute(ArenaMaster am, CommandSender sender, String... args) {
|
||||
// :(
|
||||
MobArenaStats plugin = MobArenaStatsPlugin.getInstance();
|
||||
|
||||
if (args.length < 1) {
|
||||
return false;
|
||||
}
|
||||
String slug = Slugs.create(args[0]);
|
||||
|
||||
plugin.getAsyncExecutor().execute(() -> {
|
||||
StatsStore store = plugin.getStatsStore();
|
||||
ArenaStats stats = store.getArenaStats(slug);
|
||||
sender.sendMessage("Stats for arena " + slug + ":");
|
||||
sender.sendMessage("- Highest wave: " + stats.highestWave);
|
||||
sender.sendMessage("- Longest duration: " + stats.highestSeconds + " secs");
|
||||
sender.sendMessage("- Most kills: " + stats.highestKills);
|
||||
sender.sendMessage("- Total sessions: " + stats.totalSessions);
|
||||
sender.sendMessage("- Total duration: " + stats.totalSeconds + " secs");
|
||||
sender.sendMessage("- Total kills: " + stats.totalKills);
|
||||
sender.sendMessage("- Total waves: " + stats.totalWaves);
|
||||
});
|
||||
|
||||
return true;
|
||||
}
|
||||
|
||||
@Override
|
||||
public List<String> tab(ArenaMaster am, Player player, String... args) {
|
||||
// TODO: tab complete arena slugs?
|
||||
return Command.super.tab(am, player, args);
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,56 @@
|
||||
package org.mobarena.stats.command;
|
||||
|
||||
import com.garbagemule.MobArena.Messenger;
|
||||
import com.garbagemule.MobArena.commands.Command;
|
||||
import com.garbagemule.MobArena.commands.CommandInfo;
|
||||
import com.garbagemule.MobArena.framework.ArenaMaster;
|
||||
import org.bukkit.ChatColor;
|
||||
import org.bukkit.command.CommandSender;
|
||||
import org.bukkit.entity.Player;
|
||||
import org.mobarena.stats.MobArenaStats;
|
||||
import org.mobarena.stats.MobArenaStatsPlugin;
|
||||
import org.mobarena.stats.store.StatsStore;
|
||||
|
||||
import java.util.List;
|
||||
import java.util.UUID;
|
||||
|
||||
@CommandInfo(
|
||||
name = "delete-session-stats",
|
||||
pattern = "delete-session-stats",
|
||||
usage = "/ma delete-session-stats <session-id>",
|
||||
desc = "delete all stats collected for the given session",
|
||||
permission = "mobarenastats.command.delete-session-stats"
|
||||
)
|
||||
public class DeleteSessionStatsCommand implements Command {
|
||||
|
||||
@Override
|
||||
public boolean execute(ArenaMaster am, CommandSender sender, String... args) {
|
||||
// :(
|
||||
MobArenaStats plugin = MobArenaStatsPlugin.getInstance();
|
||||
|
||||
// TODO: check args, handle non-UUID input error
|
||||
UUID sessionId = UUID.fromString(args[0]);
|
||||
|
||||
StatsStore store = plugin.getStatsStore();
|
||||
Messenger messenger = am.getGlobalMessenger();
|
||||
|
||||
plugin.getAsyncExecutor().execute(() -> {
|
||||
store.delete(sessionId);
|
||||
messenger.tell(sender, String.format(
|
||||
"Stats for session %s%s%s deleted.",
|
||||
ChatColor.YELLOW,
|
||||
sessionId,
|
||||
ChatColor.RESET
|
||||
));
|
||||
});
|
||||
|
||||
return true;
|
||||
}
|
||||
|
||||
@Override
|
||||
public List<String> tab(ArenaMaster am, Player player, String... args) {
|
||||
// TODO: tab complete session IDs?
|
||||
return Command.super.tab(am, player, args);
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,57 @@
|
||||
package org.mobarena.stats.command;
|
||||
|
||||
import com.garbagemule.MobArena.Messenger;
|
||||
import com.garbagemule.MobArena.commands.Command;
|
||||
import com.garbagemule.MobArena.commands.CommandInfo;
|
||||
import com.garbagemule.MobArena.framework.ArenaMaster;
|
||||
import org.bukkit.ChatColor;
|
||||
import org.bukkit.command.CommandSender;
|
||||
import org.mobarena.stats.MobArenaStats;
|
||||
import org.mobarena.stats.MobArenaStatsPlugin;
|
||||
import org.mobarena.stats.store.StatsExport;
|
||||
import org.mobarena.stats.store.StatsStore;
|
||||
import org.mobarena.stats.store.StatsStoreRegistry;
|
||||
|
||||
@CommandInfo(
|
||||
name = "export-stats",
|
||||
pattern = "export-stats",
|
||||
usage = "/ma export-stats",
|
||||
desc = "export the current stats store to a file in the given format",
|
||||
permission = "mobarenastats.command.export-stats"
|
||||
)
|
||||
public class ExportCommand implements Command {
|
||||
|
||||
@Override
|
||||
public boolean execute(ArenaMaster am, CommandSender sender, String... args) {
|
||||
// :(
|
||||
MobArenaStats plugin = MobArenaStatsPlugin.getInstance();
|
||||
|
||||
StatsStore store = plugin.getStatsStore();
|
||||
StatsStoreRegistry registry = plugin.getStatsStoreRegistry();
|
||||
|
||||
Messenger messenger = am.getGlobalMessenger();
|
||||
messenger.tell(sender, "Exporting stats. This may take a while...");
|
||||
plugin.getAsyncExecutor().execute(() -> {
|
||||
try {
|
||||
String filename = StatsExport.run(store, registry);
|
||||
|
||||
messenger.tell(sender, String.format(
|
||||
"Export to %s%s%s complete.",
|
||||
ChatColor.YELLOW,
|
||||
filename,
|
||||
ChatColor.RESET
|
||||
));
|
||||
} catch (Exception e) {
|
||||
messenger.tell(sender, String.format(
|
||||
"Export %sfailed%s because:\n%s",
|
||||
ChatColor.RED,
|
||||
ChatColor.RESET,
|
||||
e.getMessage()
|
||||
));
|
||||
}
|
||||
});
|
||||
|
||||
return true;
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,39 @@
|
||||
package org.mobarena.stats.command;
|
||||
|
||||
import com.garbagemule.MobArena.commands.Command;
|
||||
import com.garbagemule.MobArena.commands.CommandInfo;
|
||||
import com.garbagemule.MobArena.framework.ArenaMaster;
|
||||
import org.bukkit.command.CommandSender;
|
||||
import org.mobarena.stats.MobArenaStats;
|
||||
import org.mobarena.stats.MobArenaStatsPlugin;
|
||||
import org.mobarena.stats.store.GlobalStats;
|
||||
import org.mobarena.stats.store.StatsStore;
|
||||
|
||||
@CommandInfo(
|
||||
name = "global-stats",
|
||||
pattern = "global-stats",
|
||||
usage = "/ma global-stats",
|
||||
desc = "show stats across all sessions",
|
||||
permission = "mobarenastats.command.global-stats"
|
||||
)
|
||||
public class GlobalStatsCommand implements Command {
|
||||
|
||||
@Override
|
||||
public boolean execute(ArenaMaster am, CommandSender sender, String... args) {
|
||||
// :(
|
||||
MobArenaStats plugin = MobArenaStatsPlugin.getInstance();
|
||||
|
||||
plugin.getAsyncExecutor().execute(() -> {
|
||||
StatsStore store = plugin.getStatsStore();
|
||||
GlobalStats stats = store.getGlobalStats();
|
||||
sender.sendMessage("Global stats:");
|
||||
sender.sendMessage("- Total sessions: " + stats.totalSessions);
|
||||
sender.sendMessage("- Total duration: " + stats.totalSeconds + " secs");
|
||||
sender.sendMessage("- Total kills: " + stats.totalKills);
|
||||
sender.sendMessage("- Total waves: " + stats.totalWaves);
|
||||
});
|
||||
|
||||
return true;
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,130 @@
|
||||
package org.mobarena.stats.command;
|
||||
|
||||
import com.garbagemule.MobArena.Messenger;
|
||||
import com.garbagemule.MobArena.commands.Command;
|
||||
import com.garbagemule.MobArena.commands.CommandInfo;
|
||||
import com.garbagemule.MobArena.framework.ArenaMaster;
|
||||
import org.bukkit.ChatColor;
|
||||
import org.bukkit.command.CommandSender;
|
||||
import org.bukkit.entity.Player;
|
||||
import org.mobarena.stats.MobArenaStats;
|
||||
import org.mobarena.stats.MobArenaStatsPlugin;
|
||||
import org.mobarena.stats.store.StatsExport;
|
||||
import org.mobarena.stats.store.StatsImport;
|
||||
import org.mobarena.stats.store.StatsStore;
|
||||
import org.mobarena.stats.store.StatsStoreRegistry;
|
||||
|
||||
import java.nio.file.Files;
|
||||
import java.nio.file.Path;
|
||||
import java.util.Arrays;
|
||||
import java.util.Collections;
|
||||
import java.util.List;
|
||||
import java.util.stream.Collectors;
|
||||
|
||||
@CommandInfo(
|
||||
name = "import-stats",
|
||||
pattern = "import-stats",
|
||||
usage = "/ma import-stats <filename>",
|
||||
desc = "import stats from an database export file into the current stats store",
|
||||
permission = "mobarenastats.command.import-stats"
|
||||
)
|
||||
public class ImportCommand implements Command {
|
||||
|
||||
@Override
|
||||
public boolean execute(ArenaMaster am, CommandSender sender, String... args) {
|
||||
if (args.length < 1) {
|
||||
return false;
|
||||
}
|
||||
|
||||
// :(
|
||||
MobArenaStats plugin = MobArenaStatsPlugin.getInstance();
|
||||
|
||||
Path data = plugin.getDataFolder().toPath();
|
||||
Path file = data.resolve(args[0]);
|
||||
if (!Files.exists(file)) {
|
||||
sender.sendMessage(String.format(
|
||||
"File %s%s%s not found.",
|
||||
ChatColor.YELLOW,
|
||||
args[0],
|
||||
ChatColor.RESET
|
||||
));
|
||||
return false;
|
||||
}
|
||||
|
||||
String filename = file.getFileName().toString();
|
||||
if (!filename.startsWith(StatsExport.FILENAME_PREFIX)) {
|
||||
sender.sendMessage(String.format(
|
||||
"Not a valid database export; filename must start with %s%s%s.",
|
||||
ChatColor.YELLOW,
|
||||
StatsExport.FILENAME_PREFIX,
|
||||
ChatColor.RESET
|
||||
));
|
||||
return true;
|
||||
}
|
||||
if (!filename.endsWith(StatsExport.FILENAME_SUFFIX)) {
|
||||
sender.sendMessage(String.format(
|
||||
"Not a valid database export; filename must end with %s%s%s.",
|
||||
ChatColor.YELLOW,
|
||||
StatsExport.FILENAME_SUFFIX,
|
||||
ChatColor.RESET
|
||||
));
|
||||
return true;
|
||||
}
|
||||
|
||||
StatsStore store = plugin.getStatsStore();
|
||||
StatsStoreRegistry registry = plugin.getStatsStoreRegistry();
|
||||
|
||||
Messenger messenger = am.getGlobalMessenger();
|
||||
messenger.tell(sender, String.format(
|
||||
"Importing stats from %s%s%s. This may take a while...",
|
||||
ChatColor.YELLOW,
|
||||
filename,
|
||||
ChatColor.RESET
|
||||
));
|
||||
plugin.getAsyncExecutor().execute(() -> {
|
||||
try {
|
||||
StatsImport.run(registry, filename, store);
|
||||
|
||||
messenger.tell(sender, String.format(
|
||||
"Import from %s%s%s complete.",
|
||||
ChatColor.YELLOW,
|
||||
filename,
|
||||
ChatColor.RESET
|
||||
));
|
||||
} catch (Exception e) {
|
||||
messenger.tell(sender, String.format(
|
||||
"Import %sfailed%s because:\n%s",
|
||||
ChatColor.RED,
|
||||
ChatColor.RESET,
|
||||
e.getMessage()
|
||||
));
|
||||
}
|
||||
});
|
||||
|
||||
return true;
|
||||
}
|
||||
|
||||
@Override
|
||||
public List<String> tab(ArenaMaster am, Player player, String... args) {
|
||||
if (args.length > 1) {
|
||||
return Collections.emptyList();
|
||||
}
|
||||
|
||||
// :(
|
||||
MobArenaStats plugin = MobArenaStatsPlugin.getInstance();
|
||||
|
||||
String[] files = plugin.getDataFolder().list();
|
||||
if (files == null || files.length == 0) {
|
||||
return Collections.emptyList();
|
||||
}
|
||||
|
||||
String prefix = (args.length == 1) ? args[0] : "";
|
||||
|
||||
return Arrays.stream(files)
|
||||
.filter(filename -> filename.startsWith(prefix))
|
||||
.filter(filename -> filename.startsWith(StatsExport.FILENAME_PREFIX))
|
||||
.filter(filename -> filename.endsWith(StatsExport.FILENAME_SUFFIX))
|
||||
.collect(Collectors.toList());
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,58 @@
|
||||
package org.mobarena.stats.command;
|
||||
|
||||
import com.garbagemule.MobArena.commands.Command;
|
||||
import com.garbagemule.MobArena.commands.CommandInfo;
|
||||
import com.garbagemule.MobArena.framework.ArenaMaster;
|
||||
import org.bukkit.command.CommandSender;
|
||||
import org.bukkit.entity.Player;
|
||||
import org.mobarena.stats.MobArenaStats;
|
||||
import org.mobarena.stats.MobArenaStatsPlugin;
|
||||
import org.mobarena.stats.store.PlayerStats;
|
||||
import org.mobarena.stats.store.StatsStore;
|
||||
|
||||
import java.util.List;
|
||||
|
||||
@CommandInfo(
|
||||
name = "player-stats",
|
||||
pattern = "player-stats",
|
||||
usage = "/ma player-stats <player>",
|
||||
desc = "show overall stats for the given player",
|
||||
permission = "mobarenastats.command.player-stats"
|
||||
)
|
||||
public class PlayerStatsCommand implements Command {
|
||||
|
||||
@Override
|
||||
public boolean execute(ArenaMaster am, CommandSender sender, String... args) {
|
||||
// :(
|
||||
MobArenaStats plugin = MobArenaStatsPlugin.getInstance();
|
||||
|
||||
String name;
|
||||
if (args.length == 0) {
|
||||
if (!(sender instanceof Player)) {
|
||||
return false;
|
||||
}
|
||||
name = sender.getName();
|
||||
} else {
|
||||
name = args[0];
|
||||
}
|
||||
|
||||
plugin.getAsyncExecutor().execute(() -> {
|
||||
StatsStore store = plugin.getStatsStore();
|
||||
PlayerStats stats = store.getPlayerStats(name);
|
||||
sender.sendMessage("Stats for player " + name + ":");
|
||||
sender.sendMessage("- Total sessions: " + stats.totalSessions);
|
||||
sender.sendMessage("- Total duration: " + stats.totalSeconds + " secs");
|
||||
sender.sendMessage("- Total kills: " + stats.totalKills);
|
||||
sender.sendMessage("- Total waves: " + stats.totalWaves);
|
||||
});
|
||||
|
||||
return true;
|
||||
}
|
||||
|
||||
@Override
|
||||
public List<String> tab(ArenaMaster am, Player player, String... args) {
|
||||
// TODO: tab complete player names?
|
||||
return Command.super.tab(am, player, args);
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,23 @@
|
||||
package org.mobarena.stats.platform;
|
||||
|
||||
import org.bukkit.plugin.Plugin;
|
||||
import org.bukkit.scheduler.BukkitScheduler;
|
||||
|
||||
import java.util.concurrent.Executor;
|
||||
|
||||
public class AsyncBukkitExecutor implements Executor {
|
||||
|
||||
private final Plugin plugin;
|
||||
private final BukkitScheduler scheduler;
|
||||
|
||||
public AsyncBukkitExecutor(Plugin plugin, BukkitScheduler scheduler) {
|
||||
this.plugin = plugin;
|
||||
this.scheduler = scheduler;
|
||||
}
|
||||
|
||||
@Override
|
||||
public void execute(Runnable command) {
|
||||
scheduler.runTaskAsynchronously(plugin, command);
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,23 @@
|
||||
package org.mobarena.stats.platform;
|
||||
|
||||
import org.bukkit.plugin.Plugin;
|
||||
import org.bukkit.scheduler.BukkitScheduler;
|
||||
|
||||
import java.util.concurrent.Executor;
|
||||
|
||||
public class SyncBukkitExecutor implements Executor {
|
||||
|
||||
private final Plugin plugin;
|
||||
private final BukkitScheduler scheduler;
|
||||
|
||||
public SyncBukkitExecutor(Plugin plugin, BukkitScheduler scheduler) {
|
||||
this.plugin = plugin;
|
||||
this.scheduler = scheduler;
|
||||
}
|
||||
|
||||
@Override
|
||||
public void execute(Runnable command) {
|
||||
scheduler.runTask(plugin, command);
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,23 @@
|
||||
package org.mobarena.stats.session;
|
||||
|
||||
public enum PlayerConclusion {
|
||||
|
||||
/**
|
||||
* When an arena has a final wave and the given player reaches and
|
||||
* completes that wave, the player session concludes in a victory.
|
||||
*/
|
||||
VICTORY,
|
||||
|
||||
/**
|
||||
* When the given player dies in an arena, the player's session will
|
||||
* concludes in a defeat, even if other players are still alive.
|
||||
*/
|
||||
DEFEAT,
|
||||
|
||||
/**
|
||||
* When the given player leaves an ongoing arena, the player's session
|
||||
* will conclude in a retreat, even if other players are still alive.
|
||||
*/
|
||||
RETREAT,
|
||||
|
||||
}
|
||||
@@ -0,0 +1,38 @@
|
||||
package org.mobarena.stats.session;
|
||||
|
||||
import java.time.Instant;
|
||||
import java.util.UUID;
|
||||
|
||||
public class PlayerSessionStats {
|
||||
|
||||
public final UUID sessionId;
|
||||
public final UUID playerId;
|
||||
public final String playerName;
|
||||
|
||||
public String className;
|
||||
|
||||
public Instant joinTime;
|
||||
public Instant readyTime;
|
||||
public Instant leaveTime;
|
||||
public Instant deathTime;
|
||||
|
||||
public int kills;
|
||||
public int dmgDone;
|
||||
public int dmgTaken;
|
||||
public int swings;
|
||||
public int hits;
|
||||
public int lastWave;
|
||||
|
||||
public PlayerConclusion conclusion;
|
||||
|
||||
public PlayerSessionStats(
|
||||
UUID sessionId,
|
||||
UUID playerId,
|
||||
String playerName
|
||||
) {
|
||||
this.sessionId = sessionId;
|
||||
this.playerId = playerId;
|
||||
this.playerName = playerName;
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,130 @@
|
||||
package org.mobarena.stats.session;
|
||||
|
||||
import com.garbagemule.MobArena.framework.Arena;
|
||||
import org.bukkit.entity.Player;
|
||||
|
||||
import java.time.Instant;
|
||||
import java.util.Collection;
|
||||
import java.util.HashMap;
|
||||
import java.util.Map;
|
||||
import java.util.UUID;
|
||||
|
||||
public class Session {
|
||||
|
||||
final UUID sessionId;
|
||||
final String arenaSlug;
|
||||
|
||||
final SessionStats sessionStats;
|
||||
final Map<UUID, PlayerSessionStats> playerStats;
|
||||
|
||||
public Session(UUID sessionId, String arenaSlug) {
|
||||
this.sessionId = sessionId;
|
||||
this.arenaSlug = arenaSlug;
|
||||
|
||||
this.sessionStats = new SessionStats(sessionId, arenaSlug);
|
||||
this.playerStats = new HashMap<>();
|
||||
}
|
||||
|
||||
public void playerJoin(Player player) {
|
||||
UUID playerId = player.getUniqueId();
|
||||
String playerName = player.getName();
|
||||
PlayerSessionStats stats = new PlayerSessionStats(sessionId, playerId, playerName);
|
||||
playerStats.put(playerId, stats);
|
||||
|
||||
stats.joinTime = Instant.now();
|
||||
}
|
||||
|
||||
public void playerReady(Player player, String className) {
|
||||
UUID playerId = player.getUniqueId();
|
||||
PlayerSessionStats stats = playerStats.get(playerId);
|
||||
if (stats == null) {
|
||||
return;
|
||||
}
|
||||
|
||||
stats.readyTime = Instant.now();
|
||||
stats.className = className;
|
||||
}
|
||||
|
||||
public void playerLeave(Arena arena, Player player) {
|
||||
UUID playerId = player.getUniqueId();
|
||||
PlayerSessionStats stats = playerStats.get(playerId);
|
||||
if (stats == null) {
|
||||
return;
|
||||
}
|
||||
|
||||
stats.leaveTime = Instant.now();
|
||||
|
||||
if (stats.conclusion == null) {
|
||||
stats.conclusion = PlayerConclusion.RETREAT;
|
||||
}
|
||||
|
||||
StatsUtil.copy(arena, player, stats);
|
||||
}
|
||||
|
||||
public void playerDeath(Arena arena, Player player) {
|
||||
UUID playerId = player.getUniqueId();
|
||||
PlayerSessionStats stats = playerStats.get(playerId);
|
||||
if (stats == null) {
|
||||
return;
|
||||
}
|
||||
|
||||
stats.deathTime = Instant.now();
|
||||
|
||||
if (stats.conclusion == null) {
|
||||
stats.conclusion = PlayerConclusion.DEFEAT;
|
||||
}
|
||||
|
||||
StatsUtil.copy(arena, player, stats);
|
||||
}
|
||||
|
||||
public void start() {
|
||||
sessionStats.startTime = Instant.now();
|
||||
}
|
||||
|
||||
public void wave(int wave) {
|
||||
sessionStats.lastWave = wave;
|
||||
}
|
||||
|
||||
public void complete() {
|
||||
sessionStats.conclusion = SessionConclusion.VICTORY;
|
||||
|
||||
for (PlayerSessionStats playerStats : playerStats.values()) {
|
||||
if (playerStats.conclusion == null) {
|
||||
playerStats.conclusion = PlayerConclusion.VICTORY;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
public void end() {
|
||||
sessionStats.endTime = Instant.now();
|
||||
|
||||
if (sessionStats.conclusion == null) {
|
||||
sessionStats.conclusion = SessionConclusion.DEFEAT;
|
||||
}
|
||||
}
|
||||
|
||||
public UUID getSessionId() {
|
||||
return sessionId;
|
||||
}
|
||||
|
||||
public String getArenaSlug() {
|
||||
return arenaSlug;
|
||||
}
|
||||
|
||||
public SessionStats getSessionStats() {
|
||||
return sessionStats;
|
||||
}
|
||||
|
||||
public Collection<PlayerSessionStats> getPlayerStats() {
|
||||
return playerStats.values();
|
||||
}
|
||||
|
||||
public PlayerSessionStats getPlayerStats(UUID playerId) {
|
||||
return playerStats.get(playerId);
|
||||
}
|
||||
|
||||
public void setPlayerStats(UUID playerId, PlayerSessionStats stats) {
|
||||
playerStats.put(playerId, stats);
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,17 @@
|
||||
package org.mobarena.stats.session;
|
||||
|
||||
public enum SessionConclusion {
|
||||
|
||||
/**
|
||||
* When an arena has a final wave and one or more players reach and
|
||||
* complete that wave, the session concludes in a victory.
|
||||
*/
|
||||
VICTORY,
|
||||
|
||||
/**
|
||||
* When the last player alive in an arena dies, the session concludes
|
||||
* in a defeat, meaning the players "lost" the session.
|
||||
*/
|
||||
DEFEAT,
|
||||
|
||||
}
|
||||
@@ -0,0 +1,190 @@
|
||||
package org.mobarena.stats.session;
|
||||
|
||||
import com.garbagemule.MobArena.ArenaClass;
|
||||
import com.garbagemule.MobArena.ArenaPlayer;
|
||||
import com.garbagemule.MobArena.events.ArenaCompleteEvent;
|
||||
import com.garbagemule.MobArena.events.ArenaEndEvent;
|
||||
import com.garbagemule.MobArena.events.ArenaPlayerDeathEvent;
|
||||
import com.garbagemule.MobArena.events.ArenaPlayerJoinEvent;
|
||||
import com.garbagemule.MobArena.events.ArenaPlayerLeaveEvent;
|
||||
import com.garbagemule.MobArena.events.ArenaPlayerReadyEvent;
|
||||
import com.garbagemule.MobArena.events.ArenaStartEvent;
|
||||
import com.garbagemule.MobArena.events.NewWaveEvent;
|
||||
import com.garbagemule.MobArena.framework.Arena;
|
||||
import org.mobarena.stats.store.StatsStore;
|
||||
import org.bukkit.entity.Player;
|
||||
import org.bukkit.event.EventHandler;
|
||||
import org.bukkit.event.EventPriority;
|
||||
import org.bukkit.event.Listener;
|
||||
|
||||
import java.util.concurrent.CompletableFuture;
|
||||
import java.util.concurrent.Executor;
|
||||
import java.util.logging.Level;
|
||||
import java.util.logging.Logger;
|
||||
|
||||
public class SessionListener implements Listener {
|
||||
|
||||
private final SessionStore sessionStore;
|
||||
private final StatsStore statsStore;
|
||||
private final Executor asyncExecutor;
|
||||
private final Logger log;
|
||||
|
||||
public SessionListener(
|
||||
SessionStore sessionStore,
|
||||
StatsStore statsStore,
|
||||
Executor asyncExecutor,
|
||||
Logger log
|
||||
) {
|
||||
this.sessionStore = sessionStore;
|
||||
this.statsStore = statsStore;
|
||||
this.asyncExecutor = asyncExecutor;
|
||||
this.log = log;
|
||||
}
|
||||
|
||||
@EventHandler(priority = EventPriority.MONITOR, ignoreCancelled = true)
|
||||
public void on(ArenaPlayerJoinEvent event) {
|
||||
Arena arena = event.getArena();
|
||||
Player player = event.getPlayer();
|
||||
|
||||
Session session = sessionStore.getByArena(arena);
|
||||
if (session == null) {
|
||||
session = sessionStore.create(arena);
|
||||
}
|
||||
|
||||
session.playerJoin(player);
|
||||
}
|
||||
|
||||
@EventHandler(priority = EventPriority.MONITOR, ignoreCancelled = true)
|
||||
public void on(ArenaPlayerReadyEvent event) {
|
||||
Arena arena = event.getArena();
|
||||
Player player = event.getPlayer();
|
||||
String className = getClassName(arena, player);
|
||||
|
||||
Session session = sessionStore.getByArena(arena);
|
||||
if (session == null) {
|
||||
log.warning("Unexpected ready event for non-existent session of arena " + arena.getSlug());
|
||||
return;
|
||||
}
|
||||
|
||||
session.playerReady(player, className);
|
||||
}
|
||||
|
||||
private String getClassName(Arena arena, Player player) {
|
||||
ArenaPlayer ap = arena.getArenaPlayer(player);
|
||||
if (ap == null) {
|
||||
return null;
|
||||
}
|
||||
|
||||
ArenaClass ac = ap.getArenaClass();
|
||||
if (ac == null) {
|
||||
return null;
|
||||
}
|
||||
|
||||
return ac.getSlug();
|
||||
}
|
||||
|
||||
@EventHandler(priority = EventPriority.MONITOR, ignoreCancelled = true)
|
||||
public void on(ArenaPlayerLeaveEvent event) {
|
||||
Arena arena = event.getArena();
|
||||
Player player = event.getPlayer();
|
||||
|
||||
Session session = sessionStore.getByArena(arena);
|
||||
if (session == null) {
|
||||
log.warning("Unexpected leave event for non-existent session of arena " + arena.getSlug());
|
||||
return;
|
||||
}
|
||||
|
||||
session.playerLeave(arena, player);
|
||||
|
||||
if (!arena.isRunning()) {
|
||||
if (arena.getPlayersInLobby().size() <= 1) {
|
||||
sessionStore.delete(session);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@EventHandler(priority = EventPriority.MONITOR, ignoreCancelled = true)
|
||||
public void on(ArenaPlayerDeathEvent event) {
|
||||
Arena arena = event.getArena();
|
||||
Player player = event.getPlayer();
|
||||
|
||||
Session session = sessionStore.getByArena(arena);
|
||||
if (session == null) {
|
||||
log.warning("Unexpected death event for non-existent session of arena " + arena.getSlug());
|
||||
return;
|
||||
}
|
||||
|
||||
session.playerDeath(arena, player);
|
||||
}
|
||||
|
||||
@EventHandler(priority = EventPriority.MONITOR, ignoreCancelled = true)
|
||||
public void on(ArenaStartEvent event) {
|
||||
Arena arena = event.getArena();
|
||||
|
||||
Session session = sessionStore.getByArena(arena);
|
||||
if (session == null) {
|
||||
log.warning("Unexpected start event for non-existent session of arena " + arena.getSlug());
|
||||
return;
|
||||
}
|
||||
|
||||
session.start();
|
||||
}
|
||||
|
||||
@EventHandler(priority = EventPriority.MONITOR, ignoreCancelled = true)
|
||||
public void on(NewWaveEvent event) {
|
||||
Arena arena = event.getArena();
|
||||
int wave = event.getWaveNumber();
|
||||
|
||||
Session session = sessionStore.getByArena(arena);
|
||||
if (session == null) {
|
||||
log.warning("Unexpected wave event for non-existent session of arena " + arena.getSlug());
|
||||
return;
|
||||
}
|
||||
|
||||
session.wave(wave);
|
||||
}
|
||||
|
||||
@EventHandler(priority = EventPriority.MONITOR, ignoreCancelled = true)
|
||||
public void on(ArenaCompleteEvent event) {
|
||||
Arena arena = event.getArena();
|
||||
|
||||
Session session = sessionStore.getByArena(arena);
|
||||
if (session == null) {
|
||||
log.warning("Unexpected complete event for non-existent session of arena " + arena.getSlug());
|
||||
return;
|
||||
}
|
||||
|
||||
session.complete();
|
||||
}
|
||||
|
||||
@EventHandler(priority = EventPriority.MONITOR, ignoreCancelled = true)
|
||||
public void on(ArenaEndEvent event) {
|
||||
Arena arena = event.getArena();
|
||||
|
||||
Session session = sessionStore.getByArena(arena);
|
||||
if (session == null) {
|
||||
log.warning("Unexpected end event for non-existent session of arena " + arena.getSlug());
|
||||
return;
|
||||
}
|
||||
|
||||
session.end();
|
||||
|
||||
if (!arena.isRunning()) {
|
||||
// Session never started, so just clean up and bail
|
||||
sessionStore.delete(session);
|
||||
return;
|
||||
}
|
||||
|
||||
CompletableFuture.runAsync(() -> {
|
||||
try {
|
||||
statsStore.save(session);
|
||||
sessionStore.delete(session);
|
||||
log.info("Session (" + session.sessionId + ") for arena " + session.arenaSlug + " saved.");
|
||||
} catch (Exception e) {
|
||||
log.log(Level.SEVERE, "Failed to save session (" + session.sessionId + ") for arena " + session.arenaSlug, e);
|
||||
sessionStore.delete(session);
|
||||
}
|
||||
}, asyncExecutor);
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,23 @@
|
||||
package org.mobarena.stats.session;
|
||||
|
||||
import java.time.Instant;
|
||||
import java.util.UUID;
|
||||
|
||||
public class SessionStats {
|
||||
|
||||
public final UUID sessionId;
|
||||
public final String arenaSlug;
|
||||
|
||||
public Instant startTime;
|
||||
public Instant endTime;
|
||||
|
||||
public int lastWave;
|
||||
|
||||
public SessionConclusion conclusion;
|
||||
|
||||
public SessionStats(UUID sessionId, String arenaSlug) {
|
||||
this.sessionId = sessionId;
|
||||
this.arenaSlug = arenaSlug;
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,86 @@
|
||||
package org.mobarena.stats.session;
|
||||
|
||||
import com.garbagemule.MobArena.framework.Arena;
|
||||
|
||||
import java.util.HashMap;
|
||||
import java.util.Map;
|
||||
import java.util.UUID;
|
||||
|
||||
/**
|
||||
* In-memory store for on-going session data.
|
||||
* <p>
|
||||
* The session store is the top-level bookkeeping entity for current sessions
|
||||
* in that all {@link Session} objects are created and kept track of by this
|
||||
* store. Unlike {@link org.mobarena.stats.store.StatsStore}, which persists
|
||||
* its data, the session store is just an in-memory collection.
|
||||
*/
|
||||
public class SessionStore {
|
||||
|
||||
private final Map<String, Session> slugToSession;
|
||||
|
||||
private SessionStore() {
|
||||
this.slugToSession = new HashMap<>();
|
||||
}
|
||||
|
||||
/**
|
||||
* Create a new {@link Session} instance for the given {@link Arena}.
|
||||
* <p>
|
||||
* Note that only one session can be active per arena. The method throws
|
||||
* if it is called with an arena instance that already has an associated
|
||||
* on-going session.
|
||||
*
|
||||
* @param arena the arena to create a new session for
|
||||
* @return a new session for the given arena
|
||||
* @throws IllegalStateException if a session exists for the given arena
|
||||
*/
|
||||
public Session create(Arena arena) {
|
||||
String arenaSlug = arena.getSlug();
|
||||
|
||||
if (slugToSession.containsKey(arenaSlug)) {
|
||||
throw new IllegalStateException("A session for arena " + arenaSlug + " already exists");
|
||||
}
|
||||
|
||||
UUID sessionId = UUID.randomUUID();
|
||||
Session session = new Session(sessionId, arenaSlug);
|
||||
slugToSession.put(arenaSlug, session);
|
||||
|
||||
return session;
|
||||
}
|
||||
|
||||
/**
|
||||
* Delete the given {@link Session} from the store.
|
||||
* <p>
|
||||
* When a session is deleted, it opens up the possibility of starting a
|
||||
* new one for the associated arena.
|
||||
*
|
||||
* @param session a session to delete
|
||||
*/
|
||||
public void delete(Session session) {
|
||||
slugToSession.remove(session.getArenaSlug());
|
||||
}
|
||||
|
||||
/**
|
||||
* Look up a {@link Session} by its associated {@link Arena}.
|
||||
*
|
||||
* @param arena the arena whose session to look up
|
||||
* @return the associated session instance, or null
|
||||
*/
|
||||
public Session getByArena(Arena arena) {
|
||||
return slugToSession.get(arena.getSlug());
|
||||
}
|
||||
|
||||
/**
|
||||
* Clear the internal session map.
|
||||
* <p>
|
||||
* This method is called by MobArenaStats on reloads to try to clear any
|
||||
* residue from old sessions.
|
||||
*/
|
||||
public void clear() {
|
||||
slugToSession.clear();
|
||||
}
|
||||
|
||||
public static SessionStore createNew() {
|
||||
return new SessionStore();
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,33 @@
|
||||
package org.mobarena.stats.session;
|
||||
|
||||
import com.garbagemule.MobArena.ArenaPlayer;
|
||||
import com.garbagemule.MobArena.ArenaPlayerStatistics;
|
||||
import com.garbagemule.MobArena.framework.Arena;
|
||||
import org.bukkit.entity.Player;
|
||||
|
||||
final class StatsUtil {
|
||||
|
||||
private StatsUtil() {
|
||||
// OK BOSS
|
||||
}
|
||||
|
||||
static void copy(Arena arena, Player player, PlayerSessionStats target) {
|
||||
ArenaPlayer ap = arena.getArenaPlayer(player);
|
||||
if (ap == null) {
|
||||
return;
|
||||
}
|
||||
|
||||
ArenaPlayerStatistics aps = ap.getStats();
|
||||
if (aps == null) {
|
||||
return;
|
||||
}
|
||||
|
||||
target.kills = aps.getInt("kills");
|
||||
target.dmgDone = aps.getInt("dmgDone");
|
||||
target.dmgTaken = aps.getInt("dmgTaken");
|
||||
target.swings = aps.getInt("swings");
|
||||
target.hits = aps.getInt("hits");
|
||||
target.lastWave = aps.getInt("lastWave");
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,31 @@
|
||||
package org.mobarena.stats.store;
|
||||
|
||||
public class ArenaStats {
|
||||
|
||||
public final int highestWave;
|
||||
public final int highestSeconds;
|
||||
public final int highestKills;
|
||||
public final int totalSessions;
|
||||
public final long totalSeconds;
|
||||
public final long totalKills;
|
||||
public final long totalWaves;
|
||||
|
||||
public ArenaStats(
|
||||
int highestWave,
|
||||
int highestSeconds,
|
||||
int highestKills,
|
||||
int totalSessions,
|
||||
long totalSeconds,
|
||||
long totalKills,
|
||||
long totalWaves
|
||||
) {
|
||||
this.highestWave = highestWave;
|
||||
this.highestSeconds = highestSeconds;
|
||||
this.highestKills = highestKills;
|
||||
this.totalSessions = totalSessions;
|
||||
this.totalSeconds = totalSeconds;
|
||||
this.totalKills = totalKills;
|
||||
this.totalWaves = totalWaves;
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,67 @@
|
||||
package org.mobarena.stats.store;
|
||||
|
||||
import org.mobarena.stats.session.Session;
|
||||
|
||||
import java.io.IOException;
|
||||
import java.util.HashMap;
|
||||
import java.util.Map;
|
||||
import java.util.UUID;
|
||||
|
||||
public class CachingStatsStore implements StatsStore {
|
||||
|
||||
private final StatsStore delegate;
|
||||
|
||||
private GlobalStats globalStats;
|
||||
private final Map<String, ArenaStats> arenaStats;
|
||||
private final Map<String, PlayerStats> playerStats;
|
||||
|
||||
public CachingStatsStore(StatsStore delegate) {
|
||||
this.delegate = delegate;
|
||||
|
||||
this.globalStats = null;
|
||||
this.arenaStats = new HashMap<>();
|
||||
this.playerStats = new HashMap<>();
|
||||
}
|
||||
|
||||
@Override
|
||||
public void save(Session session) throws IOException {
|
||||
delegate.save(session);
|
||||
|
||||
globalStats = null;
|
||||
arenaStats.remove(session.getArenaSlug());
|
||||
session.getPlayerStats().forEach(stats -> playerStats.remove(stats.playerName));
|
||||
}
|
||||
|
||||
@Override
|
||||
public void delete(UUID sessionId) {
|
||||
delegate.delete(sessionId);
|
||||
|
||||
globalStats = null;
|
||||
arenaStats.clear();
|
||||
playerStats.clear();
|
||||
}
|
||||
|
||||
@Override
|
||||
public GlobalStats getGlobalStats() {
|
||||
if (globalStats == null) {
|
||||
globalStats = delegate.getGlobalStats();
|
||||
}
|
||||
return globalStats;
|
||||
}
|
||||
|
||||
@Override
|
||||
public ArenaStats getArenaStats(String slug) {
|
||||
return arenaStats.computeIfAbsent(slug, delegate::getArenaStats);
|
||||
}
|
||||
|
||||
@Override
|
||||
public PlayerStats getPlayerStats(String name) {
|
||||
return playerStats.computeIfAbsent(name, delegate::getPlayerStats);
|
||||
}
|
||||
|
||||
@Override
|
||||
public void export(StatsStore target) throws IOException {
|
||||
delegate.export(target);
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,22 @@
|
||||
package org.mobarena.stats.store;
|
||||
|
||||
public class GlobalStats {
|
||||
|
||||
public final int totalSessions;
|
||||
public final long totalSeconds;
|
||||
public final long totalKills;
|
||||
public final long totalWaves;
|
||||
|
||||
public GlobalStats(
|
||||
int totalSessions,
|
||||
long totalSeconds,
|
||||
long totalKills,
|
||||
long totalWaves
|
||||
) {
|
||||
this.totalSessions = totalSessions;
|
||||
this.totalSeconds = totalSeconds;
|
||||
this.totalKills = totalKills;
|
||||
this.totalWaves = totalWaves;
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,22 @@
|
||||
package org.mobarena.stats.store;
|
||||
|
||||
public class PlayerStats {
|
||||
|
||||
public final int totalSessions;
|
||||
public final long totalSeconds;
|
||||
public final long totalKills;
|
||||
public final long totalWaves;
|
||||
|
||||
public PlayerStats(
|
||||
int totalSessions,
|
||||
long totalSeconds,
|
||||
long totalKills,
|
||||
long totalWaves
|
||||
) {
|
||||
this.totalSessions = totalSessions;
|
||||
this.totalSeconds = totalSeconds;
|
||||
this.totalKills = totalKills;
|
||||
this.totalWaves = totalWaves;
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,27 @@
|
||||
package org.mobarena.stats.store;
|
||||
|
||||
import org.bukkit.configuration.ConfigurationSection;
|
||||
import org.bukkit.configuration.file.YamlConfiguration;
|
||||
|
||||
public class StatsExport {
|
||||
|
||||
public static final String FILENAME_PREFIX = "stats.export-";
|
||||
public static final String FILENAME_SUFFIX = ".db";
|
||||
|
||||
public static String run(
|
||||
StatsStore store,
|
||||
StatsStoreRegistry registry
|
||||
) throws Exception {
|
||||
String filename = FILENAME_PREFIX + System.currentTimeMillis() + FILENAME_SUFFIX;
|
||||
|
||||
ConfigurationSection config = new YamlConfiguration();
|
||||
config.set("type", "sqlite");
|
||||
config.set("filename", filename);
|
||||
StatsStore output = registry.create(config);
|
||||
|
||||
store.export(output);
|
||||
|
||||
return filename;
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,21 @@
|
||||
package org.mobarena.stats.store;
|
||||
|
||||
import org.bukkit.configuration.ConfigurationSection;
|
||||
import org.bukkit.configuration.file.YamlConfiguration;
|
||||
|
||||
public class StatsImport {
|
||||
|
||||
public static void run(
|
||||
StatsStoreRegistry registry,
|
||||
String filename,
|
||||
StatsStore store
|
||||
) throws Exception {
|
||||
ConfigurationSection config = new YamlConfiguration();
|
||||
config.set("type", "sqlite");
|
||||
config.set("filename", filename);
|
||||
StatsStore source = registry.create(config);
|
||||
|
||||
source.export(store);
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,49 @@
|
||||
package org.mobarena.stats.store;
|
||||
|
||||
import org.mobarena.stats.session.Session;
|
||||
|
||||
import java.io.IOException;
|
||||
import java.util.UUID;
|
||||
|
||||
/**
|
||||
* Persistent data store for session and player stats.
|
||||
* <p>
|
||||
* All store operations are <i>blocking</i>, meaning any calls to the store
|
||||
* should be handled off the main thread to prevent performance impacts.
|
||||
*/
|
||||
public interface StatsStore {
|
||||
|
||||
/**
|
||||
* Store the given {@link Session}'s data in the store.
|
||||
* <p>
|
||||
* This method should only be called with a "finished" session, i.e. a
|
||||
* session that has concluded and won't be altered after saving.
|
||||
*
|
||||
* @param session a session to store
|
||||
* @throws IOException if the operation fails due to I/O
|
||||
*/
|
||||
void save(Session session) throws IOException;
|
||||
|
||||
/**
|
||||
* Delete all data about the session with the given ID.
|
||||
* <p>
|
||||
* Removes all session and player data associated with the session of
|
||||
* the given ID, meaning these stats will be lost forever.
|
||||
*
|
||||
* @param sessionId the ID of the session whose data to delete
|
||||
*/
|
||||
void delete(UUID sessionId);
|
||||
|
||||
// TODO: docs
|
||||
GlobalStats getGlobalStats();
|
||||
|
||||
// TODO: docs
|
||||
ArenaStats getArenaStats(String slug);
|
||||
|
||||
// TODO: docs
|
||||
PlayerStats getPlayerStats(String name);
|
||||
|
||||
// TODO: docs
|
||||
void export(StatsStore target) throws IOException;
|
||||
|
||||
}
|
||||
@@ -0,0 +1,22 @@
|
||||
package org.mobarena.stats.store;
|
||||
|
||||
import org.bukkit.configuration.ConfigurationSection;
|
||||
import org.mobarena.stats.MobArenaStats;
|
||||
|
||||
@FunctionalInterface
|
||||
public interface StatsStoreFactory {
|
||||
|
||||
/**
|
||||
* Create a new stats store from the given configuration.
|
||||
*
|
||||
* @param config a configuration to set up the stats store
|
||||
* @param plugin a plugin instance for dependencies
|
||||
* @return a new stats store instance
|
||||
* @throws Exception if store creation fails
|
||||
*/
|
||||
StatsStore create(
|
||||
ConfigurationSection config,
|
||||
MobArenaStats plugin
|
||||
) throws Exception;
|
||||
|
||||
}
|
||||
@@ -0,0 +1,41 @@
|
||||
package org.mobarena.stats.store;
|
||||
|
||||
import org.bukkit.configuration.ConfigurationSection;
|
||||
import org.mobarena.stats.MobArenaStatsPlugin;
|
||||
|
||||
import java.util.HashMap;
|
||||
import java.util.Map;
|
||||
|
||||
public class StatsStoreRegistry {
|
||||
|
||||
private final Map<String, StatsStoreFactory> typeToFactory;
|
||||
private final MobArenaStatsPlugin plugin;
|
||||
|
||||
StatsStoreRegistry(MobArenaStatsPlugin plugin) {
|
||||
this.typeToFactory = new HashMap<>();
|
||||
this.plugin = plugin;
|
||||
}
|
||||
|
||||
public void register(String type, StatsStoreFactory factory) {
|
||||
typeToFactory.put(type.toLowerCase(), factory);
|
||||
}
|
||||
|
||||
public StatsStore create(ConfigurationSection config) throws Exception {
|
||||
String type = config.getString("type");
|
||||
if (type == null || type.isEmpty()) {
|
||||
throw new IllegalArgumentException("Missing 'type' in store configuration");
|
||||
}
|
||||
|
||||
StatsStoreFactory factory = typeToFactory.get(type.toLowerCase());
|
||||
if (factory == null) {
|
||||
throw new IllegalArgumentException("Unknown store type: " + type);
|
||||
}
|
||||
|
||||
return factory.create(config, plugin);
|
||||
}
|
||||
|
||||
public static StatsStoreRegistry create(MobArenaStatsPlugin plugin) {
|
||||
return new StatsStoreRegistry(plugin);
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,253 @@
|
||||
package org.mobarena.stats.store.csv;
|
||||
|
||||
import org.bukkit.configuration.ConfigurationSection;
|
||||
import org.mobarena.stats.MobArenaStats;
|
||||
import org.mobarena.stats.session.PlayerConclusion;
|
||||
import org.mobarena.stats.session.PlayerSessionStats;
|
||||
import org.mobarena.stats.session.Session;
|
||||
import org.mobarena.stats.session.SessionConclusion;
|
||||
import org.mobarena.stats.session.SessionStats;
|
||||
import org.mobarena.stats.store.ArenaStats;
|
||||
import org.mobarena.stats.store.GlobalStats;
|
||||
import org.mobarena.stats.store.PlayerStats;
|
||||
import org.mobarena.stats.store.StatsStore;
|
||||
|
||||
import java.io.BufferedWriter;
|
||||
import java.io.File;
|
||||
import java.io.FileWriter;
|
||||
import java.io.IOException;
|
||||
import java.io.PrintWriter;
|
||||
import java.nio.file.Files;
|
||||
import java.time.Instant;
|
||||
import java.time.format.DateTimeFormatter;
|
||||
import java.util.List;
|
||||
import java.util.UUID;
|
||||
import java.util.function.Function;
|
||||
import java.util.logging.Logger;
|
||||
|
||||
public class CsvStatsStore implements StatsStore {
|
||||
|
||||
private static final String[] SESSION_FIELDS = {
|
||||
"session_id",
|
||||
"arena_slug",
|
||||
"start_time",
|
||||
"end_time",
|
||||
"last_wave",
|
||||
"conclusion"
|
||||
};
|
||||
|
||||
private static final String[] PLAYER_SESSION_FIELDS = {
|
||||
"session_id",
|
||||
"player_id",
|
||||
"player_name",
|
||||
"class",
|
||||
"join_time",
|
||||
"ready_time",
|
||||
"leave_time",
|
||||
"death_time",
|
||||
"kills",
|
||||
"dmg_done",
|
||||
"dmg_taken",
|
||||
"swings",
|
||||
"hits",
|
||||
"last_wave",
|
||||
"conclusion"
|
||||
};
|
||||
|
||||
private final File folder;
|
||||
private final File sessionsFile;
|
||||
private final File playersFile;
|
||||
private final String separator;
|
||||
private final DateTimeFormatter formatter;
|
||||
private final Logger log;
|
||||
|
||||
private CsvStatsStore(
|
||||
File folder,
|
||||
String separator,
|
||||
Logger log
|
||||
) {
|
||||
this.folder = folder;
|
||||
this.sessionsFile = new File(folder, "sessions.csv");
|
||||
this.playersFile = new File(folder, "players.csv");
|
||||
this.separator = separator;
|
||||
this.formatter = DateTimeFormatter.ISO_INSTANT;
|
||||
this.log = log;
|
||||
}
|
||||
|
||||
@Override
|
||||
public void save(Session session) throws IOException {
|
||||
try {
|
||||
createDataFolder();
|
||||
saveArenaSession(session);
|
||||
savePlayerSessions(session);
|
||||
} catch (Exception e) {
|
||||
throw new IOException(e);
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
public void delete(UUID sessionId) {
|
||||
throw new UnsupportedOperationException("Session deletion is not supported by the CSV data store");
|
||||
}
|
||||
|
||||
private void createDataFolder() {
|
||||
if (!folder.exists()) {
|
||||
if (!folder.mkdirs()) {
|
||||
throw new IllegalStateException("Failed to create stats data folder");
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private void saveArenaSession(Session session) throws Exception {
|
||||
boolean writeHeader = !sessionsFile.exists();
|
||||
|
||||
try (PrintWriter writer = new PrintWriter(new BufferedWriter(new FileWriter(sessionsFile, true)))) {
|
||||
if (writeHeader) {
|
||||
String line = String.join(separator, SESSION_FIELDS);
|
||||
writer.println(line);
|
||||
}
|
||||
|
||||
SessionStats stats = session.getSessionStats();
|
||||
String line = String.join(
|
||||
separator,
|
||||
stats.sessionId.toString(),
|
||||
stats.arenaSlug,
|
||||
formatter.format(stats.startTime),
|
||||
formatter.format(stats.endTime),
|
||||
String.valueOf(stats.lastWave),
|
||||
String.valueOf(stats.conclusion)
|
||||
);
|
||||
writer.println(line);
|
||||
log.info("Session stats written to disk (" + stats.sessionId + ").");
|
||||
}
|
||||
}
|
||||
|
||||
private void savePlayerSessions(Session session) throws Exception {
|
||||
boolean writeHeader = !playersFile.exists();
|
||||
|
||||
try (PrintWriter writer = new PrintWriter(new BufferedWriter(new FileWriter(playersFile, true)))) {
|
||||
if (writeHeader) {
|
||||
String line = String.join(separator, PLAYER_SESSION_FIELDS);
|
||||
writer.println(line);
|
||||
}
|
||||
|
||||
for (PlayerSessionStats stats : session.getPlayerStats()) {
|
||||
String line = String.join(
|
||||
separator,
|
||||
stats.sessionId.toString(),
|
||||
stats.playerId.toString(),
|
||||
stats.playerName,
|
||||
stats.className,
|
||||
formatter.format(stats.joinTime),
|
||||
formatter.format(stats.readyTime),
|
||||
stats.leaveTime != null ? formatter.format(stats.leaveTime) : "",
|
||||
stats.deathTime != null ? formatter.format(stats.deathTime) : "",
|
||||
String.valueOf(stats.kills),
|
||||
String.valueOf(stats.dmgDone),
|
||||
String.valueOf(stats.dmgTaken),
|
||||
String.valueOf(stats.swings),
|
||||
String.valueOf(stats.hits),
|
||||
String.valueOf(stats.lastWave),
|
||||
String.valueOf(stats.conclusion)
|
||||
);
|
||||
writer.println(line);
|
||||
}
|
||||
log.info("Player stats written to disk (" + session.getSessionStats().sessionId + ").");
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
public GlobalStats getGlobalStats() {
|
||||
throw new UnsupportedOperationException("Queries are not supported by the CSV data store");
|
||||
}
|
||||
|
||||
@Override
|
||||
public ArenaStats getArenaStats(String slug) {
|
||||
throw new UnsupportedOperationException("Queries are not supported by the CSV data store");
|
||||
}
|
||||
|
||||
@Override
|
||||
public PlayerStats getPlayerStats(String name) {
|
||||
throw new UnsupportedOperationException("Queries are not supported by the CSV data store");
|
||||
}
|
||||
|
||||
@Override
|
||||
public void export(StatsStore target) throws IOException {
|
||||
List<String> sessionLines = Files.readAllLines(sessionsFile.toPath());
|
||||
List<String> playerLines = Files.readAllLines(playersFile.toPath());
|
||||
|
||||
for (int i = 1; i < sessionLines.size(); i++) {
|
||||
String sessionLine = sessionLines.get(i);
|
||||
String[] sessionParts = sessionLine.split(separator);
|
||||
|
||||
UUID sessionId = UUID.fromString(sessionParts[0]);
|
||||
String arenaSlug = sessionParts[1];
|
||||
Session session = new Session(sessionId, arenaSlug);
|
||||
{
|
||||
SessionStats stats = session.getSessionStats();
|
||||
stats.startTime = Instant.parse(sessionParts[2]);
|
||||
stats.endTime = Instant.parse(sessionParts[3]);
|
||||
stats.lastWave = Integer.parseInt(sessionParts[4]);
|
||||
stats.conclusion = SessionConclusion.valueOf(sessionParts[5]);
|
||||
}
|
||||
|
||||
String prefix = sessionId + separator;
|
||||
for (int j = 1; j < playerLines.size(); j++) {
|
||||
String playerLine = playerLines.get(j);
|
||||
if (!playerLine.startsWith(prefix)) {
|
||||
continue;
|
||||
}
|
||||
|
||||
String[] playerParts = playerLine.split(separator);
|
||||
{
|
||||
UUID playerId = UUID.fromString(playerParts[1]);
|
||||
String playerName = playerParts[2];
|
||||
|
||||
PlayerSessionStats stats = new PlayerSessionStats(sessionId, playerId, playerName);
|
||||
stats.className = playerParts[3];
|
||||
stats.joinTime = safe(playerParts[4], Instant::parse);
|
||||
stats.readyTime = safe(playerParts[5], Instant::parse);
|
||||
stats.leaveTime = safe(playerParts[6], Instant::parse);
|
||||
stats.deathTime = safe(playerParts[7], Instant::parse);
|
||||
stats.kills = Integer.parseInt(playerParts[8]);
|
||||
stats.dmgDone = Integer.parseInt(playerParts[9]);
|
||||
stats.dmgTaken = Integer.parseInt(playerParts[10]);
|
||||
stats.swings = Integer.parseInt(playerParts[11]);
|
||||
stats.hits = Integer.parseInt(playerParts[12]);
|
||||
stats.lastWave = Integer.parseInt(playerParts[13]);
|
||||
stats.conclusion = safe(playerParts[14], PlayerConclusion::valueOf, PlayerConclusion.DEFEAT);
|
||||
|
||||
session.setPlayerStats(playerId, stats);
|
||||
}
|
||||
}
|
||||
|
||||
target.save(session);
|
||||
}
|
||||
}
|
||||
|
||||
private static <T, R> R safe(T value, Function<T, R> parser) {
|
||||
return safe(value, parser, null);
|
||||
}
|
||||
|
||||
private static <T, R> R safe(T value, Function<T, R> parser, R def) {
|
||||
try {
|
||||
return parser.apply(value);
|
||||
} catch (Exception e) {
|
||||
return def;
|
||||
}
|
||||
}
|
||||
|
||||
public static CsvStatsStore create(
|
||||
ConfigurationSection config,
|
||||
MobArenaStats plugin
|
||||
) {
|
||||
String folder = config.getString("folder", "data");
|
||||
String separator = config.getString("separator", ";");
|
||||
|
||||
File root = new File(plugin.getDataFolder(), folder);
|
||||
Logger log = plugin.getLogger();
|
||||
|
||||
return new CsvStatsStore(root, separator, log);
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,245 @@
|
||||
package org.mobarena.stats.store.jdbc;
|
||||
|
||||
import org.bukkit.configuration.ConfigurationSection;
|
||||
import org.jdbi.v3.core.Jdbi;
|
||||
import org.jdbi.v3.core.mapper.RowMapper;
|
||||
import org.jdbi.v3.core.statement.PreparedBatch;
|
||||
import org.mobarena.stats.MobArenaStats;
|
||||
import org.mobarena.stats.session.PlayerConclusion;
|
||||
import org.mobarena.stats.session.PlayerSessionStats;
|
||||
import org.mobarena.stats.session.Session;
|
||||
import org.mobarena.stats.session.SessionConclusion;
|
||||
import org.mobarena.stats.session.SessionStats;
|
||||
import org.mobarena.stats.store.ArenaStats;
|
||||
import org.mobarena.stats.store.GlobalStats;
|
||||
import org.mobarena.stats.store.PlayerStats;
|
||||
import org.mobarena.stats.store.StatsStore;
|
||||
import org.mobarena.stats.util.ResourceLoader;
|
||||
|
||||
import java.io.IOException;
|
||||
import java.sql.Timestamp;
|
||||
import java.util.List;
|
||||
import java.util.UUID;
|
||||
import java.util.function.Function;
|
||||
import java.util.logging.Logger;
|
||||
|
||||
import static org.mobarena.stats.store.jdbc.Statement.DELETE_SESSION_DATA;
|
||||
import static org.mobarena.stats.store.jdbc.Statement.FIND_ARENA_STATS;
|
||||
import static org.mobarena.stats.store.jdbc.Statement.FIND_GLOBAL_STATS;
|
||||
import static org.mobarena.stats.store.jdbc.Statement.FIND_PLAYER_SESSIONS_BY_ID;
|
||||
import static org.mobarena.stats.store.jdbc.Statement.FIND_PLAYER_STATS;
|
||||
import static org.mobarena.stats.store.jdbc.Statement.FIND_SESSIONS;
|
||||
import static org.mobarena.stats.store.jdbc.Statement.INSERT_PLAYER_DATA;
|
||||
import static org.mobarena.stats.store.jdbc.Statement.INSERT_SESSION_DATA;
|
||||
|
||||
public class JdbcStatsStore implements StatsStore {
|
||||
|
||||
private final Jdbi jdbi;
|
||||
private final Statements statements;
|
||||
|
||||
private JdbcStatsStore(Jdbi jdbi, Statements statements) {
|
||||
this.jdbi = jdbi;
|
||||
this.statements = statements;
|
||||
}
|
||||
|
||||
@Override
|
||||
public synchronized void save(Session session) {
|
||||
jdbi.useTransaction(handle -> {
|
||||
// First the session data
|
||||
handle.createUpdate(statements.get(INSERT_SESSION_DATA))
|
||||
.bind("session_id", session.getSessionId().toString())
|
||||
.bind("arena_slug", session.getArenaSlug())
|
||||
.bind("start_time", session.getSessionStats().startTime)
|
||||
.bind("end_time", session.getSessionStats().endTime)
|
||||
.bind("last_wave", session.getSessionStats().lastWave)
|
||||
.bind("conclusion", session.getSessionStats().conclusion)
|
||||
.execute();
|
||||
|
||||
// Then all of the player data
|
||||
PreparedBatch batch = handle.prepareBatch(statements.get(INSERT_PLAYER_DATA));
|
||||
for (PlayerSessionStats player : session.getPlayerStats()) {
|
||||
batch.bind("session_id", session.getSessionId().toString());
|
||||
batch.bind("player_id", player.playerId.toString());
|
||||
batch.bind("player_name", player.playerName);
|
||||
batch.bind("class", player.className);
|
||||
batch.bind("join_time", player.joinTime);
|
||||
batch.bind("ready_time", player.readyTime);
|
||||
batch.bind("leave_time", player.leaveTime);
|
||||
batch.bind("death_time", player.deathTime);
|
||||
batch.bind("kills", player.kills);
|
||||
batch.bind("dmg_done", player.dmgDone);
|
||||
batch.bind("dmg_taken", player.dmgTaken);
|
||||
batch.bind("swings", player.swings);
|
||||
batch.bind("hits", player.hits);
|
||||
batch.bind("last_wave", player.lastWave);
|
||||
batch.bind("conclusion", player.conclusion);
|
||||
batch.add();
|
||||
}
|
||||
batch.execute();
|
||||
});
|
||||
}
|
||||
|
||||
@Override
|
||||
public void delete(UUID sessionId) {
|
||||
jdbi.useTransaction(handle -> handle
|
||||
.createUpdate(statements.get(DELETE_SESSION_DATA))
|
||||
.bind("session_id", sessionId.toString())
|
||||
.execute()
|
||||
);
|
||||
}
|
||||
|
||||
@Override
|
||||
public GlobalStats getGlobalStats() {
|
||||
return jdbi.withHandle(handle -> handle
|
||||
.createQuery(statements.get(FIND_GLOBAL_STATS))
|
||||
.map((rs, ctx) -> new GlobalStats(
|
||||
rs.getInt("total_sessions"),
|
||||
rs.getLong("total_seconds"),
|
||||
rs.getLong("total_kills"),
|
||||
rs.getLong("total_waves")
|
||||
))
|
||||
.first()
|
||||
);
|
||||
}
|
||||
|
||||
@Override
|
||||
public ArenaStats getArenaStats(String slug) {
|
||||
return jdbi.withHandle(handle -> handle
|
||||
.createQuery(statements.get(FIND_ARENA_STATS))
|
||||
.bind("arena_slug", slug)
|
||||
.map((rs, ctx) -> new ArenaStats(
|
||||
rs.getInt("highest_wave"),
|
||||
rs.getInt("highest_seconds"),
|
||||
rs.getInt("highest_kills"),
|
||||
rs.getInt("total_sessions"),
|
||||
rs.getLong("total_seconds"),
|
||||
rs.getLong("total_kills"),
|
||||
rs.getLong("total_waves")
|
||||
))
|
||||
.first()
|
||||
);
|
||||
}
|
||||
|
||||
@Override
|
||||
public PlayerStats getPlayerStats(String name) {
|
||||
return jdbi.withHandle(handle -> handle
|
||||
.createQuery(statements.get(FIND_PLAYER_STATS))
|
||||
.bind("player_name", name)
|
||||
.map((rs, ctx) -> new PlayerStats(
|
||||
rs.getInt("total_sessions"),
|
||||
rs.getLong("total_seconds"),
|
||||
rs.getLong("total_kills"),
|
||||
rs.getLong("total_waves")
|
||||
))
|
||||
.first()
|
||||
);
|
||||
}
|
||||
|
||||
@Override
|
||||
public synchronized void export(StatsStore target) throws IOException {
|
||||
jdbi.useHandle(handle -> {
|
||||
int limit = 100;
|
||||
int offset = 0;
|
||||
|
||||
while (true) {
|
||||
List<Session> sessions = handle.createQuery(statements.get(FIND_SESSIONS))
|
||||
.bind("limit", limit)
|
||||
.bind("offset", offset)
|
||||
.map(toSession())
|
||||
.list();
|
||||
|
||||
for (Session session : sessions) {
|
||||
UUID sessionId = session.getSessionId();
|
||||
|
||||
handle.createQuery(statements.get(FIND_PLAYER_SESSIONS_BY_ID))
|
||||
.bind("session_id", session.getSessionId().toString())
|
||||
.map(toPlayerStats(sessionId))
|
||||
.forEach(stats -> session.setPlayerStats(stats.playerId, stats));
|
||||
|
||||
target.save(session);
|
||||
}
|
||||
|
||||
if (sessions.size() < limit) {
|
||||
break;
|
||||
}
|
||||
|
||||
offset += limit;
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
private static RowMapper<Session> toSession() {
|
||||
return (r, ctx) -> {
|
||||
UUID sessionId = UUID.fromString(r.getString("session_id"));
|
||||
String arenaSlug = r.getString("arena_slug");
|
||||
Session session = new Session(sessionId, arenaSlug);
|
||||
|
||||
SessionStats stats = session.getSessionStats();
|
||||
stats.startTime = r.getTimestamp("start_time").toInstant();
|
||||
stats.endTime = r.getTimestamp("end_time").toInstant();
|
||||
stats.lastWave = r.getInt("last_wave");
|
||||
stats.conclusion = SessionConclusion.valueOf(r.getString("conclusion"));
|
||||
|
||||
return session;
|
||||
};
|
||||
}
|
||||
|
||||
private static RowMapper<PlayerSessionStats> toPlayerStats(UUID sessionId) {
|
||||
return (r, ctx) -> {
|
||||
UUID playerId = UUID.fromString(r.getString("player_id"));
|
||||
String playerName = r.getString("player_name");
|
||||
|
||||
PlayerSessionStats stats = new PlayerSessionStats(sessionId, playerId, playerName);
|
||||
stats.className = r.getString("class");
|
||||
stats.joinTime = safe(r.getTimestamp("join_time"), Timestamp::toInstant);
|
||||
stats.readyTime = safe(r.getTimestamp("ready_time"), Timestamp::toInstant);
|
||||
stats.leaveTime = safe(r.getTimestamp("leave_time"), Timestamp::toInstant);
|
||||
stats.deathTime = safe(r.getTimestamp("death_time"), Timestamp::toInstant);
|
||||
stats.kills = r.getInt("kills");
|
||||
stats.dmgDone = r.getInt("dmg_done");
|
||||
stats.dmgTaken = r.getInt("dmg_taken");
|
||||
stats.swings = r.getInt("swings");
|
||||
stats.hits = r.getInt("hits");
|
||||
stats.lastWave = r.getInt("last_wave");
|
||||
stats.conclusion = safe(r.getString("conclusion"), PlayerConclusion::valueOf, PlayerConclusion.DEFEAT);
|
||||
|
||||
return stats;
|
||||
};
|
||||
}
|
||||
|
||||
private static <T, R> R safe(T value, Function<T, R> parser) {
|
||||
return safe(value, parser, null);
|
||||
}
|
||||
|
||||
private static <T, R> R safe(T value, Function<T, R> parser, R def) {
|
||||
try {
|
||||
return parser.apply(value);
|
||||
} catch (Exception e) {
|
||||
return def;
|
||||
}
|
||||
}
|
||||
|
||||
public static JdbcStatsStore create(
|
||||
ConfigurationSection config,
|
||||
MobArenaStats plugin
|
||||
) throws Exception {
|
||||
String type = config.getString("type");
|
||||
String url = config.getString("url");
|
||||
String username = config.getString("username");
|
||||
String password = config.getString("password");
|
||||
Jdbi jdbi = Jdbi.create(url, username, password);
|
||||
|
||||
// Load up migrations and statements for the given type
|
||||
ResourceLoader loader = ResourceLoader.create(plugin.getClass().getClassLoader());
|
||||
Migrations migrations = Migrations.create(loader, type);
|
||||
Statements statements = Statements.create(loader, type);
|
||||
Logger log = plugin.getLogger();
|
||||
|
||||
// Bring database schema up to speed
|
||||
SchemaMigrator migrator = new SchemaMigrator(jdbi, migrations, statements, log);
|
||||
migrator.migrate();
|
||||
|
||||
return new JdbcStatsStore(jdbi, statements);
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,31 @@
|
||||
package org.mobarena.stats.store.jdbc;
|
||||
|
||||
import org.mobarena.stats.util.ResourceLoader;
|
||||
|
||||
import java.io.IOException;
|
||||
import java.net.URISyntaxException;
|
||||
import java.util.List;
|
||||
|
||||
class Migrations {
|
||||
|
||||
private final ResourceLoader loader;
|
||||
private final String type;
|
||||
|
||||
private Migrations(ResourceLoader loader, String type) {
|
||||
this.loader = loader;
|
||||
this.type = type;
|
||||
}
|
||||
|
||||
List<String> list() throws URISyntaxException, IOException {
|
||||
return loader.list(type + "/migration");
|
||||
}
|
||||
|
||||
String get(String filename) throws IOException {
|
||||
return loader.loadString(type + "/migration/" + filename);
|
||||
}
|
||||
|
||||
static Migrations create(ResourceLoader loader, String type) {
|
||||
return new Migrations(loader, type);
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,139 @@
|
||||
package org.mobarena.stats.store.jdbc;
|
||||
|
||||
import org.jdbi.v3.core.Jdbi;
|
||||
import org.jdbi.v3.core.statement.Batch;
|
||||
|
||||
import java.io.IOException;
|
||||
import java.net.URISyntaxException;
|
||||
import java.sql.Connection;
|
||||
import java.sql.DatabaseMetaData;
|
||||
import java.sql.ResultSet;
|
||||
import java.sql.SQLException;
|
||||
import java.time.Instant;
|
||||
import java.util.Arrays;
|
||||
import java.util.Collections;
|
||||
import java.util.List;
|
||||
import java.util.logging.Logger;
|
||||
import java.util.stream.Collectors;
|
||||
|
||||
import static org.mobarena.stats.store.jdbc.Statement.FIND_ALL_MIGRATIONS;
|
||||
import static org.mobarena.stats.store.jdbc.Statement.INSERT_MIGRATION;
|
||||
|
||||
class SchemaMigrator {
|
||||
|
||||
private final Jdbi jdbi;
|
||||
private final Migrations migrations;
|
||||
private final Statements statements;
|
||||
private final Logger log;
|
||||
|
||||
SchemaMigrator(
|
||||
Jdbi jdbi,
|
||||
Migrations migrations,
|
||||
Statements statements,
|
||||
Logger log
|
||||
) {
|
||||
this.jdbi = jdbi;
|
||||
this.migrations = migrations;
|
||||
this.statements = statements;
|
||||
this.log = log;
|
||||
}
|
||||
|
||||
void migrate() throws IOException, SQLException, URISyntaxException {
|
||||
List<String> filenames = migrations.list();
|
||||
List<String> completed = getCompletedMigrations();
|
||||
|
||||
filenames.removeAll(completed);
|
||||
|
||||
if (filenames.isEmpty()) {
|
||||
log.info("Schema is up to date.");
|
||||
return;
|
||||
}
|
||||
|
||||
if (completed.isEmpty()) {
|
||||
log.info("Schema is has not yet been initialized, migrating...");
|
||||
} else {
|
||||
log.info("Schema is " + filenames.size() + " version(s) behind, migrating...");
|
||||
}
|
||||
|
||||
for (String filename : filenames) {
|
||||
execute(filename);
|
||||
}
|
||||
|
||||
log.info("Schema migration complete.");
|
||||
}
|
||||
|
||||
private List<String> getCompletedMigrations() throws SQLException {
|
||||
return jdbi.withHandle(handle -> {
|
||||
// We don't really have a good way to check if the database has
|
||||
// migration info without making some actual queries, which will
|
||||
// fail if it doesn't. Instead, we can use the database metadata
|
||||
// (available via the underlying JDBC connection object) to find
|
||||
// out if the schema migrations table exists.
|
||||
Connection connection = handle.getConnection();
|
||||
DatabaseMetaData meta = connection.getMetaData();
|
||||
try (ResultSet tables = meta.getTables(null, null, "schema_migrations", null)) {
|
||||
while (tables.next()) {
|
||||
String name = tables.getString("TABLE_NAME");
|
||||
if (name.equals("schema_migrations")) {
|
||||
// Jackpot! We found the table, now query it.
|
||||
String sql = statements.get(FIND_ALL_MIGRATIONS);
|
||||
return handle.createQuery(sql)
|
||||
.map((r, ctx) -> r.getString("filename"))
|
||||
.list();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// No migrations table means fresh database.
|
||||
return Collections.emptyList();
|
||||
});
|
||||
}
|
||||
|
||||
private void execute(String filename) throws IOException {
|
||||
String content = migrations.get(filename);
|
||||
|
||||
// Migration files may contain several different statements,
|
||||
// but not all databases support multiple statements in a
|
||||
// single update, so we split the file contents by semicolon
|
||||
// and hold our breath while we invoke each part...
|
||||
List<String> parts = Arrays.stream(content.split(";"))
|
||||
.map(String::trim)
|
||||
.filter(s -> !s.isEmpty())
|
||||
.collect(Collectors.toList());
|
||||
|
||||
jdbi.useTransaction(handle -> {
|
||||
Instant executed = Instant.now();
|
||||
try {
|
||||
if (parts.size() == 1) {
|
||||
handle.execute(parts.get(0));
|
||||
} else {
|
||||
Batch batch = handle.createBatch();
|
||||
parts.forEach(batch::add);
|
||||
batch.execute();
|
||||
}
|
||||
|
||||
String sql = statements.get(INSERT_MIGRATION);
|
||||
handle.createUpdate(sql)
|
||||
.bind("filename", filename)
|
||||
.bind("executed", executed)
|
||||
.bind("success", true)
|
||||
.bind("error", (String) null)
|
||||
.execute();
|
||||
|
||||
log.info("\u2713 " + filename);
|
||||
} catch (Exception e) {
|
||||
String sql = statements.get(INSERT_MIGRATION);
|
||||
handle.createUpdate(sql)
|
||||
.bind("filename", filename)
|
||||
.bind("executed", executed)
|
||||
.bind("success", false)
|
||||
.bind("error", e.getMessage())
|
||||
.execute();
|
||||
|
||||
log.severe("\u2717 " + filename);
|
||||
throw new IllegalStateException("Migration failed: " + filename, e);
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,19 @@
|
||||
package org.mobarena.stats.store.jdbc;
|
||||
|
||||
public enum Statement {
|
||||
|
||||
FIND_ALL_MIGRATIONS,
|
||||
INSERT_MIGRATION,
|
||||
|
||||
INSERT_SESSION_DATA,
|
||||
INSERT_PLAYER_DATA,
|
||||
DELETE_SESSION_DATA,
|
||||
|
||||
FIND_ARENA_STATS,
|
||||
FIND_GLOBAL_STATS,
|
||||
FIND_PLAYER_STATS,
|
||||
|
||||
FIND_SESSIONS,
|
||||
FIND_PLAYER_SESSIONS_BY_ID,
|
||||
|
||||
}
|
||||
@@ -0,0 +1,32 @@
|
||||
package org.mobarena.stats.store.jdbc;
|
||||
|
||||
import org.mobarena.stats.util.ResourceLoader;
|
||||
|
||||
import java.io.IOException;
|
||||
import java.util.EnumMap;
|
||||
import java.util.Map;
|
||||
|
||||
class Statements {
|
||||
|
||||
private final Map<Statement, String> sql;
|
||||
|
||||
private Statements(Map<Statement, String> sql) {
|
||||
this.sql = sql;
|
||||
}
|
||||
|
||||
String get(Statement statement) {
|
||||
return sql.get(statement);
|
||||
}
|
||||
|
||||
static Statements create(ResourceLoader loader, String type) throws IOException {
|
||||
EnumMap<Statement, String> result = new EnumMap<>(Statement.class);
|
||||
for (Statement statement : Statement.values()) {
|
||||
// SCREAMING_SNAKE_CASE -> kebab-case, .sql file extension
|
||||
String filename = statement.toString().toLowerCase().replace('_', '-') + ".sql";
|
||||
String sql = loader.loadString(type + "/" + filename);
|
||||
result.put(statement, sql);
|
||||
}
|
||||
return new Statements(result);
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,39 @@
|
||||
package org.mobarena.stats.store.mariadb;
|
||||
|
||||
import org.bukkit.configuration.ConfigurationSection;
|
||||
import org.bukkit.configuration.MemoryConfiguration;
|
||||
import org.mobarena.stats.MobArenaStats;
|
||||
import org.mobarena.stats.store.jdbc.JdbcStatsStore;
|
||||
|
||||
public class MariadbStatsStore {
|
||||
|
||||
public static JdbcStatsStore create(
|
||||
ConfigurationSection config,
|
||||
MobArenaStats plugin
|
||||
) throws Exception {
|
||||
ConfigurationSection copy = new MemoryConfiguration();
|
||||
for (String key : config.getKeys(false)) {
|
||||
copy.set(key, config.get(key));
|
||||
}
|
||||
|
||||
// Note the type override of "mysql" here. This ensures that we
|
||||
// reuse the MySQL SQL files from the resources folder.
|
||||
String url = getUrl(copy);
|
||||
copy.set("type", "mysql");
|
||||
copy.set("url", url);
|
||||
|
||||
return JdbcStatsStore.create(copy, plugin);
|
||||
}
|
||||
|
||||
static String getUrl(ConfigurationSection config) {
|
||||
String host = config.getString("host", "localhost");
|
||||
int port = config.getInt("port", 3306);
|
||||
String database = config.getString("database", "mobarena_stats");
|
||||
boolean ssl = config.getBoolean("ssl", false);
|
||||
|
||||
String params = "useSSL=" + ssl;
|
||||
|
||||
return "jdbc:mariadb://" + host + ":" + port + "/" + database + "?" + params;
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,37 @@
|
||||
package org.mobarena.stats.store.mysql;
|
||||
|
||||
import org.bukkit.configuration.ConfigurationSection;
|
||||
import org.bukkit.configuration.MemoryConfiguration;
|
||||
import org.mobarena.stats.MobArenaStats;
|
||||
import org.mobarena.stats.store.jdbc.JdbcStatsStore;
|
||||
|
||||
public class MysqlStatsStore {
|
||||
|
||||
public static JdbcStatsStore create(
|
||||
ConfigurationSection config,
|
||||
MobArenaStats plugin
|
||||
) throws Exception {
|
||||
ConfigurationSection copy = new MemoryConfiguration();
|
||||
for (String key : config.getKeys(false)) {
|
||||
copy.set(key, config.get(key));
|
||||
}
|
||||
|
||||
String url = getUrl(copy);
|
||||
copy.set("type", "mysql");
|
||||
copy.set("url", url);
|
||||
|
||||
return JdbcStatsStore.create(copy, plugin);
|
||||
}
|
||||
|
||||
static String getUrl(ConfigurationSection config) {
|
||||
String host = config.getString("host", "localhost");
|
||||
int port = config.getInt("port", 3306);
|
||||
String database = config.getString("database", "mobarena_stats");
|
||||
boolean ssl = config.getBoolean("ssl", false);
|
||||
|
||||
String params = "useSSL=" + ssl;
|
||||
|
||||
return "jdbc:mysql://" + host + ":" + port + "/" + database + "?" + params;
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,38 @@
|
||||
package org.mobarena.stats.store.sqlite;
|
||||
|
||||
import org.bukkit.configuration.ConfigurationSection;
|
||||
import org.bukkit.configuration.MemoryConfiguration;
|
||||
import org.mobarena.stats.MobArenaStats;
|
||||
import org.mobarena.stats.store.jdbc.JdbcStatsStore;
|
||||
|
||||
import java.io.File;
|
||||
|
||||
public class SqliteStatsStore {
|
||||
|
||||
public static JdbcStatsStore create(
|
||||
ConfigurationSection config,
|
||||
MobArenaStats plugin
|
||||
) throws Exception {
|
||||
ConfigurationSection copy = new MemoryConfiguration();
|
||||
for (String key : config.getKeys(false)) {
|
||||
copy.set(key, config.get(key));
|
||||
}
|
||||
|
||||
File data = plugin.getDataFolder();
|
||||
String url = getUrl(copy, data);
|
||||
copy.set("type", "sqlite");
|
||||
copy.set("url", url);
|
||||
copy.addDefault("username", "sa");
|
||||
copy.addDefault("password", "");
|
||||
|
||||
return JdbcStatsStore.create(copy, plugin);
|
||||
}
|
||||
|
||||
static String getUrl(ConfigurationSection config, File data) {
|
||||
String folder = data.getPath();
|
||||
String filename = config.getString("filename", "stats.db");
|
||||
|
||||
return "jdbc:sqlite:" + folder + "/" + filename;
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,118 @@
|
||||
package org.mobarena.stats.util;
|
||||
|
||||
import java.io.ByteArrayOutputStream;
|
||||
import java.io.FileNotFoundException;
|
||||
import java.io.IOException;
|
||||
import java.io.InputStream;
|
||||
import java.net.URI;
|
||||
import java.net.URISyntaxException;
|
||||
import java.net.URL;
|
||||
import java.nio.charset.StandardCharsets;
|
||||
import java.nio.file.FileSystem;
|
||||
import java.nio.file.FileSystems;
|
||||
import java.nio.file.Files;
|
||||
import java.nio.file.Path;
|
||||
import java.nio.file.Paths;
|
||||
import java.util.Collections;
|
||||
import java.util.List;
|
||||
import java.util.NoSuchElementException;
|
||||
import java.util.stream.Collectors;
|
||||
|
||||
/**
|
||||
* Lists and loads resources via a given {@link ClassLoader}.
|
||||
* <p>
|
||||
* The primary goal of this class is to provide a developer-friendly
|
||||
* abstraction over Java's complex concept of "resources", allowing
|
||||
* client components to focus their efforts on their own context.
|
||||
* <p>
|
||||
* In general, we know what resources we're looking for, and we just
|
||||
* want to load them into memory and apply them where needed, but we
|
||||
* also want to "scan" resource "folders". The latter is fairly easy
|
||||
* in a file system context, but in a jar-file, while still somewhat
|
||||
* doable, becomes a nightmare to have to do again and again. That's
|
||||
* where this class comes in, as a mild wrapper around something that
|
||||
* can best be described as infuriating.
|
||||
*/
|
||||
public class ResourceLoader {
|
||||
|
||||
private final ClassLoader loader;
|
||||
|
||||
ResourceLoader(ClassLoader loader) {
|
||||
this.loader = loader;
|
||||
}
|
||||
|
||||
/**
|
||||
* Find all resources that match the given path.
|
||||
*
|
||||
* @param prefix a resource "prefix" to filter resources by
|
||||
* @return a list of all resources that match the given prefix
|
||||
* @throws URISyntaxException if the given path isn't a valid URI
|
||||
* in the context of the class loader
|
||||
* @throws IOException if an I/O error occurs during traversal
|
||||
*/
|
||||
public List<String> list(String prefix) throws URISyntaxException, IOException {
|
||||
URL url = loader.getResource(prefix);
|
||||
if (url == null) {
|
||||
throw new NoSuchElementException("No resources found at " + prefix);
|
||||
}
|
||||
|
||||
URI uri = url.toURI();
|
||||
if (uri.getScheme().equals("jar")) {
|
||||
try (FileSystem fs = FileSystems.newFileSystem(uri, Collections.emptyMap())) {
|
||||
Path path = fs.getPath(prefix);
|
||||
return walk(path);
|
||||
}
|
||||
} else {
|
||||
Path path = Paths.get(uri);
|
||||
return walk(path);
|
||||
}
|
||||
}
|
||||
|
||||
private List<String> walk(Path path) throws IOException {
|
||||
// When we traverse the path, we want to skip the folder
|
||||
// denoted by the path itself, and this is always first
|
||||
// in the stream.
|
||||
return Files.walk(path, 1)
|
||||
.skip(1)
|
||||
.map(Path::getFileName)
|
||||
.map(Path::toString)
|
||||
.sorted()
|
||||
.collect(Collectors.toList());
|
||||
}
|
||||
|
||||
/**
|
||||
* Load the resource at the given path, interpreting its contents
|
||||
* as UTF-8 encoded text.
|
||||
*
|
||||
* @param path the path to the resource to load
|
||||
* @return the contents of the resource at the given path
|
||||
* @throws IOException if an I/O error occurs during loading
|
||||
*/
|
||||
public String loadString(String path) throws IOException {
|
||||
InputStream is = loader.getResourceAsStream(path);
|
||||
if (is == null) {
|
||||
throw new FileNotFoundException("Resource not found: " + path);
|
||||
}
|
||||
|
||||
ByteArrayOutputStream output = new ByteArrayOutputStream();
|
||||
byte[] buffer = new byte[1024];
|
||||
int length;
|
||||
while ((length = is.read(buffer)) != -1) {
|
||||
output.write(buffer, 0, length);
|
||||
}
|
||||
|
||||
return output.toString(StandardCharsets.UTF_8.name());
|
||||
}
|
||||
|
||||
/**
|
||||
* Create a new resource loader with the given {@link ClassLoader}
|
||||
* as its source.
|
||||
*
|
||||
* @param loader a class loader to use as a source of resources
|
||||
* @return a new resource loader
|
||||
*/
|
||||
public static ResourceLoader create(ClassLoader loader) {
|
||||
return new ResourceLoader(loader);
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,59 @@
|
||||
#----------------------------------------------------------------------
|
||||
# The store is where all the collected data is kept. Different store
|
||||
# types are supported:
|
||||
#
|
||||
# - sqlite: stores stats in an SQLite database
|
||||
# - mysql: stores stats in a MySQL/MariaDB database
|
||||
# - csv: stores stats in local CSV files
|
||||
#
|
||||
# Stores may require configuration of additional properties, such as
|
||||
# file paths or database credentials.
|
||||
#----------------------------------------------------------------------
|
||||
store:
|
||||
|
||||
#--------------------------------------------------------------------
|
||||
# Which type of store to use.
|
||||
#
|
||||
# Changing this value will _not_ result in an automatic conversion
|
||||
# of existing store data. To transfer data to a different store,
|
||||
# make an export of the current store first, then change type and
|
||||
# import the exported data.
|
||||
#
|
||||
type: sqlite
|
||||
#--------------------------------------------------------------------
|
||||
|
||||
#--------------------------------------------------------------------
|
||||
# SQLite store properties
|
||||
#
|
||||
# - filename: name of the database file, relative to plugin folder
|
||||
#
|
||||
filename: stats.db
|
||||
#--------------------------------------------------------------------
|
||||
|
||||
#--------------------------------------------------------------------
|
||||
# MySQL/MariaDB store properties
|
||||
#
|
||||
# - host: where the database instance is hosted
|
||||
# - port: database port number
|
||||
# - database: name of the database (must exist!)
|
||||
# - username: username of a valid database user
|
||||
# - password: password of a valid database user
|
||||
# - ssl: whether to use SSL for database connections
|
||||
#
|
||||
#host: localhost
|
||||
#port: 3306
|
||||
#database: ''
|
||||
#username: ''
|
||||
#password: ''
|
||||
#ssl: false
|
||||
#--------------------------------------------------------------------
|
||||
|
||||
#--------------------------------------------------------------------
|
||||
# CSV store properties
|
||||
#
|
||||
# - folder: where to store data files, relative to plugin folder
|
||||
# - separator: symbol to separate fields and values with
|
||||
#
|
||||
#folder: data
|
||||
#separator: ';'
|
||||
#--------------------------------------------------------------------
|
||||
@@ -0,0 +1,3 @@
|
||||
DELETE
|
||||
FROM sessions
|
||||
WHERE session_id = :session_id;
|
||||
@@ -0,0 +1,4 @@
|
||||
SELECT *
|
||||
FROM schema_migrations
|
||||
WHERE success = TRUE
|
||||
ORDER BY filename;
|
||||
@@ -0,0 +1,21 @@
|
||||
SELECT *
|
||||
FROM
|
||||
(
|
||||
SELECT
|
||||
COUNT(1) AS total_sessions,
|
||||
MAX(last_wave) AS highest_wave,
|
||||
SUM(last_wave) AS total_waves,
|
||||
MAX(TIMESTAMPDIFF(second, start_time, end_time)) AS highest_seconds,
|
||||
SUM(TIMESTAMPDIFF(second, start_time, end_time)) AS total_seconds
|
||||
FROM sessions
|
||||
WHERE arena_slug = :arena_slug
|
||||
) AS t1,
|
||||
(
|
||||
SELECT
|
||||
SUM(p.kills) AS total_kills,
|
||||
MAX(p.kills) AS highest_kills
|
||||
FROM sessions s
|
||||
JOIN player_sessions p
|
||||
ON p.session_id = s.id
|
||||
WHERE s.arena_slug = :arena_slug
|
||||
) AS t2;
|
||||
@@ -0,0 +1,16 @@
|
||||
SELECT *
|
||||
FROM
|
||||
(
|
||||
SELECT
|
||||
COUNT(1) AS total_sessions,
|
||||
SUM(TIMESTAMPDIFF(second, start_time, end_time)) AS total_seconds,
|
||||
SUM(last_wave) AS total_waves
|
||||
FROM sessions
|
||||
) AS t1,
|
||||
(
|
||||
SELECT
|
||||
SUM(p.kills) AS total_kills
|
||||
FROM sessions s
|
||||
JOIN player_sessions p
|
||||
ON p.session_id = s.id
|
||||
) AS t2;
|
||||
@@ -0,0 +1,5 @@
|
||||
SELECT p.*
|
||||
FROM player_sessions p
|
||||
JOIN sessions s
|
||||
ON s.id = p.session_id
|
||||
WHERE s.session_id = :session_id;
|
||||
@@ -0,0 +1,9 @@
|
||||
SELECT
|
||||
COUNT(1) AS total_sessions,
|
||||
SUM(TIMESTAMPDIFF(second, s.start_time, COALESCE(p.death_time, p.leave_time, s.end_time))) AS total_seconds,
|
||||
SUM(p.kills) AS total_kills,
|
||||
SUM(p.last_wave) AS total_waves
|
||||
FROM sessions s
|
||||
JOIN player_sessions p
|
||||
ON p.session_id = s.id
|
||||
WHERE p.player_name = :player_name;
|
||||
@@ -0,0 +1,4 @@
|
||||
SELECT *
|
||||
FROM sessions
|
||||
LIMIT :limit
|
||||
OFFSET :offset;
|
||||
@@ -0,0 +1,15 @@
|
||||
INSERT INTO schema_migrations (
|
||||
filename,
|
||||
executed,
|
||||
success,
|
||||
error
|
||||
) VALUES (
|
||||
:filename,
|
||||
:executed,
|
||||
:success,
|
||||
:error
|
||||
) ON DUPLICATE KEY UPDATE
|
||||
executed = VALUES(executed),
|
||||
success = VALUES(success),
|
||||
error = VALUES(error)
|
||||
;
|
||||
@@ -0,0 +1,37 @@
|
||||
INSERT INTO player_sessions (
|
||||
player_id,
|
||||
player_name,
|
||||
session_id,
|
||||
class,
|
||||
join_time,
|
||||
ready_time,
|
||||
leave_time,
|
||||
death_time,
|
||||
kills,
|
||||
dmg_done,
|
||||
dmg_taken,
|
||||
swings,
|
||||
hits,
|
||||
last_wave,
|
||||
conclusion
|
||||
) VALUES (
|
||||
:player_id,
|
||||
:player_name,
|
||||
(
|
||||
SELECT id
|
||||
FROM sessions s
|
||||
WHERE s.session_id = :session_id
|
||||
),
|
||||
:class,
|
||||
:join_time,
|
||||
:ready_time,
|
||||
:leave_time,
|
||||
:death_time,
|
||||
:kills,
|
||||
:dmg_done,
|
||||
:dmg_taken,
|
||||
:swings,
|
||||
:hits,
|
||||
:last_wave,
|
||||
:conclusion
|
||||
);
|
||||
@@ -0,0 +1,15 @@
|
||||
INSERT INTO sessions (
|
||||
session_id,
|
||||
arena_slug,
|
||||
start_time,
|
||||
end_time,
|
||||
last_wave,
|
||||
conclusion
|
||||
) VALUES (
|
||||
:session_id,
|
||||
:arena_slug,
|
||||
:start_time,
|
||||
:end_time,
|
||||
:last_wave,
|
||||
:conclusion
|
||||
);
|
||||
@@ -0,0 +1,7 @@
|
||||
-- Schema migrations
|
||||
CREATE TABLE IF NOT EXISTS schema_migrations (
|
||||
filename VARCHAR(60) PRIMARY KEY,
|
||||
executed TIMESTAMP NOT NULL,
|
||||
success BOOLEAN NOT NULL,
|
||||
error TEXT NULL
|
||||
);
|
||||
@@ -0,0 +1,16 @@
|
||||
-- Overall session data
|
||||
CREATE TABLE IF NOT EXISTS sessions (
|
||||
id INTEGER PRIMARY KEY AUTO_INCREMENT,
|
||||
session_id CHAR(36) NOT NULL,
|
||||
arena_slug VARCHAR(30) NOT NULL,
|
||||
start_time DATETIME NOT NULL,
|
||||
end_time DATETIME NOT NULL,
|
||||
last_wave INTEGER NOT NULL,
|
||||
conclusion VARCHAR(10) NOT NULL
|
||||
);
|
||||
|
||||
-- Create a unique index on the UUID for "player queries"
|
||||
CREATE UNIQUE INDEX idx_sessions_session_id ON sessions (session_id);
|
||||
|
||||
-- Create an index on the arena slug for "arena queries"
|
||||
CREATE INDEX idx_sessions_arena_slug ON sessions (arena_slug);
|
||||
@@ -0,0 +1,25 @@
|
||||
-- Player-specific session data.
|
||||
CREATE TABLE IF NOT EXISTS player_sessions (
|
||||
session_id INTEGER NOT NULL,
|
||||
player_id CHAR(36) NOT NULL,
|
||||
player_name VARCHAR(30) NOT NULL,
|
||||
class VARCHAR(30) NOT NULL,
|
||||
join_time DATETIME NOT NULL,
|
||||
ready_time DATETIME NULL,
|
||||
leave_time DATETIME NULL,
|
||||
death_time DATETIME NULL,
|
||||
kills INTEGER NOT NULL,
|
||||
dmg_done INTEGER NOT NULL,
|
||||
dmg_taken INTEGER NOT NULL,
|
||||
swings INTEGER NOT NULL,
|
||||
hits INTEGER NOT NULL,
|
||||
last_wave INTEGER NOT NULL,
|
||||
conclusion VARCHAR(10) NOT NULL,
|
||||
FOREIGN KEY (session_id) REFERENCES sessions (id) ON DELETE CASCADE
|
||||
);
|
||||
|
||||
-- Create an index on the player UUID for "online queries"
|
||||
CREATE INDEX idx_player_sessions_player_id ON player_sessions (player_id);
|
||||
|
||||
-- Create an index on the player name for "offline queries"
|
||||
CREATE INDEX idx_player_sessions_player_name ON player_sessions (player_name);
|
||||
@@ -0,0 +1,6 @@
|
||||
name: MobArenaStats
|
||||
author: garbagemule
|
||||
main: org.mobarena.stats.MobArenaStatsPlugin
|
||||
version: '${project.version}'
|
||||
api-version: 1.13
|
||||
softdepend: [MobArena]
|
||||
@@ -0,0 +1,3 @@
|
||||
DELETE
|
||||
FROM sessions
|
||||
WHERE session_id = :session_id;
|
||||
@@ -0,0 +1,4 @@
|
||||
SELECT *
|
||||
FROM schema_migrations
|
||||
WHERE success = TRUE
|
||||
ORDER BY filename;
|
||||
@@ -0,0 +1,21 @@
|
||||
SELECT *
|
||||
FROM
|
||||
(
|
||||
SELECT
|
||||
COUNT(1) AS total_sessions,
|
||||
MAX(last_wave) AS highest_wave,
|
||||
SUM(last_wave) AS total_waves,
|
||||
MAX((end_time / 1000) - (start_time / 1000)) AS highest_seconds,
|
||||
SUM((end_time / 1000) - (start_time / 1000)) AS total_seconds
|
||||
FROM sessions
|
||||
WHERE arena_slug = :arena_slug
|
||||
) AS t1,
|
||||
(
|
||||
SELECT
|
||||
SUM(p.kills) AS total_kills,
|
||||
MAX(p.kills) AS highest_kills
|
||||
FROM sessions s
|
||||
JOIN player_sessions p
|
||||
ON p.session_id = s.id
|
||||
WHERE s.arena_slug = :arena_slug
|
||||
) AS t2;
|
||||
@@ -0,0 +1,16 @@
|
||||
SELECT *
|
||||
FROM
|
||||
(
|
||||
SELECT
|
||||
COUNT(1) AS total_sessions,
|
||||
SUM((end_time / 1000) - (start_time / 1000)) AS total_seconds,
|
||||
SUM(last_wave) AS total_waves
|
||||
FROM sessions
|
||||
) AS t1,
|
||||
(
|
||||
SELECT
|
||||
SUM(p.kills) AS total_kills
|
||||
FROM sessions s
|
||||
JOIN player_sessions p
|
||||
ON p.session_id = s.id
|
||||
) AS t2;
|
||||
@@ -0,0 +1,5 @@
|
||||
SELECT p.*
|
||||
FROM player_sessions p
|
||||
JOIN sessions s
|
||||
ON s.id = p.session_id
|
||||
WHERE s.session_id = :session_id;
|
||||
@@ -0,0 +1,9 @@
|
||||
SELECT
|
||||
COUNT(1) AS total_sessions,
|
||||
SUM((COALESCE(p.death_time, p.leave_time, s.end_time) / 1000) - (start_time / 1000)) AS total_seconds,
|
||||
SUM(p.kills) AS total_kills,
|
||||
SUM(p.last_wave) AS total_waves
|
||||
FROM sessions s
|
||||
JOIN player_sessions p
|
||||
ON p.session_id = s.id
|
||||
WHERE p.player_name = :player_name;
|
||||
@@ -0,0 +1,4 @@
|
||||
SELECT *
|
||||
FROM sessions
|
||||
LIMIT :limit
|
||||
OFFSET :offset;
|
||||
@@ -0,0 +1,15 @@
|
||||
INSERT INTO schema_migrations (
|
||||
filename,
|
||||
executed,
|
||||
success,
|
||||
error
|
||||
) VALUES (
|
||||
:filename,
|
||||
:executed,
|
||||
:success,
|
||||
:error
|
||||
) ON CONFLICT (filename) DO UPDATE SET
|
||||
executed = excluded.executed,
|
||||
success = excluded.success,
|
||||
error = excluded.error
|
||||
;
|
||||
@@ -0,0 +1,37 @@
|
||||
INSERT INTO player_sessions (
|
||||
player_id,
|
||||
player_name,
|
||||
session_id,
|
||||
class,
|
||||
join_time,
|
||||
ready_time,
|
||||
leave_time,
|
||||
death_time,
|
||||
kills,
|
||||
dmg_done,
|
||||
dmg_taken,
|
||||
swings,
|
||||
hits,
|
||||
last_wave,
|
||||
conclusion
|
||||
) VALUES (
|
||||
:player_id,
|
||||
:player_name,
|
||||
(
|
||||
SELECT id
|
||||
FROM sessions s
|
||||
WHERE s.session_id = :session_id
|
||||
),
|
||||
:class,
|
||||
:join_time,
|
||||
:ready_time,
|
||||
:leave_time,
|
||||
:death_time,
|
||||
:kills,
|
||||
:dmg_done,
|
||||
:dmg_taken,
|
||||
:swings,
|
||||
:hits,
|
||||
:last_wave,
|
||||
:conclusion
|
||||
);
|
||||
@@ -0,0 +1,15 @@
|
||||
INSERT INTO sessions (
|
||||
session_id,
|
||||
arena_slug,
|
||||
start_time,
|
||||
end_time,
|
||||
last_wave,
|
||||
conclusion
|
||||
) VALUES (
|
||||
:session_id,
|
||||
:arena_slug,
|
||||
:start_time,
|
||||
:end_time,
|
||||
:last_wave,
|
||||
:conclusion
|
||||
);
|
||||
@@ -0,0 +1,7 @@
|
||||
-- Schema migrations
|
||||
CREATE TABLE IF NOT EXISTS schema_migrations (
|
||||
filename TEXT PRIMARY KEY,
|
||||
executed TIMESTAMP NOT NULL,
|
||||
success INTEGER NOT NULL,
|
||||
error TEXT NULL
|
||||
);
|
||||
@@ -0,0 +1,16 @@
|
||||
-- Overall session data
|
||||
CREATE TABLE IF NOT EXISTS sessions (
|
||||
id INTEGER PRIMARY KEY AUTOINCREMENT,
|
||||
session_id TEXT NOT NULL,
|
||||
arena_slug TEXT NOT NULL,
|
||||
start_time TIMESTAMP NOT NULL,
|
||||
end_time TIMESTAMP NOT NULL,
|
||||
last_wave INTEGER NOT NULL,
|
||||
conclusion TEXT NOT NULL
|
||||
);
|
||||
|
||||
-- Create a unique index on the UUID for "player queries"
|
||||
CREATE UNIQUE INDEX idx_sessions_session_id ON sessions (session_id);
|
||||
|
||||
-- Create an index on the arena slug for "arena queries"
|
||||
CREATE INDEX idx_sessions_arena_slug ON sessions (arena_slug);
|
||||
@@ -0,0 +1,25 @@
|
||||
-- Player-specific session data.
|
||||
CREATE TABLE IF NOT EXISTS player_sessions (
|
||||
session_id INTEGER NOT NULL,
|
||||
player_id TEXT NOT NULL,
|
||||
player_name TEXT NOT NULL,
|
||||
class TEXT NOT NULL,
|
||||
join_time TIMESTAMP NOT NULL,
|
||||
ready_time TIMESTAMP NULL,
|
||||
leave_time TIMESTAMP NULL,
|
||||
death_time TIMESTAMP NULL,
|
||||
kills INTEGER NOT NULL,
|
||||
dmg_done INTEGER NOT NULL,
|
||||
dmg_taken INTEGER NOT NULL,
|
||||
swings INTEGER NOT NULL,
|
||||
hits INTEGER NOT NULL,
|
||||
last_wave INTEGER NOT NULL,
|
||||
conclusion TEXT NOT NULL,
|
||||
FOREIGN KEY (session_id) REFERENCES sessions (id) ON DELETE CASCADE
|
||||
);
|
||||
|
||||
-- Create an index on the player UUID for "online queries"
|
||||
CREATE INDEX idx_player_sessions_player_id ON player_sessions (player_id);
|
||||
|
||||
-- Create an index on the player name for "offline queries"
|
||||
CREATE INDEX idx_player_sessions_player_name ON player_sessions (player_name);
|
||||
@@ -0,0 +1,26 @@
|
||||
package org.mobarena.stats.session;
|
||||
|
||||
import com.garbagemule.MobArena.framework.Arena;
|
||||
import org.bukkit.entity.Player;
|
||||
|
||||
import java.util.UUID;
|
||||
|
||||
import static org.mockito.Mockito.mock;
|
||||
import static org.mockito.Mockito.when;
|
||||
|
||||
class Mocks {
|
||||
|
||||
static Arena arena(String arenaSlug) {
|
||||
Arena arena = mock(Arena.class);
|
||||
when(arena.getSlug()).thenReturn(arenaSlug);
|
||||
return arena;
|
||||
}
|
||||
|
||||
static Player player(UUID playerId, String playerName) {
|
||||
Player player = mock(Player.class);
|
||||
when(player.getUniqueId()).thenReturn(playerId);
|
||||
when(player.getName()).thenReturn(playerName);
|
||||
return player;
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,346 @@
|
||||
package org.mobarena.stats.session;
|
||||
|
||||
import com.garbagemule.MobArena.ArenaClass;
|
||||
import com.garbagemule.MobArena.ArenaPlayer;
|
||||
import com.garbagemule.MobArena.events.ArenaCompleteEvent;
|
||||
import com.garbagemule.MobArena.events.ArenaEndEvent;
|
||||
import com.garbagemule.MobArena.events.ArenaPlayerDeathEvent;
|
||||
import com.garbagemule.MobArena.events.ArenaPlayerJoinEvent;
|
||||
import com.garbagemule.MobArena.events.ArenaPlayerLeaveEvent;
|
||||
import com.garbagemule.MobArena.events.ArenaPlayerReadyEvent;
|
||||
import com.garbagemule.MobArena.events.ArenaStartEvent;
|
||||
import com.garbagemule.MobArena.events.NewWaveEvent;
|
||||
import com.garbagemule.MobArena.framework.Arena;
|
||||
import org.junit.jupiter.api.BeforeEach;
|
||||
import org.junit.jupiter.api.Test;
|
||||
import org.junit.jupiter.api.extension.ExtendWith;
|
||||
import org.mobarena.stats.store.StatsStore;
|
||||
import org.bukkit.entity.Player;
|
||||
import org.mockito.junit.jupiter.MockitoExtension;
|
||||
|
||||
import java.io.IOException;
|
||||
import java.util.Arrays;
|
||||
import java.util.Collections;
|
||||
import java.util.HashSet;
|
||||
import java.util.concurrent.Executor;
|
||||
import java.util.logging.Level;
|
||||
import java.util.logging.Logger;
|
||||
|
||||
import static org.mockito.Mockito.*;
|
||||
|
||||
@ExtendWith(MockitoExtension.class)
|
||||
class SessionListenerTest {
|
||||
|
||||
SessionStore sessionStore;
|
||||
StatsStore statsStore;
|
||||
Executor asyncExecutor;
|
||||
Logger log;
|
||||
SessionListener subject;
|
||||
|
||||
@BeforeEach
|
||||
void setup() {
|
||||
sessionStore = mock(SessionStore.class);
|
||||
statsStore = mock(StatsStore.class);
|
||||
asyncExecutor = Runnable::run;
|
||||
log = mock(Logger.class);
|
||||
subject = new SessionListener(
|
||||
sessionStore,
|
||||
statsStore,
|
||||
asyncExecutor,
|
||||
log
|
||||
);
|
||||
}
|
||||
|
||||
@Test
|
||||
void freshJoinCreatesNewSessionAndCallsJoin() {
|
||||
Player player = mock(Player.class);
|
||||
Arena arena = mock(Arena.class);
|
||||
Session session = mock(Session.class);
|
||||
when(sessionStore.getByArena(arena)).thenReturn(null);
|
||||
when(sessionStore.create(arena)).thenReturn(session);
|
||||
ArenaPlayerJoinEvent event = new ArenaPlayerJoinEvent(player, arena);
|
||||
|
||||
subject.on(event);
|
||||
|
||||
verify(session).playerJoin(player);
|
||||
}
|
||||
|
||||
@Test
|
||||
void nextJoinCallsPlayerJoinOnExistingSession() {
|
||||
Player player = mock(Player.class);
|
||||
Arena arena = mock(Arena.class);
|
||||
Session session = mock(Session.class);
|
||||
when(sessionStore.getByArena(arena)).thenReturn(session);
|
||||
ArenaPlayerJoinEvent event = new ArenaPlayerJoinEvent(player, arena);
|
||||
|
||||
subject.on(event);
|
||||
|
||||
verify(sessionStore, never()).create(arena);
|
||||
verify(session).playerJoin(player);
|
||||
}
|
||||
|
||||
@Test
|
||||
void logsWarningIfPlayerReadyInNonExistentSession() {
|
||||
Player player = mock(Player.class);
|
||||
Arena arena = mock(Arena.class);
|
||||
when(sessionStore.getByArena(arena)).thenReturn(null);
|
||||
ArenaPlayerReadyEvent event = new ArenaPlayerReadyEvent(player, arena);
|
||||
|
||||
subject.on(event);
|
||||
|
||||
verify(log).warning(anyString());
|
||||
}
|
||||
|
||||
@Test
|
||||
void callsPlayerReady() {
|
||||
String className = "knight";
|
||||
Player player = mock(Player.class);
|
||||
ArenaPlayer ap = mock(ArenaPlayer.class);
|
||||
ArenaClass ac = mock(ArenaClass.class);
|
||||
Arena arena = mock(Arena.class);
|
||||
Session session = mock(Session.class);
|
||||
when(arena.getArenaPlayer(player)).thenReturn(ap);
|
||||
when(ap.getArenaClass()).thenReturn(ac);
|
||||
when(ac.getSlug()).thenReturn(className);
|
||||
when(sessionStore.getByArena(arena)).thenReturn(session);
|
||||
ArenaPlayerReadyEvent event = new ArenaPlayerReadyEvent(player, arena);
|
||||
|
||||
subject.on(event);
|
||||
|
||||
verify(session).playerReady(player, className);
|
||||
}
|
||||
|
||||
@Test
|
||||
void logsWarningIfPlayerLeavesInNonExistentSession() {
|
||||
Player player = mock(Player.class);
|
||||
Arena arena = mock(Arena.class);
|
||||
when(sessionStore.getByArena(arena)).thenReturn(null);
|
||||
ArenaPlayerLeaveEvent event = new ArenaPlayerLeaveEvent(player, arena);
|
||||
|
||||
subject.on(event);
|
||||
|
||||
verify(log).warning(anyString());
|
||||
}
|
||||
|
||||
@Test
|
||||
void callsPlayerLeaveInLobby() {
|
||||
Player player = mock(Player.class);
|
||||
Arena arena = mock(Arena.class);
|
||||
Session session = mock(Session.class);
|
||||
when(arena.isRunning()).thenReturn(false);
|
||||
when(arena.getPlayersInLobby()).thenReturn(Collections.singleton(player));
|
||||
when(sessionStore.getByArena(arena)).thenReturn(session);
|
||||
ArenaPlayerLeaveEvent event = new ArenaPlayerLeaveEvent(player, arena);
|
||||
|
||||
subject.on(event);
|
||||
|
||||
verify(session).playerLeave(arena, player);
|
||||
}
|
||||
|
||||
@Test
|
||||
void deletesSessionIfLastPlayerInLobby() {
|
||||
Player player = mock(Player.class);
|
||||
Arena arena = mock(Arena.class);
|
||||
Session session = mock(Session.class);
|
||||
when(arena.isRunning()).thenReturn(false);
|
||||
when(arena.getPlayersInLobby()).thenReturn(Collections.singleton(player));
|
||||
when(sessionStore.getByArena(arena)).thenReturn(session);
|
||||
ArenaPlayerLeaveEvent event = new ArenaPlayerLeaveEvent(player, arena);
|
||||
|
||||
subject.on(event);
|
||||
|
||||
verify(sessionStore).delete(session);
|
||||
}
|
||||
|
||||
@Test
|
||||
void doesNotDeleteSessionIfMorePlayersInLobby() {
|
||||
Player player = mock(Player.class);
|
||||
Player other = mock(Player.class);
|
||||
Arena arena = mock(Arena.class);
|
||||
Session session = mock(Session.class);
|
||||
when(arena.isRunning()).thenReturn(false);
|
||||
when(arena.getPlayersInLobby()).thenReturn(new HashSet<>(Arrays.asList(player, other)));
|
||||
when(sessionStore.getByArena(arena)).thenReturn(session);
|
||||
ArenaPlayerLeaveEvent event = new ArenaPlayerLeaveEvent(player, arena);
|
||||
|
||||
subject.on(event);
|
||||
|
||||
verify(sessionStore, never()).delete(session);
|
||||
}
|
||||
|
||||
@Test
|
||||
void callsPlayerLeaveInArenaButDoesNotDeleteSession() {
|
||||
Player player = mock(Player.class);
|
||||
Arena arena = mock(Arena.class);
|
||||
Session session = mock(Session.class);
|
||||
when(arena.isRunning()).thenReturn(true);
|
||||
when(sessionStore.getByArena(arena)).thenReturn(session);
|
||||
ArenaPlayerLeaveEvent event = new ArenaPlayerLeaveEvent(player, arena);
|
||||
|
||||
subject.on(event);
|
||||
|
||||
verify(session).playerLeave(arena, player);
|
||||
verify(sessionStore, never()).delete(session);
|
||||
}
|
||||
|
||||
@Test
|
||||
void logsWarningIfPlayerDiesInNonExistentSession() {
|
||||
Player player = mock(Player.class);
|
||||
Arena arena = mock(Arena.class);
|
||||
when(sessionStore.getByArena(arena)).thenReturn(null);
|
||||
ArenaPlayerDeathEvent event = new ArenaPlayerDeathEvent(player, arena, true);
|
||||
|
||||
subject.on(event);
|
||||
|
||||
verify(log).warning(anyString());
|
||||
}
|
||||
|
||||
@Test
|
||||
void callsPlayerDeath() {
|
||||
Player player = mock(Player.class);
|
||||
Arena arena = mock(Arena.class);
|
||||
Session session = mock(Session.class);
|
||||
when(sessionStore.getByArena(arena)).thenReturn(session);
|
||||
ArenaPlayerDeathEvent event = new ArenaPlayerDeathEvent(player, arena, true);
|
||||
|
||||
subject.on(event);
|
||||
|
||||
verify(session).playerDeath(arena, player);
|
||||
}
|
||||
|
||||
@Test
|
||||
void logsWarningIfArenaStartsWithoutSession() {
|
||||
Arena arena = mock(Arena.class);
|
||||
when(sessionStore.getByArena(arena)).thenReturn(null);
|
||||
ArenaStartEvent event = new ArenaStartEvent(arena);
|
||||
|
||||
subject.on(event);
|
||||
|
||||
verify(log).warning(anyString());
|
||||
}
|
||||
|
||||
@Test
|
||||
void callsStart() {
|
||||
Arena arena = mock(Arena.class);
|
||||
Session session = mock(Session.class);
|
||||
when(sessionStore.getByArena(arena)).thenReturn(session);
|
||||
ArenaStartEvent event = new ArenaStartEvent(arena);
|
||||
|
||||
subject.on(event);
|
||||
|
||||
verify(session).start();
|
||||
}
|
||||
|
||||
@Test
|
||||
void logsWarningIfWaveSpawnsWithoutSession() {
|
||||
Arena arena = mock(Arena.class);
|
||||
int wave = 3;
|
||||
when(sessionStore.getByArena(arena)).thenReturn(null);
|
||||
NewWaveEvent event = new NewWaveEvent(arena, null, wave);
|
||||
|
||||
subject.on(event);
|
||||
|
||||
verify(log).warning(anyString());
|
||||
}
|
||||
|
||||
@Test
|
||||
void callsWave() {
|
||||
Arena arena = mock(Arena.class);
|
||||
int wave = 3;
|
||||
Session session = mock(Session.class);
|
||||
when(sessionStore.getByArena(arena)).thenReturn(session);
|
||||
NewWaveEvent event = new NewWaveEvent(arena, null, wave);
|
||||
|
||||
subject.on(event);
|
||||
|
||||
verify(session).wave(wave);
|
||||
}
|
||||
|
||||
@Test
|
||||
void logsWarningIfArenaCompletesWithoutSession() {
|
||||
Arena arena = mock(Arena.class);
|
||||
when(sessionStore.getByArena(arena)).thenReturn(null);
|
||||
ArenaCompleteEvent event = new ArenaCompleteEvent(arena);
|
||||
|
||||
subject.on(event);
|
||||
|
||||
verify(log).warning(anyString());
|
||||
}
|
||||
|
||||
@Test
|
||||
void callsComplete() {
|
||||
Arena arena = mock(Arena.class);
|
||||
Session session = mock(Session.class);
|
||||
when(sessionStore.getByArena(arena)).thenReturn(session);
|
||||
ArenaCompleteEvent event = new ArenaCompleteEvent(arena);
|
||||
|
||||
subject.on(event);
|
||||
|
||||
verify(session).complete();
|
||||
}
|
||||
|
||||
@Test
|
||||
void logsWarningIfArenaEndsWithoutSession() {
|
||||
Arena arena = mock(Arena.class);
|
||||
when(sessionStore.getByArena(arena)).thenReturn(null);
|
||||
ArenaEndEvent event = new ArenaEndEvent(arena);
|
||||
|
||||
subject.on(event);
|
||||
|
||||
verify(log).warning(anyString());
|
||||
}
|
||||
|
||||
@Test
|
||||
void callsEndAndDeletesSession() {
|
||||
Arena arena = mock(Arena.class);
|
||||
Session session = mock(Session.class);
|
||||
when(sessionStore.getByArena(arena)).thenReturn(session);
|
||||
ArenaEndEvent event = new ArenaEndEvent(arena);
|
||||
|
||||
subject.on(event);
|
||||
|
||||
verify(session).end();
|
||||
verify(sessionStore).delete(session);
|
||||
}
|
||||
|
||||
@Test
|
||||
void doesNotSaveSessionIfNeverStarted() throws IOException {
|
||||
Arena arena = mock(Arena.class);
|
||||
Session session = mock(Session.class);
|
||||
when(arena.isRunning()).thenReturn(false);
|
||||
when(sessionStore.getByArena(arena)).thenReturn(session);
|
||||
ArenaEndEvent event = new ArenaEndEvent(arena);
|
||||
|
||||
subject.on(event);
|
||||
|
||||
verify(statsStore, never()).save(session);
|
||||
}
|
||||
|
||||
@Test
|
||||
void logsInfoIfSessionSaveSucceeds() {
|
||||
Arena arena = mock(Arena.class);
|
||||
Session session = mock(Session.class);
|
||||
when(arena.isRunning()).thenReturn(true);
|
||||
when(sessionStore.getByArena(arena)).thenReturn(session);
|
||||
ArenaEndEvent event = new ArenaEndEvent(arena);
|
||||
|
||||
subject.on(event);
|
||||
|
||||
verify(log).info(anyString());
|
||||
}
|
||||
|
||||
@Test
|
||||
void logsErrorIfSessionSaveThrows() throws IOException {
|
||||
Arena arena = mock(Arena.class);
|
||||
Session session = mock(Session.class);
|
||||
when(arena.isRunning()).thenReturn(true);
|
||||
when(sessionStore.getByArena(arena)).thenReturn(session);
|
||||
doThrow(new IOException()).when(statsStore).save(session);
|
||||
ArenaEndEvent event = new ArenaEndEvent(arena);
|
||||
|
||||
subject.on(event);
|
||||
|
||||
verify(log).log(eq(Level.SEVERE), anyString(), any(IOException.class));
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,61 @@
|
||||
package org.mobarena.stats.session;
|
||||
|
||||
import com.garbagemule.MobArena.framework.Arena;
|
||||
import org.junit.jupiter.api.BeforeEach;
|
||||
import org.junit.jupiter.api.Test;
|
||||
|
||||
import static org.hamcrest.CoreMatchers.*;
|
||||
import static org.hamcrest.MatcherAssert.*;
|
||||
import static org.junit.jupiter.api.Assertions.*;
|
||||
|
||||
class SessionStoreTest {
|
||||
|
||||
SessionStore subject;
|
||||
|
||||
@BeforeEach
|
||||
void setup() {
|
||||
subject = SessionStore.createNew();
|
||||
}
|
||||
|
||||
@Test
|
||||
void createThrowsIfSessionAlreadyExists() {
|
||||
Arena arena = Mocks.arena("jungle");
|
||||
subject.create(arena);
|
||||
|
||||
assertThrows(
|
||||
IllegalStateException.class,
|
||||
() -> subject.create(arena)
|
||||
);
|
||||
}
|
||||
|
||||
@Test
|
||||
void getByArenaOnFreshStoreReturnsNull() {
|
||||
Arena arena = Mocks.arena("castle");
|
||||
|
||||
Session result = subject.getByArena(arena);
|
||||
|
||||
assertThat(result, is(nullValue()));
|
||||
}
|
||||
|
||||
@Test
|
||||
void getByArenaAfterCreateReturnsSameSession() {
|
||||
Arena arena = Mocks.arena("castle");
|
||||
|
||||
Session expected = subject.create(arena);
|
||||
Session result = subject.getByArena(arena);
|
||||
|
||||
assertThat(result, equalTo(expected));
|
||||
}
|
||||
|
||||
@Test
|
||||
void getByArenaAfterDeleteReturnsNull() {
|
||||
Arena arena = Mocks.arena("castle");
|
||||
|
||||
Session session = subject.create(arena);
|
||||
subject.delete(session);
|
||||
Session result = subject.getByArena(arena);
|
||||
|
||||
assertThat(result, is(nullValue()));
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,283 @@
|
||||
package org.mobarena.stats.session;
|
||||
|
||||
import com.garbagemule.MobArena.ArenaPlayer;
|
||||
import com.garbagemule.MobArena.framework.Arena;
|
||||
import org.bukkit.entity.Player;
|
||||
import org.junit.jupiter.api.BeforeEach;
|
||||
import org.junit.jupiter.api.Test;
|
||||
import org.junit.jupiter.api.extension.ExtendWith;
|
||||
import org.mockito.junit.jupiter.MockitoExtension;
|
||||
|
||||
import java.util.UUID;
|
||||
|
||||
import static org.hamcrest.CoreMatchers.*;
|
||||
import static org.hamcrest.MatcherAssert.*;
|
||||
import static org.mockito.Mockito.*;
|
||||
|
||||
@ExtendWith(MockitoExtension.class)
|
||||
class SessionTest {
|
||||
|
||||
Session subject;
|
||||
|
||||
@BeforeEach
|
||||
void setup() {
|
||||
UUID sessionId = UUID.fromString("cafebabe-ea75-dead-beef-deadcafebabe");
|
||||
String arenaSlug = "castle";
|
||||
subject = new Session(
|
||||
sessionId,
|
||||
arenaSlug
|
||||
);
|
||||
}
|
||||
|
||||
@Test
|
||||
void emptySessionHasNoPlayerStats() {
|
||||
assertThat(subject.getPlayerStats().size(), equalTo(0));
|
||||
}
|
||||
|
||||
@Test
|
||||
void initPlayerStatsOnJoin() {
|
||||
UUID playerId = UUID.fromString("cafebabe-ea75-dead-beef-deadcafebabe");
|
||||
String playerName = "garbagemule";
|
||||
Player player = Mocks.player(playerId, playerName);
|
||||
|
||||
subject.playerJoin(player);
|
||||
|
||||
PlayerSessionStats actual = subject.getPlayerStats(playerId);
|
||||
assertThat(actual.playerId, equalTo(playerId));
|
||||
assertThat(actual.playerName, equalTo(playerName));
|
||||
assertThat(actual.className, nullValue());
|
||||
assertThat(actual.readyTime, nullValue());
|
||||
assertThat(actual.leaveTime, nullValue());
|
||||
assertThat(actual.deathTime, nullValue());
|
||||
assertThat(actual.kills, equalTo(0));
|
||||
assertThat(actual.dmgDone, equalTo(0));
|
||||
assertThat(actual.dmgTaken, equalTo(0));
|
||||
assertThat(actual.swings, equalTo(0));
|
||||
assertThat(actual.hits, equalTo(0));
|
||||
assertThat(actual.lastWave, equalTo(0));
|
||||
assertThat(actual.conclusion, nullValue());
|
||||
}
|
||||
|
||||
@Test
|
||||
void setJoinTimeOnJoin() {
|
||||
UUID playerId = UUID.fromString("cafebabe-ea75-dead-beef-deadcafebabe");
|
||||
Player player = Mocks.player(playerId, "garbagemule");
|
||||
|
||||
subject.playerJoin(player);
|
||||
|
||||
PlayerSessionStats actual = subject.getPlayerStats(playerId);
|
||||
assertThat(actual.joinTime, notNullValue());
|
||||
}
|
||||
|
||||
@Test
|
||||
void setReadyTimeOnReady() {
|
||||
UUID playerId = UUID.fromString("cafebabe-ea75-dead-beef-deadcafebabe");
|
||||
Player player = Mocks.player(playerId, "garbagemule");
|
||||
String className = "knight";
|
||||
subject.playerJoin(player);
|
||||
|
||||
subject.playerReady(player, className);
|
||||
|
||||
PlayerSessionStats actual = subject.getPlayerStats(playerId);
|
||||
assertThat(actual.readyTime, notNullValue());
|
||||
}
|
||||
|
||||
@Test
|
||||
void setClassNameOnReady() {
|
||||
UUID playerId = UUID.fromString("cafebabe-ea75-dead-beef-deadcafebabe");
|
||||
Player player = Mocks.player(playerId, "garbagemule");
|
||||
String className = "knight";
|
||||
subject.playerJoin(player);
|
||||
|
||||
subject.playerReady(player, className);
|
||||
|
||||
PlayerSessionStats actual = subject.getPlayerStats(playerId);
|
||||
assertThat(actual.className, equalTo(className));
|
||||
}
|
||||
|
||||
@Test
|
||||
void setLeaveTimeOnLeave() {
|
||||
UUID playerId = UUID.fromString("cafebabe-ea75-dead-beef-deadcafebabe");
|
||||
Player player = Mocks.player(playerId, "garbagemule");
|
||||
Arena arena = mock(Arena.class);
|
||||
ArenaPlayer ap = mock(ArenaPlayer.class);
|
||||
when(arena.getArenaPlayer(player)).thenReturn(ap);
|
||||
subject.playerJoin(player);
|
||||
|
||||
subject.playerLeave(arena, player);
|
||||
|
||||
PlayerSessionStats actual = subject.getPlayerStats(playerId);
|
||||
assertThat(actual.leaveTime, notNullValue());
|
||||
}
|
||||
|
||||
@Test
|
||||
void setRetreatOnLeaveIfNoOtherConclusion() {
|
||||
UUID playerId = UUID.fromString("cafebabe-ea75-dead-beef-deadcafebabe");
|
||||
Player player = Mocks.player(playerId, "garbagemule");
|
||||
Arena arena = mock(Arena.class);
|
||||
ArenaPlayer ap = mock(ArenaPlayer.class);
|
||||
when(arena.getArenaPlayer(player)).thenReturn(ap);
|
||||
subject.playerJoin(player);
|
||||
|
||||
subject.playerLeave(arena, player);
|
||||
|
||||
PlayerSessionStats actual = subject.getPlayerStats(playerId);
|
||||
assertThat(actual.conclusion, equalTo(PlayerConclusion.RETREAT));
|
||||
}
|
||||
|
||||
@Test
|
||||
void dontOverwriteConclusionOnLeave() {
|
||||
UUID playerId = UUID.fromString("cafebabe-ea75-dead-beef-deadcafebabe");
|
||||
Player player = Mocks.player(playerId, "garbagemule");
|
||||
Arena arena = mock(Arena.class);
|
||||
ArenaPlayer ap = mock(ArenaPlayer.class);
|
||||
when(arena.getArenaPlayer(player)).thenReturn(ap);
|
||||
subject.playerJoin(player);
|
||||
subject.getPlayerStats(playerId).conclusion = PlayerConclusion.VICTORY;
|
||||
|
||||
subject.playerLeave(arena, player);
|
||||
|
||||
PlayerSessionStats actual = subject.getPlayerStats(playerId);
|
||||
assertThat(actual.conclusion, not(equalTo(PlayerConclusion.RETREAT)));
|
||||
}
|
||||
|
||||
@Test
|
||||
void setDeathTimeOnDeath() {
|
||||
UUID playerId = UUID.fromString("cafebabe-ea75-dead-beef-deadcafebabe");
|
||||
Player player = Mocks.player(playerId, "garbagemule");
|
||||
Arena arena = mock(Arena.class);
|
||||
ArenaPlayer ap = mock(ArenaPlayer.class);
|
||||
when(arena.getArenaPlayer(player)).thenReturn(ap);
|
||||
subject.playerJoin(player);
|
||||
|
||||
subject.playerDeath(arena, player);
|
||||
|
||||
PlayerSessionStats actual = subject.getPlayerStats(playerId);
|
||||
assertThat(actual.deathTime, notNullValue());
|
||||
}
|
||||
|
||||
@Test
|
||||
void setDefeatOnDeathIfNoOtherConclusion() {
|
||||
UUID playerId = UUID.fromString("cafebabe-ea75-dead-beef-deadcafebabe");
|
||||
Player player = Mocks.player(playerId, "garbagemule");
|
||||
Arena arena = mock(Arena.class);
|
||||
ArenaPlayer ap = mock(ArenaPlayer.class);
|
||||
when(arena.getArenaPlayer(player)).thenReturn(ap);
|
||||
subject.playerJoin(player);
|
||||
|
||||
subject.playerDeath(arena, player);
|
||||
|
||||
PlayerSessionStats actual = subject.getPlayerStats(playerId);
|
||||
assertThat(actual.conclusion, equalTo(PlayerConclusion.DEFEAT));
|
||||
}
|
||||
|
||||
@Test
|
||||
void dontOverwriteConclusionOnDeath() {
|
||||
UUID playerId = UUID.fromString("cafebabe-ea75-dead-beef-deadcafebabe");
|
||||
Player player = Mocks.player(playerId, "garbagemule");
|
||||
Arena arena = mock(Arena.class);
|
||||
ArenaPlayer ap = mock(ArenaPlayer.class);
|
||||
when(arena.getArenaPlayer(player)).thenReturn(ap);
|
||||
subject.playerJoin(player);
|
||||
subject.getPlayerStats(playerId).conclusion = PlayerConclusion.VICTORY;
|
||||
|
||||
subject.playerDeath(arena, player);
|
||||
|
||||
PlayerSessionStats actual = subject.getPlayerStats(playerId);
|
||||
assertThat(actual.conclusion, not(equalTo(PlayerConclusion.DEFEAT)));
|
||||
}
|
||||
|
||||
@Test
|
||||
void initSessionStatsOnCreate() {
|
||||
SessionStats actual = subject.getSessionStats();
|
||||
assertThat(actual.sessionId, notNullValue());
|
||||
assertThat(actual.startTime, nullValue());
|
||||
assertThat(actual.endTime, nullValue());
|
||||
assertThat(actual.lastWave, equalTo(0));
|
||||
assertThat(actual.conclusion, nullValue());
|
||||
}
|
||||
|
||||
@Test
|
||||
void setStartTimeOnStart() {
|
||||
subject.start();
|
||||
|
||||
SessionStats actual = subject.getSessionStats();
|
||||
assertThat(actual.startTime, notNullValue());
|
||||
}
|
||||
|
||||
@Test
|
||||
void setLastWaveTimeOnWave() {
|
||||
int wave = 3;
|
||||
|
||||
subject.wave(wave);
|
||||
|
||||
SessionStats actual = subject.getSessionStats();
|
||||
assertThat(actual.lastWave, equalTo(wave));
|
||||
}
|
||||
|
||||
@Test
|
||||
void setVictoryOnComplete() {
|
||||
subject.complete();
|
||||
|
||||
SessionStats actual = subject.getSessionStats();
|
||||
assertThat(actual.conclusion, equalTo(SessionConclusion.VICTORY));
|
||||
}
|
||||
|
||||
@Test
|
||||
void setSurvivorVictoryOnComplete() {
|
||||
UUID playerId = UUID.fromString("ca11ab1e-cafe-babe-ea75-babecafebeef");
|
||||
Player player = Mocks.player(playerId, "garbagemule");
|
||||
subject.playerJoin(player);
|
||||
|
||||
subject.complete();
|
||||
|
||||
PlayerSessionStats actual = subject.getPlayerStats(playerId);
|
||||
assertThat(actual.conclusion, equalTo(PlayerConclusion.VICTORY));
|
||||
}
|
||||
|
||||
@Test
|
||||
void dontOverwriteCorpseConclusionOnComplete() {
|
||||
UUID corpseId = UUID.fromString("deadbeef-dead-dead-dead-deadcafebeef");
|
||||
Player corpse = Mocks.player(corpseId, "trashdonkey");
|
||||
UUID survivorId = UUID.fromString("ca11ab1e-cafe-babe-ea75-babecafebeef");
|
||||
Player survivor = Mocks.player(survivorId, "garbagemule");
|
||||
Arena arena = mock(Arena.class);
|
||||
ArenaPlayer ap = mock(ArenaPlayer.class);
|
||||
when(arena.getArenaPlayer(corpse)).thenReturn(ap);
|
||||
subject.playerJoin(corpse);
|
||||
subject.playerJoin(survivor);
|
||||
subject.playerDeath(arena, corpse);
|
||||
|
||||
subject.complete();
|
||||
|
||||
PlayerSessionStats actual = subject.getPlayerStats(corpseId);
|
||||
assertThat(actual.conclusion, equalTo(PlayerConclusion.DEFEAT));
|
||||
}
|
||||
|
||||
@Test
|
||||
void setEndTimeTimeOnEnd() {
|
||||
subject.end();
|
||||
|
||||
SessionStats actual = subject.getSessionStats();
|
||||
assertThat(actual.endTime, notNullValue());
|
||||
}
|
||||
|
||||
@Test
|
||||
void setDefeatOnEnd() {
|
||||
subject.end();
|
||||
|
||||
SessionStats actual = subject.getSessionStats();
|
||||
assertThat(actual.conclusion, equalTo(SessionConclusion.DEFEAT));
|
||||
}
|
||||
|
||||
@Test
|
||||
void dontOverwriteConclusionOnEnd() {
|
||||
subject.complete();
|
||||
|
||||
subject.end();
|
||||
|
||||
SessionStats actual = subject.getSessionStats();
|
||||
assertThat(actual.conclusion, not(equalTo(SessionConclusion.DEFEAT)));
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,55 @@
|
||||
package org.mobarena.stats.session;
|
||||
|
||||
import com.garbagemule.MobArena.ArenaPlayer;
|
||||
import com.garbagemule.MobArena.ArenaPlayerStatistics;
|
||||
import com.garbagemule.MobArena.framework.Arena;
|
||||
import org.bukkit.entity.Player;
|
||||
import org.junit.jupiter.api.Test;
|
||||
import org.junit.jupiter.api.extension.ExtendWith;
|
||||
import org.mockito.junit.jupiter.MockitoExtension;
|
||||
|
||||
import java.util.UUID;
|
||||
|
||||
import static org.hamcrest.CoreMatchers.*;
|
||||
import static org.hamcrest.MatcherAssert.*;
|
||||
import static org.mockito.Mockito.*;
|
||||
|
||||
@ExtendWith(MockitoExtension.class)
|
||||
class StatsUtilTest {
|
||||
|
||||
@Test
|
||||
void copiesStatsFromMobArenaObject() {
|
||||
UUID sessionId = UUID.fromString("cafebabe-ea75-dead-beef-deadcafebabe");
|
||||
UUID playerId = UUID.fromString("babecafe-dead-beef-ea75-deadbeefbeef");
|
||||
String playerName = "garbagemule";
|
||||
int kills = 18;
|
||||
int dmgDone = 1587;
|
||||
int dmgTaken = 7159;
|
||||
int swings = 1457;
|
||||
int hits = 1337;
|
||||
int lastWave = 11;
|
||||
Player player = mock(Player.class);
|
||||
Arena arena = mock(Arena.class);
|
||||
ArenaPlayer ap = mock(ArenaPlayer.class);
|
||||
ArenaPlayerStatistics aps = mock(ArenaPlayerStatistics.class);
|
||||
when(arena.getArenaPlayer(player)).thenReturn(ap);
|
||||
when(ap.getStats()).thenReturn(aps);
|
||||
when(aps.getInt("kills")).thenReturn(kills);
|
||||
when(aps.getInt("dmgDone")).thenReturn(dmgDone);
|
||||
when(aps.getInt("dmgTaken")).thenReturn(dmgTaken);
|
||||
when(aps.getInt("swings")).thenReturn(swings);
|
||||
when(aps.getInt("hits")).thenReturn(hits);
|
||||
when(aps.getInt("lastWave")).thenReturn(lastWave);
|
||||
PlayerSessionStats target = new PlayerSessionStats(sessionId, playerId, playerName);
|
||||
|
||||
StatsUtil.copy(arena, player, target);
|
||||
|
||||
assertThat(target.kills, equalTo(kills));
|
||||
assertThat(target.dmgDone, equalTo(dmgDone));
|
||||
assertThat(target.dmgTaken, equalTo(dmgTaken));
|
||||
assertThat(target.swings, equalTo(swings));
|
||||
assertThat(target.hits, equalTo(hits));
|
||||
assertThat(target.lastWave, equalTo(lastWave));
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,22 @@
|
||||
package org.mobarena.stats.store;
|
||||
|
||||
import org.bukkit.configuration.ConfigurationSection;
|
||||
import org.junit.jupiter.api.Test;
|
||||
|
||||
import static org.mockito.Mockito.*;
|
||||
|
||||
class StatsExportTest {
|
||||
|
||||
@Test
|
||||
void exportsToTargetStore() throws Exception {
|
||||
StatsStore store = mock(StatsStore.class);
|
||||
StatsStore target = mock(StatsStore.class);
|
||||
StatsStoreRegistry registry = mock(StatsStoreRegistry.class);
|
||||
when(registry.create(any(ConfigurationSection.class))).thenReturn(target);
|
||||
|
||||
StatsExport.run(store, registry);
|
||||
|
||||
verify(store).export(target);
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,23 @@
|
||||
package org.mobarena.stats.store;
|
||||
|
||||
import org.bukkit.configuration.ConfigurationSection;
|
||||
import org.junit.jupiter.api.Test;
|
||||
|
||||
import static org.mockito.Mockito.*;
|
||||
|
||||
class StatsImportTest {
|
||||
|
||||
@Test
|
||||
void exportsFromSourceStore() throws Exception {
|
||||
String filename = "stats.export-1234.db";
|
||||
StatsStore store = mock(StatsStore.class);
|
||||
StatsStore source = mock(StatsStore.class);
|
||||
StatsStoreRegistry registry = mock(StatsStoreRegistry.class);
|
||||
when(registry.create(any(ConfigurationSection.class))).thenReturn(source);
|
||||
|
||||
StatsImport.run(registry, filename, store);
|
||||
|
||||
verify(source).export(store);
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,366 @@
|
||||
package org.mobarena.stats.store;
|
||||
|
||||
import org.junit.jupiter.api.Test;
|
||||
import org.mobarena.stats.session.PlayerConclusion;
|
||||
import org.mobarena.stats.session.PlayerSessionStats;
|
||||
import org.mobarena.stats.session.Session;
|
||||
import org.mobarena.stats.session.SessionConclusion;
|
||||
import org.mobarena.stats.session.SessionStats;
|
||||
|
||||
import java.time.Instant;
|
||||
import java.util.UUID;
|
||||
|
||||
import static org.hamcrest.CoreMatchers.*;
|
||||
import static org.hamcrest.MatcherAssert.*;
|
||||
|
||||
/**
|
||||
* Generic stats store integration test class.
|
||||
* <p>
|
||||
* For stores with complete implementations, creating a dervied test class
|
||||
* that follows the naming conventions of the Maven Failsafe Plugin will
|
||||
* result in the tests being run against the store during the integration
|
||||
* test phase.
|
||||
* <p>
|
||||
* Derived classes must implement the abstract {@link #getStore()} method,
|
||||
* which provides the parent class with a test subject.
|
||||
*
|
||||
* @see <a href="https://maven.apache.org/surefire/maven-failsafe-plugin/examples/inclusion-exclusion.html">Maven Failsafe Plugin naming conventions</a>
|
||||
*/
|
||||
public abstract class StatsStoreIT {
|
||||
|
||||
/**
|
||||
* The template method that delivers a store instance for use in all
|
||||
* of the tests in this class. Called at the beginning of every test,
|
||||
* this method is expected to return the same instance throughout the
|
||||
* entire test run to save on time.
|
||||
*
|
||||
* @return a StatsStore instance
|
||||
*/
|
||||
public abstract StatsStore getStore();
|
||||
|
||||
/**
|
||||
* A very basic test that saves a session and deletes is afterwards.
|
||||
* <p>
|
||||
* Humble but important, if this test succeeds, writes should work just
|
||||
* fine for the given database implementation.
|
||||
*/
|
||||
@Test
|
||||
void simpleSessionSaveAndDelete() throws Exception {
|
||||
StatsStore subject = getStore();
|
||||
|
||||
// Player
|
||||
UUID id = UUID.fromString("deadbeef-ea75-dead-babe-deadbeef0001");
|
||||
String name = "alice";
|
||||
|
||||
// Create and save a session
|
||||
UUID sessionId = UUID.fromString("cafebabe-ea75-dead-beef-deadbabe0001");
|
||||
String arenaSlug = "castle";
|
||||
Session session = new Session(sessionId, arenaSlug);
|
||||
set(session, 300, 23, SessionConclusion.DEFEAT);
|
||||
set(session, id, name, "tank", -59, 0, null, 672, 3, 6, PlayerConclusion.DEFEAT);
|
||||
subject.save(session);
|
||||
|
||||
// Delete the session again
|
||||
subject.delete(sessionId);
|
||||
}
|
||||
|
||||
/**
|
||||
* Two players join an arena, play different classes, and produce very
|
||||
* different results.
|
||||
* <p>
|
||||
* The goal of this test is to ensure that the session is captured "for"
|
||||
* both players, and that the "globals" add up as expected (one session,
|
||||
* max of waves, sum of kills).
|
||||
*/
|
||||
@Test
|
||||
void twoPlayerSession() throws Exception {
|
||||
StatsStore subject = getStore();
|
||||
|
||||
// Player 1
|
||||
UUID id1 = UUID.fromString("deadbeef-ea75-dead-cafe-deadbeef0002");
|
||||
String name1 = "bob";
|
||||
|
||||
// Player 2
|
||||
UUID id2 = UUID.fromString("deadbeef-ea75-dead-cafe-deadbeef0003");
|
||||
String name2 = "carol";
|
||||
|
||||
// Create and save the session
|
||||
UUID sessionId = UUID.fromString("cafebabe-ea75-dead-beef-deadbabe0002");
|
||||
String arenaSlug = "island";
|
||||
Session session = new Session(sessionId, arenaSlug);
|
||||
set(session, 610, 23, SessionConclusion.DEFEAT);
|
||||
set(session, id1, name1, "tank", -197, -45, null, 310, 3, 6, PlayerConclusion.DEFEAT);
|
||||
set(session, id2, name2, "archer", -99, 0, null, 610, 27, 23, PlayerConclusion.DEFEAT);
|
||||
subject.save(session);
|
||||
|
||||
try {
|
||||
// For global stats, we expect to see:
|
||||
// - Total sessions: 1
|
||||
// - Total duration: 610 secs
|
||||
// - Total kills: 3 + 27 = 30
|
||||
// - Total waves: 23
|
||||
{
|
||||
GlobalStats stats = subject.getGlobalStats();
|
||||
test(stats, 1, 610, 30, 23);
|
||||
}
|
||||
|
||||
// For arena-specific stats, because we only have a single
|
||||
// session, we expect to see the same values for totals,
|
||||
// but a real "high score" for the kills:
|
||||
// - Highest wave: 23
|
||||
// - Longest duration: 610 secs
|
||||
// - Highest kills: 27
|
||||
{
|
||||
ArenaStats stats = subject.getArenaStats(arenaSlug);
|
||||
test(stats, 23, 610, 27, 1, 610, 30, 23);
|
||||
}
|
||||
|
||||
// For player-specific stats, we expect to see individual numbers:
|
||||
// - Total sessions: 1 for both
|
||||
// - Total duration: 310 and 610 secs
|
||||
// - Total kills: 3 and 27
|
||||
// - Total waves: 6 and 23
|
||||
{
|
||||
PlayerStats stats = subject.getPlayerStats(name1);
|
||||
test(stats, 1, 310, 3, 6);
|
||||
}
|
||||
{
|
||||
PlayerStats stats = subject.getPlayerStats(name2);
|
||||
test(stats, 1, 610, 27, 23);
|
||||
}
|
||||
} finally {
|
||||
subject.delete(sessionId);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* A solid mix of arenas and players.
|
||||
* <p>
|
||||
* This is "the big one" where multiple players join multiple arenas in
|
||||
* various combinations, which means the stats should "stretch" in the
|
||||
* extremes to show any inconsistencies.
|
||||
*/
|
||||
@Test
|
||||
void multiPlayerMultiSession() throws Exception {
|
||||
StatsStore subject = getStore();
|
||||
|
||||
// Player 1
|
||||
UUID id1 = UUID.fromString("deadbeef-ea75-dead-cafe-deadbeef0004");
|
||||
String name1 = "dennis";
|
||||
|
||||
// Player 2
|
||||
UUID id2 = UUID.fromString("deadbeef-ea75-dead-cafe-deadbeef0005");
|
||||
String name2 = "eunice";
|
||||
|
||||
// Player 3
|
||||
UUID id3 = UUID.fromString("deadbeef-ea75-dead-cafe-deadbeef0006");
|
||||
String name3 = "frank";
|
||||
|
||||
// Player 4
|
||||
UUID id4 = UUID.fromString("deadbeef-ea75-dead-cafe-deadbeef0007");
|
||||
String name4 = "gloria";
|
||||
|
||||
// Arena slugs
|
||||
String slug1 = "jungle";
|
||||
String slug2 = "caverns";
|
||||
|
||||
// Session IDs
|
||||
UUID sessionId1 = UUID.fromString("cafebabe-ea75-dead-beef-deadbabe0003");
|
||||
UUID sessionId2 = UUID.fromString("cafebabe-ea75-dead-beef-deadbabe0004");
|
||||
UUID sessionId3 = UUID.fromString("cafebabe-ea75-dead-beef-deadbabe0005");
|
||||
|
||||
// Create and save the sessions
|
||||
{
|
||||
Session session = new Session(sessionId1, slug1);
|
||||
set(session, 730, 11, SessionConclusion.DEFEAT);
|
||||
set(session, id1, name1, "chemist", -10, 0, 100, null, 1, 3, PlayerConclusion.RETREAT);
|
||||
set(session, id2, name2, "oddjob", -50, -5, null, 730, 11, 11, PlayerConclusion.DEFEAT);
|
||||
subject.save(session);
|
||||
}
|
||||
{
|
||||
Session session = new Session(sessionId2, slug1);
|
||||
set(session, 400, 20, SessionConclusion.VICTORY);
|
||||
set(session, id1, name1, "tank", -120, -60, null, 310, 5, 5, PlayerConclusion.DEFEAT);
|
||||
set(session, id3, name3, "chemist", -110, -50, null, null, 10, 20, PlayerConclusion.VICTORY);
|
||||
subject.save(session);
|
||||
}
|
||||
{
|
||||
Session session = new Session(sessionId3, slug2);
|
||||
set(session, 610, 25, SessionConclusion.DEFEAT);
|
||||
set(session, id1, name1, "tank", -197, -45, null, 610, 2, 25, PlayerConclusion.DEFEAT);
|
||||
set(session, id2, name2, "archer", -99, 0, null, 550, 150, 15, PlayerConclusion.DEFEAT);
|
||||
set(session, id3, name3, "knight", -99, -10, null, 500, 10, 10, PlayerConclusion.DEFEAT);
|
||||
set(session, id4, name4, "oddjob", -10, -5, 200, null, 1, 3, PlayerConclusion.RETREAT);
|
||||
subject.save(session);
|
||||
}
|
||||
|
||||
try {
|
||||
// Global stats:
|
||||
// - Total sessions: 3
|
||||
// - Total duration: (730 + 400 + 610) = 1740 secs
|
||||
// - Total kills: (11 + 1) + (5 + 10) + (2 + 150 + 10 + 1) = 190
|
||||
// - Total waves: (11 + 20 + 25) = 56
|
||||
{
|
||||
GlobalStats stats = subject.getGlobalStats();
|
||||
test(stats, 3, 1740, 190, 56);
|
||||
}
|
||||
|
||||
// First arena stats:
|
||||
// - Highest wave: 20 (second session)
|
||||
// - Longest duration: 730 secs (first session)
|
||||
// - Highest kills: 11 (first session)
|
||||
// - Total sessions: 2
|
||||
// - Total duration: 730 + 400 = 1130 secs
|
||||
// - Total kills: (11 + 1) + (5 + 10) = 27
|
||||
// - Total waves: 11 + 20 = 31
|
||||
{
|
||||
ArenaStats stats = subject.getArenaStats(slug1);
|
||||
test(stats, 20, 730, 11, 2, 1130, 27, 31);
|
||||
}
|
||||
|
||||
// Second arena stats:
|
||||
// - Highest wave: 25
|
||||
// - Longest duration: 610
|
||||
// - Highest kills: 150
|
||||
// - Total sessions: 1
|
||||
// - Total duration: 610
|
||||
// - Total kills: (2 + 150 + 10 + 1) = 163
|
||||
// - Total waves: 25
|
||||
{
|
||||
ArenaStats stats = subject.getArenaStats(slug2);
|
||||
test(stats, 25, 610, 150, 1, 610, 163, 25);
|
||||
}
|
||||
|
||||
// Player 1 stats:
|
||||
// - Total sessions: 3
|
||||
// - Total duration: (100 + 310 + 610) = 1020
|
||||
// - Total kills: (1 + 5 + 2) = 8
|
||||
// - Total waves: (3 + 5 + 25) = 33
|
||||
{
|
||||
PlayerStats stats = subject.getPlayerStats(name1);
|
||||
test(stats, 3, 1020, 8, 33);
|
||||
}
|
||||
|
||||
// Player 2 stats:
|
||||
// - Total sessions: 2
|
||||
// - Total duration: (730 + 550) = 1280
|
||||
// - Total kills: (11 + 150) = 161
|
||||
// - Total waves: (11 + 15) = 26
|
||||
{
|
||||
PlayerStats stats = subject.getPlayerStats(name2);
|
||||
test(stats, 2, 1280, 161, 26);
|
||||
}
|
||||
|
||||
// Player 3 stats:
|
||||
// - Total sessions: 2
|
||||
// - Total duration: (400 + 500) = 900
|
||||
// - Total kills: (10 + 10) = 20
|
||||
// - Total waves: (20 + 10) = 30
|
||||
{
|
||||
PlayerStats stats = subject.getPlayerStats(name3);
|
||||
test(stats, 2, 900, 20, 30);
|
||||
}
|
||||
|
||||
// Player 4 stats:
|
||||
// - Total sessions: 1
|
||||
// - Total duration: 200
|
||||
// - Total kills: 1
|
||||
// - Total waves: 3
|
||||
{
|
||||
PlayerStats stats = subject.getPlayerStats(name4);
|
||||
test(stats, 1, 200, 1, 3);
|
||||
}
|
||||
} finally {
|
||||
subject.delete(sessionId1);
|
||||
subject.delete(sessionId2);
|
||||
subject.delete(sessionId3);
|
||||
}
|
||||
}
|
||||
|
||||
static final Instant epoch = Instant.parse("2021-06-28T10:00:00Z");
|
||||
|
||||
private static void set(
|
||||
Session session,
|
||||
int endOffset,
|
||||
int lastWave,
|
||||
SessionConclusion conclusion
|
||||
) {
|
||||
SessionStats stats = session.getSessionStats();
|
||||
stats.startTime = epoch;
|
||||
stats.endTime = epoch.plusSeconds(endOffset);
|
||||
stats.lastWave = lastWave;
|
||||
stats.conclusion = conclusion;
|
||||
}
|
||||
|
||||
private static void set(
|
||||
Session session,
|
||||
UUID playerId,
|
||||
String playerName,
|
||||
String className,
|
||||
int joinOffset,
|
||||
int readyOffset,
|
||||
Integer leaveOffset,
|
||||
Integer deathOffset,
|
||||
int kills,
|
||||
int lastWave,
|
||||
PlayerConclusion conclusion
|
||||
) {
|
||||
PlayerSessionStats stats = new PlayerSessionStats(session.getSessionId(), playerId, playerName);
|
||||
stats.className = className;
|
||||
stats.joinTime = epoch.plusSeconds(joinOffset);
|
||||
stats.readyTime = epoch.plusSeconds(readyOffset);
|
||||
stats.leaveTime = (leaveOffset != null) ? epoch.plusSeconds(leaveOffset) : null;
|
||||
stats.deathTime = (deathOffset != null) ? epoch.plusSeconds(deathOffset) : null;
|
||||
stats.kills = kills;
|
||||
stats.lastWave = lastWave;
|
||||
stats.conclusion = conclusion;
|
||||
session.setPlayerStats(stats.playerId, stats);
|
||||
}
|
||||
|
||||
private static void test(
|
||||
GlobalStats stats,
|
||||
int totalSessions,
|
||||
long totalSeconds,
|
||||
long totalKills,
|
||||
long totalWaves
|
||||
) {
|
||||
assertThat(stats.totalSessions, equalTo(totalSessions));
|
||||
assertThat(stats.totalSeconds, equalTo(totalSeconds));
|
||||
assertThat(stats.totalKills, equalTo(totalKills));
|
||||
assertThat(stats.totalWaves, equalTo(totalWaves));
|
||||
}
|
||||
|
||||
private static void test(
|
||||
ArenaStats stats,
|
||||
int highestWave,
|
||||
int highestSeconds,
|
||||
int highestKills,
|
||||
int totalSessions,
|
||||
long totalSeconds,
|
||||
long totalKills,
|
||||
long totalWaves
|
||||
) {
|
||||
assertThat(stats.highestWave, equalTo(highestWave));
|
||||
assertThat(stats.highestSeconds, equalTo(highestSeconds));
|
||||
assertThat(stats.highestKills, equalTo(highestKills));
|
||||
assertThat(stats.totalSessions, equalTo(totalSessions));
|
||||
assertThat(stats.totalSeconds, equalTo(totalSeconds));
|
||||
assertThat(stats.totalKills, equalTo(totalKills));
|
||||
assertThat(stats.totalWaves, equalTo(totalWaves));
|
||||
}
|
||||
|
||||
private static void test(
|
||||
PlayerStats stats,
|
||||
int totalSessions,
|
||||
long totalSeconds,
|
||||
long totalKills,
|
||||
long totalWaves
|
||||
) {
|
||||
assertThat(stats.totalSessions, equalTo(totalSessions));
|
||||
assertThat(stats.totalSeconds, equalTo(totalSeconds));
|
||||
assertThat(stats.totalKills, equalTo(totalKills));
|
||||
assertThat(stats.totalWaves, equalTo(totalWaves));
|
||||
}
|
||||
|
||||
|
||||
}
|
||||
@@ -0,0 +1,41 @@
|
||||
package org.mobarena.stats.store.jdbc;
|
||||
|
||||
import org.junit.jupiter.api.Test;
|
||||
import org.mobarena.stats.util.ResourceLoader;
|
||||
|
||||
import static org.hamcrest.CoreMatchers.*;
|
||||
import static org.hamcrest.MatcherAssert.*;
|
||||
|
||||
/**
|
||||
* This very simple test just ensures that all of the supported JDBC-based
|
||||
* store types have all the necessary SQL statement files. The actual call to
|
||||
* {@link Statements#create(ResourceLoader, String)} will throw an exception
|
||||
* if a file is missing, but the unit test ensures that it has content.
|
||||
* <p>
|
||||
* The tight coupling with {@link org.mobarena.stats.util.ResourceLoader} is
|
||||
* not as daunting as it may seem, since {@link Statements} itself is a hard
|
||||
* bootstrap-only utility class, and its usage is carefully wrapped in other
|
||||
* bootstrap components.
|
||||
*/
|
||||
class StatementsTest {
|
||||
|
||||
@Test
|
||||
void sqlite() throws Exception {
|
||||
test("sqlite");
|
||||
}
|
||||
|
||||
@Test
|
||||
void mysql() throws Exception {
|
||||
test("mysql");
|
||||
}
|
||||
|
||||
private void test(String type) throws Exception {
|
||||
ResourceLoader loader = ResourceLoader.create(Statements.class.getClassLoader());
|
||||
Statements statements = Statements.create(loader, type);
|
||||
for (Statement statement : Statement.values()) {
|
||||
String sql = statements.get(statement);
|
||||
assertThat(sql, notNullValue());
|
||||
}
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,50 @@
|
||||
package org.mobarena.stats.store.mariadb;
|
||||
|
||||
import org.bukkit.configuration.ConfigurationSection;
|
||||
import org.bukkit.configuration.MemoryConfiguration;
|
||||
import org.junit.jupiter.api.BeforeAll;
|
||||
import org.mobarena.stats.MobArenaStats;
|
||||
import org.mobarena.stats.store.StatsStore;
|
||||
import org.mobarena.stats.store.StatsStoreIT;
|
||||
import org.mobarena.stats.store.jdbc.JdbcStatsStore;
|
||||
import org.testcontainers.containers.MariaDBContainer;
|
||||
import org.testcontainers.junit.jupiter.Container;
|
||||
import org.testcontainers.junit.jupiter.Testcontainers;
|
||||
|
||||
import java.util.logging.Logger;
|
||||
|
||||
import static org.mockito.Mockito.*;
|
||||
|
||||
@SuppressWarnings("rawtypes")
|
||||
@Testcontainers
|
||||
public class MariadbStatsStoreIT extends StatsStoreIT {
|
||||
|
||||
@Container
|
||||
static final MariaDBContainer mariadb = new MariaDBContainer("mariadb:10.4");
|
||||
|
||||
static StatsStore subject;
|
||||
|
||||
@BeforeAll
|
||||
static void setup() throws Exception {
|
||||
// Set up fake configuration
|
||||
ConfigurationSection config = new MemoryConfiguration();
|
||||
config.set("type", "mysql");
|
||||
config.set("url", mariadb.getJdbcUrl());
|
||||
config.set("username", mariadb.getUsername());
|
||||
config.set("password", mariadb.getPassword());
|
||||
|
||||
// Set up fake plugin
|
||||
Logger log = mock(Logger.class);
|
||||
MobArenaStats plugin = mock(MobArenaStats.class);
|
||||
when(plugin.getLogger()).thenReturn(log);
|
||||
|
||||
// Create a real store test subject
|
||||
subject = JdbcStatsStore.create(config, plugin);
|
||||
}
|
||||
|
||||
@Override
|
||||
public StatsStore getStore() {
|
||||
return subject;
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,37 @@
|
||||
package org.mobarena.stats.store.mariadb;
|
||||
|
||||
import org.bukkit.configuration.ConfigurationSection;
|
||||
import org.bukkit.configuration.file.YamlConfiguration;
|
||||
import org.junit.jupiter.api.Test;
|
||||
import org.mobarena.stats.store.mysql.MysqlStatsStore;
|
||||
|
||||
import static org.hamcrest.CoreMatchers.equalTo;
|
||||
import static org.hamcrest.MatcherAssert.assertThat;
|
||||
|
||||
class MariadbStatsStoreTest {
|
||||
|
||||
@Test
|
||||
void getUrlDefaultValues() {
|
||||
ConfigurationSection config = new YamlConfiguration();
|
||||
|
||||
String result = MariadbStatsStore.getUrl(config);
|
||||
|
||||
String expected = "jdbc:mariadb://localhost:3306/mobarena_stats?useSSL=false";
|
||||
assertThat(result, equalTo(expected));
|
||||
}
|
||||
|
||||
@Test
|
||||
void getUrlConstructsJdbcUrl() {
|
||||
ConfigurationSection config = new YamlConfiguration();
|
||||
config.set("host", "stats.example.com");
|
||||
config.set("port", 1337);
|
||||
config.set("database", "mastats");
|
||||
config.set("ssl", true);
|
||||
|
||||
String result = MariadbStatsStore.getUrl(config);
|
||||
|
||||
String expected = "jdbc:mariadb://stats.example.com:1337/mastats?useSSL=true";
|
||||
assertThat(result, equalTo(expected));
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,50 @@
|
||||
package org.mobarena.stats.store.mysql;
|
||||
|
||||
import org.bukkit.configuration.ConfigurationSection;
|
||||
import org.bukkit.configuration.MemoryConfiguration;
|
||||
import org.junit.jupiter.api.BeforeAll;
|
||||
import org.mobarena.stats.MobArenaStats;
|
||||
import org.mobarena.stats.store.StatsStore;
|
||||
import org.mobarena.stats.store.StatsStoreIT;
|
||||
import org.mobarena.stats.store.jdbc.JdbcStatsStore;
|
||||
import org.testcontainers.containers.MySQLContainer;
|
||||
import org.testcontainers.junit.jupiter.Container;
|
||||
import org.testcontainers.junit.jupiter.Testcontainers;
|
||||
|
||||
import java.util.logging.Logger;
|
||||
|
||||
import static org.mockito.Mockito.*;
|
||||
|
||||
@SuppressWarnings("rawtypes")
|
||||
@Testcontainers
|
||||
public class MysqlStatsStoreIT extends StatsStoreIT {
|
||||
|
||||
@Container
|
||||
static final MySQLContainer mysql = new MySQLContainer("mysql:5.7");
|
||||
|
||||
static StatsStore subject;
|
||||
|
||||
@BeforeAll
|
||||
static void setup() throws Exception {
|
||||
// Set up fake configuration
|
||||
ConfigurationSection config = new MemoryConfiguration();
|
||||
config.set("type", "mysql");
|
||||
config.set("url", mysql.getJdbcUrl());
|
||||
config.set("username", mysql.getUsername());
|
||||
config.set("password", mysql.getPassword());
|
||||
|
||||
// Set up fake plugin
|
||||
Logger log = mock(Logger.class);
|
||||
MobArenaStats plugin = mock(MobArenaStats.class);
|
||||
when(plugin.getLogger()).thenReturn(log);
|
||||
|
||||
// Create a real store test subject
|
||||
subject = JdbcStatsStore.create(config, plugin);
|
||||
}
|
||||
|
||||
@Override
|
||||
public StatsStore getStore() {
|
||||
return subject;
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,37 @@
|
||||
package org.mobarena.stats.store.mysql;
|
||||
|
||||
import org.bukkit.configuration.ConfigurationSection;
|
||||
import org.bukkit.configuration.file.YamlConfiguration;
|
||||
import org.junit.jupiter.api.Test;
|
||||
import org.mobarena.stats.store.mysql.MysqlStatsStore;
|
||||
|
||||
import static org.hamcrest.CoreMatchers.*;
|
||||
import static org.hamcrest.MatcherAssert.*;
|
||||
|
||||
class MysqlStatsStoreTest {
|
||||
|
||||
@Test
|
||||
void getUrlDefaultValues() {
|
||||
ConfigurationSection config = new YamlConfiguration();
|
||||
|
||||
String result = MysqlStatsStore.getUrl(config);
|
||||
|
||||
String expected = "jdbc:mysql://localhost:3306/mobarena_stats?useSSL=false";
|
||||
assertThat(result, equalTo(expected));
|
||||
}
|
||||
|
||||
@Test
|
||||
void getUrlConstructsJdbcUrl() {
|
||||
ConfigurationSection config = new YamlConfiguration();
|
||||
config.set("host", "stats.example.com");
|
||||
config.set("port", 1337);
|
||||
config.set("database", "mastats");
|
||||
config.set("ssl", true);
|
||||
|
||||
String result = MysqlStatsStore.getUrl(config);
|
||||
|
||||
String expected = "jdbc:mysql://stats.example.com:1337/mastats?useSSL=true";
|
||||
assertThat(result, equalTo(expected));
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,44 @@
|
||||
package org.mobarena.stats.store.sqlite;
|
||||
|
||||
import org.bukkit.configuration.ConfigurationSection;
|
||||
import org.bukkit.configuration.MemoryConfiguration;
|
||||
import org.junit.jupiter.api.BeforeAll;
|
||||
import org.junit.jupiter.api.io.TempDir;
|
||||
import org.mobarena.stats.MobArenaStats;
|
||||
import org.mobarena.stats.store.StatsStore;
|
||||
import org.mobarena.stats.store.StatsStoreIT;
|
||||
|
||||
import java.io.File;
|
||||
import java.util.logging.Logger;
|
||||
|
||||
import static org.mockito.Mockito.*;
|
||||
|
||||
public class SqliteStatsStoreIT extends StatsStoreIT {
|
||||
|
||||
@TempDir
|
||||
static File data;
|
||||
|
||||
static StatsStore subject;
|
||||
|
||||
@BeforeAll
|
||||
static void setup() throws Exception {
|
||||
// Set up fake configuration
|
||||
ConfigurationSection config = new MemoryConfiguration();
|
||||
config.set("type", "sqlite");
|
||||
|
||||
// Set up fake plugin
|
||||
Logger log = mock(Logger.class);
|
||||
MobArenaStats plugin = mock(MobArenaStats.class);
|
||||
when(plugin.getLogger()).thenReturn(log);
|
||||
when(plugin.getDataFolder()).thenReturn(data);
|
||||
|
||||
// Create a real store test subject
|
||||
subject = SqliteStatsStore.create(config, plugin);
|
||||
}
|
||||
|
||||
@Override
|
||||
public StatsStore getStore() {
|
||||
return subject;
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,38 @@
|
||||
package org.mobarena.stats.store.sqlite;
|
||||
|
||||
import org.bukkit.configuration.ConfigurationSection;
|
||||
import org.bukkit.configuration.file.YamlConfiguration;
|
||||
import org.junit.jupiter.api.Test;
|
||||
import org.mobarena.stats.store.sqlite.SqliteStatsStore;
|
||||
|
||||
import java.io.File;
|
||||
|
||||
import static org.hamcrest.CoreMatchers.*;
|
||||
import static org.hamcrest.MatcherAssert.*;
|
||||
|
||||
class SqliteStatsStoreTest {
|
||||
|
||||
@Test
|
||||
void getUrlDefaultValues() {
|
||||
ConfigurationSection config = new YamlConfiguration();
|
||||
File data = new File("data");
|
||||
|
||||
String result = SqliteStatsStore.getUrl(config, data);
|
||||
|
||||
String expected = "jdbc:sqlite:" + data.getPath() + "/stats.db";
|
||||
assertThat(result, equalTo(expected));
|
||||
}
|
||||
|
||||
@Test
|
||||
void getUrlConstructsJdbcUrl() {
|
||||
ConfigurationSection config = new YamlConfiguration();
|
||||
config.set("filename", "HECK-YES.db");
|
||||
File data = new File("data");
|
||||
|
||||
String result = SqliteStatsStore.getUrl(config, data);
|
||||
|
||||
String expected = "jdbc:sqlite:" + data.getPath() + "/HECK-YES.db";
|
||||
assertThat(result, equalTo(expected));
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,213 @@
|
||||
package org.mobarena.stats.util;
|
||||
|
||||
import org.junit.jupiter.api.Test;
|
||||
|
||||
import java.io.File;
|
||||
import java.io.FileInputStream;
|
||||
import java.io.FileOutputStream;
|
||||
import java.io.InputStream;
|
||||
import java.net.URL;
|
||||
import java.net.URLClassLoader;
|
||||
import java.nio.file.Files;
|
||||
import java.nio.file.Path;
|
||||
import java.nio.file.Paths;
|
||||
import java.util.ArrayDeque;
|
||||
import java.util.Arrays;
|
||||
import java.util.Deque;
|
||||
import java.util.List;
|
||||
import java.util.jar.JarEntry;
|
||||
import java.util.jar.JarOutputStream;
|
||||
|
||||
import static org.hamcrest.CoreMatchers.*;
|
||||
import static org.hamcrest.MatcherAssert.*;
|
||||
|
||||
/**
|
||||
* Resource loading is no joke. In IDEs and build tools, resources
|
||||
* typically sit in a file system folder like src/main/resources,
|
||||
* which means the URI scheme is "file:". When a plugin is deployed
|
||||
* to a Minecraft server, however, the URI scheme changes to "jar:",
|
||||
* which means any operation that is scheme-dependent will have to
|
||||
* support both schemes for a good developer experience...
|
||||
* <p>
|
||||
* Loading a specific resource is scheme-independent, but iterating
|
||||
* resources isn't. The resource loader provides a "list" method to
|
||||
* list all the resources under a given prefix path, which means it
|
||||
* has to iterate (part of) the classpath, so it has to know which
|
||||
* scheme it's working under.
|
||||
* <p>
|
||||
* Thus, to properly unit test the resource loader's jar-specific
|
||||
* code path, we need to somehow provide a class loader that will
|
||||
* resolve resources with the jar URI scheme.
|
||||
* <p>
|
||||
* As it turns out, here be dragons...
|
||||
*/
|
||||
class ResourceLoaderTest {
|
||||
|
||||
@Test
|
||||
void listResourcesInDirectory() throws Exception {
|
||||
// The normal class loader from the test class will properly
|
||||
// resolve the resources in src/test/resources because this
|
||||
// folder is part of the class path during test runs, so we
|
||||
// don't have to do anything special here.
|
||||
ClassLoader loader = getClass().getClassLoader();
|
||||
ResourceLoader subject = new ResourceLoader(loader);
|
||||
|
||||
List<String> result = subject.list("dummy/migration");
|
||||
|
||||
List<String> expected = Arrays.asList(
|
||||
"V1__baseline.sql",
|
||||
"V2__new_stuff.sql",
|
||||
"V3__changed_stuff.sql"
|
||||
);
|
||||
assertThat(result, equalTo(expected));
|
||||
}
|
||||
|
||||
@Test
|
||||
void loadResourceInDirectory() throws Exception {
|
||||
ClassLoader loader = getClass().getClassLoader();
|
||||
ResourceLoader subject = new ResourceLoader(loader);
|
||||
String name = "dummy/migration/V1__baseline.sql";
|
||||
|
||||
String result = subject.loadString(name);
|
||||
|
||||
String expected = String.join(
|
||||
"\n",
|
||||
"-- Some database baseline",
|
||||
"CREATE TABLE IF NOT EXISTS bob(id INTEGER PRIMARY KEY AUTOINCREMENT);",
|
||||
""
|
||||
);
|
||||
assertThat(result, equalTo(expected));
|
||||
}
|
||||
|
||||
@Test
|
||||
void listResourcesInJarFile() throws Exception {
|
||||
// For the jar case, we wrap the test resources in a real,
|
||||
// and temporary, jar-file. This is extremely complex stuff
|
||||
// for a unit test, but it does mean we get a test case that
|
||||
// hits that specific code path for a boost of confidence.
|
||||
Path jar = createJarWithTestResources();
|
||||
try {
|
||||
// We also need a special class loader that can access
|
||||
// the contents of the jar-file with the correct scheme,
|
||||
// and while this isn't as complex, the URL/URI stuff is
|
||||
// pretty intricate.
|
||||
ClassLoader loader = createJarClassLoader(jar);
|
||||
ResourceLoader subject = new ResourceLoader(loader);
|
||||
|
||||
List<String> result = subject.list("dummy/migration");
|
||||
|
||||
List<String> expected = Arrays.asList(
|
||||
"V1__baseline.sql",
|
||||
"V2__new_stuff.sql",
|
||||
"V3__changed_stuff.sql"
|
||||
);
|
||||
assertThat(result, equalTo(expected));
|
||||
} finally {
|
||||
Files.deleteIfExists(jar);
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
void loadResourceInJarFile() throws Exception {
|
||||
Path jar = createJarWithTestResources();
|
||||
try {
|
||||
ClassLoader loader = createJarClassLoader(jar);
|
||||
ResourceLoader subject = new ResourceLoader(loader);
|
||||
String name = "dummy/migration/V1__baseline.sql";
|
||||
|
||||
String result = subject.loadString(name);
|
||||
|
||||
String expected = String.join(
|
||||
"\n",
|
||||
"-- Some database baseline",
|
||||
"CREATE TABLE IF NOT EXISTS bob(id INTEGER PRIMARY KEY AUTOINCREMENT);",
|
||||
""
|
||||
);
|
||||
assertThat(result, equalTo(expected));
|
||||
} finally {
|
||||
Files.deleteIfExists(jar);
|
||||
}
|
||||
}
|
||||
|
||||
private static Path createJarWithTestResources() throws Exception {
|
||||
// To create a jar file, we write some bytes to a jar output
|
||||
// stream, along with some jar-specific convenience functions
|
||||
// related to the concept of "entries". The implementation is
|
||||
// an iterative version of this solution from StackOverflow:
|
||||
//
|
||||
// https://stackoverflow.com/a/59351837/2221849
|
||||
//
|
||||
// Each file (and folder) in the test resources folder needs
|
||||
// to be written to the jar file as an "entry". Directories
|
||||
// are just empty entries that end in a forward slash (/),
|
||||
// while files are names and some actual bytes.
|
||||
//
|
||||
// We have to "relativize" the paths before writing the names
|
||||
// down, because the "root" starts in src/test/resources, and
|
||||
// we want to strip that part out of the names in the actual
|
||||
// jar file.
|
||||
Path jar = Files.createTempFile("mobarena-stats_", ".jar");
|
||||
try {
|
||||
JarOutputStream target = new JarOutputStream(new FileOutputStream(jar.toFile()));
|
||||
File root = Paths.get("src", "test", "resources").toFile();
|
||||
Deque<File> queue = new ArrayDeque<>();
|
||||
queue.push(root);
|
||||
while (!queue.isEmpty()) {
|
||||
File file = queue.pop();
|
||||
File relative = root.toPath().relativize(file.toPath()).toFile();
|
||||
String name = relative.getPath().replace("\\", "/");
|
||||
if (file.isDirectory()) {
|
||||
if (!name.isEmpty()) {
|
||||
JarEntry entry = new JarEntry(name + "/");
|
||||
entry.setTime(file.lastModified());
|
||||
target.putNextEntry(entry);
|
||||
target.closeEntry();
|
||||
}
|
||||
File[] children = file.listFiles();
|
||||
if (children != null) {
|
||||
for (File child : children) {
|
||||
queue.push(child);
|
||||
}
|
||||
}
|
||||
} else {
|
||||
JarEntry entry = new JarEntry(name);
|
||||
entry.setTime(file.lastModified());
|
||||
target.putNextEntry(entry);
|
||||
try (InputStream is = new FileInputStream(file)) {
|
||||
byte[] buffer = new byte[1024];
|
||||
int length;
|
||||
while ((length = is.read(buffer)) != -1) {
|
||||
target.write(buffer, 0, length);
|
||||
}
|
||||
target.closeEntry();
|
||||
}
|
||||
}
|
||||
}
|
||||
target.close();
|
||||
} catch (Exception up) {
|
||||
Files.deleteIfExists(jar);
|
||||
throw up;
|
||||
}
|
||||
|
||||
return jar;
|
||||
}
|
||||
|
||||
private static ClassLoader createJarClassLoader(Path jar) throws Exception {
|
||||
// I'll be honest and admit that I have no clue about the
|
||||
// structure of these URLs, but it turns out the the "!/"
|
||||
// suffix is of utmost importance.
|
||||
//
|
||||
// My guess is that it's necessary because the jar-scheme
|
||||
// "wraps" the file-scheme, and so it needs a dedicated
|
||||
// separator to get the following format:
|
||||
//
|
||||
// jar:file:<path-on-file-system>!/<path-in-jar-file>
|
||||
//
|
||||
// That is, the "!/" is there to indicate the end of the
|
||||
// file system path and the start of the jar-file path.
|
||||
String file = jar.toUri().toURL() + "!/";
|
||||
URL url = new URL("jar", "", file);
|
||||
return new URLClassLoader(new URL[]{url}, null);
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,2 @@
|
||||
-- Some database baseline
|
||||
CREATE TABLE IF NOT EXISTS bob(id INTEGER PRIMARY KEY AUTOINCREMENT);
|
||||
@@ -0,0 +1,2 @@
|
||||
-- Some new stuff
|
||||
ALTER TABLE bob ADD age INTEGER;
|
||||
@@ -0,0 +1,2 @@
|
||||
-- Some more changes
|
||||
ALTER TABLE bob ADD nickname TEXT;
|
||||
@@ -0,0 +1,2 @@
|
||||
-- A query
|
||||
SELECT 1;
|
||||
@@ -0,0 +1,4 @@
|
||||
name: MobArenaStats
|
||||
author: garbagemule
|
||||
main: org.mobarena.stats.MobArenaStatsPlugin
|
||||
version: '1.0'
|
||||
Reference in New Issue
Block a user