diff --git a/.github/workflows/release.yml b/.github/workflows/release.yml
index 0cbdd8b..12bbde1 100644
--- a/.github/workflows/release.yml
+++ b/.github/workflows/release.yml
@@ -26,6 +26,7 @@ jobs:
matrix:
os: [ ubuntu-latest ]
java: [ 17 ]
+ if: github.ref_type != 'tag'
steps:
- name: Checkout Repository
uses: actions/checkout@v4
@@ -48,13 +49,11 @@ jobs:
path: ${{ github.workspace }}/build/libs/
release:
- needs:
- - build
runs-on: ubuntu-latest
strategy:
matrix:
java: [ 17 ]
- if: github.ref_type == 'tag' || ((github.ref_name == 'main' || github.ref_name == 'master') && github.event_name != 'schedule')
+ if: github.ref_type == 'tag'
steps:
- name: Checkout Repository
uses: actions/checkout@v4
@@ -73,17 +72,11 @@ jobs:
echo "CUSTOM_VERSION=${{ github.ref_name }}" >> $GITHUB_ENV
- name: Build with Gradle
- if: github.ref_type != 'tag'
- run: ./gradlew clean build
-
- - name: Build with Gradle
- if: github.ref_type == 'tag'
run: ./gradlew clean build -PcustomVersion=${{ env.CUSTOM_VERSION }}
- name: Create Release
uses: softprops/action-gh-release@v1
id: release
- if: github.ref_type == 'tag'
with:
name: ${{ format('Release {0}', github.ref_name) }}
files: ${{ github.workspace }}/build/libs/*
diff --git a/.github/workflows/stale.yml b/.github/workflows/stale.yml
index 581de34..a7d9100 100644
--- a/.github/workflows/stale.yml
+++ b/.github/workflows/stale.yml
@@ -12,7 +12,7 @@ jobs:
stale:
runs-on: ubuntu-latest
steps:
- - uses: actions/stale@v8
+ - uses: actions/stale@v9
with:
stale-issue-message: ' This issue has been automatically marked as stale because it has been open for 60 days with no activity.'
stale-pr-message: 'This PR has been automatically marked as stale because it has been open for 60 days with no activity.'
diff --git a/build.gradle.kts b/build.gradle.kts
index 8497846..e596110 100644
--- a/build.gradle.kts
+++ b/build.gradle.kts
@@ -12,14 +12,14 @@ plugins {
id("xyz.jpenilla.run-paper") version "2.2.2" // Adds runServer and runMojangMappedServer tasks for testing
id("net.minecrell.plugin-yml.bukkit") version "0.6.0" // Automatic plugin.yml generation
id("io.papermc.paperweight.userdev") version "1.5.9" // Used to develop internal plugins using Mojang mappings, See https://github.com/PaperMC/paperweight
- id("org.flywaydb.flyway") version "10.0.0" // Database migrations
+ id("org.flywaydb.flyway") version "10.2.0" // Database migrations
eclipse
idea
}
group = "com.github.alathra"
-version = "3.0.0-RC-1"
+version = "3.0.0"
description = ""
val mainPackage = "${project.group}.${rootProject.name}"
@@ -62,8 +62,8 @@ repositories {
}
dependencies {
- compileOnly("org.jetbrains:annotations:24.0.1")
- annotationProcessor("org.jetbrains:annotations:24.0.1")
+ compileOnly("org.jetbrains:annotations:24.1.0")
+ annotationProcessor("org.jetbrains:annotations:24.1.0")
paperweight.paperDevBundle("1.20.2-R0.1-SNAPSHOT")
implementation("space.arim.morepaperlib:morepaperlib:latest.release")
@@ -73,13 +73,13 @@ dependencies {
exclude("net.kyori")
}
- implementation("dev.jorel:commandapi-bukkit-shade:9.2.0")
+ implementation("dev.jorel:commandapi-bukkit-shade:9.3.0")
compileOnly("me.clip:placeholderapi:2.11.4") {
exclude("me.clip.placeholderapi.libs", "kyori")
}
compileOnly("com.github.MilkBowl:VaultAPI:1.7")
- compileOnly("com.palmergames.bukkit.towny:towny:0.99.6.0") {
+ compileOnly("com.palmergames.bukkit.towny:towny:0.100.0.8") {
exclude("com.palmergames.adventure")
}
compileOnly("me.neznamy:tab-api:4.0.0")
@@ -90,10 +90,10 @@ dependencies {
// Database Dependencies
implementation("com.zaxxer:HikariCP:5.1.0")
- library("org.flywaydb:flyway-core:10.0.1")
- library("org.flywaydb:flyway-mysql:10.0.1")
- library("org.flywaydb:flyway-database-hsqldb:10.0.1")
- library("org.jooq:jooq:3.18.7")
+ library("org.flywaydb:flyway-core:10.2.0")
+ library("org.flywaydb:flyway-mysql:10.2.0")
+ library("org.flywaydb:flyway-database-hsqldb:10.2.0")
+ library("org.jooq:jooq:3.19.0")
// JDBC Drivers
library("org.hsqldb:hsqldb:2.7.2")
@@ -103,7 +103,6 @@ dependencies {
}
tasks {
- // NOTE: Use when developing plugins using Mojang mappings
assemble {
dependsOn(reobfJar)
}
@@ -163,11 +162,11 @@ tasks {
// Automatically install dependencies
downloadPlugins {
-// modrinth("carbon", "2.1.0-beta.21")
-// github("jpenilla", "MiniMOTD", "v2.0.13", "minimotd-bukkit-2.0.13.jar")
-// hangar("squaremap", "1.2.0")
-// url("https://download.luckperms.net/1515/bukkit/loader/LuckPerms-Bukkit-5.4.102.jar")
+ url("https://ci.dmulloy2.net/job/ProtocolLib/lastStableBuild/artifact/build/libs/ProtocolLib.jar")
github("MilkBowl", "Vault", "1.7.3", "Vault.jar")
+ url("https://download.luckperms.net/1521/bukkit/loader/LuckPerms-Bukkit-5.4.108.jar")
+ modrinth("tab-was-taken", "4.0.9")
+// url("https://www.spigotmc.org/resources/skulls-the-ultimate-head-database.90098/download?version=520217/Skulls.jar")
}
}
}
@@ -266,9 +265,9 @@ task("generateSources") {
buildscript {
dependencies {
- classpath("org.jooq:jooq:3.18.7")
- classpath("org.jooq:jooq-meta:3.18.7")
- classpath("org.jooq:jooq-codegen:3.18.7")
+ classpath("org.jooq:jooq:3.19.0")
+ classpath("org.jooq:jooq-meta:3.19.0")
+ classpath("org.jooq:jooq-codegen:3.19.0")
classpath("com.h2database:h2:2.2.224")
}
}
diff --git a/src/main/java/com/github/alathra/AlathranWars/Main.java b/src/main/java/com/github/alathra/AlathranWars/AlathranWars.java
similarity index 67%
rename from src/main/java/com/github/alathra/AlathranWars/Main.java
rename to src/main/java/com/github/alathra/AlathranWars/AlathranWars.java
index 3ecf2d1..b6a6c3c 100644
--- a/src/main/java/com/github/alathra/AlathranWars/Main.java
+++ b/src/main/java/com/github/alathra/AlathranWars/AlathranWars.java
@@ -1,13 +1,13 @@
package com.github.alathra.AlathranWars;
import com.github.alathra.AlathranWars.commands.CommandManager;
+import com.github.alathra.AlathranWars.config.ConfigHandler;
import com.github.alathra.AlathranWars.conflict.WarManager;
-import com.github.alathra.AlathranWars.data.ConfigManager;
-import com.github.alathra.AlathranWars.data.DataManager;
+import com.github.alathra.AlathranWars.db.DatabaseHandler;
+import com.github.alathra.AlathranWars.db.DatabaseQueries;
import com.github.alathra.AlathranWars.hooks.HookManager;
import com.github.alathra.AlathranWars.items.WarItemRegistry;
import com.github.alathra.AlathranWars.listeners.ListenerHandler;
-import com.github.alathra.AlathranWars.utility.SQLQueries;
import net.milkbowl.vault.economy.Economy;
import org.bukkit.plugin.RegisteredServiceProvider;
import org.bukkit.plugin.java.JavaPlugin;
@@ -15,26 +15,18 @@ import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import space.arim.morepaperlib.MorePaperLib;
-public class Main extends JavaPlugin {
+public class AlathranWars extends JavaPlugin {
public static @Nullable Economy econ = null;
- private static Main instance = null;
private static MorePaperLib paperLib;
- private ConfigManager configManager;
- private DataManager dataManager;
- private CommandManager commandManager;
+ private static AlathranWars instance;
+ private ConfigHandler configHandler;
+ private DatabaseHandler databaseHandler;
private ListenerHandler listenerHandler;
+
+ private CommandManager commandManager;
private HookManager hookManager;
- @NotNull
- public static Main getInstance() {
- return instance;
- }
-
- public static MorePaperLib getPaperLib() {
- return paperLib;
- }
-
@SuppressWarnings("rawtypes")
private boolean setupEconomy() {
if (this.getServer().getPluginManager().getPlugin("Vault") == null) {
@@ -49,54 +41,62 @@ public class Main extends JavaPlugin {
return econ != null;
}
- @Override
public void onLoad() {
instance = this;
- paperLib = new MorePaperLib(getInstance());
+ paperLib = new MorePaperLib(instance);
WarManager.getInstance();
- configManager = new ConfigManager(getInstance());
- dataManager = new DataManager(getInstance());
- commandManager = new CommandManager(getInstance());
- listenerHandler = new ListenerHandler(getInstance());
+ configHandler = new ConfigHandler(instance);
+ databaseHandler = new DatabaseHandler(instance);
+ commandManager = new CommandManager(instance);
+ listenerHandler = new ListenerHandler(instance);
hookManager = new HookManager();
- configManager.onLoad();
- dataManager.onLoad();
+ configHandler.onLoad();
+ databaseHandler.onLoad();
commandManager.onLoad();
listenerHandler.onLoad();
hookManager.onLoad();
}
- @Override
public void onEnable() {
this.saveDefaultConfig();
new WarItemRegistry();
setupEconomy();
- configManager.onEnable();
- dataManager.onEnable();
+ configHandler.onEnable();
+ databaseHandler.onEnable();
commandManager.onEnable();
listenerHandler.onEnable();
hookManager.onEnable();
WarManager.getInstance().loadAll();
}
- @Override
public void onDisable() {
getPaperLib().scheduling().cancelGlobalTasks();
- SQLQueries.saveAll();
- configManager.onDisable();
+ DatabaseQueries.saveAll();
commandManager.onDisable();
listenerHandler.onDisable();
hookManager.onDisable();
- dataManager.onDisable();
+ databaseHandler.onDisable();
+ configHandler.onDisable();
}
- public ConfigManager getConfigManager() {
- return configManager;
+ @NotNull
+ public static AlathranWars getInstance() {
+ return instance;
}
- public DataManager getDataManager() {
- return dataManager;
+ public static MorePaperLib getPaperLib() {
+ return paperLib;
+ }
+
+ @NotNull
+ public DatabaseHandler getDataHandler() {
+ return databaseHandler;
+ }
+
+ @NotNull
+ public ConfigHandler getConfigHandler() {
+ return configHandler;
}
}
diff --git a/src/main/java/com/github/alathra/AlathranWars/Reloadable.java b/src/main/java/com/github/alathra/AlathranWars/Reloadable.java
new file mode 100644
index 0000000..d0e4e40
--- /dev/null
+++ b/src/main/java/com/github/alathra/AlathranWars/Reloadable.java
@@ -0,0 +1,21 @@
+package com.github.alathra.AlathranWars;
+
+/**
+ * Implemented in classes that should support being reloaded IE executing the methods during runtime after startup.
+ */
+public interface Reloadable {
+ /**
+ * On plugin load.
+ */
+ void onLoad();
+
+ /**
+ * On plugin enable.
+ */
+ void onEnable();
+
+ /**
+ * On plugin disable.
+ */
+ void onDisable();
+}
diff --git a/src/main/java/com/github/alathra/AlathranWars/commands/AdminCommands.java b/src/main/java/com/github/alathra/AlathranWars/commands/AdminCommands.java
index 7fba975..31194fd 100644
--- a/src/main/java/com/github/alathra/AlathranWars/commands/AdminCommands.java
+++ b/src/main/java/com/github/alathra/AlathranWars/commands/AdminCommands.java
@@ -1,6 +1,6 @@
package com.github.alathra.AlathranWars.commands;
-import com.github.alathra.AlathranWars.Main;
+import com.github.alathra.AlathranWars.AlathranWars;
import com.github.alathra.AlathranWars.items.WarItemRegistry;
import com.github.alathra.AlathranWars.utility.UtilsChat;
import com.github.milkdrinkers.colorparser.ColorParser;
@@ -51,7 +51,7 @@ public class AdminCommands {
throw CommandAPIBukkit.failWithAdventureComponent(ColorParser.of(UtilsChat.getPrefix() + "Invalid item argument.").build());
@Nullable ItemStack stack;
- if (argItem.contains(Main.getInstance().getName().toLowerCase())) {
+ if (argItem.contains(AlathranWars.getInstance().getName().toLowerCase())) {
stack = WarItemRegistry.getInstance().getOrNullNamespace(argItem);
} else {
stack = WarItemRegistry.getInstance().getOrNull(argItem);
diff --git a/src/main/java/com/github/alathra/AlathranWars/commands/CommandManager.java b/src/main/java/com/github/alathra/AlathranWars/commands/CommandManager.java
index 7c814b0..a977986 100644
--- a/src/main/java/com/github/alathra/AlathranWars/commands/CommandManager.java
+++ b/src/main/java/com/github/alathra/AlathranWars/commands/CommandManager.java
@@ -1,13 +1,13 @@
package com.github.alathra.AlathranWars.commands;
-import com.github.alathra.AlathranWars.Main;
+import com.github.alathra.AlathranWars.AlathranWars;
import dev.jorel.commandapi.CommandAPI;
import dev.jorel.commandapi.CommandAPIBukkitConfig;
public class CommandManager {
- private final Main instance;
+ private final AlathranWars instance;
- public CommandManager(Main instance) {
+ public CommandManager(AlathranWars instance) {
this.instance = instance;
}
diff --git a/src/main/java/com/github/alathra/AlathranWars/commands/CommandUtil.java b/src/main/java/com/github/alathra/AlathranWars/commands/CommandUtil.java
index 1468a65..c7625ee 100644
--- a/src/main/java/com/github/alathra/AlathranWars/commands/CommandUtil.java
+++ b/src/main/java/com/github/alathra/AlathranWars/commands/CommandUtil.java
@@ -1,6 +1,6 @@
package com.github.alathra.AlathranWars.commands;
-import com.github.alathra.AlathranWars.Main;
+import com.github.alathra.AlathranWars.AlathranWars;
import com.github.alathra.AlathranWars.conflict.Side;
import com.github.alathra.AlathranWars.conflict.War;
import com.github.alathra.AlathranWars.conflict.WarManager;
@@ -641,14 +641,14 @@ public class CommandUtil {
long regTime = res.getRegistered();
int playTicks = Bukkit.getPlayer(res.getUUID()).getStatistic(Statistic.PLAY_ONE_MINUTE);
int out = 0;
- if (Main.getInstance().getConfig().getInt("minimumPlayerAge") > 0) {
+ if (AlathranWars.getInstance().getConfig().getInt("minimumPlayerAge") > 0) {
//compare the join date, if they joined less that min age ago it is true
- if ((System.currentTimeMillis() - regTime) < 86400000L * Main.getInstance().getConfig().getInt("minimumPlayerAge"))
+ if ((System.currentTimeMillis() - regTime) < 86400000L * AlathranWars.getInstance().getConfig().getInt("minimumPlayerAge"))
out = 1;
}
- if (Main.getInstance().getConfig().getInt("minimumPlayTime") > 0) {
+ if (AlathranWars.getInstance().getConfig().getInt("minimumPlayTime") > 0) {
//check playtime, if its less than min its true
- if (playTicks < (Main.getInstance().getConfig().getInt("minimumPlayTime") * (60 * 60 * 20))) out = 2;
+ if (playTicks < (AlathranWars.getInstance().getConfig().getInt("minimumPlayTime") * (60 * 60 * 20))) out = 2;
}
return out;
diff --git a/src/main/java/com/github/alathra/AlathranWars/commands/SiegeCommands.java b/src/main/java/com/github/alathra/AlathranWars/commands/SiegeCommands.java
index 58bbc97..4f4ba9e 100644
--- a/src/main/java/com/github/alathra/AlathranWars/commands/SiegeCommands.java
+++ b/src/main/java/com/github/alathra/AlathranWars/commands/SiegeCommands.java
@@ -1,10 +1,11 @@
package com.github.alathra.AlathranWars.commands;
-import com.github.alathra.AlathranWars.Main;
+import com.github.alathra.AlathranWars.AlathranWars;
import com.github.alathra.AlathranWars.conflict.Side;
import com.github.alathra.AlathranWars.conflict.War;
import com.github.alathra.AlathranWars.conflict.WarManager;
import com.github.alathra.AlathranWars.conflict.battle.siege.Siege;
+import com.github.alathra.AlathranWars.enums.battle.BattleVictoryReason;
import com.github.alathra.AlathranWars.utility.UtilsChat;
import com.github.milkdrinkers.colorparser.ColorParser;
import com.palmergames.bukkit.towny.TownyAPI;
@@ -151,7 +152,7 @@ public class SiegeCommands {
if (location.distance(townLocation) <= Siege.BATTLEFIELD_START_MIN_RANGE && !asAdmin)
throw CommandAPIBukkit.failWithAdventureComponent(ColorParser.of("You need to be further than blocks away from the town to start a siege!").parseMinimessagePlaceholder("range", String.valueOf(Siege.BATTLEFIELD_START_MIN_RANGE)).build());
- if ((Main.econ.getBalance(siegeLeader) < Siege.SIEGE_VICTORY_MONEY) && !asAdmin)
+ if ((AlathranWars.econ.getBalance(siegeLeader) < Siege.SIEGE_VICTORY_MONEY) && !asAdmin)
throw CommandAPIBukkit.failWithAdventureComponent(ColorParser.of("You need to have $ to start a siege!").parseMinimessagePlaceholder("amount", String.valueOf(Siege.SIEGE_VICTORY_MONEY)).build());
side.setSiegeGrace();
@@ -176,7 +177,7 @@ public class SiegeCommands {
if (!(args.get("siege") instanceof final @NotNull Siege siege))
throw CommandAPIBukkit.failWithAdventureComponent(ColorParser.of("Invalid siege.").build());
- siege.equalWin();
+ siege.equalWin(BattleVictoryReason.ADMIN_COMMAND);
}
private static void siegeAbandon(Player p, @NotNull CommandArguments args, boolean asAdmin) throws WrapperCommandSyntaxException {
@@ -187,13 +188,7 @@ public class SiegeCommands {
if (siegeLeader != p && !asAdmin)
throw CommandAPIBukkit.failWithAdventureComponent(ColorParser.of("You are not the leader of this siege.").build());
- Bukkit.broadcast(
- ColorParser.of("The siege at has been abandoned.")
- .parseMinimessagePlaceholder("prefix", UtilsChat.getPrefix())
- .parseMinimessagePlaceholder("town", siege.getTown().getName())
- .build()
- );
- siege.defendersWin();
+ siege.defendersWin(BattleVictoryReason.OPPONENT_RETREAT);
}
private static void siegeSurrender(Player p, @NotNull CommandArguments args, boolean asAdmin) throws WrapperCommandSyntaxException {
@@ -212,13 +207,7 @@ public class SiegeCommands {
if (!asAdmin && !canKingSurrender && !canMayorSurrender)
throw CommandAPIBukkit.failWithAdventureComponent(ColorParser.of("You cannot surrender this town.").build());
- Bukkit.broadcast(
- ColorParser.of("The town of has surrendered.")
- .parseMinimessagePlaceholder("prefix", UtilsChat.getPrefix())
- .parseMinimessagePlaceholder("town", siege.getTown().getName())
- .build()
- );
- siege.attackersWin();
+ siege.attackersWin(BattleVictoryReason.OPPONENT_RETREAT);
}
private static void siegeList(@NotNull Player sender, CommandArguments args) throws WrapperCommandSyntaxException {
diff --git a/src/main/java/com/github/alathra/AlathranWars/commands/WarCommands.java b/src/main/java/com/github/alathra/AlathranWars/commands/WarCommands.java
index d48e695..2516319 100644
--- a/src/main/java/com/github/alathra/AlathranWars/commands/WarCommands.java
+++ b/src/main/java/com/github/alathra/AlathranWars/commands/WarCommands.java
@@ -1,8 +1,6 @@
package com.github.alathra.AlathranWars.commands;
-import com.github.alathra.AlathranWars.conflict.Side;
-import com.github.alathra.AlathranWars.conflict.War;
-import com.github.alathra.AlathranWars.conflict.WarManager;
+import com.github.alathra.AlathranWars.conflict.*;
import com.github.alathra.AlathranWars.listeners.war.PlayerJoinListener;
import com.github.alathra.AlathranWars.utility.UtilsChat;
import com.github.milkdrinkers.colorparser.ColorParser;
@@ -163,33 +161,42 @@ public class WarCommands {
// Implement permission checking here if this is ever going to be exposed to players
// Create war depending on what args have been passed, attempt to create nation wars first
+ WarBuilder builder = new WarBuilder()
+ .setUuid(UUID.randomUUID())
+ .setLabel(argLabel)
+ .setEvent(event);
if (nation1 != null) {
if (nation2 != null) { // Nation vs Nation
-
// Allow civil wars
if (nation2.getUUID() != nation1.getUUID()) {
- new War(argLabel, nation1, nation2, event);
+ builder
+ .setAggressor(nation1)
+ .setVictim(nation2);
} else {
- new War(argLabel, town1, town2, event);
+ builder
+ .setAggressor(town1)
+ .setVictim(town2);
}
-
} else if (town2 != null) { // Nation vs Town
-
- new War(argLabel, nation1, town2, event);
-
+ builder
+ .setAggressor(nation1)
+ .setVictim(town2);
}
} else if (town1 != null) {
-
if (town2 != null) { // Town vs Town
-
- new War(argLabel, town1, town2, event);
-
+ builder
+ .setAggressor(town1)
+ .setVictim(town2);
} else if (nation2 != null) { // Nation vs Town
-
- new War(argLabel, town1, nation2, event);
-
+ builder
+ .setAggressor(town1)
+ .setVictim(nation2);
}
-
+ }
+ try {
+ builder.create(); // TODO Add war to list
+ } catch (SideCreationException e) {
+ throw new RuntimeException(e);
}
}
diff --git a/src/main/java/com/github/alathra/AlathranWars/config/ConfigHandler.java b/src/main/java/com/github/alathra/AlathranWars/config/ConfigHandler.java
new file mode 100644
index 0000000..5a2539f
--- /dev/null
+++ b/src/main/java/com/github/alathra/AlathranWars/config/ConfigHandler.java
@@ -0,0 +1,47 @@
+package com.github.alathra.AlathranWars.config;
+
+import com.github.alathra.AlathranWars.AlathranWars;
+import com.github.alathra.AlathranWars.Reloadable;
+import com.github.milkdrinkers.Crate.Config;
+
+import javax.inject.Singleton;
+
+/**
+ * A class that generates/loads & provides access to a configuration file.
+ */
+@Singleton
+public class ConfigHandler implements Reloadable {
+ private final AlathranWars alathranWars;
+ private Config cfg;
+
+ /**
+ * Instantiates a new Config handler.
+ *
+ * @param alathranWars the plugin instance
+ */
+ public ConfigHandler(AlathranWars alathranWars) {
+ this.alathranWars = alathranWars;
+ }
+
+ @Override
+ public void onLoad() {
+ cfg = new Config("config", alathranWars.getDataFolder().getPath(), alathranWars.getResource("config.yml")); // Create a config file from the template in our resources folder
+ }
+
+ @Override
+ public void onEnable() {
+ }
+
+ @Override
+ public void onDisable() {
+ }
+
+ /**
+ * Gets alathranWars config object.
+ *
+ * @return the alathranWars config object
+ */
+ public Config getConfig() {
+ return cfg;
+ }
+}
diff --git a/src/main/java/com/github/alathra/AlathranWars/conflict/Side.java b/src/main/java/com/github/alathra/AlathranWars/conflict/Side.java
index 121d495..d0395f8 100644
--- a/src/main/java/com/github/alathra/AlathranWars/conflict/Side.java
+++ b/src/main/java/com/github/alathra/AlathranWars/conflict/Side.java
@@ -1,9 +1,10 @@
package com.github.alathra.AlathranWars.conflict;
import com.github.alathra.AlathranWars.conflict.battle.siege.Siege;
-import com.github.alathra.AlathranWars.enums.BattleSide;
-import com.github.alathra.AlathranWars.enums.BattleTeam;
+import com.github.alathra.AlathranWars.enums.battle.BattleSide;
+import com.github.alathra.AlathranWars.enums.battle.BattleTeam;
import com.github.alathra.AlathranWars.listeners.war.PlayerJoinListener;
+import com.palmergames.bukkit.towny.object.Government;
import com.palmergames.bukkit.towny.object.Nation;
import com.palmergames.bukkit.towny.object.Resident;
import com.palmergames.bukkit.towny.object.Town;
@@ -16,6 +17,7 @@ import org.jetbrains.annotations.Nullable;
import java.time.Duration;
import java.time.Instant;
import java.util.HashSet;
+import java.util.Objects;
import java.util.Set;
import java.util.UUID;
import java.util.stream.Collectors;
@@ -46,7 +48,7 @@ public class Side {
public Side(
UUID warUUID,
UUID uuid,
- Town town,
+ Government government,
BattleSide side,
BattleTeam team,
String name,
@@ -58,12 +60,11 @@ public class Side {
Set surrenderedPlayersIncludingOffline,
Instant siegeGrace,
Instant raidGrace
- ) {
+ ) throws SideCreationException {
this.warUUID = warUUID;
this.uuid = uuid;
this.side = side;
this.team = team;
- this.town = town;
this.name = name;
this.towns = towns;
@@ -78,10 +79,73 @@ public class Side {
this.siegeGrace = siegeGrace;
this.raidGrace = raidGrace;
+ if (government instanceof Nation nation) {
+ this.town = nation.getCapital();
+ } else if (government instanceof Town town2) {
+ this.town = town2;
+ } else {
+ throw new SideCreationException("No town or nation specified!");
+ }
+
calculateOnlinePlayers();
}
- public Side(UUID warUUID, UUID uuid, Town town, BattleSide side, BattleTeam team) {
+ /*public Side(UUID warUUID, UUID uuid, Town town, boolean isNation, BattleSide side, BattleTeam team) {
+ this.warUUID = warUUID;
+ this.uuid = uuid;
+ this.side = side;
+ this.team = team;
+ this.town = town;
+ this.name = this.town.getName();
+
+ this.towns = new HashSet<>();
+ this.nations = new HashSet<>();
+ this.playersIncludingOffline = new HashSet<>();
+ this.players = new HashSet<>();
+
+ this.surrenderedTowns = new HashSet<>();
+ this.surrenderedNations = new HashSet<>();
+ this.surrenderedPlayersIncludingOffline = new HashSet<>();
+
+ if (isNation)
+ addNation(Objects.requireNonNull(this.town.getNationOrNull()));
+ else
+ addTown(this.town);
+
+ calculateOnlinePlayers();
+ }*/
+
+ public Side(UUID warUUID, UUID uuid, Government government, BattleSide side, BattleTeam team) throws SideCreationException {
+ this.warUUID = warUUID;
+ this.uuid = uuid;
+ this.side = side;
+ this.team = team;
+
+ this.towns = new HashSet<>();
+ this.nations = new HashSet<>();
+ this.playersIncludingOffline = new HashSet<>();
+ this.players = new HashSet<>();
+
+ this.surrenderedTowns = new HashSet<>();
+ this.surrenderedNations = new HashSet<>();
+ this.surrenderedPlayersIncludingOffline = new HashSet<>();
+
+ if (government instanceof Nation nation) {
+ this.town = nation.getCapital();
+ addNation(nation);
+ } else if (government instanceof Town town2) {
+ this.town = town2;
+ addTown(town2);
+ } else {
+ throw new SideCreationException("No town or nation specified!");
+ }
+
+ this.name = this.town.getName();
+
+ calculateOnlinePlayers();
+ }
+
+ /*public Side(UUID warUUID, UUID uuid, Town town, BattleSide side, BattleTeam team) {
this.warUUID = warUUID;
this.uuid = uuid;
this.side = side;
@@ -123,7 +187,7 @@ public class Side {
addNation(nation);
calculateOnlinePlayers();
- }
+ }*/
public BattleSide getSide() {
return side;
diff --git a/src/main/java/com/github/alathra/AlathranWars/conflict/SideBuilder.java b/src/main/java/com/github/alathra/AlathranWars/conflict/SideBuilder.java
new file mode 100644
index 0000000..9ab1fde
--- /dev/null
+++ b/src/main/java/com/github/alathra/AlathranWars/conflict/SideBuilder.java
@@ -0,0 +1,162 @@
+package com.github.alathra.AlathranWars.conflict;
+
+import com.github.alathra.AlathranWars.enums.battle.BattleSide;
+import com.github.alathra.AlathranWars.enums.battle.BattleTeam;
+import com.palmergames.bukkit.towny.object.Government;
+import com.palmergames.bukkit.towny.object.Nation;
+import com.palmergames.bukkit.towny.object.Town;
+import org.bukkit.entity.Player;
+
+import java.time.Instant;
+import java.util.Set;
+import java.util.UUID;
+
+public class SideBuilder {
+ public SideBuilder() {}
+
+ public Side buildOld() throws SideCreationException {
+// if (warUUID == null || uuid == null || town == null || side == null || team == null || name == null ||
+// towns == null || nations == null || playersIncludingOffline == null ||
+// surrenderedTowns == null || surrenderedNations == null || surrenderedPlayersIncludingOffline == null ||
+// siegeGrace == null || raidGrace == null
+// ) throw new IllegalStateException("Missing state to create Side 1");
+
+ if (warUUID == null || uuid == null
+ ) throw new IllegalStateException("Missing state to create Side 1.2");
+
+ if (government == null
+ ) throw new IllegalStateException("Missing state to create Side 1.3");
+ if (side == null
+ ) throw new IllegalStateException("Missing state to create Side 1.1");
+
+ if ( team == null || name == null ||
+ towns == null || nations == null
+ ) throw new IllegalStateException("Missing state to create Side 1");
+
+ if (playersIncludingOffline == null ||
+ surrenderedTowns == null || surrenderedNations == null || surrenderedPlayersIncludingOffline == null ||
+ siegeGrace == null || raidGrace == null
+ ) throw new IllegalStateException("Missing state to create Side 2");
+
+ return new Side(
+ warUUID,
+ uuid,
+ government,
+ side,
+ team,
+ name,
+ towns,
+ nations,
+ playersIncludingOffline,
+ surrenderedTowns,
+ surrenderedNations,
+ surrenderedPlayersIncludingOffline,
+ siegeGrace,
+ raidGrace
+ );
+ }
+
+ public Side buildNew() throws SideCreationException {
+ if (warUUID == null || uuid == null || government == null || side == null || team == null)
+ throw new IllegalStateException("Missing state to create new Side");
+
+ return new Side(
+ warUUID,
+ uuid,
+ government,
+ side,
+ team
+ );
+ }
+
+ public SideBuilder setWarUUID(UUID warUUID) {
+ this.warUUID = warUUID;
+ return this;
+ }
+
+ public SideBuilder setUuid(UUID uuid) {
+ this.uuid = uuid;
+ return this;
+ }
+
+ public SideBuilder setSide(BattleSide side) {
+ this.side = side;
+ return this;
+ }
+
+ public SideBuilder setTeam(BattleTeam team) {
+ this.team = team;
+ return this;
+ }
+
+ public SideBuilder setName(String name) {
+ this.name = name;
+ return this;
+ }
+
+ public SideBuilder setLeader(Government target) {
+ this.government = target;
+ return this;
+ }
+
+ public SideBuilder setTowns(Set towns) {
+ this.towns = towns;
+ return this;
+ }
+
+ public SideBuilder setNations(Set nations) {
+ this.nations = nations;
+ return this;
+ }
+
+ public SideBuilder setPlayersIncludingOffline(Set playersIncludingOffline) {
+ this.playersIncludingOffline = playersIncludingOffline;
+ return this;
+ }
+
+ public SideBuilder setSurrenderedTowns(Set surrenderedTowns) {
+ this.surrenderedTowns = surrenderedTowns;
+ return this;
+ }
+
+ public SideBuilder setSurrenderedNations(Set surrenderedNations) {
+ this.surrenderedNations = surrenderedNations;
+ return this;
+ }
+
+ public SideBuilder setSurrenderedPlayersIncludingOffline(Set surrenderedPlayersIncludingOffline) {
+ this.surrenderedPlayersIncludingOffline = surrenderedPlayersIncludingOffline;
+ return this;
+ }
+
+ public SideBuilder setSiegeGrace(Instant siegeGrace) {
+ this.siegeGrace = siegeGrace;
+ return this;
+ }
+
+ public SideBuilder setRaidGrace(Instant raidGrace) {
+ this.raidGrace = raidGrace;
+ return this;
+ }
+
+ private UUID warUUID;
+ private UUID uuid;
+ private BattleSide side;
+ private BattleTeam team;
+ private String name;
+
+ private Government government;
+ private Town town;
+
+ private Set towns;
+ private Set nations;
+ private Set playersIncludingOffline;
+ private Set surrenderedTowns;
+ private Set surrenderedNations;
+ private Set surrenderedPlayersIncludingOffline;
+ private Instant siegeGrace;
+ private Instant raidGrace;
+
+
+
+}
diff --git a/src/main/java/com/github/alathra/AlathranWars/conflict/SideCreationException.java b/src/main/java/com/github/alathra/AlathranWars/conflict/SideCreationException.java
new file mode 100644
index 0000000..999b053
--- /dev/null
+++ b/src/main/java/com/github/alathra/AlathranWars/conflict/SideCreationException.java
@@ -0,0 +1,7 @@
+package com.github.alathra.AlathranWars.conflict;
+
+public class SideCreationException extends Exception {
+ public SideCreationException(String errorMessage) {
+ super(errorMessage);
+ }
+}
diff --git a/src/main/java/com/github/alathra/AlathranWars/conflict/War.java b/src/main/java/com/github/alathra/AlathranWars/conflict/War.java
index 1130f29..848de94 100644
--- a/src/main/java/com/github/alathra/AlathranWars/conflict/War.java
+++ b/src/main/java/com/github/alathra/AlathranWars/conflict/War.java
@@ -2,14 +2,20 @@ package com.github.alathra.AlathranWars.conflict;
import com.github.alathra.AlathranWars.conflict.battle.raid.Raid;
import com.github.alathra.AlathranWars.conflict.battle.siege.Siege;
-import com.github.alathra.AlathranWars.enums.BattleSide;
-import com.github.alathra.AlathranWars.enums.BattleTeam;
+import com.github.alathra.AlathranWars.db.DatabaseQueries;
import com.github.alathra.AlathranWars.enums.ConflictType;
+import com.github.alathra.AlathranWars.enums.WarDeleteReason;
+import com.github.alathra.AlathranWars.enums.battle.BattleSide;
+import com.github.alathra.AlathranWars.enums.battle.BattleTeam;
+import com.github.alathra.AlathranWars.enums.battle.BattleVictoryReason;
+import com.github.alathra.AlathranWars.events.PreWarCreateEvent;
+import com.github.alathra.AlathranWars.events.PreWarDeleteEvent;
+import com.github.alathra.AlathranWars.events.WarCreateEvent;
+import com.github.alathra.AlathranWars.events.WarDeleteEvent;
import com.github.alathra.AlathranWars.listeners.war.PlayerJoinListener;
-import com.github.alathra.AlathranWars.utility.SQLQueries;
-import com.github.alathra.AlathranWars.utility.UUIDUtil;
import com.github.alathra.AlathranWars.utility.UtilsChat;
import com.github.milkdrinkers.colorparser.ColorParser;
+import com.palmergames.bukkit.towny.object.Government;
import com.palmergames.bukkit.towny.object.Nation;
import com.palmergames.bukkit.towny.object.Town;
import dev.jorel.commandapi.CommandAPIBukkit;
@@ -40,8 +46,8 @@ public class War extends Conflict {
private final ConflictType conflictType = ConflictType.WAR;
private boolean event = false;
- private final @NotNull Side side1;
- private final Side side2;
+ private @NotNull Side side1;
+ private Side side2;
private final Side attacker; // Reference variable to side1 or side2
private final Side defender; // Reference variable to side1 or side2
@@ -75,6 +81,68 @@ public class War extends Conflict {
resume();
}
+ public War(
+ UUID uuid,
+ String label,
+ Government aggressor,
+ Government victim,
+ boolean event
+ ) throws SideCreationException, WrapperCommandSyntaxException {
+ this.uuid = uuid;
+ this.label = label;
+
+ this.name = "%s.vs.%s".formatted(aggressor.getName(), victim.getName());
+ if (WarManager.getInstance().getWar(this.name) != null)
+ throw CommandAPIBukkit.failWithAdventureComponent(ColorParser.of(UtilsChat.getPrefix() + "A war already exists with that name!").build());
+
+// final @NotNull UUID side1UUID = UUIDUtil.generateSideUUID(null);
+// final @NotNull UUID side2UUID = UUIDUtil.generateSideUUID(side1UUID);
+
+ // TODO Side builder that uses aggressorIsNation &
+// if (!aggressorIsNation && !victimIsNation) {
+// this.side1 = new Side(this.uuid, side1UUID, aggressor, BattleSide.ATTACKER, BattleTeam.SIDE_1);
+// this.side2 = new Side(this.uuid, side2UUID, victim, BattleSide.DEFENDER, BattleTeam.SIDE_2);
+// } else if (!aggressorIsNation && victimIsNation) {
+// this.side1 = new Side(this.uuid, side1UUID, aggressor, BattleSide.ATTACKER, BattleTeam.SIDE_1);
+// this.side2 = new Side(this.uuid, side2UUID, victim.getNationOrNull(), BattleSide.DEFENDER, BattleTeam.SIDE_2);
+// } else if (aggressorIsNation && !victimIsNation) {
+// this.side1 = new Side(this.uuid, side1UUID, aggressor.getNationOrNull(), BattleSide.ATTACKER, BattleTeam.SIDE_1);
+// this.side2 = new Side(this.uuid, side2UUID, victim, BattleSide.DEFENDER, BattleTeam.SIDE_2);
+// } else if (aggressorIsNation && victimIsNation) {
+// this.side1 = new Side(this.uuid, side1UUID, aggressor.getNationOrNull(), BattleSide.ATTACKER, BattleTeam.SIDE_1);
+// this.side2 = new Side(this.uuid, side2UUID, victim.getNationOrNull(), BattleSide.DEFENDER, BattleTeam.SIDE_2);
+// }
+
+ this.side1 = new SideBuilder()
+ .setWarUUID(this.uuid)
+ .setUuid(UUID.randomUUID())
+ .setLeader(aggressor)
+ .setSide(BattleSide.ATTACKER)
+ .setTeam(BattleTeam.SIDE_1)
+ .buildNew();
+ this.side2 = new SideBuilder()
+ .setWarUUID(this.uuid)
+ .setUuid(UUID.randomUUID())
+ .setLeader(victim)
+ .setSide(BattleSide.DEFENDER)
+ .setTeam(BattleTeam.SIDE_2)
+ .buildNew();
+
+ this.attacker = side1.getSide().equals(BattleSide.ATTACKER) ? this.side1 : this.side2;
+ this.defender = side1.getSide().equals(BattleSide.DEFENDER) ? this.side1 : this.side2;
+ this.event = event;
+
+ if (!new PreWarCreateEvent(this).callEvent())
+ return;
+
+ // TODO All logic below this point should be separated out
+ WarManager.getInstance().addWar(this);
+
+ start();
+
+ new WarCreateEvent(this).callEvent();
+ }
+
/**
* Instantiates a new New war.
*
@@ -82,7 +150,72 @@ public class War extends Conflict {
* @param aggressor the side 1
* @param victim the side 2
*/
- public War(final String label, @NotNull Town aggressor, @NotNull Town victim, boolean event) throws WrapperCommandSyntaxException {
+ /*public War(
+ UUID uuid,
+ String label,
+ Town aggressor,
+ Town victim,
+ boolean aggressorIsNation,
+ boolean victimIsNation,
+ boolean event
+ ) throws WrapperCommandSyntaxException {
+ this.uuid = uuid;
+ this.label = label;
+
+ final String aggressorName = aggressorIsNation ? Objects.requireNonNull(aggressor.getNationOrNull()).getName() : aggressor.getName();
+ final String victimName = victimIsNation ? Objects.requireNonNull(victim.getNationOrNull()).getName() : victim.getName();
+ this.name = "%s.vs.%s".formatted(aggressorName, victimName);
+ if (WarManager.getInstance().getWar(this.name) != null)
+ throw CommandAPIBukkit.failWithAdventureComponent(ColorParser.of(UtilsChat.getPrefix() + "A war already exists with that name!").build());
+
+ final @NotNull UUID side1UUID = UUIDUtil.generateSideUUID(null);
+ final @NotNull UUID side2UUID = UUIDUtil.generateSideUUID(side1UUID);
+
+ // TODO Side builder that uses aggressorIsNation &
+ if (!aggressorIsNation && !victimIsNation) {
+ this.side1 = new Side(this.uuid, side1UUID, aggressor, BattleSide.ATTACKER, BattleTeam.SIDE_1);
+ this.side2 = new Side(this.uuid, side2UUID, victim, BattleSide.DEFENDER, BattleTeam.SIDE_2);
+ } else if (!aggressorIsNation && victimIsNation) {
+ this.side1 = new Side(this.uuid, side1UUID, aggressor, BattleSide.ATTACKER, BattleTeam.SIDE_1);
+ this.side2 = new Side(this.uuid, side2UUID, victim.getNationOrNull(), BattleSide.DEFENDER, BattleTeam.SIDE_2);
+ } else if (aggressorIsNation && !victimIsNation) {
+ this.side1 = new Side(this.uuid, side1UUID, aggressor.getNationOrNull(), BattleSide.ATTACKER, BattleTeam.SIDE_1);
+ this.side2 = new Side(this.uuid, side2UUID, victim, BattleSide.DEFENDER, BattleTeam.SIDE_2);
+ } else if (aggressorIsNation && victimIsNation) {
+ this.side1 = new Side(this.uuid, side1UUID, aggressor.getNationOrNull(), BattleSide.ATTACKER, BattleTeam.SIDE_1);
+ this.side2 = new Side(this.uuid, side2UUID, victim.getNationOrNull(), BattleSide.DEFENDER, BattleTeam.SIDE_2);
+ }
+
+ this.side1 = new SideBuilder()
+ .setWarUUID(this.uuid)
+ .setUuid(side1UUID)
+ .setLeader(aggressorIsNation ? aggressor.getNationOrNull() : aggressor)
+ .setSide(BattleSide.ATTACKER)
+ .setTeam(BattleTeam.SIDE_1)
+ .buildNew();
+
+ this.attacker = side1.getSide().equals(BattleSide.ATTACKER) ? this.side1 : this.side2;
+ this.defender = side1.getSide().equals(BattleSide.DEFENDER) ? this.side1 : this.side2;
+ this.event = event;
+
+ if (!new PreWarCreateEvent(this).callEvent())
+ return;
+
+ WarManager.getInstance().addWar(this);
+
+ start();
+
+ new WarCreateEvent(this).callEvent();
+ }*/
+
+ /**
+ * Instantiates a new New war.
+ *
+ * @param label the name
+ * @param aggressor the side 1
+ * @param victim the side 2
+ */
+ /*public War(final String label, @NotNull Town aggressor, @NotNull Town victim, boolean event) throws WrapperCommandSyntaxException {
this.uuid = UUIDUtil.generateWarUUID();
this.name = "%s.vs.%s".formatted(aggressor.getName(), victim.getName());
this.label = label;
@@ -99,9 +232,14 @@ public class War extends Conflict {
this.defender = side1.getSide().equals(BattleSide.DEFENDER) ? this.side1 : this.side2;
this.event = event;
+ if (!new PreWarCreateEvent(this).callEvent())
+ return;
+
WarManager.getInstance().addWar(this);
start();
+
+ new WarCreateEvent(this).callEvent();
}
public War(final String label, @NotNull Nation aggressor, @NotNull Nation victim, boolean event) throws WrapperCommandSyntaxException {
@@ -121,9 +259,14 @@ public class War extends Conflict {
this.defender = side1.getSide().equals(BattleSide.DEFENDER) ? this.side1 : this.side2;
this.event = event;
+ if (!new PreWarCreateEvent(this).callEvent())
+ return;
+
WarManager.getInstance().addWar(this);
start();
+
+ new WarCreateEvent(this).callEvent();
}
public War(final String label, @NotNull Town aggressor, @NotNull Nation victim, boolean event) throws WrapperCommandSyntaxException {
@@ -143,9 +286,14 @@ public class War extends Conflict {
this.defender = side1.getSide().equals(BattleSide.DEFENDER) ? this.side1 : this.side2;
this.event = event;
+ if (!new PreWarCreateEvent(this).callEvent())
+ return;
+
WarManager.getInstance().addWar(this);
start();
+
+ new WarCreateEvent(this).callEvent();
}
public War(final String label, @NotNull Nation aggressor, @NotNull Town victim, boolean event) throws WrapperCommandSyntaxException {
@@ -165,11 +313,16 @@ public class War extends Conflict {
this.defender = side1.getSide().equals(BattleSide.DEFENDER) ? this.side1 : this.side2;
this.event = event;
+ if (!new PreWarCreateEvent(this).callEvent())
+ return;
+
WarManager.getInstance().addWar(this);
start();
- }
+ new WarCreateEvent(this).callEvent();
+ }
+*/
/**
* Gets uuid.
*
@@ -351,6 +504,10 @@ public class War extends Conflict {
raids.add(raid);
}
+ public void removeRaid(Raid raid) {
+ raids.remove(raid);
+ }
+
@NotNull
public Set getPlayers() {
return Stream.concat(
@@ -455,9 +612,9 @@ public class War extends Conflict {
getSieges().forEach(siege -> { // TODO INFINITE LOOP, runs surrenderTown
if (siege.getTown().equals(town)) {
if (siege.getAttackerSide().equals(townSide)) {
- siege.defendersWin();
+ siege.defendersWin(BattleVictoryReason.ADMIN_CANCEL);
} else {
- siege.attackersWin();
+ siege.attackersWin(BattleVictoryReason.ADMIN_CANCEL);
}
}
});
@@ -608,15 +765,20 @@ public class War extends Conflict {
side2.applyNameTags();
}
- public void end() {
+ public void end(WarDeleteReason reason) {
+ if (!new PreWarDeleteEvent(this, reason).callEvent())
+ return;
+
getSieges().forEach(Siege::stop);
getAllTowns().forEach(Occupation::removeOccupied);
- SQLQueries.deleteWar(this);
+ DatabaseQueries.deleteWar(this);
WarManager.getInstance().removeWar(this);
// Run check after war is removed to cleanup player tags
getPlayers().forEach(PlayerJoinListener::checkPlayer);
+
+ new WarDeleteEvent(this, reason).callEvent();
}
public void defeat(@NotNull Side loserSide) {
@@ -630,7 +792,7 @@ public class War extends Conflict {
.build()
);
- end();
+ end(WarDeleteReason.DEFEAT);
}
// White defeat/force end war
@@ -640,7 +802,7 @@ public class War extends Conflict {
.build()
);
- end();
+ end(WarDeleteReason.DRAW);
}
public void setEvent(boolean event) {
diff --git a/src/main/java/com/github/alathra/AlathranWars/conflict/WarBuilder.java b/src/main/java/com/github/alathra/AlathranWars/conflict/WarBuilder.java
new file mode 100644
index 0000000..54e5488
--- /dev/null
+++ b/src/main/java/com/github/alathra/AlathranWars/conflict/WarBuilder.java
@@ -0,0 +1,172 @@
+package com.github.alathra.AlathranWars.conflict;
+
+import com.github.alathra.AlathranWars.conflict.battle.raid.Raid;
+import com.github.alathra.AlathranWars.conflict.battle.siege.Siege;
+import com.github.alathra.AlathranWars.enums.ConflictType;
+import com.palmergames.bukkit.towny.object.Government;
+import com.palmergames.bukkit.towny.object.Nation;
+import com.palmergames.bukkit.towny.object.Town;
+import dev.jorel.commandapi.exceptions.WrapperCommandSyntaxException;
+import org.jetbrains.annotations.NotNull;
+
+import java.util.HashSet;
+import java.util.Optional;
+import java.util.Set;
+import java.util.UUID;
+
+public class WarBuilder {
+ private UUID uuid;
+ private String name;
+ private String label;
+ private ConflictType conflictType = ConflictType.WAR;
+ private boolean event = false;
+ private Side side1;
+ private Side side2;
+ private Set sieges = new HashSet<>();
+ private Set raids = new HashSet<>();
+
+ private Town aggressorTown;
+ private Optional aggressorNation = Optional.empty();
+ private Town victimTown;
+ private Optional victimNation = Optional.empty();
+
+ private Government aggressor;
+ private Government victim;
+
+ public WarBuilder() {}
+
+ public War resume() {
+ if (
+ uuid == null ||
+ name == null ||
+ label == null ||
+ side1 == null ||
+ side2 == null ||
+ sieges == null ||
+ raids == null
+ ) {
+ throw new IllegalStateException();
+ }
+
+ return new War(
+ uuid,
+ name,
+ label,
+ side1,
+ side2,
+ sieges,
+ raids,
+ event
+ );
+ }
+
+ /*public War create() throws WrapperCommandSyntaxException {
+ this.setUuid(UUID.randomUUID());
+
+ if (aggressorNation.isEmpty() && aggressorTown != null) {
+ // TODO Throw
+ }
+ if (victimNation.isEmpty() && victimTown != null) {
+ // TODO Throw
+ }
+
+ return new War(
+ uuid,
+ label,
+ aggressorTown,
+ victimTown,
+ aggressorNation.isPresent(),
+ victimNation.isPresent(),
+ event
+ );
+ }*/
+
+ public War create() throws WrapperCommandSyntaxException, SideCreationException {
+ this.setUuid(UUID.randomUUID());
+
+ return new War(
+ uuid,
+ label,
+ aggressor,
+ victim,
+ event
+ );
+ }
+
+ public WarBuilder setUuid(UUID uuid) {
+ this.uuid = uuid;
+ return this;
+ }
+
+ public WarBuilder setName(String name) {
+ this.name = name;
+ return this;
+ }
+
+ public WarBuilder setLabel(String label) {
+ this.label = label;
+ return this;
+ }
+
+ public WarBuilder setConflictType(ConflictType conflictType) {
+ this.conflictType = conflictType;
+ return this;
+ }
+
+ public WarBuilder setSide1(Side side1) {
+ this.side1 = side1;
+ return this;
+ }
+
+ public WarBuilder setSide2(Side side2) {
+ this.side2 = side2;
+ return this;
+ }
+
+ public WarBuilder setEvent(boolean event) {
+ this.event = event;
+ return this;
+ }
+
+ public WarBuilder setSieges(Set sieges) {
+ this.sieges = sieges;
+ return this;
+ }
+
+ public WarBuilder setRaids(Set raids) {
+ this.raids = raids;
+ return this;
+ }
+
+ public WarBuilder setAggressorTown(Town target) {
+ this.aggressorTown = target;
+ return this;
+ }
+
+ public WarBuilder setAggressorNation(Nation target) {
+ this.aggressorTown = target.getCapital();
+ this.aggressorNation = Optional.of(target);
+ return this;
+ }
+
+ public WarBuilder setVictimTown(Town target) {
+ this.victimTown = target;
+ return this;
+ }
+
+ public WarBuilder setVictimNation(Nation target) {
+ this.victimTown = target.getCapital();
+ this.victimNation = Optional.of(target);
+ return this;
+ }
+
+ public WarBuilder setAggressor(Government aggressor) {
+ this.aggressor = aggressor;
+ return this;
+ }
+
+ public WarBuilder setVictim(Government victim) {
+ this.victim = victim;
+ return this;
+ }
+}
diff --git a/src/main/java/com/github/alathra/AlathranWars/conflict/WarCreationException.java b/src/main/java/com/github/alathra/AlathranWars/conflict/WarCreationException.java
new file mode 100644
index 0000000..fec1cbb
--- /dev/null
+++ b/src/main/java/com/github/alathra/AlathranWars/conflict/WarCreationException.java
@@ -0,0 +1,7 @@
+package com.github.alathra.AlathranWars.conflict;
+
+public class WarCreationException extends SideCreationException {
+ public WarCreationException(String errorMessage) {
+ super(errorMessage);
+ }
+}
diff --git a/src/main/java/com/github/alathra/AlathranWars/conflict/WarManager.java b/src/main/java/com/github/alathra/AlathranWars/conflict/WarManager.java
index 462a721..7058520 100644
--- a/src/main/java/com/github/alathra/AlathranWars/conflict/WarManager.java
+++ b/src/main/java/com/github/alathra/AlathranWars/conflict/WarManager.java
@@ -2,7 +2,7 @@ package com.github.alathra.AlathranWars.conflict;
import com.github.alathra.AlathranWars.conflict.battle.raid.Raid;
import com.github.alathra.AlathranWars.conflict.battle.siege.Siege;
-import com.github.alathra.AlathranWars.utility.SQLQueries;
+import com.github.alathra.AlathranWars.db.DatabaseQueries;
import com.palmergames.bukkit.towny.object.Nation;
import com.palmergames.bukkit.towny.object.Town;
import org.bukkit.Bukkit;
@@ -36,7 +36,7 @@ public class WarManager {
}
public void loadAll() {
- wars = SQLQueries.loadAll();
+ wars = DatabaseQueries.loadAll();
}
@NotNull
diff --git a/src/main/java/com/github/alathra/AlathranWars/conflict/battle/Battle.java b/src/main/java/com/github/alathra/AlathranWars/conflict/battle/Battle.java
index 262ef78..3286211 100644
--- a/src/main/java/com/github/alathra/AlathranWars/conflict/battle/Battle.java
+++ b/src/main/java/com/github/alathra/AlathranWars/conflict/battle/Battle.java
@@ -1,5 +1,7 @@
package com.github.alathra.AlathranWars.conflict.battle;
+import com.github.alathra.AlathranWars.enums.battle.BattleType;
+import com.github.alathra.AlathranWars.enums.battle.BattleVictoryReason;
import org.jetbrains.annotations.NotNull;
import java.util.UUID;
@@ -9,9 +11,9 @@ public interface Battle {
void stop(); // Ends battle
void resume(); // Resume battle after server restart or plugin reload
- void attackersWin(); // A Attacker victory
- void defendersWin(); // A Defender victory
- void equalWin(); // A Draw
+ void attackersWin(BattleVictoryReason reason); // A Attacker victory
+ void defendersWin(BattleVictoryReason reason); // A Defender victory
+ void equalWin(BattleVictoryReason reason); // A Draw
UUID uuid = null; // Battle UUID
@@ -39,4 +41,8 @@ public interface Battle {
return getUUID().equals(battle.getUUID());
}
+ BattleType battleType = null;
+ default BattleType getBattleType() {
+ return battleType;
+ }
}
diff --git a/src/main/java/com/github/alathra/AlathranWars/conflict/battle/beam/CrystalLaser.java b/src/main/java/com/github/alathra/AlathranWars/conflict/battle/beam/CrystalLaser.java
index 835d4fd..82b6547 100644
--- a/src/main/java/com/github/alathra/AlathranWars/conflict/battle/beam/CrystalLaser.java
+++ b/src/main/java/com/github/alathra/AlathranWars/conflict/battle/beam/CrystalLaser.java
@@ -51,7 +51,7 @@ public class CrystalLaser extends Laser {
* @see #executeEnd(Runnable) to add Runnable-s to execute when the laser will stop
*/
public CrystalLaser(Location start, Location end, int duration, int distance) throws ReflectiveOperationException {
- super(start, end, duration, distance);
+ super(start, new Location(end.getWorld(), end.getBlockX(), end.getBlockY(), end.getBlockZ()), duration, distance);
fakeCrystalDataWatcher = Packets.createFakeDataWatcher();
Packets.setCrystalWatcher(fakeCrystalDataWatcher, end);
diff --git a/src/main/java/com/github/alathra/AlathranWars/conflict/battle/beam/Laser.java b/src/main/java/com/github/alathra/AlathranWars/conflict/battle/beam/Laser.java
index 933d913..b5f6ddd 100644
--- a/src/main/java/com/github/alathra/AlathranWars/conflict/battle/beam/Laser.java
+++ b/src/main/java/com/github/alathra/AlathranWars/conflict/battle/beam/Laser.java
@@ -24,7 +24,9 @@ SOFTWARE.
package com.github.alathra.AlathranWars.conflict.battle.beam;
-import com.github.alathra.AlathranWars.Main;
+import com.github.alathra.AlathranWars.AlathranWars;
+import com.github.alathra.AlathranWars.utility.Logger;
+import com.github.milkdrinkers.colorparser.ColorParser;
import org.bukkit.Location;
import org.bukkit.entity.Player;
import org.bukkit.plugin.Plugin;
@@ -65,8 +67,8 @@ public abstract class Laser {
throw new IllegalStateException("The Laser Beam API is disabled. An error has occured during initialization.");
if (start.getWorld() != end.getWorld())
throw new IllegalArgumentException("Locations do not belong to the same worlds.");
- this.start = start;
- this.end = end;
+ this.start = start.clone();
+ this.end = end.clone();
this.duration = duration;
distanceSquared = distance < 0 ? -1 : distance * distance;
}
@@ -103,7 +105,6 @@ public abstract class Laser {
*/
public void start(Plugin plugin) {
if (task != null) throw new IllegalStateException("Task already started");
-// if (runnable != null) throw new IllegalStateException("Task already started");
this.plugin = plugin;
Runnable runnable = new BukkitRunnable() {
int time = 0;
@@ -128,28 +129,11 @@ public abstract class Laser {
}
time++;
} catch (ReflectiveOperationException e) {
- e.printStackTrace();
+ Logger.get().error(ColorParser.of("Laser packer exception: ").build(), e);
}
}
-
- /*@Override
- public synchronized void cancel() throws IllegalStateException {
- super.cancel();
- runnable = null;
- try {
- for (Player p : show) {
- sendDestroyPackets(p);
- }
- show.clear();
- executeEnd.forEach(Runnable::run);
- } catch (ReflectiveOperationException e) {
- e.printStackTrace();
- }
- }*/
};
-// main.runTaskTimerAsynchronously(plugin, 0L, durationInTicks ? 1L : 20L);
-// Main.getPaperLib().scheduling().asyncScheduler().run(main);
- task = Main.getPaperLib().scheduling().asyncScheduler().runAtFixedRate(runnable, Duration.ZERO, Duration.ofMillis(durationInTicks ? 50L : 1000L));
+ task = AlathranWars.getPaperLib().scheduling().asyncScheduler().runAtFixedRate(runnable, Duration.ZERO, Duration.ofMillis(durationInTicks ? 50L : 1000L));
}
/**
@@ -200,7 +184,7 @@ public abstract class Laser {
* @return where exactly is the start position of the laser located
*/
public Location getStart() {
- return start;
+ return start.clone();
}
/**
@@ -209,7 +193,7 @@ public abstract class Laser {
* @return where exactly is the end position of the laser located
*/
public Location getEnd() {
- return end;
+ return end.clone();
}
protected abstract void sendStartPackets(Player p, boolean hasSeen) throws ReflectiveOperationException;
diff --git a/src/main/java/com/github/alathra/AlathranWars/conflict/battle/beam/Packets.java b/src/main/java/com/github/alathra/AlathranWars/conflict/battle/beam/Packets.java
index ade4f28..71fd964 100644
--- a/src/main/java/com/github/alathra/AlathranWars/conflict/battle/beam/Packets.java
+++ b/src/main/java/com/github/alathra/AlathranWars/conflict/battle/beam/Packets.java
@@ -24,8 +24,9 @@ SOFTWARE.
package com.github.alathra.AlathranWars.conflict.battle.beam;
+import com.github.alathra.AlathranWars.utility.Logger;
+import com.github.milkdrinkers.colorparser.ColorParser;
import net.minecraft.world.entity.Entity;
-import net.minecraft.world.entity.EntityType;
import net.minecraft.world.entity.animal.Squid;
import net.minecraft.world.entity.boss.enderdragon.EndCrystal;
import org.bukkit.Bukkit;
@@ -39,13 +40,9 @@ import java.lang.reflect.Method;
import java.util.List;
import java.util.Optional;
import java.util.UUID;
-import java.util.logging.Level;
-import java.util.logging.LogRecord;
-import java.util.logging.Logger;
class Packets {
public static boolean enabled = false;
- private static Logger logger;
static int version;
private static int versionMinor;
private static final String npack = "net.minecraft.server." + Bukkit.getServer().getClass().getPackage().getName().replace(".", ",").split(",")[3];
@@ -84,16 +81,6 @@ class Packets {
static {
try {
- logger = new Logger("GuardianBeam", null) {
- @Override
- public void log(LogRecord logRecord) {
- logRecord.setMessage("[GuardianBeam] " + logRecord.getMessage());
- super.log(logRecord);
- }
- };
- logger.setParent(Bukkit.getServer().getLogger());
- logger.setLevel(Level.ALL);
-
// e.g. Bukkit.getServer().getClass().getPackage().getName() -> org.bukkit.craftbukkit.v1_17_R1
String[] versions = Bukkit.getServer().getClass().getPackage().getName().split("\\.")[3].substring(1).split("_");
version = Integer.parseInt(versions[1]); // 1.X
@@ -102,14 +89,11 @@ class Packets {
versions = Bukkit.getBukkitVersion().split("-R")[0].split("\\.");
versionMinor = versions.length <= 2 ? 0 : Integer.parseInt(versions[2]);
} else versionMinor = Integer.parseInt(versions[2].substring(1)); // 1.X.Y
-// logger.info("Found server version 1." + version + "." + versionMinor);
ProtocolMappings mappings = ProtocolMappings.getMappings(version);
if (mappings == null) {
mappings = ProtocolMappings.values()[ProtocolMappings.values().length - 1];
-// logger.warning("Loaded not matching version of the mappings for your server version (1." + version + "." + versionMinor + ")");
}
-// logger.info("Loaded mappings " + mappings.name());
Class> entityTypesClass = getNMSClass("world.entity", "EntityTypes");
Class entityClass = Entity.class;
@@ -161,7 +145,10 @@ class Packets {
getHandle = Class.forName(cpack + "entity.CraftPlayer").getDeclaredMethod("getHandle");
playerConnection = getNMSClass("server.level", "EntityPlayer")
.getDeclaredField(version < 17 ? "playerConnection" : (version < 20 ? "b" : "c"));
- sendPacket = getNMSClass("server.network", "PlayerConnection").getMethod(version < 18 ? "sendPacket" : "a", getNMSClass("network.protocol", "Packet"));
+ playerConnection.setAccessible(true);
+ sendPacket = getNMSClass("server.network", "PlayerConnection").getMethod(
+ version < 18 ? "sendPacket" : (version >= 20 && versionMinor >= 2 ? "b" : "a"),
+ getNMSClass("network.protocol", "Packet"));
if (version >= 17) {
setUUID = entityClass.getDeclaredMethod("a_", UUID.class);
@@ -170,12 +157,11 @@ class Packets {
enabled = true;
} catch (Exception e) {
- e.printStackTrace();
- String errorMsg = "Laser Beam reflection failed to initialize. The util is disabled. Please ensure your version (" + Bukkit.getServer().getClass().getPackage().getName() + ") is supported.";
- if (logger == null)
- System.err.println(errorMsg);
- else
- logger.severe(errorMsg);
+ Logger.get().error(
+ ColorParser.of("Laser reflection failed to initialize. The utility is disabled. Please ensure your version () is supported.")
+ .parseMinimessagePlaceholder("version", Bukkit.getServer().getClass().getPackage().getName())
+ .build()
+ , e);
}
}
@@ -324,7 +310,12 @@ class Packets {
}
},
- V1_20(20, "an", "b", "e", "c", "d", 89, 38, "V", "aT", "B", "a", "g"),
+ V1_20(20, null, "b", "e", "c", "d", 89, 38, "V", "aT", "B", "a", "g") {
+ @Override
+ public String getWatcherFlags() {
+ return versionMinor < 2 ? "an" : "ao";
+ }
+ },
;
private final int major;
diff --git a/src/main/java/com/github/alathra/AlathranWars/conflict/battle/raid/Raid.java b/src/main/java/com/github/alathra/AlathranWars/conflict/battle/raid/Raid.java
index a8b3888..92e981f 100644
--- a/src/main/java/com/github/alathra/AlathranWars/conflict/battle/raid/Raid.java
+++ b/src/main/java/com/github/alathra/AlathranWars/conflict/battle/raid/Raid.java
@@ -1,6 +1,636 @@
package com.github.alathra.AlathranWars.conflict.battle.raid;
+import com.github.alathra.AlathranWars.AlathranWars;
+import com.github.alathra.AlathranWars.conflict.Side;
+import com.github.alathra.AlathranWars.conflict.War;
import com.github.alathra.AlathranWars.conflict.battle.Battle;
+import com.github.alathra.AlathranWars.enums.CaptureProgressDirection;
+import com.github.alathra.AlathranWars.enums.battle.*;
+import com.github.alathra.AlathranWars.events.battle.BattleResultEvent;
+import com.github.alathra.AlathranWars.events.battle.PreBattleResultEvent;
+import com.github.milkdrinkers.colorparser.ColorParser;
+import com.palmergames.bukkit.towny.object.Town;
+import com.palmergames.bukkit.towny.object.TownBlock;
+import net.kyori.adventure.bossbar.BossBar;
+import net.kyori.adventure.key.Key;
+import net.kyori.adventure.sound.Sound;
+import net.kyori.adventure.text.Component;
+import net.kyori.adventure.title.Title;
+import org.bukkit.Bukkit;
+import org.bukkit.Location;
+import org.bukkit.OfflinePlayer;
+import org.bukkit.entity.Player;
+import org.jetbrains.annotations.NotNull;
+import org.jetbrains.annotations.Nullable;
-public class Raid extends Battle {
+import java.time.Duration;
+import java.time.Instant;
+import java.util.*;
+import java.util.stream.Collectors;
+import java.util.stream.Stream;
+
+public class Raid implements Battle {
+ public static final Duration RAID_DURATION = Duration.ofMinutes(60);
+ public static final int MAX_RAID_PROGRESS_MINUTES = 8; // How many minutes attackers will need to be on point uncontested for to reach 100%
+ public static final int MAX_RAID_PROGRESS = 60 * 10 * MAX_RAID_PROGRESS_MINUTES; // On reaching this, the attackers win. 10 points is added per second
+ public static final Duration ATTACKERS_MUST_TOUCH_END = Duration.ofMinutes(40); // If point is not touched in this much time, defenders win
+ public static final Duration ATTACKERS_MUST_TOUCH_REVERT = Duration.ofSeconds(60); // If point is not touched in this much time, raid progress begins reverting
+ public static final int BATTLEFIELD_RANGE = 500;
+ public static final int BATTLEFIELD_START_MAX_RANGE = BATTLEFIELD_RANGE * 2;
+ public static final int BATTLEFIELD_START_MIN_RANGE = 75;
+ public static final double SIEGE_VICTORY_MONEY = 2500.0;
+
+ private final @NotNull UUID uuid;
+ private final Set attackers = new HashSet<>(); // Players inside battlefield
+ private final Set defenders = new HashSet<>(); // Players inside battlefield
+ private final Set attackerPlayers = new HashSet<>();
+ private final Set defenderPlayers = new HashSet<>();
+ private final Set attackerPlayersIncludingOffline = new HashSet<>();
+ private final Set defenderPlayersIncludingOffline = new HashSet<>();
+ private @NotNull War war; // War which raid belongs to
+ private Instant endTime;
+ private int raidProgress = 0;
+ private Instant lastTouched;
+ private RaidRunnable raidRunnable;
+ private Town town; // Town of the raid
+ private boolean side1AreAttackers; // bool of if side1 being attacker
+ private OfflinePlayer raidLeader;
+ private @Nullable TownBlock homeBlock = null;
+ private @Nullable Location townSpawn = null;
+ private @Nullable BossBar activeBossBar = null;
+ private boolean stopped = false; // Used to track if the raid has been already deleted
+
+ public Raid(final @NotNull War war, final Town town, Player raidLeader) {
+ uuid = UUID.randomUUID();
+
+ endTime = Instant.now().plus(RAID_DURATION);
+ lastTouched = Instant.now();
+
+ this.war = war;
+ this.town = town;
+ this.raidLeader = raidLeader;
+
+ side1AreAttackers = war.getTownSide(town).getTeam().equals(BattleTeam.SIDE_2);
+
+ if (getSide1AreAttackers()) {
+ attackerPlayersIncludingOffline.addAll(getWar().getSide1().getPlayersIncludingOffline());
+ defenderPlayersIncludingOffline.addAll(getWar().getSide2().getPlayersIncludingOffline());
+ } else {
+ attackerPlayersIncludingOffline.addAll(getWar().getSide2().getPlayersIncludingOffline());
+ defenderPlayersIncludingOffline.addAll(getWar().getSide1().getPlayersIncludingOffline());
+ }
+ calculateOnlinePlayers();
+ }
+
+ // Construct when loading from DB
+ public Raid(War war, @NotNull UUID uuid, Town town, OfflinePlayer raidLeader, Instant endTime, Instant lastTouched, int raidProgress, Set attackerPlayersIncludingOffline, Set defenderPlayersIncludingOffline) {
+ this.war = war;
+ this.uuid = uuid;
+ this.town = town;
+ this.raidLeader = raidLeader;
+ this.endTime = endTime;
+ this.lastTouched = lastTouched;
+ this.raidProgress = raidProgress;
+ this.attackerPlayersIncludingOffline.addAll(attackerPlayersIncludingOffline);
+ this.defenderPlayersIncludingOffline.addAll(defenderPlayersIncludingOffline);
+
+ side1AreAttackers = war.getTownSide(town).getTeam().equals(BattleTeam.SIDE_2);
+
+ calculateOnlinePlayers();
+ }
+
+ /**
+ * Starts a raid
+ */
+ public void start() {
+ raidRunnable = new RaidRunnable(this);
+ if (!war.isEvent())
+ AlathranWars.econ.withdrawPlayer(raidLeader, SIEGE_VICTORY_MONEY);
+
+ final Title.Times times = Title.Times.times(Duration.ofMillis(500), Duration.ofMillis(3500), Duration.ofMillis(500));
+ final Title defTitle = Title.title(
+ ColorParser.of("")
+ .parseMinimessagePlaceholder("town", town.getName())
+ .build(),
+ ColorParser.of("Is under raid, defend!")
+ .build(),
+ times
+ );
+ final Title attTitle = Title.title(
+ ColorParser.of("")
+ .parseMinimessagePlaceholder("town", town.getName())
+ .build(),
+ ColorParser.of("Has been put to raid, attack!")
+ .build(),
+ times
+ );
+
+ final List soundList = List.of(
+ Sound.sound(Key.key("item.goat_horn.sound.0"), Sound.Source.VOICE, 0.5f, new Random().nextFloat(0.9F, 1.0F)),
+ Sound.sound(Key.key("item.goat_horn.sound.2"), Sound.Source.VOICE, 0.5f, new Random().nextFloat(0.9F, 1.0F)),
+ Sound.sound(Key.key("item.goat_horn.sound.3"), Sound.Source.VOICE, 0.5f, new Random().nextFloat(0.9F, 1.0F)),
+ Sound.sound(Key.key("item.goat_horn.sound.7"), Sound.Source.VOICE, 0.5f, new Random().nextFloat(0.9F, 1.0F))
+ );
+
+ getDefenderPlayers().forEach(player -> {
+ player.showTitle(defTitle);
+ player.playSound(soundList.get(new Random().nextInt(1, soundList.size())));
+ });
+
+ getAttackerPlayers().forEach(player -> {
+ player.showTitle(attTitle);
+ player.playSound(soundList.get(new Random().nextInt(1, soundList.size())));
+ });
+ }
+
+ /**
+ * Resumes a raid (after a server restart e.t.c.)
+ */
+ public void resume() {
+ raidRunnable = new RaidRunnable(this, getRaidProgress());
+ }
+
+ /**
+ * Stops a raid
+ */
+ public void stop() {
+ if (stopped) return;
+ stopped = true;
+ raidRunnable.cancel();
+// DatabaseQueries.deleteRaid(this); // TODO Delete raid
+ war.removeRaid(this);
+ }
+
+ public void attackersWin(BattleVictoryReason reason) {
+ if (!new PreBattleResultEvent(war, this, BattleType.SIEGE, BattleVictor.ATTACKER, reason).callEvent()) return;
+
+ if (!war.isEvent()) {
+ AlathranWars.econ.depositPlayer(raidLeader, SIEGE_VICTORY_MONEY);
+ double amt;
+
+ if (town.getAccount().getHoldingBalance() > 10000.0) {
+ amt = Math.floor(town.getAccount().getHoldingBalance()) / 4.0;
+ town.getAccount().withdraw(amt, "Raid Defeat");
+ } else {
+ town.getAccount().withdraw(SIEGE_VICTORY_MONEY, "Raid Defeat");
+ amt = SIEGE_VICTORY_MONEY;
+ }
+
+ AlathranWars.econ.depositPlayer(raidLeader, amt);
+ }
+
+ if (side1AreAttackers) {
+ war.getSide1().addScore(50);
+ war.getSide2().addScore(5);
+ } else {
+ war.getSide1().addScore(5);
+ war.getSide2().addScore(50);
+ }
+
+ new BattleResultEvent(war, this, BattleVictor.ATTACKER, reason).callEvent();
+
+ stop();
+
+ if (!war.isEvent()) {
+ Side townSide = getWar().getTownSide(town);
+ Side attackerSide = getAttackerSide();
+
+ if (attackerSide.equals(townSide)) {
+ if (townSide.isTownSurrendered(town))
+ war.unsurrenderTown(town);
+ } else {
+ if (!townSide.isTownSurrendered(town))
+ war.surrenderTown(town);
+ }
+ }
+ }
+
+ public void defendersWin(BattleVictoryReason reason) {
+ if (!new PreBattleResultEvent(war, this, BattleType.SIEGE, BattleVictor.DEFENDER, reason).callEvent()) return;
+
+ if (!war.isEvent())
+ town.getAccount().deposit(SIEGE_VICTORY_MONEY, "Raid Victory");
+
+ if (side1AreAttackers) {
+ war.getSide2().addScore(10);
+ } else {
+ war.getSide1().addScore(10);
+ }
+
+ new BattleResultEvent(war, this, BattleVictor.DEFENDER, reason).callEvent();
+
+ stop();
+ }
+
+ /**
+ * No winner declared
+ */
+ public void equalWin(BattleVictoryReason reason) {
+ if (!new PreBattleResultEvent(war, this, BattleType.SIEGE, BattleVictor.DRAW, reason).callEvent()) return;
+
+ new BattleResultEvent(war, this, BattleVictor.DRAW, reason).callEvent();
+
+ stop();
+ }
+
+ @NotNull
+ public Instant getLastTouched() {
+ return lastTouched;
+ }
+
+ public void setLastTouched(Instant lastTouched) {
+ this.lastTouched = lastTouched;
+ }
+
+ public int getRaidProgress() {
+ return raidProgress;
+ }
+
+ public void setRaidProgress(int raidProgress) {
+ if (raidProgress < 0) {
+ raidProgress = 0;
+ } else if (raidProgress > MAX_RAID_PROGRESS) {
+ raidProgress = MAX_RAID_PROGRESS;
+ }
+ this.raidProgress = raidProgress;
+ }
+
+ public float getRaidProgressPercentage() {
+ return (getRaidProgress() * 1.0f) / MAX_RAID_PROGRESS;
+ }
+
+ @NotNull
+ public War getWar() {
+ return war;
+ }
+
+ public void setWar(final War war) {
+ this.war = war;
+ }
+
+ @NotNull
+ public Town getTown() {
+ return town;
+ }
+
+ public void setTown(final Town town) {
+ this.town = town;
+ }
+
+ /**
+ * Gets attacker name string
+ */
+ @NotNull
+ public Side getAttackerSide() {
+ return side1AreAttackers ? war.getSide1() : war.getSide2();
+ }
+
+ /**
+ * Gets defender name string
+ */
+ @NotNull
+ public Side getDefenderSide() {
+ return side1AreAttackers ? war.getSide2() : war.getSide1();
+ }
+
+ // SECTION Display Bar
+
+ public void updateDisplayBar(@NotNull CaptureProgressDirection progressDirection) {
+ if (activeBossBar == null)
+ createNewDisplayBar();
+
+ for (@NotNull Player p : Bukkit.getOnlinePlayers()) {
+ p.hideBossBar(activeBossBar);
+ }
+
+ for (@Nullable Player p : this.getPlayersOnBattlefield()) {
+ if (p != null)
+ p.showBossBar(activeBossBar);
+ }
+
+ final String color = switch (progressDirection) {
+ case UP -> {
+ if (getAttackerSide().getSide().equals(BattleSide.ATTACKER)) {
+ activeBossBar.color(BossBar.Color.RED);
+ yield "";
+ } else {
+ activeBossBar.color(BossBar.Color.BLUE);
+ yield "";
+ }
+ }
+ case CONTESTED -> {
+ activeBossBar.color(BossBar.Color.YELLOW);
+ yield "";
+ }
+ case UNCONTESTED -> {
+ activeBossBar.color(BossBar.Color.WHITE);
+ yield "";
+ }
+ case DOWN -> {
+ if (getAttackerSide().getSide().equals(BattleSide.ATTACKER)) {
+ activeBossBar.color(BossBar.Color.BLUE);
+ yield "";
+ } else {
+ activeBossBar.color(BossBar.Color.RED);
+ yield "";
+ }
+ }
+ };
+
+ if (Instant.now().isBefore(getEndTime())) {
+ activeBossBar.name(
+ ColorParser.of("Capture Progress: %s
+ * Internal stop method for battles which triggers cleanup methods
*/
public void stop() {
if (stopped) return;
stopped = true;
siegeRunnable.cancel();
- SQLQueries.deleteSiege(this);
- war.removeSiege(this);
+ DatabaseQueries.deleteSiege(this); // TODO Run as latent event?
+ war.removeSiege(this); // TODO Run as latent event?
}
- public void attackersWin() {
+ /**
+ * Stop a battle in favor of the attackers
+ * @param reason what triggered the end
+ */
+ public void attackersWin(BattleVictoryReason reason) {
+ if (!new PreBattleResultEvent(war, this, BattleType.SIEGE, BattleVictor.ATTACKER, reason).callEvent()) return;
+
if (!war.isEvent()) {
- Main.econ.depositPlayer(siegeLeader, SIEGE_VICTORY_MONEY);
+ AlathranWars.econ.depositPlayer(siegeLeader, SIEGE_VICTORY_MONEY);
double amt;
if (town.getAccount().getHoldingBalance() > 10000.0) {
@@ -178,136 +181,37 @@ public class Siege implements Battle {
amt = SIEGE_VICTORY_MONEY;
}
- Main.econ.depositPlayer(siegeLeader, amt);
+ AlathranWars.econ.depositPlayer(siegeLeader, amt);
}
- Bukkit.broadcast(ColorParser.of("The town of has been sacked and placed under occupation by the armies of !")
- .parseMinimessagePlaceholder("prefix", UtilsChat.getPrefix())
- .parseMinimessagePlaceholder("town", town.getName())
- .parseMinimessagePlaceholder("attacker", getAttackerSide().getName())
- .build());
-
- final Title vicAttackTitle = Title.title(
- ColorParser.of("Victory")
- .build(),
- ColorParser.of(" has been captured!")
- .parseMinimessagePlaceholder("town", town.getName())
- .build(),
- TITLE_TIMES
- );
- final Title losAttackTitle = Title.title(
- ColorParser.of("Defeat")
- .build(),
- ColorParser.of(" has been lost!")
- .parseMinimessagePlaceholder("town", town.getName())
- .build(),
- TITLE_TIMES
- );
- getAttackers().forEach(player -> {
- player.showTitle(vicAttackTitle);
- player.playSound(SOUND_VICTORY);
- });
- getDefenders().forEach(player -> {
- player.showTitle(losAttackTitle);
- player.playSound(SOUND_DEFEAT);
- });
-
- if (side1AreAttackers) {
- war.getSide1().addScore(50);
- war.getSide2().addScore(5);
- } else {
- war.getSide1().addScore(5);
- war.getSide2().addScore(50);
- }
-
- stop();
-
- if (!war.isEvent()) {
- Side townSide = getWar().getTownSide(town);
- Side attackerSide = getAttackerSide();
-
- if (attackerSide.equals(townSide)) {
- if (townSide.isTownSurrendered(town))
- war.unsurrenderTown(town);
- } else {
- if (!townSide.isTownSurrendered(town))
- war.surrenderTown(town);
- }
- }
- }
-
- public void defendersWin() {
- if (!war.isEvent())
- town.getAccount().deposit(SIEGE_VICTORY_MONEY, "Siege Victory");
-
- Bukkit.broadcast(
- ColorParser.of("The siege of has been lifted by the defenders!")
- .parseMinimessagePlaceholder("prefix", UtilsChat.getPrefix())
- .parseMinimessagePlaceholder("town", town.getName())
- .build()
- );
-
- final Title vicDefendTitle = Title.title(
- ColorParser.of("Defeat")
- .build(),
- ColorParser.of("We failed to capture !")
- .parseMinimessagePlaceholder("town", town.getName())
- .build(),
- TITLE_TIMES
- );
- final Title losDefendTitle = Title.title(
- ColorParser.of("Victory")
- .build(),
- ColorParser.of(" has been made safe!")
- .parseMinimessagePlaceholder("town", town.getName())
- .build(),
- TITLE_TIMES
- );
- getAttackers().forEach(player -> {
- player.showTitle(vicDefendTitle);
- player.playSound(SOUND_DEFEAT);
- });
- getDefenders().forEach(player -> {
- player.showTitle(losDefendTitle);
- player.playSound(SOUND_VICTORY);
- });
-
- if (side1AreAttackers) {
- war.getSide2().addScore(10);
- } else {
- war.getSide1().addScore(10);
- }
+ new BattleResultEvent(war, this, BattleVictor.ATTACKER, reason).callEvent();
stop();
}
/**
- * No winner declared
+ * Stop a battle in favor of the defenders
+ * @param reason what triggered the end
*/
- public void equalWin() {
- Bukkit.broadcast(
- ColorParser.of("The siege of has ended in a draw!")
- .parseMinimessagePlaceholder("prefix", UtilsChat.getPrefix())
- .parseMinimessagePlaceholder("town", town.getName())
- .build()
- );
+ public void defendersWin(BattleVictoryReason reason) {
+ if (!new PreBattleResultEvent(war, this, BattleType.SIEGE, BattleVictor.DEFENDER, reason).callEvent()) return;
- final Title drawTitle = Title.title(
- ColorParser.of("Draw")
- .build(),
- ColorParser.of("The siege at has ended!")
- .parseMinimessagePlaceholder("town", town.getName())
- .build(),
- TITLE_TIMES
- );
- getAttackers().forEach(player -> {
- player.showTitle(drawTitle);
- player.playSound(SOUND_DEFEAT);
- });
- getDefenders().forEach(player -> {
- player.showTitle(drawTitle);
- player.playSound(SOUND_DEFEAT);
- });
+ if (!war.isEvent())
+ town.getAccount().deposit(SIEGE_VICTORY_MONEY, "Siege Victory");
+
+ new BattleResultEvent(war, this, BattleVictor.DEFENDER, reason).callEvent();
+
+ stop();
+ }
+
+ /**
+ * End a battle in favor of no one
+ * @param reason what triggered the end
+ */
+ public void equalWin(BattleVictoryReason reason) {
+ if (!new PreBattleResultEvent(war, this, BattleType.SIEGE, BattleVictor.DRAW, reason).callEvent()) return;
+
+ new BattleResultEvent(war, this, BattleVictor.DRAW, reason).callEvent();
stop();
}
@@ -361,7 +265,7 @@ public class Siege implements Battle {
*/
@NotNull
public Side getAttackerSide() {
- return side1AreAttackers ? war.getSide1() : war.getSide2();
+ return getSide1AreAttackers() ? war.getSide1() : war.getSide2();
}
/**
@@ -369,7 +273,7 @@ public class Siege implements Battle {
*/
@NotNull
public Side getDefenderSide() {
- return side1AreAttackers ? war.getSide2() : war.getSide1();
+ return getSide1AreAttackers() ? war.getSide2() : war.getSide1();
}
// SECTION Display Bar
@@ -476,6 +380,13 @@ public class Siege implements Battle {
return getUUID().equals(siege.getUUID());
}
+ // SECTION BattleType
+
+ @Override
+ public BattleType getBattleType() {
+ return battleType;
+ }
+
// SECTION Accessors & Getters
@Nullable
@@ -667,6 +578,9 @@ public class Siege implements Battle {
}
public void calculateBattlefieldPlayers(@NotNull Location location) {
+ final Set previousAttackersOnBattlefield = new HashSet<>(attackers);
+ final Set previousDefendersOnBattlefield = new HashSet<>(defenders);
+
final @NotNull Set attackersOnBattlefield = attackerPlayers.stream()
.filter(OfflinePlayer::isOnline)
.filter(p -> location.getWorld().equals(p.getLocation().getWorld()))
@@ -684,5 +598,29 @@ public class Siege implements Battle {
defenders.clear();
defenders.addAll(defendersOnBattlefield);
+
+ // Emit events for players leaving & entering the battlefield
+ for (Player p : previousAttackersOnBattlefield) {
+ if (p.isConnected() && !attackers.contains(p)) {
+ // TODO Player left battlefield
+ }
+ }
+ for (Player p : attackers) {
+ if (p.isConnected() && !previousAttackersOnBattlefield.contains(p)) {
+ // TODO Player entered battlefield
+ }
+ }
+
+ for (Player p : previousDefendersOnBattlefield) {
+ if (p.isConnected() && !defenders.contains(p)) {
+ // TODO Player left battlefield
+ }
+ }
+
+ for (Player p : defenders) {
+ if (p.isConnected() && !previousDefendersOnBattlefield.contains(p)) {
+ // TODO Player entered battlefield
+ }
+ }
}
}
diff --git a/src/main/java/com/github/alathra/AlathranWars/conflict/battle/siege/SiegeRunnable.java b/src/main/java/com/github/alathra/AlathranWars/conflict/battle/siege/SiegeRunnable.java
index b98d31c..dd93390 100644
--- a/src/main/java/com/github/alathra/AlathranWars/conflict/battle/siege/SiegeRunnable.java
+++ b/src/main/java/com/github/alathra/AlathranWars/conflict/battle/siege/SiegeRunnable.java
@@ -1,10 +1,11 @@
package com.github.alathra.AlathranWars.conflict.battle.siege;
-import com.github.alathra.AlathranWars.Main;
+import com.github.alathra.AlathranWars.AlathranWars;
import com.github.alathra.AlathranWars.conflict.battle.beam.CrystalLaser;
import com.github.alathra.AlathranWars.conflict.battle.beam.Laser;
-import com.github.alathra.AlathranWars.enums.BattleSide;
+import com.github.alathra.AlathranWars.enums.battle.BattleSide;
import com.github.alathra.AlathranWars.enums.CaptureProgressDirection;
+import com.github.alathra.AlathranWars.enums.battle.BattleVictoryReason;
import com.github.alathra.AlathranWars.utility.UtilsChat;
import com.github.milkdrinkers.colorparser.ColorParser;
import com.palmergames.bukkit.towny.object.Town;
@@ -48,7 +49,7 @@ public class SiegeRunnable implements Runnable {
nextAnnouncement = Instant.now().plus(ANNOUNCEMENT_COOLDOWN);
- task = Main.getPaperLib().scheduling().globalRegionalScheduler().runAtFixedRate(this, 0L, 20L);
+ task = AlathranWars.getPaperLib().scheduling().globalRegionalScheduler().runAtFixedRate(this, 0L, 20L);
siege.updateDisplayBar(CONTESTED);
}
@@ -69,7 +70,7 @@ public class SiegeRunnable implements Runnable {
nextAnnouncement = Instant.now().plus(ANNOUNCEMENT_COOLDOWN);
- task = Main.getPaperLib().scheduling().globalRegionalScheduler().runAtFixedRate(this, 0L, 20L);
+ task = AlathranWars.getPaperLib().scheduling().globalRegionalScheduler().runAtFixedRate(this, 0L, 20L);
siege.updateDisplayBar(CONTESTED);
}
@@ -111,14 +112,14 @@ public class SiegeRunnable implements Runnable {
Instant.now().isAfter(siege.getLastTouched().plus(ATTACKERS_MUST_TOUCH_END)))
) {
cancel();
- siege.defendersWin();
+ siege.defendersWin(BattleVictoryReason.OPPONENT_LOST);
return;
}
// Attackers captured the town
if (siege.getSiegeProgress() >= MAX_SIEGE_PROGRESS) {
cancel();
- siege.attackersWin();
+ siege.attackersWin(BattleVictoryReason.OPPONENT_LOST);
return;
}
@@ -245,7 +246,7 @@ public class SiegeRunnable implements Runnable {
@NotNull Location loc2 = new Location(loc1.getWorld(), loc1.getX(), loc1.getY() + 350D, loc1.getZ());
beam = new CrystalLaser(loc1, loc2, -1, 300);
- beam.start(Main.getInstance());
+ beam.start(AlathranWars.getInstance());
} catch (ReflectiveOperationException ignored) {
}
}
diff --git a/src/main/java/com/github/alathra/AlathranWars/data/ConfigManager.java b/src/main/java/com/github/alathra/AlathranWars/data/ConfigManager.java
deleted file mode 100644
index cf13707..0000000
--- a/src/main/java/com/github/alathra/AlathranWars/data/ConfigManager.java
+++ /dev/null
@@ -1,28 +0,0 @@
-package com.github.alathra.AlathranWars.data;
-
-import com.github.alathra.AlathranWars.Main;
-import com.github.milkdrinkers.Crate.Config;
-
-public class ConfigManager {
- private final Main instance;
- private Config cfg;
-
- public ConfigManager(Main instance) {
- this.instance = instance;
- }
-
- public void onLoad() {
- cfg = new Config("config", instance.getDataFolder().getPath(), instance.getResource("config.yml"));
- }
-
- public void onEnable() {
- }
-
- public void onDisable() {
-
- }
-
- public Config getConfig() {
- return cfg;
- }
-}
diff --git a/src/main/java/com/github/alathra/AlathranWars/data/DataManager.java b/src/main/java/com/github/alathra/AlathranWars/data/DataManager.java
deleted file mode 100644
index 726d209..0000000
--- a/src/main/java/com/github/alathra/AlathranWars/data/DataManager.java
+++ /dev/null
@@ -1,115 +0,0 @@
-package com.github.alathra.AlathranWars.data;
-
-import com.github.alathra.AlathranWars.Main;
-import com.github.alathra.AlathranWars.utility.Config;
-import com.github.alathra.AlathranWars.utility.SQLQueries;
-import com.zaxxer.hikari.HikariConfig;
-import com.zaxxer.hikari.HikariDataSource;
-import org.jetbrains.annotations.NotNull;
-
-import java.io.File;
-import java.io.IOException;
-import java.sql.Connection;
-import java.sql.SQLException;
-
-public class DataManager {
- private final Main instance;
- private HikariDataSource hikariDataSource;
-
- public DataManager(Main instance) {
- this.instance = instance;
- }
-
- public void onLoad() {
- openConnection();
- SQLQueries.initDB();
- }
-
- public void onEnable() {
- }
-
- public void onDisable() {
- closeDatabaseConnection();
- }
-
- @NotNull
- public Connection getConnection() throws SQLException {
- if (hikariDataSource == null)
- throw new SQLException("Unable to get a connection from the pool. (hikariDataSource is null)");
-
- Connection connection = hikariDataSource.getConnection();
- if (connection == null)
- throw new SQLException("Unable to get a connection from the pool. (HikariDataSource#getConnection returned null)");
-
- return connection;
- }
-
- @NotNull
- public HikariDataSource getDataSource() {
- return hikariDataSource;
- }
-
- private void openConnection() {
- if (hikariDataSource != null)
- return;
-
- HikariConfig hikariConfig = new HikariConfig();
-
- final boolean mysqlEnabled = Config.get().getBoolean("mysql.enabled");
-
- if (mysqlEnabled) {
- hikariConfig.setDataSourceClassName("org.mariadb.jdbc.MariaDbDataSource");
- hikariConfig.addDataSourceProperty("url", "jdbc:mariadb://%s/%s".formatted(
- Config.get().get("mysql.host", "127.0.0.1:3306"),
- Config.get().get("mysql.database", "database")
- ));
- hikariConfig.setUsername(Config.get().get("mysql.user", "username"));
- hikariConfig.setPassword(Config.get().get("mysql.pass", "123"));
- hikariConfig.setConnectionTimeout(5000);
- hikariConfig.setKeepaliveTime(0);
- } else {
- @NotNull File dataFolder = new File(instance.getDataFolder(), "database.db");
-
- if (!dataFolder.exists()) {
- try {
- if (!dataFolder.createNewFile())
- instance.getLogger().severe("File write error: database.db (1)");
- } catch (IOException e) {
- instance.getLogger().severe("File write error: database.db (2) - %s".formatted(e.getMessage()));
- }
- }
-
- hikariConfig.setJdbcUrl("jdbc:sqlite:" + dataFolder);
- hikariConfig.setConnectionInitSql("PRAGMA journal_mode=WAL; PRAGMA busy_timeout=30000");
- hikariConfig.setConnectionTimeout(30000);
- }
-
- hikariConfig.setPoolName("althranwars-hikari");
- hikariConfig.setMaximumPoolSize(10);
- hikariConfig.setMinimumIdle(10);
- hikariConfig.setInitializationFailTimeout(-1); // We try to create tables after this anyways which will error if no connection
-
- hikariDataSource = new HikariDataSource(hikariConfig);
- }
-
- private void closeDatabaseConnection() {
- instance.getLogger().info("Closing database connection...");
-
- if (hikariDataSource == null) {
- instance.getLogger().severe("Skipped closing database connection because the data source is null. Was there a previous error which needs to be fixed? Check your console logs!");
- return;
- }
-
- if (hikariDataSource.isClosed()) {
- instance.getLogger().info("Skipped closing database connection: connection is already closed.");
- return;
- }
-
- try {
- hikariDataSource.close();
- } catch (Exception e) {
- instance.getLogger().severe("Error closing database connections:");
- e.printStackTrace();
- }
- }
-}
diff --git a/src/main/java/com/github/alathra/AlathranWars/db/DatabaseHandler.java b/src/main/java/com/github/alathra/AlathranWars/db/DatabaseHandler.java
new file mode 100644
index 0000000..2a79f49
--- /dev/null
+++ b/src/main/java/com/github/alathra/AlathranWars/db/DatabaseHandler.java
@@ -0,0 +1,303 @@
+package com.github.alathra.AlathranWars.db;
+
+import com.github.alathra.AlathranWars.AlathranWars;
+import com.github.alathra.AlathranWars.Reloadable;
+import com.github.alathra.AlathranWars.db.flyway.DatabaseMigrationException;
+import com.github.alathra.AlathranWars.db.flyway.DatabaseMigrationHandler;
+import com.github.alathra.AlathranWars.db.jooq.JooqContext;
+import com.github.alathra.AlathranWars.utility.Cfg;
+import com.github.alathra.AlathranWars.utility.Logger;
+import com.zaxxer.hikari.HikariConfig;
+import com.zaxxer.hikari.HikariDataSource;
+import org.jetbrains.annotations.NotNull;
+
+import javax.inject.Singleton;
+import java.io.File;
+import java.sql.Connection;
+import java.sql.SQLException;
+import java.util.Map;
+
+/**
+ * Class that handles HikariCP connection pool, jOOQ and Flyway migrations.
+ */
+@Singleton
+public class DatabaseHandler implements Reloadable {
+ private final AlathranWars alathranWars;
+ private boolean isConnected = false;
+ private HikariDataSource hikariDataSource;
+ private DatabaseType database;
+ private JooqContext jooqContext;
+
+ /**
+ * Instantiates a new Data handler.
+ *
+ * @param alathranWars the plugin instance
+ */
+ public DatabaseHandler(AlathranWars alathranWars) {
+ this.alathranWars = alathranWars;
+ }
+
+ /**
+ * On plugin load.
+ */
+ @Override
+ public void onLoad() {
+ try {
+ openConnection();
+ isConnected = true;
+ } catch (Exception e) {
+ Logger.get().error("[DB] Database initialization error: ", e);
+ } finally {
+ if (!isConnected()) {
+ Logger.get().warn("[DB] Failed to initialize database connection. Functionality will be limited.");
+ }
+ }
+ }
+
+ /**
+ * On plugin enable.
+ */
+ @Override
+ public void onEnable() {
+ }
+
+ /**
+ * On plugin disable.
+ */
+ @Override
+ public void onDisable() {
+ try {
+ closeDatabaseConnection();
+ isConnected = false;
+ } catch (Exception e) {
+ Logger.get().error("[DB] Error closing database connections:", e);
+ }
+ }
+
+ /**
+ * Returns if the database is setup and functioning properly.
+ *
+ * @return the boolean
+ */
+ public boolean isConnected() {
+ return isConnected;
+ }
+
+ /**
+ * Gets db.
+ *
+ * @return the db
+ */
+ public DatabaseType getDB() {
+ return database;
+ }
+
+ /**
+ * Gets jooq context.
+ *
+ * @return the jooq context
+ */
+ public JooqContext getJooqContext() {
+ return jooqContext;
+ }
+
+ /**
+ * Gets a connection from the connection pool.
+ *
+ * @return the connection
+ * @throws SQLException the sql exception
+ */
+ @NotNull
+ public Connection getConnection() throws SQLException {
+ if (hikariDataSource == null)
+ throw new SQLException("[DB] Unable to getConnection a connection from the pool. (HikariDataSource returned null)");
+
+ final Connection connection = hikariDataSource.getConnection();
+ if (connection == null)
+ throw new SQLException("[DB] Unable to getConnection a connection from the pool. (HikariDataSource#getConnection returned null)");
+
+ return connection;
+ }
+
+ /**
+ * Creates a connection pool using HikariCP and executes Flyway migrations.
+ */
+ private void openConnection() {
+ if (hikariDataSource != null) {
+ Logger.get().warn("[DB] Attempted to create a new database pool while running!");
+ return;
+ }
+
+ final HikariConfig hikariConfig = new HikariConfig();
+ final String vendorName = Cfg.get().get("db.type", DatabaseType.HSQLDB.getDriverName());
+ final DatabaseType db = DatabaseType.getDatabaseTypeFromJdbcPrefix(vendorName);
+
+ if (db == null) {
+ Logger.get().warn("[DB] Invalid database type was specified!");
+ return;
+ }
+
+ final String host = Cfg.get().get("db.host", "127.0.0.1");
+ final String port = Cfg.get().get("db.port", "3306");
+ final String database = Cfg.get().get("db.database", "database");
+ final String username = Cfg.get().get("db.user", "root");
+ final String password = Cfg.get().get("db.pass", "");
+
+ final String connectionProperties = switch (db) {
+ case H2 -> DatabaseType.H2.formatJdbcConnectionProperties(
+ Map.of(
+ "AUTO_SERVER", "TRUE",
+ "MODE", "MySQL", // MySQL support mode
+ "CASE_INSENSITIVE_IDENTIFIERS", "TRUE",
+ "IGNORECASE", "TRUE"
+ )
+ );
+ case HSQLDB -> DatabaseType.HSQLDB.formatJdbcConnectionProperties(
+ Map.of(
+ "sql.syntax_mys", "true", // MySQL support mode
+ // Prevent execution of multiple queries in one Statement
+ "sql.restrict_exec", true,
+ // Make the names of generated indexes the same as the names of the constraints
+ "sql.sys_index_names", true,
+ /*
+ * Enforce SQL standards on
+ * 1.) table and column names
+ * 2.) ambiguous column references
+ * 3.) illegal type conversions
+ */
+ "sql.enforce_names", true,
+ "sql.enforce_refs", true,
+ "sql.enforce_types", true,
+ // Respect interrupt status during query execution
+ "hsqldb.tx_interrupt_rollback", true,
+ // Use CACHED tables by default
+ "hsqldb.default_table_type", "cached",
+ // Needed for use with connection init-SQL (hikariConf.setConnectionInitSql)
+ "allowMultiQueries", true,
+ // Help debug in case of exceptions
+ "dumpQueriesOnException", true
+ )
+ );
+ case MARIADB -> DatabaseType.MARIADB.formatJdbcConnectionProperties(
+ Map.of(
+ // Performance improvements
+ "autocommit", false,
+ "defaultFetchSize", 1000,
+
+ // Help debug in case of deadlock
+ "includeInnodbStatusInDeadlockExceptions", true,
+ "includeThreadDumpInDeadlockExceptions", true,
+
+ // https://github.com/brettwooldridge/HikariCP/wiki/Rapid-Recovery#mysql
+ "socketTimeout", 14000L,
+ // Needed for use with connection init-SQL (hikariConf.setConnectionInitSql)
+ "allowMultiQueries", true,
+ // Help debug in case of exceptions
+ "dumpQueriesOnException", true
+ )
+ );
+ case MYSQL -> DatabaseType.MYSQL.formatJdbcConnectionProperties(
+ Map.of(
+ // Performance improvements
+ "autocommit", false,
+ "defaultFetchSize", 1000,
+
+ // Help debug in case of deadlock
+ "includeInnodbStatusInDeadlockExceptions", true,
+ "includeThreadDumpInDeadlockExceptions", true,
+
+ // https://github.com/brettwooldridge/HikariCP/wiki/Rapid-Recovery#mysql
+ "socketTimeout", 14000L,
+ // Needed for use with connection init-SQL (hikariConf.setConnectionInitSql)
+ "allowMultiQueries", true,
+ // Help debug in case of exceptions
+ "dumpQueriesOnException", true
+ )
+ );
+ };
+
+ switch (db) {
+ case HSQLDB, H2 -> {
+ final String subfolder = "data";
+ final String fileName = "database";
+ final String fileExtension = switch (db) {
+ case HSQLDB -> ".hsql";
+ case H2 -> ".mv.db";
+ default -> "";
+ };
+ final String fileNameWithExtension = fileName + fileExtension;
+
+ // Set credentials for HSQL and H2
+ hikariConfig.setUsername("SA");
+ hikariConfig.setPassword("");
+
+ hikariConfig.setDataSourceClassName(db.getDataSourceClassName());
+ hikariConfig.addDataSourceProperty("url", "jdbc:%s:%s".formatted(
+ db.getJdbcPrefix(),
+ alathranWars.getDataFolder().getAbsolutePath() + File.separatorChar + subfolder + File.separatorChar + (db.equals(DatabaseType.H2) ? fileName : fileNameWithExtension) + connectionProperties
+ ));
+ }
+ case MYSQL, MARIADB -> {
+ hikariConfig.setDataSourceClassName(db.getDataSourceClassName());
+ hikariConfig.addDataSourceProperty("url", "jdbc:%s://%s%s/%s".formatted(
+ db.getJdbcPrefix(),
+ host,
+ ":%s".formatted(port),
+ database + connectionProperties
+ ));
+
+ hikariConfig.setUsername(username);
+ hikariConfig.setPassword(password);
+
+ hikariConfig.setKeepaliveTime(0);
+ }
+ }
+
+ hikariConfig.setConnectionTimeout(14000);
+ hikariConfig.setMaxLifetime(25000000);
+ hikariConfig.setInitializationFailTimeout(-1); // We try to create tables after this anyways which will error if no connection
+
+ final int poolSize = Cfg.get().getOrDefault("db.poolsize", 10);
+ hikariConfig.setMaximumPoolSize(poolSize);
+ hikariConfig.setMinimumIdle(poolSize);
+
+ hikariConfig.setPoolName("%s-hikari".formatted(AlathranWars.getInstance().getName()));
+ hikariConfig.setAutoCommit(true);
+ hikariConfig.setTransactionIsolation("TRANSACTION_REPEATABLE_READ");
+ hikariConfig.setIsolateInternalQueries(true);
+ hikariConfig.setConnectionInitSql(db.getConnectionInitSql());
+
+ this.hikariDataSource = new HikariDataSource(hikariConfig);
+ this.database = db;
+ this.jooqContext = new JooqContext(db.getSQLDialect());
+
+ try {
+ new DatabaseMigrationHandler(Cfg.get(), hikariDataSource, db)
+ .migrate();
+ } catch (DatabaseMigrationException e) {
+ Logger.get().error("[DB] Failed to migrate database. Please backup your database and report the issue.", e);
+ }
+ }
+
+ /**
+ * Closes the connection pool.
+ */
+ private void closeDatabaseConnection() throws Exception {
+ Logger.get().info("[DB] Closing database connection...");
+
+ if (hikariDataSource == null) {
+ Logger.get().error("[DB] Skipped closing database connection because the data source is null. Was there a previous error which needs to be fixed? Check your console logs!");
+ return;
+ }
+
+ if (hikariDataSource.isClosed()) {
+ Logger.get().info("[DB] Skipped closing database connection: connection is already closed.");
+ return;
+ }
+
+ hikariDataSource.close();
+ hikariDataSource = null;
+
+ Logger.get().info("[DB] Closed database connection.");
+ }
+}
diff --git a/src/main/java/com/github/alathra/AlathranWars/db/DatabaseQueries.java b/src/main/java/com/github/alathra/AlathranWars/db/DatabaseQueries.java
new file mode 100644
index 0000000..9cbd3fc
--- /dev/null
+++ b/src/main/java/com/github/alathra/AlathranWars/db/DatabaseQueries.java
@@ -0,0 +1,553 @@
+package com.github.alathra.AlathranWars.db;
+
+import com.github.alathra.AlathranWars.conflict.*;
+import com.github.alathra.AlathranWars.conflict.battle.siege.Siege;
+import com.github.alathra.AlathranWars.enums.battle.BattleSide;
+import com.github.alathra.AlathranWars.enums.battle.BattleTeam;
+import com.github.alathra.AlathranWars.utility.DB;
+import com.github.alathra.AlathranWars.utility.Logger;
+import com.palmergames.bukkit.towny.TownyAPI;
+import com.palmergames.bukkit.towny.object.Nation;
+import com.palmergames.bukkit.towny.object.Town;
+import org.bukkit.Bukkit;
+import org.bukkit.OfflinePlayer;
+import org.jetbrains.annotations.Contract;
+import org.jetbrains.annotations.NotNull;
+import org.jetbrains.annotations.Nullable;
+import org.jooq.DSLContext;
+import org.jooq.Record;
+import org.jooq.Result;
+import org.jooq.exception.DataAccessException;
+
+import java.nio.ByteBuffer;
+import java.sql.Connection;
+import java.sql.SQLException;
+import java.sql.Savepoint;
+import java.sql.Timestamp;
+import java.time.Instant;
+import java.time.LocalDateTime;
+import java.time.ZoneOffset;
+import java.util.HashSet;
+import java.util.Set;
+import java.util.UUID;
+import java.util.stream.Collectors;
+
+import static com.github.alathra.AlathranWars.db.schema.Tables.*;
+
+/**
+ * A holder class for all SQL queries
+ */
+public abstract class DatabaseQueries {
+ private interface LambdaInterface {
+ void execute(Connection connection, DSLContext dslContext) throws SQLException, DataAccessException;
+ }
+
+ private static void transactionWrapper(Connection con, LambdaInterface lambda) throws SQLException, DataAccessException {
+ DSLContext context = DB.getContext(con);
+
+ final Savepoint savePoint = con.setSavepoint();
+ final boolean autoCommit = con.getAutoCommit();
+
+ try {
+ con.setAutoCommit(false);
+
+ lambda.execute(con, context);
+
+ con.commit();
+ } catch (SQLException | DataAccessException e) {
+ con.rollback(savePoint);
+ } finally {
+ con.setAutoCommit(autoCommit);
+ }
+ }
+
+ public static byte[] convertUUIDToBytes(UUID uuid) {
+ ByteBuffer buffer = ByteBuffer.wrap(new byte[16]);
+ buffer.putLong(uuid.getMostSignificantBits());
+ buffer.putLong(uuid.getLeastSignificantBits());
+ return buffer.array();
+ }
+
+ public static UUID convertBytesToUUID(byte[] bytes) {
+ ByteBuffer byteBuffer = ByteBuffer.wrap(bytes);
+ return new UUID(byteBuffer.getLong(), byteBuffer.getLong());
+ }
+
+ // Setters
+
+ public static void saveAll() {
+ try (
+ Connection con = DB.getConnection();
+ ) {
+ DSLContext context = DB.getContext(con);
+
+ for (War war : WarManager.getInstance().getWars()) {
+ context
+// .insertInto(LIST)
+// .set(LIST.UUID, DatabaseQueries.convertUUIDToBytes(war.getUUID()))
+// .set(LIST.NAME, war.getName())
+// .set(LIST.LABEL, war.getLabel())
+// .set(LIST.SIDE1, DatabaseQueries.convertUUIDToBytes(war.getSide1().getUUID()))
+// .set(LIST.SIDE2, DatabaseQueries.convertUUIDToBytes(war.getSide2().getUUID()))
+// .set(LIST.EVENT, war.isEvent() ? (byte) 1 : (byte) 0)
+ .insertInto(LIST, LIST.UUID, LIST.NAME, LIST.LABEL, LIST.SIDE1, LIST.SIDE2, LIST.EVENT)
+ .values(
+ DatabaseQueries.convertUUIDToBytes(war.getUUID()),
+ war.getName(),
+ war.getLabel(),
+ DatabaseQueries.convertUUIDToBytes(war.getSide1().getUUID()),
+ DatabaseQueries.convertUUIDToBytes(war.getSide2().getUUID()),
+ war.isEvent() ? (byte) 1 : (byte) 0
+ )
+ .onDuplicateKeyUpdate()
+ .set(LIST.NAME, war.getName())
+ .set(LIST.LABEL, war.getLabel())
+ .set(LIST.SIDE1, DatabaseQueries.convertUUIDToBytes(war.getSide1().getUUID()))
+ .set(LIST.SIDE2, DatabaseQueries.convertUUIDToBytes(war.getSide2().getUUID()))
+ .execute();
+
+ // Save sides
+ for (Side side : war.getSides()) {
+ saveSide(con, side);
+ }
+
+ // Save sieges
+ for (Siege siege : war.getSieges()) {
+ saveSiege(con, siege);
+ }
+ }
+ } catch (SQLException e) {
+ Logger.get().error("SQL Query failed to save data!", e);
+ }
+ }
+
+ public static void saveSide(Connection con, Side side) {
+ try {
+ DSLContext context = DB.getContext(con);
+
+ context
+ .insertInto(SIDES, SIDES.WAR, SIDES.UUID, SIDES.SIDE, SIDES.TEAM, SIDES.NAME, SIDES.TOWN, SIDES.SIEGEGRACE, SIDES.RAIDGRACE)
+ .values(
+ convertUUIDToBytes(side.getWar().getUUID()),
+ convertUUIDToBytes(side.getUUID()),
+ side.getSide().toString(),
+ side.getTeam().toString(),
+ side.getName(),
+ convertUUIDToBytes(side.getTown().getUUID()),
+ LocalDateTime.ofInstant(side.getSiegeGrace(), ZoneOffset.UTC),
+ LocalDateTime.ofInstant(side.getRaidGrace(), ZoneOffset.UTC)
+ )
+ .onDuplicateKeyUpdate()
+ .set(SIDES.SIDE, side.getSide().toString())
+ .set(SIDES.TEAM, side.getTeam().toString())
+ .set(SIDES.NAME, side.getName())
+ .set(SIDES.TOWN, convertUUIDToBytes(side.getTown().getUUID()))
+ .set(SIDES.SIEGEGRACE, LocalDateTime.ofInstant(side.getSiegeGrace(), ZoneOffset.UTC))
+ .set(SIDES.RAIDGRACE, LocalDateTime.ofInstant(side.getRaidGrace(), ZoneOffset.UTC))
+ .execute();
+
+ saveSideNations(con, side);
+ saveSideTowns(con, side);
+ saveSidePlayers(con, side);
+ } catch (DataAccessException e) {
+ Logger.get().error("SQL Query failed to save side!", e);
+ }
+ }
+
+ public static void saveSideNations(Connection con, Side side) {
+ try {
+ transactionWrapper(con, (connection, context) -> {
+ context
+ .deleteFrom(SIDES_NATIONS)
+ .where(SIDES_NATIONS.SIDE.equal(convertUUIDToBytes(side.getUUID())))
+ .execute();
+
+ for (Nation nation : side.getNations()) {
+ context.insertInto(SIDES_NATIONS, SIDES_NATIONS.SIDE, SIDES_NATIONS.NATION, SIDES_NATIONS.SURRENDERED)
+ .values(
+ convertUUIDToBytes(side.getUUID()),
+ convertUUIDToBytes(nation.getUUID()),
+ (byte) 0
+ )
+ .execute();
+ }
+
+ for (Nation nation : side.getSurrenderedNations()) {
+ context.insertInto(SIDES_NATIONS, SIDES_NATIONS.SIDE, SIDES_NATIONS.NATION, SIDES_NATIONS.SURRENDERED)
+ .values(
+ convertUUIDToBytes(side.getUUID()),
+ convertUUIDToBytes(nation.getUUID()),
+ (byte) 1
+ )
+ .execute();
+ }
+ });
+ } catch (SQLException | DataAccessException e) {
+ Logger.get().error("SQL Query failed to save side nations!", e);
+ }
+ }
+
+ public static void saveSideTowns(Connection con, Side side) {
+ try {
+ transactionWrapper(con, (connection, context) -> {
+ context
+ .deleteFrom(SIDES_TOWNS)
+ .where(SIDES_TOWNS.SIDE.equal(convertUUIDToBytes(side.getUUID())))
+ .execute();
+
+ for (Town town : side.getTowns()) {
+ context.insertInto(SIDES_TOWNS, SIDES_TOWNS.SIDE, SIDES_TOWNS.TOWN, SIDES_TOWNS.SURRENDERED)
+ .values(
+ convertUUIDToBytes(side.getUUID()),
+ convertUUIDToBytes(town.getUUID()),
+ (byte) 0
+ )
+ .execute();
+ }
+
+ for (Town town : side.getSurrenderedTowns()) {
+ context.insertInto(SIDES_TOWNS, SIDES_TOWNS.SIDE, SIDES_TOWNS.TOWN, SIDES_TOWNS.SURRENDERED)
+ .values(
+ convertUUIDToBytes(side.getUUID()),
+ convertUUIDToBytes(town.getUUID()),
+ (byte) 1
+ )
+ .execute();
+ }
+ });
+ } catch (SQLException | DataAccessException e) {
+ Logger.get().error("SQL Query failed to save side towns!", e);
+ }
+ }
+
+ public static void saveSidePlayers(Connection con, Side side) {
+ try {
+ transactionWrapper(con, (connection, context) -> {
+ context
+ .deleteFrom(SIDES_PLAYERS)
+ .where(SIDES_PLAYERS.SIDE.equal(convertUUIDToBytes(side.getUUID())))
+ .execute();
+
+ for (UUID uuid : side.getPlayersIncludingOffline()) {
+ context.insertInto(SIDES_PLAYERS, SIDES_PLAYERS.SIDE, SIDES_PLAYERS.PLAYER, SIDES_PLAYERS.SURRENDERED)
+ .values(
+ convertUUIDToBytes(side.getUUID()),
+ convertUUIDToBytes(uuid),
+ (byte) 0
+ )
+ .execute();
+ }
+
+ for (UUID uuid : side.getSurrenderedPlayersIncludingOffline()) {
+ context.insertInto(SIDES_PLAYERS, SIDES_PLAYERS.SIDE, SIDES_PLAYERS.PLAYER, SIDES_PLAYERS.SURRENDERED)
+ .values(
+ convertUUIDToBytes(side.getUUID()),
+ convertUUIDToBytes(uuid),
+ (byte) 1
+ )
+ .execute();
+ }
+ });
+ } catch (SQLException | DataAccessException e) {
+ Logger.get().error("SQL Query failed to save side players!", e);
+ }
+ }
+
+ private static void saveSiege(Connection con, Siege siege) {
+ try {
+ DSLContext context = DB.getContext(con);
+
+ context.insertInto(SIEGES, SIEGES.WAR, SIEGES.UUID, SIEGES.TOWN, SIEGES.SIEGELEADER, SIEGES.ENDTIME, SIEGES.LASTTOUCHED, SIEGES.SIEGEPROGRESS)
+ .values(
+ convertUUIDToBytes(siege.getWar().getUUID()),
+ convertUUIDToBytes(siege.getUUID()),
+ convertUUIDToBytes(siege.getTown().getUUID()),
+ convertUUIDToBytes(siege.getSiegeLeader().getUniqueId()),
+ LocalDateTime.ofInstant(siege.getEndTime(), ZoneOffset.UTC),
+ LocalDateTime.ofInstant(siege.getLastTouched(), ZoneOffset.UTC),
+ siege.getSiegeProgress()
+ )
+ .onDuplicateKeyUpdate()
+ .set(SIEGES.WAR, convertUUIDToBytes(siege.getWar().getUUID()))
+ .set(SIEGES.TOWN, convertUUIDToBytes(siege.getTown().getUUID()))
+ .set(SIEGES.SIEGELEADER, convertUUIDToBytes(siege.getSiegeLeader().getUniqueId()))
+ .set(SIEGES.ENDTIME, LocalDateTime.ofInstant(siege.getEndTime(), ZoneOffset.UTC))
+ .set(SIEGES.LASTTOUCHED, LocalDateTime.ofInstant(siege.getLastTouched(), ZoneOffset.UTC))
+ .set(SIEGES.SIEGEPROGRESS, siege.getSiegeProgress())
+ .execute();
+
+ saveSiegePlayers(con, siege);
+ } catch (DataAccessException e) {
+ Logger.get().error("SQL Query threw an error!", e);
+ }
+ }
+
+ public static void saveSiegePlayers(Connection con, Siege siege) {
+ try {
+ transactionWrapper(con, (connection, context) -> {
+ context
+ .deleteFrom(SIEGE_PLAYERS)
+ .where(SIEGE_PLAYERS.SIEGE.equal(convertUUIDToBytes(siege.getUUID())))
+ .execute();
+
+ for (UUID uuid : siege.getAttackerPlayersIncludingOffline()) {
+ context.insertInto(SIEGE_PLAYERS, SIEGE_PLAYERS.SIEGE, SIEGE_PLAYERS.PLAYER, SIEGE_PLAYERS.TEAM)
+ .values(
+ convertUUIDToBytes(siege.getUUID()),
+ convertUUIDToBytes(uuid),
+ (byte) 0
+ )
+ .execute();
+ }
+
+ for (UUID uuid : siege.getDefenderPlayersIncludingOffline()) {
+ context.insertInto(SIEGE_PLAYERS, SIEGE_PLAYERS.SIEGE, SIEGE_PLAYERS.PLAYER, SIEGE_PLAYERS.TEAM)
+ .values(
+ convertUUIDToBytes(siege.getUUID()),
+ convertUUIDToBytes(uuid),
+ (byte) 1
+ )
+ .execute();
+ }
+ });
+ } catch (SQLException | DataAccessException e) {
+ Logger.get().error("SQL Query threw an error!", e);
+ }
+ }
+
+ // Getters
+ public static @NotNull Set loadAll() {
+ Set wars = new HashSet<>();
+
+ try (
+ Connection con = DB.getConnection();
+ ) {
+ DSLContext context = DB.getContext(con);
+
+ Result result = context.select()
+ .from(LIST)
+ .fetch();
+
+ for (Record r : result) {
+ UUID uuid = convertBytesToUUID(r.get(LIST.UUID));
+ String name = r.get(LIST.NAME);
+ String label = r.get(LIST.LABEL);
+ @Nullable Side side1 = loadSide(con, uuid, convertBytesToUUID(r.get(LIST.SIDE1)));
+ @Nullable Side side2 = loadSide(con, uuid, convertBytesToUUID(r.get(LIST.SIDE2)));
+ boolean event = r.get(LIST.EVENT, Boolean.class);
+
+ wars.add( // TODO IllegalStateException
+ new WarBuilder()
+ .setUuid(uuid)
+ .setName(name)
+ .setLabel(label)
+ .setSide1(side1)
+ .setSide2(side2)
+ .setSieges(new HashSet<>())
+ .setRaids(new HashSet<>())
+ .setEvent(event)
+ .resume()
+ );
+ }
+
+ for (War war : wars) {
+ @NotNull Set sieges = loadSieges(con, war);
+ war.setSieges(sieges);
+ }
+ } catch (SQLException | DataAccessException e) {
+ Logger.get().error("SQL Query threw an error!", e);
+ }
+
+ return wars;
+ }
+
+ @Contract("_, _, _ -> new")
+ public static @Nullable Side loadSide(Connection con, UUID warUUID, UUID uuid) {
+ try {
+ DSLContext context = DB.getContext(con);
+
+ Record r = context.select()
+ .from(SIDES)
+ .where(SIDES.WAR.equal(convertUUIDToBytes(warUUID)))
+ .and(SIDES.UUID.equal(convertUUIDToBytes(uuid)))
+ .fetchOne();
+
+ if (r == null) return null;
+
+ // Side data
+ BattleSide side = BattleSide.valueOf(r.get(SIDES.SIDE));
+ BattleTeam team = BattleTeam.valueOf(r.get(SIDES.TEAM));
+ String name = r.get(SIDES.NAME);
+ @Nullable Town town = TownyAPI.getInstance().getTown(convertBytesToUUID(r.get(SIDES.TOWN)));
+ Instant siegeGrace = r.get(SIDES.SIEGEGRACE).toInstant(ZoneOffset.UTC);
+ Instant raidGrace = r.get(SIDES.RAIDGRACE).toInstant(ZoneOffset.UTC);
+
+ // Load players
+ Set players = new HashSet<>();
+ Set playersSurrendered = new HashSet<>();
+ Result resultPlayers = context.select()
+ .from(SIDES_PLAYERS)
+ .where(SIDES_PLAYERS.SIDE.equal(convertUUIDToBytes(uuid)))
+ .fetch();
+ resultPlayers.forEach(
+ record -> {
+ if (record.get(SIDES_PLAYERS.SURRENDERED).equals((byte) 0)) {
+ players.add(convertBytesToUUID(record.get(SIDES_PLAYERS.PLAYER)));
+ } else {
+ playersSurrendered.add(convertBytesToUUID(record.get(SIDES_PLAYERS.PLAYER)));
+ }
+ }
+ );
+
+ // Load nations
+ Set nations = new HashSet<>();
+ Set nationsSurrendered = new HashSet<>();
+ Result resultNations = context.select()
+ .from(SIDES_NATIONS)
+ .where(SIDES_NATIONS.SIDE.equal(convertUUIDToBytes(uuid)))
+ .fetch();
+ resultNations.forEach(
+ record -> {
+ final UUID identifier = convertBytesToUUID(record.get(SIDES_NATIONS.NATION));
+ if (record.get(SIDES_NATIONS.SURRENDERED).equals((byte) 0)) {
+ @Nullable Nation nation = TownyAPI.getInstance().getNation(identifier);
+ if (nation != null)
+ nations.add(nation);
+ } else {
+ @Nullable Nation nation = TownyAPI.getInstance().getNation(identifier);
+ if (nation != null)
+ nationsSurrendered.add(nation);
+ }
+ }
+ );
+
+ // Load towns
+ Set towns = new HashSet<>();
+ Set townsSurrendered = new HashSet<>();
+ Result resultTowns = context.select()
+ .from(SIDES_TOWNS)
+ .where(SIDES_TOWNS.SIDE.equal(convertUUIDToBytes(uuid)))
+ .fetch();
+ resultTowns.forEach(
+ record -> {
+ final UUID identifier = convertBytesToUUID(record.get(SIDES_TOWNS.TOWN));
+ if (record.get(SIDES_TOWNS.SURRENDERED).equals((byte) 0)) {
+ @Nullable Town town2 = TownyAPI.getInstance().getTown(identifier);
+ if (town2 != null)
+ towns.add(town2);
+ } else {
+ @Nullable Town town2 = TownyAPI.getInstance().getTown(identifier);
+ if (town2 != null)
+ townsSurrendered.add(town2);
+ }
+ }
+ );
+
+ return new SideBuilder() // TODO IllegalStateException
+ .setWarUUID(warUUID)
+ .setUuid(uuid)
+ .setLeader(town)
+ .setSide(side)
+ .setTeam(team)
+ .setName(name)
+ .setTowns(towns)
+ .setNations(nations)
+ .setPlayersIncludingOffline(players)
+ .setSurrenderedTowns(townsSurrendered)
+ .setSurrenderedNations(nationsSurrendered)
+ .setSurrenderedPlayersIncludingOffline(playersSurrendered)
+ .setSiegeGrace(siegeGrace)
+ .setRaidGrace(raidGrace)
+ .buildOld();
+ } catch (SideCreationException e) {
+ Logger.get().error("SQL Query threw an error!", e);
+ }
+ return null;
+ }
+
+ public static @NotNull Set loadSieges(Connection con, War war) {
+ Set sieges = new HashSet<>();
+
+ try {
+ DSLContext context = DB.getContext(con);
+
+ Result result = context.select()
+ .from(SIEGES)
+ .where(SIEGES.WAR.equal(convertUUIDToBytes(war.getUUID())))
+ .fetch();
+
+ for (Record r : result) {
+ UUID uuid = convertBytesToUUID(r.get(SIEGES.UUID));
+ @Nullable Town town = TownyAPI.getInstance().getTown(convertBytesToUUID(r.get(SIEGES.TOWN)));
+ OfflinePlayer siegeLeader = Bukkit.getOfflinePlayer(convertBytesToUUID(r.get(SIEGES.SIEGELEADER)));
+ Instant endTime = r.get(SIEGES.ENDTIME).toInstant(ZoneOffset.UTC);
+ Instant lastTouched = r.get(SIEGES.LASTTOUCHED).toInstant(ZoneOffset.UTC);
+ int siegeProgress = r.get(SIEGES.SIEGEPROGRESS);
+ Set attackersIncludingOffline = new HashSet<>();
+ Set defendersIncludingOffline = new HashSet<>();
+
+ Result resultPlayers = context.select()
+ .from(SIEGE_PLAYERS)
+ .where(SIEGE_PLAYERS.SIEGE.equal(convertUUIDToBytes(uuid)))
+ .fetch();
+ resultPlayers.forEach(
+ record -> {
+ if (record.get(SIEGE_PLAYERS.TEAM).equals((byte) 0)) {
+ attackersIncludingOffline.add(convertBytesToUUID(record.get(SIEGE_PLAYERS.PLAYER)));
+ } else {
+ defendersIncludingOffline.add(convertBytesToUUID(record.get(SIEGE_PLAYERS.PLAYER)));
+ }
+ }
+ );
+
+ sieges.add(new Siege(
+ war,
+ uuid,
+ town,
+ siegeLeader,
+ endTime,
+ lastTouched,
+ siegeProgress,
+ attackersIncludingOffline,
+ defendersIncludingOffline
+ ));
+ }
+ } catch (DataAccessException e) {
+ Logger.get().error("SQL Query threw an error!", e);
+ }
+
+ return sieges;
+ }
+
+ // Deleters
+
+ public static void deleteWar(War war) {
+ try (
+ Connection con = DB.getConnection();
+ ) {
+ DSLContext context = DB.getContext(con);
+
+ context
+ .deleteFrom(LIST)
+ .where(LIST.UUID.equal(convertUUIDToBytes(war.getUUID())))
+ .execute();
+ } catch (SQLException | DataAccessException e) {
+ Logger.get().error("SQL Query threw an error!", e);
+ }
+ }
+
+ public static void deleteSiege(Siege siege) {
+ try (
+ Connection con = DB.getConnection();
+ ) {
+ DSLContext context = DB.getContext(con);
+
+ context
+ .deleteFrom(SIEGES)
+ .where(SIEGES.UUID.equal(convertUUIDToBytes(siege.getUUID())))
+ .execute();
+ } catch (SQLException | DataAccessException e) {
+ Logger.get().error("SQL Query threw an error!", e);
+ }
+ }
+}
diff --git a/src/main/java/com/github/alathra/AlathranWars/db/DatabaseType.java b/src/main/java/com/github/alathra/AlathranWars/db/DatabaseType.java
new file mode 100644
index 0000000..5bcb089
--- /dev/null
+++ b/src/main/java/com/github/alathra/AlathranWars/db/DatabaseType.java
@@ -0,0 +1,287 @@
+package com.github.alathra.AlathranWars.db;
+
+import com.mysql.cj.jdbc.MysqlDataSource;
+import org.h2.jdbcx.JdbcDataSource;
+import org.hsqldb.jdbc.JDBCDataSource;
+import org.jetbrains.annotations.Nullable;
+import org.jooq.SQLDialect;
+import org.mariadb.jdbc.MariaDbDataSource;
+
+import java.util.List;
+import java.util.Map;
+
+/**
+ * Enum containing information for handling different Database types.
+ */
+public enum DatabaseType {
+ /**
+ * HSQLDB database type.
+ */
+ HSQLDB("HSQLDB", org.hsqldb.jdbcDriver.class.getName(), JDBCDataSource.class.getName(), "hsqldb", ';', ';'),
+ /**
+ * H2 Database Engine database type.
+ */
+ H2("H2", org.h2.Driver.class.getName(), JdbcDataSource.class.getName(), "h2", ';', ';'),
+ /**
+ * MySQL database type.
+ */
+ MYSQL("MySQL", com.mysql.jdbc.Driver.class.getName(), MysqlDataSource.class.getName(), "mysql", '?', '&'),
+ /**
+ * MariaDB database type.
+ */
+ MARIADB("MariaDB", org.mariadb.jdbc.Driver.class.getName(), MariaDbDataSource.class.getName(), "mariadb", '?', '&'),
+ ;
+
+ private final String driverName;
+ private final String driverClassName;
+ private final String dataSourceClassName;
+ private final String jdbcPrefix;
+ private final char jdbcPropertyPrefix;
+ private final char jdbcPropertySeparator;
+
+ DatabaseType(String driverName, String driverClassName, String dataSourceClassName, String jdbcPrefix, char jdbcPropertyPrefix, char jdbcPropertySeparator) {
+ this.driverName = driverName;
+ this.driverClassName = driverClassName;
+ this.dataSourceClassName = dataSourceClassName;
+ this.jdbcPrefix = jdbcPrefix;
+ this.jdbcPropertyPrefix = jdbcPropertyPrefix;
+ this.jdbcPropertySeparator = jdbcPropertySeparator;
+ }
+
+ /**
+ * Gets driver name.
+ *
+ * @return the driver name
+ */
+ public String getDriverName() {
+ return driverName;
+ }
+
+ /**
+ * Gets driver class name.
+ *
+ * @return the driver class name
+ */
+ public String getDriverClassName() {
+ return driverClassName;
+ }
+
+ /**
+ * Gets data source class name.
+ *
+ * @return the data source class name
+ */
+ public String getDataSourceClassName() {
+ return dataSourceClassName;
+ }
+
+ /**
+ * Gets the jdbc prefix.
+ *
+ * @return the jdbc prefix like mysql or mariadb
+ */
+ public String getJdbcPrefix() {
+ return jdbcPrefix;
+ }
+
+ /**
+ * Gets the jdbc property prefix.
+ *
+ * @return the jdbc property prefix like {@literal ;} or {@literal ?}
+ */
+ public char getJdbcPropertyPrefix() {
+ return jdbcPropertyPrefix;
+ }
+
+ /**
+ * Gets the jdbc property separator.
+ *
+ * @return the jdbc property separator like {@literal ;} or {@literal &}
+ */
+ public char getJdbcPropertySeparator() {
+ return jdbcPropertySeparator;
+ }
+
+ /**
+ * Format a map of connection properties into a valid jdbc connection properties string.
+ *
+ * @param properties the properties
+ * @return the string
+ */
+ public String formatJdbcConnectionProperties(Map properties) {
+ if (properties.isEmpty()) return "";
+
+ List connectionProperties = properties.entrySet().stream()
+ .map(map -> "%s=%s".formatted(map.getKey(), map.getValue()))
+ .toList();
+
+ return jdbcPropertyPrefix + String.join(Character.toString(jdbcPropertySeparator), connectionProperties);
+ }
+
+
+ /**
+ * Gets database type from jdbc prefix.
+ *
+ * @param prefix the prefix
+ * @return the database type or null
+ */
+ @Nullable
+ public static DatabaseType getDatabaseTypeFromJdbcPrefix(String prefix) {
+ for (DatabaseType type : DatabaseType.values()) {
+ if (type.equals(prefix.toLowerCase())) {
+ return type;
+ };
+ }
+
+ return null;
+ }
+
+ @Override
+ public String toString() {
+ return getDriverName();
+ }
+
+ /**
+ * Check if this DatabaseType is equal to another.
+ *
+ * @param DatabaseType the database type
+ * @return boolean
+ */
+ public boolean equals(DatabaseType DatabaseType) {
+ return this.equals(DatabaseType.getDriverName());
+ }
+
+ /**
+ * Check if this DatabaseType is equal to another.
+ *
+ * @param databaseTypeName the database type name
+ * @return boolean
+ */
+ public boolean equals(String databaseTypeName) {
+ return this.getDriverName().equalsIgnoreCase(databaseTypeName);
+ }
+
+ /**
+ * Gets sql dialect for this DatabaseType.
+ *
+ * @return the sql dialect
+ */
+ public SQLDialect getSQLDialect() {
+ return switch (this) {
+ case HSQLDB -> SQLDialect.HSQLDB;
+ case H2 -> SQLDialect.H2;
+ case MYSQL -> SQLDialect.MYSQL;
+ case MARIADB -> SQLDialect.MARIADB;
+ };
+ }
+
+ /**
+ * Gets column suffix for this DatabaseType.
+ *
+ * @return the column suffix
+ */
+ public String getColumnSuffix() {
+ return switch (this) {
+ case HSQLDB -> "";
+ case H2, MARIADB, MYSQL -> " VIRTUAL";
+ };
+ }
+
+ /**
+ * Gets table defaults for this DatabaseType.
+ *
+ * @return the table defaults
+ */
+ public String getTableDefaults() {
+ return switch (this) {
+ case H2, HSQLDB -> "";
+ case MARIADB, MYSQL -> " CHARACTER SET utf8mb4 COLLATE utf8mb4_bin";
+ };
+ }
+
+ /**
+ * Gets uuid type for this DatabaseType.
+ *
+ * @return the uuid type
+ */
+ public String getUuidType() {
+ return switch (this) {
+ case HSQLDB -> "UUID";
+ case H2, MARIADB, MYSQL -> "BINARY(16)";
+ };
+ }
+
+ /**
+ * Gets inet type for this DatabaseType.
+ *
+ * @return the inet type
+ */
+ public String getInetType() {
+ return "VARBINARY(16)";
+ }
+
+ /**
+ * Gets binary type for this DatabaseType.
+ *
+ * @return the binary type
+ */
+ public String getBinaryType() {
+ return "BLOB";
+ }
+
+ /**
+ * Gets alter view statement for this DatabaseType.
+ *
+ * @return the alter view statement
+ */
+ public String getAlterViewStatement() {
+ return switch (this) {
+ case H2, HSQLDB, MYSQL, MARIADB -> "ALTER VIEW";
+ };
+ }
+
+ /**
+ * Gets connection init sql for this DatabaseType.
+ *
+ * @return the connection init sql
+ */
+ public String getConnectionInitSql() {
+ return switch (this) {
+ case HSQLDB -> "SET DATABASE TRANSACTION CONTROL MVLOCKS;";
+ case MARIADB -> "SET NAMES utf8mb4 COLLATE utf8mb4_bin; " + setSqlModes(
+ // MariaDB defaults
+ "STRICT_TRANS_TABLES",
+ "ERROR_FOR_DIVISION_BY_ZERO",
+ "NO_AUTO_CREATE_USER",
+ "NO_ENGINE_SUBSTITUTION",
+ // ANSI SQL Compliance
+ "ANSI",
+ "NO_BACKSLASH_ESCAPES",
+ "SIMULTANEOUS_ASSIGNMENT", // MDEV-13417
+ "NO_ZERO_IN_DATE",
+ "NO_ZERO_DATE");
+ case H2 -> "";
+ case MYSQL -> "SET NAMES utf8mb4 COLLATE utf8mb4_bin; " + setSqlModes(
+ // MySQL defaults
+ "STRICT_TRANS_TABLES",
+ "ERROR_FOR_DIVISION_BY_ZERO",
+ "NO_ENGINE_SUBSTITUTION",
+ // ANSI SQL Compliance
+ "ANSI",
+ "NO_BACKSLASH_ESCAPES",
+ "NO_ZERO_IN_DATE",
+ "NO_ZERO_DATE");
+ };
+ }
+
+ /**
+ * Generates a concatenated SQL query from the specified parameters.
+ *
+ * @param sqlModes database parameters
+ * @return string
+ */
+ private static String setSqlModes(String... sqlModes) {
+ final String modes = String.join(",", sqlModes);
+ return "SET @@SQL_MODE = CONCAT(@@SQL_MODE, '," + modes + "')";
+ }
+}
\ No newline at end of file
diff --git a/src/main/java/com/github/alathra/AlathranWars/db/flyway/DatabaseMigrationException.java b/src/main/java/com/github/alathra/AlathranWars/db/flyway/DatabaseMigrationException.java
new file mode 100644
index 0000000..0d85975
--- /dev/null
+++ b/src/main/java/com/github/alathra/AlathranWars/db/flyway/DatabaseMigrationException.java
@@ -0,0 +1,7 @@
+package com.github.alathra.AlathranWars.db.flyway;
+
+public class DatabaseMigrationException extends Exception {
+ public DatabaseMigrationException(Throwable t) {
+ super(t);
+ }
+}
diff --git a/src/main/java/com/github/alathra/AlathranWars/db/flyway/DatabaseMigrationHandler.java b/src/main/java/com/github/alathra/AlathranWars/db/flyway/DatabaseMigrationHandler.java
new file mode 100644
index 0000000..fa75f68
--- /dev/null
+++ b/src/main/java/com/github/alathra/AlathranWars/db/flyway/DatabaseMigrationHandler.java
@@ -0,0 +1,101 @@
+package com.github.alathra.AlathranWars.db.flyway;
+
+import com.github.alathra.AlathranWars.db.DatabaseType;
+import com.github.milkdrinkers.Crate.Config;
+import org.flywaydb.core.Flyway;
+import org.flywaydb.core.api.ClassProvider;
+import org.flywaydb.core.api.FlywayException;
+import org.flywaydb.core.api.migration.JavaMigration;
+
+import javax.sql.DataSource;
+import java.util.List;
+import java.util.Map;
+
+/**
+ * Handles Flyway migrations.
+ */
+public class DatabaseMigrationHandler {
+ // List of Java migrations
+ private final List> migrations = List.of(
+ );
+
+ private final Config config;
+ private final DataSource dataSource;
+ private final DatabaseType databaseType;
+ private Flyway flyway;
+
+ /**
+ * Instantiates a new Database migration handler.
+ *
+ * @param config the config
+ * @param dataSource the data source
+ * @param databaseType the database type
+ */
+ public DatabaseMigrationHandler(Config config, DataSource dataSource, DatabaseType databaseType) {
+ this.config = config;
+ this.dataSource = dataSource;
+ this.databaseType = databaseType;
+ initializeFlywayInstance();
+ }
+
+ private void initializeFlywayInstance() {
+ final ClassProvider javaMigrationClassProvider = new FlywayMigrationsProvider(migrations);
+ final String SQL_TABLE_PREFIX = config.getOrDefault("db.prefix", "example_");
+ final Map SQL_PLACEHOLDERS = Map.of(
+ "tablePrefix", SQL_TABLE_PREFIX,
+ "columnSuffix", databaseType.getColumnSuffix(),
+ "tableDefaults", databaseType.getTableDefaults(),
+ "uuidType", databaseType.getUuidType(),
+ "inetType", databaseType.getInetType(),
+ "binaryType", databaseType.getBinaryType(),
+ "alterViewStatement", databaseType.getAlterViewStatement()
+ );
+
+ this.flyway = Flyway
+ .configure(getClass().getClassLoader())
+ .baselineOnMigrate(true)
+ .baselineVersion("0.0")
+ .validateMigrationNaming(true)
+ .javaMigrationClassProvider(javaMigrationClassProvider)
+ .dataSource(dataSource)
+ .locations(
+ "classpath:database-migrations",
+ "db/migration"
+ )
+ .table(SQL_TABLE_PREFIX + "schema_history") // Configure tables and migrations
+ .placeholders(SQL_PLACEHOLDERS)
+ .load();
+ }
+
+ /**
+ * Execute Flyway migration. All pending migrations will be applied in order.
+ *
+ * @throws DatabaseMigrationException database migration exception
+ */
+ public void migrate() throws DatabaseMigrationException {
+ try {
+ this.flyway.migrate();
+ } catch (FlywayException e) {
+ throw new DatabaseMigrationException(e);
+ }
+ }
+
+ /**
+ * Executes Flyway repair. Repairs the Flyway schema history table. This will perform the following actions:
+ *
+ *
+ * - Remove any failed migrations on databases without DDL transactions (User objects left behind must still be cleaned up manually)
+ * - Realign the checksums, descriptions and types of the applied migration
+ *
+ *
+ * @throws DatabaseMigrationException database migration exception
+ */
+ public void repair() throws DatabaseMigrationException {
+ try {
+ if (config.getOrDefault("db.repair", false))
+ this.flyway.repair();
+ } catch (FlywayException e) {
+ throw new DatabaseMigrationException(e);
+ }
+ }
+}
diff --git a/src/main/java/com/github/alathra/AlathranWars/db/flyway/FlywayMigrationsProvider.java b/src/main/java/com/github/alathra/AlathranWars/db/flyway/FlywayMigrationsProvider.java
new file mode 100644
index 0000000..1a4d4f3
--- /dev/null
+++ b/src/main/java/com/github/alathra/AlathranWars/db/flyway/FlywayMigrationsProvider.java
@@ -0,0 +1,20 @@
+package com.github.alathra.AlathranWars.db.flyway;
+
+import org.flywaydb.core.api.ClassProvider;
+import org.flywaydb.core.api.migration.JavaMigration;
+
+import java.util.Collection;
+import java.util.List;
+
+public record FlywayMigrationsProvider(
+ List> migrations
+) implements ClassProvider {
+ public FlywayMigrationsProvider(List> migrations) {
+ this.migrations = List.copyOf(migrations);
+ }
+
+ @Override
+ public Collection> getClasses() {
+ return migrations;
+ }
+}
diff --git a/src/main/java/com/github/alathra/AlathranWars/db/flyway/migration/V3__Example.java b/src/main/java/com/github/alathra/AlathranWars/db/flyway/migration/V3__Example.java
new file mode 100644
index 0000000..01409ec
--- /dev/null
+++ b/src/main/java/com/github/alathra/AlathranWars/db/flyway/migration/V3__Example.java
@@ -0,0 +1,22 @@
+package com.github.alathra.AlathranWars.db.flyway.migration;
+
+import org.flywaydb.core.api.migration.BaseJavaMigration;
+import org.flywaydb.core.api.migration.Context;
+
+public class V3__Example extends BaseJavaMigration {
+ @Override
+ public void migrate(Context flywayContext) throws Exception {
+ /*try {
+ final DSLContext context = DB.getContext(flywayContext.getConnection());
+
+ context.alterTable(TEST).addColumn(field(name("meme"), VARCHAR)).execute();
+
+ context
+ .alterTableIfExists(TEST)
+ .addColumnIfNotExists(field(name("column_name"), VARCHAR(32).notNull()*//*.defaultValue("default")*//*))
+ .execute();
+ } catch (Exception e) {
+ Logger.get().error(e.getMessage());
+ }*/
+ }
+}
diff --git a/src/main/java/com/github/alathra/AlathranWars/db/jooq/JooqContext.java b/src/main/java/com/github/alathra/AlathranWars/db/jooq/JooqContext.java
new file mode 100644
index 0000000..380a4ef
--- /dev/null
+++ b/src/main/java/com/github/alathra/AlathranWars/db/jooq/JooqContext.java
@@ -0,0 +1,92 @@
+package com.github.alathra.AlathranWars.db.jooq;
+
+import com.github.alathra.AlathranWars.utility.Cfg;
+import org.jooq.*;
+import org.jooq.conf.*;
+import org.jooq.exception.DataAccessException;
+import org.jooq.impl.DefaultConfiguration;
+import org.jooq.tools.JooqLogger;
+
+import java.sql.Connection;
+import java.util.regex.Pattern;
+
+/**
+ * Utility class for getting jOOQ Context to use with HikariCP.
+ */
+public final class JooqContext {
+ static {
+ JooqLogger.globalThreshold(Log.Level.ERROR); // Silence JOOQ warnings
+ }
+
+ private static final String TABLE_PREFIX = Cfg.get().getOrDefault("db.prefix", "example_"); // The table prefix as grabbed from config
+ private static final Pattern MATCH_ALL_EXCEPT_INFORMATION_SCHEMA = Pattern.compile("^(?!INFORMATION_SCHEMA)(.*?)$");
+ private static final Pattern MATCH_ALL = Pattern.compile("^(.*?)$");
+ private static final String REPLACEMENT = "%s$0".formatted(TABLE_PREFIX); //
+ private final SQLDialect dialect;
+
+ /**
+ * Instantiates a new Jooq context.
+ *
+ * @param dialect the getSQLDialect
+ */
+ public JooqContext(SQLDialect dialect) {
+ this.dialect = dialect;
+ }
+
+ /**
+ * Create DSL Context.
+ *
+ * @param connection the connection
+ * @return the dsl context
+ */
+ public DSLContext createContext(Connection connection) {
+ record SimpleConnectionProvider(Connection connection) implements ConnectionProvider {
+
+ @Override
+ public Connection acquire() throws DataAccessException {
+ return connection;
+ }
+
+ @Override
+ public void release(Connection connection) throws DataAccessException {}
+ }
+ return createWith(new SimpleConnectionProvider(connection));
+ }
+
+ /**
+ * Applies default configuration
+ *
+ * @param connectionProvider A connection lifecycle handler API.
+ * @return DSLContext
+ */
+ private DSLContext createWith(ConnectionProvider connectionProvider) {
+ return new DefaultConfiguration()
+ .set(connectionProvider)
+ .set(dialect)
+ .set(createSettings())
+ .set(new ExecuteListenerProvider[0])
+ .dsl();
+ }
+
+ /**
+ * Returns base settings for DSL Contexts.
+ *
+ * @return Settings
+ */
+ private Settings createSettings() {
+ return new Settings()
+ .withBackslashEscaping(BackslashEscaping.OFF)
+ .withRenderSchema(false)
+ .withRenderMapping(new RenderMapping() // Support the tables having custom prefix
+ .withSchemata(new MappedSchema()
+ .withInputExpression(MATCH_ALL_EXCEPT_INFORMATION_SCHEMA)
+ .withTables(new MappedTable()
+ .withInputExpression(MATCH_ALL)
+ .withOutput(REPLACEMENT)
+ )
+ )
+ )
+ .withRenderQuotedNames(RenderQuotedNames.ALWAYS)
+ .withRenderNameCase(RenderNameCase.LOWER);
+ }
+}
\ No newline at end of file
diff --git a/src/main/java/com/github/alathra/AlathranWars/enums/BattleTeam.java b/src/main/java/com/github/alathra/AlathranWars/enums/BattleTeam.java
deleted file mode 100644
index 1843b15..0000000
--- a/src/main/java/com/github/alathra/AlathranWars/enums/BattleTeam.java
+++ /dev/null
@@ -1,6 +0,0 @@
-package com.github.alathra.AlathranWars.enums;
-
-public enum BattleTeam {
- SIDE_1,
- SIDE_2,
-}
diff --git a/src/main/java/com/github/alathra/AlathranWars/enums/WarDeleteReason.java b/src/main/java/com/github/alathra/AlathranWars/enums/WarDeleteReason.java
new file mode 100644
index 0000000..b75d557
--- /dev/null
+++ b/src/main/java/com/github/alathra/AlathranWars/enums/WarDeleteReason.java
@@ -0,0 +1,6 @@
+package com.github.alathra.AlathranWars.enums;
+
+public enum WarDeleteReason {
+ DRAW,
+ DEFEAT,
+}
diff --git a/src/main/java/com/github/alathra/AlathranWars/enums/BattleSide.java b/src/main/java/com/github/alathra/AlathranWars/enums/battle/BattleSide.java
similarity index 56%
rename from src/main/java/com/github/alathra/AlathranWars/enums/BattleSide.java
rename to src/main/java/com/github/alathra/AlathranWars/enums/battle/BattleSide.java
index c7d6b62..4f6710b 100644
--- a/src/main/java/com/github/alathra/AlathranWars/enums/BattleSide.java
+++ b/src/main/java/com/github/alathra/AlathranWars/enums/battle/BattleSide.java
@@ -1,4 +1,4 @@
-package com.github.alathra.AlathranWars.enums;
+package com.github.alathra.AlathranWars.enums.battle;
public enum BattleSide {
ATTACKER,
diff --git a/src/main/java/com/github/alathra/AlathranWars/enums/battle/BattleTeam.java b/src/main/java/com/github/alathra/AlathranWars/enums/battle/BattleTeam.java
new file mode 100644
index 0000000..d40e3f1
--- /dev/null
+++ b/src/main/java/com/github/alathra/AlathranWars/enums/battle/BattleTeam.java
@@ -0,0 +1,6 @@
+package com.github.alathra.AlathranWars.enums.battle;
+
+public enum BattleTeam {
+ SIDE_1,
+ SIDE_2,
+}
diff --git a/src/main/java/com/github/alathra/AlathranWars/enums/battle/BattleType.java b/src/main/java/com/github/alathra/AlathranWars/enums/battle/BattleType.java
new file mode 100644
index 0000000..e9ce508
--- /dev/null
+++ b/src/main/java/com/github/alathra/AlathranWars/enums/battle/BattleType.java
@@ -0,0 +1,6 @@
+package com.github.alathra.AlathranWars.enums.battle;
+
+public enum BattleType {
+ SIEGE,
+ RAID,
+}
diff --git a/src/main/java/com/github/alathra/AlathranWars/enums/battle/BattleVictor.java b/src/main/java/com/github/alathra/AlathranWars/enums/battle/BattleVictor.java
new file mode 100644
index 0000000..85364d2
--- /dev/null
+++ b/src/main/java/com/github/alathra/AlathranWars/enums/battle/BattleVictor.java
@@ -0,0 +1,7 @@
+package com.github.alathra.AlathranWars.enums.battle;
+
+public enum BattleVictor {
+ ATTACKER,
+ DEFENDER,
+ DRAW,
+}
diff --git a/src/main/java/com/github/alathra/AlathranWars/enums/battle/BattleVictoryReason.java b/src/main/java/com/github/alathra/AlathranWars/enums/battle/BattleVictoryReason.java
new file mode 100644
index 0000000..c20cb00
--- /dev/null
+++ b/src/main/java/com/github/alathra/AlathranWars/enums/battle/BattleVictoryReason.java
@@ -0,0 +1,8 @@
+package com.github.alathra.AlathranWars.enums.battle;
+
+public enum BattleVictoryReason {
+ OPPONENT_LOST,
+ OPPONENT_RETREAT,
+ ADMIN_COMMAND,
+ ADMIN_CANCEL,
+}
diff --git a/src/main/java/com/github/alathra/AlathranWars/events/PreWarCreateEvent.java b/src/main/java/com/github/alathra/AlathranWars/events/PreWarCreateEvent.java
index 615524e..ba54cdf 100644
--- a/src/main/java/com/github/alathra/AlathranWars/events/PreWarCreateEvent.java
+++ b/src/main/java/com/github/alathra/AlathranWars/events/PreWarCreateEvent.java
@@ -1,5 +1,6 @@
package com.github.alathra.AlathranWars.events;
+import com.github.alathra.AlathranWars.conflict.War;
import org.bukkit.event.Cancellable;
import org.bukkit.event.Event;
import org.bukkit.event.HandlerList;
@@ -8,6 +9,11 @@ import org.jetbrains.annotations.NotNull;
public class PreWarCreateEvent extends Event implements Cancellable {
private static final HandlerList HANDLER_LIST = new HandlerList();
private boolean cancelled;
+ private War war;
+
+ public PreWarCreateEvent(War war) {
+ this.war = war;
+ }
/**
* Gets the cancellation state of this event. A cancelled event will not
@@ -35,4 +41,12 @@ public class PreWarCreateEvent extends Event implements Cancellable {
public @NotNull HandlerList getHandlers() {
return HANDLER_LIST;
}
+
+ public static HandlerList getHandlerList() {
+ return HANDLER_LIST;
+ }
+
+ public War getWar() {
+ return war;
+ }
}
diff --git a/src/main/java/com/github/alathra/AlathranWars/events/PreWarDeleteEvent.java b/src/main/java/com/github/alathra/AlathranWars/events/PreWarDeleteEvent.java
index c954f7b..143df21 100644
--- a/src/main/java/com/github/alathra/AlathranWars/events/PreWarDeleteEvent.java
+++ b/src/main/java/com/github/alathra/AlathranWars/events/PreWarDeleteEvent.java
@@ -1,5 +1,7 @@
package com.github.alathra.AlathranWars.events;
+import com.github.alathra.AlathranWars.conflict.War;
+import com.github.alathra.AlathranWars.enums.WarDeleteReason;
import org.bukkit.event.Cancellable;
import org.bukkit.event.Event;
import org.bukkit.event.HandlerList;
@@ -8,6 +10,13 @@ import org.jetbrains.annotations.NotNull;
public class PreWarDeleteEvent extends Event implements Cancellable {
private static final HandlerList HANDLER_LIST = new HandlerList();
private boolean cancelled;
+ private War war;
+ private WarDeleteReason reason;
+
+ public PreWarDeleteEvent(War war, WarDeleteReason reason) {
+ this.war = war;
+ this.reason = reason;
+ }
/**
* Gets the cancellation state of this event. A cancelled event will not
@@ -35,4 +44,16 @@ public class PreWarDeleteEvent extends Event implements Cancellable {
public @NotNull HandlerList getHandlers() {
return HANDLER_LIST;
}
+
+ public static HandlerList getHandlerList() {
+ return HANDLER_LIST;
+ }
+
+ public War getWar() {
+ return war;
+ }
+
+ public WarDeleteReason getReason() {
+ return reason;
+ }
}
diff --git a/src/main/java/com/github/alathra/AlathranWars/events/WarCreateEvent.java b/src/main/java/com/github/alathra/AlathranWars/events/WarCreateEvent.java
index 5be9040..667367d 100644
--- a/src/main/java/com/github/alathra/AlathranWars/events/WarCreateEvent.java
+++ b/src/main/java/com/github/alathra/AlathranWars/events/WarCreateEvent.java
@@ -1,38 +1,28 @@
package com.github.alathra.AlathranWars.events;
-import org.bukkit.event.Cancellable;
+import com.github.alathra.AlathranWars.conflict.War;
import org.bukkit.event.Event;
import org.bukkit.event.HandlerList;
import org.jetbrains.annotations.NotNull;
-public class WarCreateEvent extends Event implements Cancellable {
+public class WarCreateEvent extends Event {
private static final HandlerList HANDLER_LIST = new HandlerList();
- private boolean cancelled;
+ private War war;
- /**
- * Gets the cancellation state of this event. A cancelled event will not
- * be executed in the server, but will still pass to other plugins
- *
- * @return true if this event is cancelled
- */
- @Override
- public boolean isCancelled() {
- return this.cancelled;
- }
-
- /**
- * Sets the cancellation state of this event. A cancelled event will not
- * be executed in the server, but will still pass to other plugins.
- *
- * @param cancelled true if you wish to cancel this event
- */
- @Override
- public void setCancelled(boolean cancelled) {
- this.cancelled = cancelled;
+ public WarCreateEvent(War war) {
+ this.war = war;
}
@Override
public @NotNull HandlerList getHandlers() {
return HANDLER_LIST;
}
+
+ public static HandlerList getHandlerList() {
+ return HANDLER_LIST;
+ }
+
+ public War getWar() {
+ return war;
+ }
}
diff --git a/src/main/java/com/github/alathra/AlathranWars/events/WarDeleteEvent.java b/src/main/java/com/github/alathra/AlathranWars/events/WarDeleteEvent.java
index 37a21b7..31f8098 100644
--- a/src/main/java/com/github/alathra/AlathranWars/events/WarDeleteEvent.java
+++ b/src/main/java/com/github/alathra/AlathranWars/events/WarDeleteEvent.java
@@ -1,38 +1,35 @@
package com.github.alathra.AlathranWars.events;
-import org.bukkit.event.Cancellable;
+import com.github.alathra.AlathranWars.conflict.War;
+import com.github.alathra.AlathranWars.enums.WarDeleteReason;
import org.bukkit.event.Event;
import org.bukkit.event.HandlerList;
import org.jetbrains.annotations.NotNull;
-public class WarDeleteEvent extends Event implements Cancellable {
+public class WarDeleteEvent extends Event {
private static final HandlerList HANDLER_LIST = new HandlerList();
- private boolean cancelled;
+ private War war;
+ private WarDeleteReason reason;
- /**
- * Gets the cancellation state of this event. A cancelled event will not
- * be executed in the server, but will still pass to other plugins
- *
- * @return true if this event is cancelled
- */
- @Override
- public boolean isCancelled() {
- return this.cancelled;
- }
-
- /**
- * Sets the cancellation state of this event. A cancelled event will not
- * be executed in the server, but will still pass to other plugins.
- *
- * @param cancelled true if you wish to cancel this event
- */
- @Override
- public void setCancelled(boolean cancelled) {
- this.cancelled = cancelled;
+ public WarDeleteEvent(War war, WarDeleteReason reason) {
+ this.war = war;
+ this.reason = reason;
}
@Override
public @NotNull HandlerList getHandlers() {
return HANDLER_LIST;
}
+
+ public static HandlerList getHandlerList() {
+ return HANDLER_LIST;
+ }
+
+ public War getWar() {
+ return war;
+ }
+
+ public WarDeleteReason getReason() {
+ return reason;
+ }
}
diff --git a/src/main/java/com/github/alathra/AlathranWars/events/battle/BattleResultEvent.java b/src/main/java/com/github/alathra/AlathranWars/events/battle/BattleResultEvent.java
new file mode 100644
index 0000000..d2b12b6
--- /dev/null
+++ b/src/main/java/com/github/alathra/AlathranWars/events/battle/BattleResultEvent.java
@@ -0,0 +1,49 @@
+package com.github.alathra.AlathranWars.events.battle;
+
+import com.github.alathra.AlathranWars.conflict.War;
+import com.github.alathra.AlathranWars.conflict.battle.Battle;
+import com.github.alathra.AlathranWars.enums.battle.BattleVictor;
+import com.github.alathra.AlathranWars.enums.battle.BattleVictoryReason;
+import org.bukkit.event.Event;
+import org.bukkit.event.HandlerList;
+import org.jetbrains.annotations.NotNull;
+
+public class BattleResultEvent extends Event {
+ private static final HandlerList HANDLER_LIST = new HandlerList();
+ private final War war;
+ private final Battle battle;
+ private final BattleVictor battleVictor;
+ private final BattleVictoryReason battleVictoryReason;
+
+ public BattleResultEvent(War war, Battle battle, BattleVictor battleVictor, BattleVictoryReason battleVictoryReason) {
+ this.war = war;
+ this.battle = battle;
+ this.battleVictor = battleVictor;
+ this.battleVictoryReason = battleVictoryReason;
+ }
+
+ @Override
+ public @NotNull HandlerList getHandlers() {
+ return HANDLER_LIST;
+ }
+
+ public static HandlerList getHandlerList() {
+ return HANDLER_LIST;
+ }
+
+ public War getWar() {
+ return war;
+ }
+
+ public Battle getBattle() {
+ return battle;
+ }
+
+ public BattleVictor getBattleVictor() {
+ return battleVictor;
+ }
+
+ public BattleVictoryReason getBattleVictoryReason() {
+ return battleVictoryReason;
+ }
+}
diff --git a/src/main/java/com/github/alathra/AlathranWars/events/battle/BattleStartEvent.java b/src/main/java/com/github/alathra/AlathranWars/events/battle/BattleStartEvent.java
new file mode 100644
index 0000000..a977369
--- /dev/null
+++ b/src/main/java/com/github/alathra/AlathranWars/events/battle/BattleStartEvent.java
@@ -0,0 +1,35 @@
+package com.github.alathra.AlathranWars.events.battle;
+
+import com.github.alathra.AlathranWars.conflict.War;
+import com.github.alathra.AlathranWars.conflict.battle.Battle;
+import org.bukkit.event.Event;
+import org.bukkit.event.HandlerList;
+import org.jetbrains.annotations.NotNull;
+
+public class BattleStartEvent extends Event {
+ private static final HandlerList HANDLER_LIST = new HandlerList();
+ private final War war;
+ private final Battle battle;
+
+ public BattleStartEvent(War war, Battle battle) {
+ this.war = war;
+ this.battle = battle;
+ }
+
+ @Override
+ public @NotNull HandlerList getHandlers() {
+ return HANDLER_LIST;
+ }
+
+ public static HandlerList getHandlerList() {
+ return HANDLER_LIST;
+ }
+
+ public War getWar() {
+ return war;
+ }
+
+ public Battle getBattle() {
+ return battle;
+ }
+}
diff --git a/src/main/java/com/github/alathra/AlathranWars/events/battle/PreBattleResultEvent.java b/src/main/java/com/github/alathra/AlathranWars/events/battle/PreBattleResultEvent.java
new file mode 100644
index 0000000..2cf76b2
--- /dev/null
+++ b/src/main/java/com/github/alathra/AlathranWars/events/battle/PreBattleResultEvent.java
@@ -0,0 +1,80 @@
+package com.github.alathra.AlathranWars.events.battle;
+
+import com.github.alathra.AlathranWars.conflict.War;
+import com.github.alathra.AlathranWars.conflict.battle.Battle;
+import com.github.alathra.AlathranWars.enums.battle.BattleType;
+import com.github.alathra.AlathranWars.enums.battle.BattleVictor;
+import com.github.alathra.AlathranWars.enums.battle.BattleVictoryReason;
+import org.bukkit.event.Cancellable;
+import org.bukkit.event.Event;
+import org.bukkit.event.HandlerList;
+import org.jetbrains.annotations.NotNull;
+
+public class PreBattleResultEvent extends Event implements Cancellable {
+ private static final HandlerList HANDLER_LIST = new HandlerList();
+ private boolean cancelled;
+ private War war;
+ private final Battle battle;
+ private final BattleType battleType;
+ private final BattleVictor battleVictor;
+ private final BattleVictoryReason battleVictoryReason;
+
+ public PreBattleResultEvent(War war, Battle battle, BattleType battleType, BattleVictor battleVictor, BattleVictoryReason battleVictoryReason) {
+ this.war = war;
+ this.battle = battle;
+ this.battleType = battleType;
+ this.battleVictor = battleVictor;
+ this.battleVictoryReason = battleVictoryReason;
+ }
+
+ /**
+ * Gets the cancellation state of this event. A cancelled event will not
+ * be executed in the server, but will still pass to other plugins
+ *
+ * @return true if this event is cancelled
+ */
+ @Override
+ public boolean isCancelled() {
+ return this.cancelled;
+ }
+
+ /**
+ * Sets the cancellation state of this event. A cancelled event will not
+ * be executed in the server, but will still pass to other plugins.
+ *
+ * @param cancelled true if you wish to cancel this event
+ */
+ @Override
+ public void setCancelled(boolean cancelled) {
+ this.cancelled = cancelled;
+ }
+
+ @Override
+ public @NotNull HandlerList getHandlers() {
+ return HANDLER_LIST;
+ }
+
+ public static HandlerList getHandlerList() {
+ return HANDLER_LIST;
+ }
+
+ public War getWar() {
+ return war;
+ }
+
+ public Battle getBattle() {
+ return battle;
+ }
+
+ public BattleType getBattleType() {
+ return battleType;
+ }
+
+ public BattleVictor getBattleVictor() {
+ return battleVictor;
+ }
+
+ public BattleVictoryReason getBattleVictoryReason() {
+ return battleVictoryReason;
+ }
+}
diff --git a/src/main/java/com/github/alathra/AlathranWars/events/battle/PreBattleStartEvent.java b/src/main/java/com/github/alathra/AlathranWars/events/battle/PreBattleStartEvent.java
new file mode 100644
index 0000000..43d3218
--- /dev/null
+++ b/src/main/java/com/github/alathra/AlathranWars/events/battle/PreBattleStartEvent.java
@@ -0,0 +1,66 @@
+package com.github.alathra.AlathranWars.events.battle;
+
+import com.github.alathra.AlathranWars.conflict.War;
+import com.github.alathra.AlathranWars.conflict.battle.Battle;
+import com.github.alathra.AlathranWars.enums.battle.BattleType;
+import org.bukkit.event.Cancellable;
+import org.bukkit.event.Event;
+import org.bukkit.event.HandlerList;
+import org.jetbrains.annotations.NotNull;
+
+public class PreBattleStartEvent extends Event implements Cancellable {
+ private static final HandlerList HANDLER_LIST = new HandlerList();
+ private boolean cancelled;
+ private War war;
+ private final Battle battle;
+ private final BattleType battleType;
+
+ public PreBattleStartEvent(War war, Battle battle, BattleType battleType) {
+ this.war = war;
+ this.battle = battle;
+ this.battleType = battleType;
+ }
+
+ /**
+ * Gets the cancellation state of this event. A cancelled event will not
+ * be executed in the server, but will still pass to other plugins
+ *
+ * @return true if this event is cancelled
+ */
+ @Override
+ public boolean isCancelled() {
+ return this.cancelled;
+ }
+
+ /**
+ * Sets the cancellation state of this event. A cancelled event will not
+ * be executed in the server, but will still pass to other plugins.
+ *
+ * @param cancelled true if you wish to cancel this event
+ */
+ @Override
+ public void setCancelled(boolean cancelled) {
+ this.cancelled = cancelled;
+ }
+
+ @Override
+ public @NotNull HandlerList getHandlers() {
+ return HANDLER_LIST;
+ }
+
+ public static HandlerList getHandlerList() {
+ return HANDLER_LIST;
+ }
+
+ public War getWar() {
+ return war;
+ }
+
+ public Battle getBattle() {
+ return battle;
+ }
+
+ public BattleType getBattleType() {
+ return battleType;
+ }
+}
diff --git a/src/main/java/com/github/alathra/AlathranWars/events/battle/PreSiegeEndEvent.java b/src/main/java/com/github/alathra/AlathranWars/events/battle/PreSiegeEndEvent.java
deleted file mode 100644
index f6d50ed..0000000
--- a/src/main/java/com/github/alathra/AlathranWars/events/battle/PreSiegeEndEvent.java
+++ /dev/null
@@ -1,4 +0,0 @@
-package com.github.alathra.AlathranWars.events.battle;
-
-public class PreSiegeEndEvent {
-}
diff --git a/src/main/java/com/github/alathra/AlathranWars/events/battle/PreSiegeStartEvent.java b/src/main/java/com/github/alathra/AlathranWars/events/battle/PreSiegeStartEvent.java
deleted file mode 100644
index 2e3995d..0000000
--- a/src/main/java/com/github/alathra/AlathranWars/events/battle/PreSiegeStartEvent.java
+++ /dev/null
@@ -1,4 +0,0 @@
-package com.github.alathra.AlathranWars.events.battle;
-
-public class PreSiegeStartEvent {
-}
diff --git a/src/main/java/com/github/alathra/AlathranWars/events/battle/SiegeEndEvent.java b/src/main/java/com/github/alathra/AlathranWars/events/battle/SiegeEndEvent.java
deleted file mode 100644
index fa9ef1b..0000000
--- a/src/main/java/com/github/alathra/AlathranWars/events/battle/SiegeEndEvent.java
+++ /dev/null
@@ -1,4 +0,0 @@
-package com.github.alathra.AlathranWars.events.battle;
-
-public class SiegeEndEvent {
-}
diff --git a/src/main/java/com/github/alathra/AlathranWars/events/battle/SiegeStartEvent.java b/src/main/java/com/github/alathra/AlathranWars/events/battle/SiegeStartEvent.java
deleted file mode 100644
index 6540644..0000000
--- a/src/main/java/com/github/alathra/AlathranWars/events/battle/SiegeStartEvent.java
+++ /dev/null
@@ -1,4 +0,0 @@
-package com.github.alathra.AlathranWars.events.battle;
-
-public class SiegeStartEvent {
-}
diff --git a/src/main/java/com/github/alathra/AlathranWars/items/WarItemRegistry.java b/src/main/java/com/github/alathra/AlathranWars/items/WarItemRegistry.java
index dd02ecd..87cc3dc 100644
--- a/src/main/java/com/github/alathra/AlathranWars/items/WarItemRegistry.java
+++ b/src/main/java/com/github/alathra/AlathranWars/items/WarItemRegistry.java
@@ -1,6 +1,6 @@
package com.github.alathra.AlathranWars.items;
-import com.github.alathra.AlathranWars.Main;
+import com.github.alathra.AlathranWars.AlathranWars;
import com.github.alathra.AlathranWars.items.item.RamItem;
import org.bukkit.inventory.ItemStack;
import org.jetbrains.annotations.NotNull;
@@ -12,7 +12,7 @@ import java.util.stream.Collectors;
public class WarItemRegistry {
- public static final String namespace = Main.getInstance().getName().toLowerCase();
+ public static final String namespace = AlathranWars.getInstance().getName().toLowerCase();
private static final HashMap itemRegistry = new HashMap<>();
private static WarItemRegistry instance;
@@ -22,13 +22,13 @@ public class WarItemRegistry {
public WarItemRegistry() {
instance = this;
-// Main.warLogger.log(UtilsChat.getPrefix() + "Registering AlathranWars items.");
+// AlathranWars.warLogger.log(UtilsChat.getPrefix() + "Registering AlathranWars items.");
itemRegistry.put(registryName("ram"), new RamItem());
//THIS BREAKS EVERYTHING???? TODO
// Bukkit.getServer().addRecipe(new RamItem().getRecipe());
-// Main.warLogger.log(UtilsChat.getPrefix() + "Registered AlathranWars items.");
+// AlathranWars.warLogger.log(UtilsChat.getPrefix() + "Registered AlathranWars items.");
}
public static WarItemRegistry getInstance() {
diff --git a/src/main/java/com/github/alathra/AlathranWars/items/WarRecipeRegistry.java b/src/main/java/com/github/alathra/AlathranWars/items/WarRecipeRegistry.java
index 0d38cc5..d72dcdc 100644
--- a/src/main/java/com/github/alathra/AlathranWars/items/WarRecipeRegistry.java
+++ b/src/main/java/com/github/alathra/AlathranWars/items/WarRecipeRegistry.java
@@ -14,11 +14,11 @@ public class WarRecipeRegistry {
public WarRecipeRegistry() {
instance = this;
-// Main.warLogger.log(UtilsChat.getPrefix() + "Registering AlathranWars recipes.");
+// AlathranWars.warLogger.log(UtilsChat.getPrefix() + "Registering AlathranWars recipes.");
// register(WarItemRegistry.registryName("ram"), new RamItem().getRecipes());
-// Main.warLogger.log(UtilsChat.getPrefix() + "Registered AlathranWars recipes.");
+// AlathranWars.warLogger.log(UtilsChat.getPrefix() + "Registered AlathranWars recipes.");
}
public static WarRecipeRegistry getInstance() {
diff --git a/src/main/java/com/github/alathra/AlathranWars/items/item/RamItem.java b/src/main/java/com/github/alathra/AlathranWars/items/item/RamItem.java
index 518c8ec..ff30792 100644
--- a/src/main/java/com/github/alathra/AlathranWars/items/item/RamItem.java
+++ b/src/main/java/com/github/alathra/AlathranWars/items/item/RamItem.java
@@ -1,6 +1,6 @@
package com.github.alathra.AlathranWars.items.item;
-import com.github.alathra.AlathranWars.Main;
+import com.github.alathra.AlathranWars.AlathranWars;
import com.github.alathra.AlathranWars.items.IWarItem;
import com.github.alathra.AlathranWars.items.WarItemRegistry;
import com.github.milkdrinkers.colorparser.ColorParser;
@@ -38,7 +38,7 @@ public class RamItem implements IWarItem {
@Override
public @NotNull Recipe getRecipe() {
@Nullable ItemStack output = WarItemRegistry.getInstance().getOrNull("ram");
- @NotNull NamespacedKey key = new NamespacedKey(Main.getInstance(), "ram");
+ @NotNull NamespacedKey key = new NamespacedKey(AlathranWars.getInstance(), "ram");
@NotNull ShapedRecipe recipe = new ShapedRecipe(key, output);
recipe.shape("$@$", "B##");
recipe.setIngredient('@', Material.STICK);
diff --git a/src/main/java/com/github/alathra/AlathranWars/listeners/ListenerHandler.java b/src/main/java/com/github/alathra/AlathranWars/listeners/ListenerHandler.java
index 3f7f016..fa83f6f 100644
--- a/src/main/java/com/github/alathra/AlathranWars/listeners/ListenerHandler.java
+++ b/src/main/java/com/github/alathra/AlathranWars/listeners/ListenerHandler.java
@@ -1,36 +1,44 @@
package com.github.alathra.AlathranWars.listeners;
-import com.github.alathra.AlathranWars.Main;
+import com.github.alathra.AlathranWars.AlathranWars;
+import com.github.alathra.AlathranWars.Reloadable;
import com.github.alathra.AlathranWars.listeners.items.PlayerInteractListener;
-import com.github.alathra.AlathranWars.listeners.siege.BlockBreakPlaceListener;
-import com.github.alathra.AlathranWars.listeners.siege.PlayerDeathListener;
-import com.github.alathra.AlathranWars.listeners.siege.PlayerQuitListener;
-import com.github.alathra.AlathranWars.listeners.siege.PlayerSitListener;
+import com.github.alathra.AlathranWars.listeners.siege.*;
import com.github.alathra.AlathranWars.listeners.war.NationListener;
import com.github.alathra.AlathranWars.listeners.war.PlayerJoinListener;
import com.github.alathra.AlathranWars.listeners.war.TownListener;
+import org.bukkit.Bukkit;
/**
* A class to handle registration of event listeners.
*/
-public class ListenerHandler {
- private final Main instance;
+public class ListenerHandler implements Reloadable {
+ private final AlathranWars instance;
- public ListenerHandler(Main instance) {
+ public ListenerHandler(AlathranWars instance) {
this.instance = instance;
}
+ @Override
public void onLoad() {
-
}
+ @Override
public void onEnable() {
// Sieges
instance.getServer().getPluginManager().registerEvents(new com.github.alathra.AlathranWars.listeners.siege.PlayerJoinListener(), instance);
instance.getServer().getPluginManager().registerEvents(new PlayerQuitListener(), instance);
instance.getServer().getPluginManager().registerEvents(new BlockBreakPlaceListener(), instance);
instance.getServer().getPluginManager().registerEvents(new PlayerDeathListener(), instance);
- instance.getServer().getPluginManager().registerEvents(new PlayerSitListener(), instance);
+ if (Bukkit.getServer().getPluginManager().isPluginEnabled("Graves"))
+ instance.getServer().getPluginManager().registerEvents(new PlayerGraveListener(), instance);
+ if (Bukkit.getServer().getPluginManager().isPluginEnabled("HeadsPlus"))
+ instance.getServer().getPluginManager().registerEvents(new PlayerHeadsPlusListener(), instance);
+ if (Bukkit.getServer().getPluginManager().isPluginEnabled("GSit"))
+ instance.getServer().getPluginManager().registerEvents(new PlayerSitListener(), instance);
+
+ // Battles
+ instance.getServer().getPluginManager().registerEvents(new SiegeListener(), instance);
// Wars
instance.getServer().getPluginManager().registerEvents(new NationListener(), instance);
@@ -42,7 +50,7 @@ public class ListenerHandler {
instance.getServer().getPluginManager().registerEvents(new PlayerInteractListener(), instance);
}
+ @Override
public void onDisable() {
-
}
}
\ No newline at end of file
diff --git a/src/main/java/com/github/alathra/AlathranWars/listeners/items/PlayerInteractListener.java b/src/main/java/com/github/alathra/AlathranWars/listeners/items/PlayerInteractListener.java
index 2308666..74291cd 100644
--- a/src/main/java/com/github/alathra/AlathranWars/listeners/items/PlayerInteractListener.java
+++ b/src/main/java/com/github/alathra/AlathranWars/listeners/items/PlayerInteractListener.java
@@ -1,6 +1,6 @@
package com.github.alathra.AlathranWars.listeners.items;
-import com.github.alathra.AlathranWars.Main;
+import com.github.alathra.AlathranWars.AlathranWars;
import com.github.alathra.AlathranWars.conflict.WarManager;
import com.github.alathra.AlathranWars.conflict.battle.siege.Siege;
import com.github.alathra.AlathranWars.items.WarItemRegistry;
@@ -104,7 +104,7 @@ public class PlayerInteractListener implements Listener {
return;
}
player.sendMessage(ColorParser.of(UtilsChat.getPrefix() + "Break it down alright!").parseLegacy().build());
- brokenDoors.put(getDoorPos(clicked, door), System.currentTimeMillis() + (1000L * Main.getInstance().getConfig().getInt("batteringRamEffectiveness")));
+ brokenDoors.put(getDoorPos(clicked, door), System.currentTimeMillis() + (1000L * AlathranWars.getInstance().getConfig().getInt("batteringRamEffectiveness")));
door.setOpen(!door.isOpen());
clicked.setBlockData(door);
player.getInventory().getItemInMainHand().setAmount(player.getInventory().getItemInMainHand().getAmount() - 1);
diff --git a/src/main/java/com/github/alathra/AlathranWars/listeners/siege/BlockBreakPlaceListener.java b/src/main/java/com/github/alathra/AlathranWars/listeners/siege/BlockBreakPlaceListener.java
index 705a565..3a6ba13 100644
--- a/src/main/java/com/github/alathra/AlathranWars/listeners/siege/BlockBreakPlaceListener.java
+++ b/src/main/java/com/github/alathra/AlathranWars/listeners/siege/BlockBreakPlaceListener.java
@@ -1,7 +1,7 @@
package com.github.alathra.AlathranWars.listeners.siege;
import com.github.alathra.AlathranWars.conflict.battle.siege.Siege;
-import com.github.alathra.AlathranWars.enums.BattleSide;
+import com.github.alathra.AlathranWars.enums.battle.BattleSide;
import com.github.alathra.AlathranWars.utility.Utils;
import com.github.milkdrinkers.colorparser.ColorParser;
import com.palmergames.bukkit.towny.event.actions.TownyBuildEvent;
diff --git a/src/main/java/com/github/alathra/AlathranWars/listeners/siege/PlayerDeathListener.java b/src/main/java/com/github/alathra/AlathranWars/listeners/siege/PlayerDeathListener.java
index 463c4df..6fab997 100644
--- a/src/main/java/com/github/alathra/AlathranWars/listeners/siege/PlayerDeathListener.java
+++ b/src/main/java/com/github/alathra/AlathranWars/listeners/siege/PlayerDeathListener.java
@@ -5,39 +5,14 @@ import com.github.alathra.AlathranWars.utility.Utils;
import com.palmergames.bukkit.towny.event.deathprice.NationPaysDeathPriceEvent;
import com.palmergames.bukkit.towny.event.deathprice.PlayerPaysDeathPriceEvent;
import com.palmergames.bukkit.towny.event.deathprice.TownPaysDeathPriceEvent;
-import com.ranull.graves.event.GraveCreateEvent;
-import io.github.thatsmusic99.headsplus.api.events.PlayerHeadDropEvent;
-import org.bukkit.entity.EntityType;
import org.bukkit.entity.Player;
import org.bukkit.event.EventHandler;
+import org.bukkit.event.EventPriority;
import org.bukkit.event.Listener;
import org.bukkit.event.entity.PlayerDeathEvent;
public class PlayerDeathListener implements Listener {
- @EventHandler
- private void onHeadDrop(PlayerHeadDropEvent e) {
- Siege siege = Utils.getClosestSiege(e.getDeadPlayer(), false);
- if (siege == null) return;
-
- if (!Utils.isOnSiegeBattlefield(e.getDeadPlayer(), siege)) return;
-
- e.setCancelled(true);
- }
-
- @EventHandler
- private void onGraveCreate(GraveCreateEvent e) {
- if (!e.getEntityType().equals(EntityType.PLAYER)) return;
- if (!(e.getEntity() instanceof Player p)) return;
-
- Siege siege = Utils.getClosestSiege(p, false);
- if (siege == null) return;
-
- if (!Utils.isOnSiegeBattlefield(p, siege)) return;
-
- e.setCancelled(true);
- }
-
- @EventHandler
+ @EventHandler(priority = EventPriority.HIGHEST)
public void onPlayerPaysDeathPrice(PlayerPaysDeathPriceEvent e) {
Player p = e.getDeadResident().getPlayer();
Siege siege = Utils.getClosestSiege(p, true);
@@ -48,7 +23,7 @@ public class PlayerDeathListener implements Listener {
e.setCancelled(true);
}
- @EventHandler
+ @EventHandler(priority = EventPriority.HIGHEST)
public void onPlayerPaysDeathPrice(TownPaysDeathPriceEvent e) {
Player p = e.getDeadResident().getPlayer();
Siege siege = Utils.getClosestSiege(p, true);
@@ -59,7 +34,7 @@ public class PlayerDeathListener implements Listener {
e.setCancelled(true);
}
- @EventHandler
+ @EventHandler(priority = EventPriority.HIGHEST)
public void onPlayerPaysDeathPrice(NationPaysDeathPriceEvent e) {
Player p = e.getDeadResident().getPlayer();
Siege siege = Utils.getClosestSiege(p, true);
@@ -70,7 +45,7 @@ public class PlayerDeathListener implements Listener {
e.setCancelled(true);
}
- @EventHandler
+ @EventHandler(priority = EventPriority.HIGHEST)
private void onPlayerDeath(PlayerDeathEvent e) {
Player victim = e.getPlayer();
Player attacker = e.getPlayer().getKiller();
@@ -88,7 +63,7 @@ public class PlayerDeathListener implements Listener {
}
}
- @EventHandler
+ @EventHandler(priority = EventPriority.HIGHEST)
private void onPlayerSuicide(PlayerDeathEvent e) {
Player victim = e.getPlayer();
Player attacker = e.getPlayer().getKiller();
diff --git a/src/main/java/com/github/alathra/AlathranWars/listeners/siege/PlayerGraveListener.java b/src/main/java/com/github/alathra/AlathranWars/listeners/siege/PlayerGraveListener.java
new file mode 100644
index 0000000..2c10895
--- /dev/null
+++ b/src/main/java/com/github/alathra/AlathranWars/listeners/siege/PlayerGraveListener.java
@@ -0,0 +1,26 @@
+package com.github.alathra.AlathranWars.listeners.siege;
+
+import com.github.alathra.AlathranWars.conflict.battle.siege.Siege;
+import com.github.alathra.AlathranWars.utility.Utils;
+import com.ranull.graves.event.GraveCreateEvent;
+import org.bukkit.entity.EntityType;
+import org.bukkit.entity.Player;
+import org.bukkit.event.EventHandler;
+import org.bukkit.event.EventPriority;
+import org.bukkit.event.Listener;
+
+public class PlayerGraveListener implements Listener {
+ @EventHandler(priority = EventPriority.HIGHEST)
+ private void onGraveCreate(GraveCreateEvent e) {
+ if (!e.getEntityType().equals(EntityType.PLAYER)) return;
+ if (!(e.getEntity() instanceof Player p)) return;
+
+ Siege siege = Utils.getClosestSiege(p, false);
+ if (siege == null) return;
+
+ if (!Utils.isOnSiegeBattlefield(p, siege)) return;
+
+ e.setCancelled(true);
+ }
+}
+
diff --git a/src/main/java/com/github/alathra/AlathranWars/listeners/siege/PlayerHeadsPlusListener.java b/src/main/java/com/github/alathra/AlathranWars/listeners/siege/PlayerHeadsPlusListener.java
new file mode 100644
index 0000000..91e559b
--- /dev/null
+++ b/src/main/java/com/github/alathra/AlathranWars/listeners/siege/PlayerHeadsPlusListener.java
@@ -0,0 +1,19 @@
+package com.github.alathra.AlathranWars.listeners.siege;
+
+import com.github.alathra.AlathranWars.conflict.battle.siege.Siege;
+import com.github.alathra.AlathranWars.utility.Utils;
+import io.github.thatsmusic99.headsplus.api.events.PlayerHeadDropEvent;
+import org.bukkit.event.EventHandler;
+import org.bukkit.event.Listener;
+
+public class PlayerHeadsPlusListener implements Listener {
+ @EventHandler
+ private void onHeadDrop(PlayerHeadDropEvent e) {
+ Siege siege = Utils.getClosestSiege(e.getDeadPlayer(), false);
+ if (siege == null) return;
+
+ if (!Utils.isOnSiegeBattlefield(e.getDeadPlayer(), siege)) return;
+
+ e.setCancelled(true);
+ }
+}
diff --git a/src/main/java/com/github/alathra/AlathranWars/listeners/siege/PlayerJoinListener.java b/src/main/java/com/github/alathra/AlathranWars/listeners/siege/PlayerJoinListener.java
index ba58f3b..a275b97 100644
--- a/src/main/java/com/github/alathra/AlathranWars/listeners/siege/PlayerJoinListener.java
+++ b/src/main/java/com/github/alathra/AlathranWars/listeners/siege/PlayerJoinListener.java
@@ -2,7 +2,7 @@ package com.github.alathra.AlathranWars.listeners.siege;
import com.github.alathra.AlathranWars.conflict.WarManager;
import com.github.alathra.AlathranWars.conflict.battle.siege.Siege;
-import com.github.alathra.AlathranWars.enums.BattleSide;
+import com.github.alathra.AlathranWars.enums.battle.BattleSide;
import org.bukkit.entity.Player;
import org.bukkit.event.EventHandler;
import org.bukkit.event.Listener;
diff --git a/src/main/java/com/github/alathra/AlathranWars/listeners/siege/PlayerQuitListener.java b/src/main/java/com/github/alathra/AlathranWars/listeners/siege/PlayerQuitListener.java
index f019783..5a4885e 100644
--- a/src/main/java/com/github/alathra/AlathranWars/listeners/siege/PlayerQuitListener.java
+++ b/src/main/java/com/github/alathra/AlathranWars/listeners/siege/PlayerQuitListener.java
@@ -2,7 +2,7 @@ package com.github.alathra.AlathranWars.listeners.siege;
import com.github.alathra.AlathranWars.conflict.WarManager;
import com.github.alathra.AlathranWars.conflict.battle.siege.Siege;
-import com.github.alathra.AlathranWars.enums.BattleSide;
+import com.github.alathra.AlathranWars.enums.battle.BattleSide;
import org.bukkit.entity.Player;
import org.bukkit.event.EventHandler;
import org.bukkit.event.Listener;
diff --git a/src/main/java/com/github/alathra/AlathranWars/listeners/siege/PlayerSitListener.java b/src/main/java/com/github/alathra/AlathranWars/listeners/siege/PlayerSitListener.java
index 6543852..51a59e3 100644
--- a/src/main/java/com/github/alathra/AlathranWars/listeners/siege/PlayerSitListener.java
+++ b/src/main/java/com/github/alathra/AlathranWars/listeners/siege/PlayerSitListener.java
@@ -5,11 +5,12 @@ import com.github.alathra.AlathranWars.utility.Utils;
import dev.geco.gsit.api.event.PreEntitySitEvent;
import org.bukkit.entity.Player;
import org.bukkit.event.EventHandler;
+import org.bukkit.event.EventPriority;
import org.bukkit.event.Listener;
public class PlayerSitListener implements Listener {
- @EventHandler
- public void onSit2(PreEntitySitEvent e) {
+ @EventHandler(priority = EventPriority.HIGHEST)
+ public void onSit(PreEntitySitEvent e) {
if (!(e.getEntity() instanceof Player p)) return;
Siege siege = Utils.getClosestSiege(p, false);
diff --git a/src/main/java/com/github/alathra/AlathranWars/listeners/siege/SiegeListener.java b/src/main/java/com/github/alathra/AlathranWars/listeners/siege/SiegeListener.java
new file mode 100644
index 0000000..12f6de6
--- /dev/null
+++ b/src/main/java/com/github/alathra/AlathranWars/listeners/siege/SiegeListener.java
@@ -0,0 +1,260 @@
+package com.github.alathra.AlathranWars.listeners.siege;
+
+import com.github.alathra.AlathranWars.conflict.Side;
+import com.github.alathra.AlathranWars.conflict.War;
+import com.github.alathra.AlathranWars.conflict.battle.siege.Siege;
+import com.github.alathra.AlathranWars.enums.battle.BattleType;
+import com.github.alathra.AlathranWars.enums.battle.BattleVictoryReason;
+import com.github.alathra.AlathranWars.events.battle.BattleResultEvent;
+import com.github.alathra.AlathranWars.events.battle.BattleStartEvent;
+import com.github.alathra.AlathranWars.utility.UtilsChat;
+import com.github.milkdrinkers.colorparser.ColorParser;
+import com.palmergames.bukkit.towny.object.Town;
+import net.kyori.adventure.key.Key;
+import net.kyori.adventure.sound.Sound;
+import net.kyori.adventure.title.Title;
+import org.bukkit.Bukkit;
+import org.bukkit.event.EventHandler;
+import org.bukkit.event.EventPriority;
+import org.bukkit.event.Listener;
+
+import java.time.Duration;
+import java.util.List;
+import java.util.Random;
+
+public class SiegeListener implements Listener {
+ private final static Title.Times TITLE_TIMES = Title.Times.times(Duration.ofMillis(500), Duration.ofMillis(3500), Duration.ofMillis(500));
+ private final static Sound SOUND_VICTORY = Sound.sound(Key.key("item.goat_horn.sound.0"), Sound.Source.VOICE, 0.5f, 1.0F);
+ private final static Sound SOUND_DEFEAT = Sound.sound(Key.key("entity.wither.death"), Sound.Source.VOICE, 0.5f, 1.0F);
+ private final static List SOUND_GOATHORNS = List.of(
+ Sound.sound(Key.key("item.goat_horn.sound.0"), Sound.Source.VOICE, 0.5f, new Random().nextFloat(0.9F, 1.0F)),
+ Sound.sound(Key.key("item.goat_horn.sound.2"), Sound.Source.VOICE, 0.5f, new Random().nextFloat(0.9F, 1.0F)),
+ Sound.sound(Key.key("item.goat_horn.sound.3"), Sound.Source.VOICE, 0.5f, new Random().nextFloat(0.9F, 1.0F)),
+ Sound.sound(Key.key("item.goat_horn.sound.7"), Sound.Source.VOICE, 0.5f, new Random().nextFloat(0.9F, 1.0F))
+ );
+
+ /**
+ * On battle start UI handling.
+ *
+ * @param e event
+ */
+ @EventHandler(priority = EventPriority.LOW)
+ public void onBattleStart(BattleStartEvent e) {
+ if (!e.getBattle().getBattleType().equals(BattleType.SIEGE)) return;
+
+ if (!(e.getBattle() instanceof Siege siege)) return;
+
+ final Title defTitle = Title.title(
+ ColorParser.of("")
+ .parseMinimessagePlaceholder("town", siege.getTown().getName())
+ .build(),
+ ColorParser.of("Is under siege, defend!")
+ .build(),
+ TITLE_TIMES
+ );
+ final Title attTitle = Title.title(
+ ColorParser.of("")
+ .parseMinimessagePlaceholder("town", siege.getTown().getName())
+ .build(),
+ ColorParser.of("Has been put to siege, attack!")
+ .build(),
+ TITLE_TIMES
+ );
+
+ siege.getDefenderPlayers().forEach(player -> {
+ player.showTitle(defTitle);
+ player.playSound(SOUND_GOATHORNS.get(new Random().nextInt(1, SOUND_GOATHORNS.size())));
+ });
+
+ siege.getAttackerPlayers().forEach(player -> {
+ player.showTitle(attTitle);
+ player.playSound(SOUND_GOATHORNS.get(new Random().nextInt(1, SOUND_GOATHORNS.size())));
+ });
+ }
+
+ /**
+ * On battle end UI handling.
+ *
+ * @param e event
+ */
+ @EventHandler(priority = EventPriority.LOW)
+ public void onBattleResult(BattleResultEvent e) {
+ if (!e.getBattle().getBattleType().equals(BattleType.SIEGE)) return;
+
+ if (!(e.getBattle() instanceof Siege siege)) return;
+
+ switch (e.getBattleVictor()) {
+ case ATTACKER -> {
+ if (e.getBattleVictoryReason().equals(BattleVictoryReason.OPPONENT_RETREAT)) {
+ Bukkit.broadcast(
+ ColorParser.of("The town of has surrendered.")
+ .parseMinimessagePlaceholder("prefix", UtilsChat.getPrefix())
+ .parseMinimessagePlaceholder("town", siege.getTown().getName())
+ .build()
+ );
+ } else {
+ Bukkit.broadcast(ColorParser.of("The town of has been sacked and placed under occupation by the armies of !")
+ .parseMinimessagePlaceholder("prefix", UtilsChat.getPrefix())
+ .parseMinimessagePlaceholder("town", siege.getTown().getName())
+ .parseMinimessagePlaceholder("attacker", siege.getAttackerSide().getName())
+ .build());
+ }
+
+ final Title vicAttackTitle = Title.title(
+ ColorParser.of("Victory")
+ .build(),
+ ColorParser.of(" has been captured!")
+ .parseMinimessagePlaceholder("town", siege.getTown().getName())
+ .build(),
+ TITLE_TIMES
+ );
+ final Title losAttackTitle = Title.title(
+ ColorParser.of("Defeat")
+ .build(),
+ ColorParser.of(" has been lost!")
+ .parseMinimessagePlaceholder("town", siege.getTown().getName())
+ .build(),
+ TITLE_TIMES
+ );
+ siege.getAttackers().forEach(player -> {
+ player.showTitle(vicAttackTitle);
+ player.playSound(SOUND_VICTORY);
+ });
+ siege.getDefenders().forEach(player -> {
+ player.showTitle(losAttackTitle);
+ player.playSound(SOUND_DEFEAT);
+ });
+ }
+ case DEFENDER -> {
+ if (e.getBattleVictoryReason().equals(BattleVictoryReason.OPPONENT_RETREAT)) {
+ Bukkit.broadcast(
+ ColorParser.of("The siege at has been abandoned by the attackers.")
+ .parseMinimessagePlaceholder("prefix", UtilsChat.getPrefix())
+ .parseMinimessagePlaceholder("town", siege.getTown().getName())
+ .build()
+ );
+ } else {
+ Bukkit.broadcast(
+ ColorParser.of("The siege of has been lifted by the defenders!")
+ .parseMinimessagePlaceholder("prefix", UtilsChat.getPrefix())
+ .parseMinimessagePlaceholder("town", siege.getTown().getName())
+ .build()
+ );
+ }
+
+ final Title vicDefendTitle = Title.title(
+ ColorParser.of("Defeat")
+ .build(),
+ ColorParser.of("We failed to capture !")
+ .parseMinimessagePlaceholder("town", siege.getTown().getName())
+ .build(),
+ TITLE_TIMES
+ );
+ final Title losDefendTitle = Title.title(
+ ColorParser.of("Victory")
+ .build(),
+ ColorParser.of(" has been made safe!")
+ .parseMinimessagePlaceholder("town", siege.getTown().getName())
+ .build(),
+ TITLE_TIMES
+ );
+ siege.getAttackers().forEach(player -> {
+ player.showTitle(vicDefendTitle);
+ player.playSound(SOUND_DEFEAT);
+ });
+ siege.getDefenders().forEach(player -> {
+ player.showTitle(losDefendTitle);
+ player.playSound(SOUND_VICTORY);
+ });
+ }
+ case DRAW -> {
+ Bukkit.broadcast(
+ ColorParser.of("The siege of has ended in a draw!")
+ .parseMinimessagePlaceholder("prefix", UtilsChat.getPrefix())
+ .parseMinimessagePlaceholder("town", siege.getTown().getName())
+ .build()
+ );
+
+ final Title drawTitle = Title.title(
+ ColorParser.of("Draw")
+ .build(),
+ ColorParser.of("The siege at has ended!")
+ .parseMinimessagePlaceholder("town", siege.getTown().getName())
+ .build(),
+ TITLE_TIMES
+ );
+ siege.getAttackers().forEach(player -> {
+ player.showTitle(drawTitle);
+ player.playSound(SOUND_DEFEAT);
+ });
+ siege.getDefenders().forEach(player -> {
+ player.showTitle(drawTitle);
+ player.playSound(SOUND_DEFEAT);
+ });
+ }
+ }
+ }
+
+ /**
+ * On battle end handle occupation results.
+ *
+ * @param e event
+ */
+ @EventHandler(priority = EventPriority.HIGHEST)
+ public void onBattleResultOccupy(BattleResultEvent e) {
+ if (!e.getBattle().getBattleType().equals(BattleType.SIEGE)) return;
+
+ if (!(e.getBattle() instanceof Siege siege)) return;
+
+ switch (e.getBattleVictor()) {
+ case ATTACKER -> {
+ War war = e.getWar();
+
+ if (war.isEvent()) return;
+
+ Town town = siege.getTown();
+ Side townSide = war.getTownSide(town);
+
+ if (townSide == null) return;
+
+ final boolean isLiberation = siege.getAttackerSide().equals(townSide); // Is the town being liberated or occupied
+
+ if (isLiberation) { // Liberation siege
+ if (townSide.isTownSurrendered(town)) {
+ war.unsurrenderTown(town);
+ }
+ } else { // Occupation siege
+ if (!townSide.isTownSurrendered(town)) {
+ war.surrenderTown(town);
+ }
+ }
+ }
+ case DEFENDER, DRAW -> {
+ }
+ }
+ }
+
+ /**
+ * On battle end handle war score distribution.
+ *
+ * @param e event
+ */
+ @EventHandler(priority = EventPriority.HIGHEST)
+ public void onBattleResultWarScore(BattleResultEvent e) {
+ if (!e.getBattle().getBattleType().equals(BattleType.SIEGE)) return;
+
+ if (!(e.getBattle() instanceof Siege siege)) return;
+
+ switch (e.getBattleVictor()) {
+ case ATTACKER -> {
+ siege.getAttackerSide().addScore(50);
+ siege.getDefenderSide().addScore(5);
+ }
+ case DEFENDER -> {
+ siege.getDefenderSide().addScore(10);
+ }
+ case DRAW -> {
+ }
+ }
+ }
+}
diff --git a/src/main/java/com/github/alathra/AlathranWars/utility/Cfg.java b/src/main/java/com/github/alathra/AlathranWars/utility/Cfg.java
new file mode 100644
index 0000000..6c49812
--- /dev/null
+++ b/src/main/java/com/github/alathra/AlathranWars/utility/Cfg.java
@@ -0,0 +1,19 @@
+package com.github.alathra.AlathranWars.utility;
+
+import com.github.alathra.AlathranWars.AlathranWars;
+import com.github.alathra.AlathranWars.config.ConfigHandler;
+import com.github.milkdrinkers.Crate.Config;
+import org.jetbrains.annotations.NotNull;
+
+/**
+ * Convenience class for accessing {@link ConfigHandler#getConfig}
+ */
+public abstract class Cfg {
+ /**
+ * Convenience method for {@link ConfigHandler#getConfig} to getConnection {@link Config}
+ */
+ @NotNull
+ public static Config get() {
+ return AlathranWars.getInstance().getConfigHandler().getConfig();
+ }
+}
diff --git a/src/main/java/com/github/alathra/AlathranWars/utility/Config.java b/src/main/java/com/github/alathra/AlathranWars/utility/Config.java
deleted file mode 100644
index f7ceeb6..0000000
--- a/src/main/java/com/github/alathra/AlathranWars/utility/Config.java
+++ /dev/null
@@ -1,13 +0,0 @@
-package com.github.alathra.AlathranWars.utility;
-
-import com.github.alathra.AlathranWars.Main;
-import org.jetbrains.annotations.NotNull;
-
-/**
- * Convenience class for accessing {@link com.github.alathra.AlathranWars.data.ConfigManager}
- */
-public abstract class Config {
- public static @NotNull com.github.milkdrinkers.Crate.Config get() {
- return Main.getInstance().getConfigManager().getConfig();
- }
-}
diff --git a/src/main/java/com/github/alathra/AlathranWars/utility/DB.java b/src/main/java/com/github/alathra/AlathranWars/utility/DB.java
index e13cb42..908626a 100644
--- a/src/main/java/com/github/alathra/AlathranWars/utility/DB.java
+++ b/src/main/java/com/github/alathra/AlathranWars/utility/DB.java
@@ -1,21 +1,39 @@
package com.github.alathra.AlathranWars.utility;
-import com.github.alathra.AlathranWars.Main;
-import com.zaxxer.hikari.HikariDataSource;
+import com.github.alathra.AlathranWars.AlathranWars;
+import com.github.alathra.AlathranWars.db.DatabaseHandler;
+import com.github.alathra.AlathranWars.db.DatabaseType;
+import com.github.alathra.AlathranWars.db.jooq.JooqContext;
import org.jetbrains.annotations.NotNull;
+import org.jooq.DSLContext;
import java.sql.Connection;
import java.sql.SQLException;
/**
- * Convenience class for accessing {@link com.github.alathra.AlathranWars.data.DataManager }
+ * Convenience class for accessing methods in {@link DatabaseHandler#getConnection}
*/
public abstract class DB {
- public static @NotNull Connection get() throws SQLException {
- return Main.getInstance().getDataManager().getConnection();
+ /**
+ * Convenience method for {@link DatabaseHandler#getConnection} to getConnection {@link Connection}
+ */
+ @NotNull
+ public static Connection getConnection() throws SQLException {
+ return AlathranWars.getInstance().getDataHandler().getConnection();
}
- public static @NotNull HikariDataSource getDataSource() {
- return Main.getInstance().getDataManager().getDataSource();
+ /**
+ * Convenience method for {@link JooqContext#createContext(Connection)} to getConnection {@link DSLContext}
+ */
+ @NotNull
+ public static DSLContext getContext(Connection con) {
+ return AlathranWars.getInstance().getDataHandler().getJooqContext().createContext(con);
+ }
+
+ /**
+ * Convenience method for {@link DatabaseHandler#getDB()} to getConnection {@link DatabaseType}
+ */
+ public static DatabaseType getDB() {
+ return AlathranWars.getInstance().getDataHandler().getDB();
}
}
diff --git a/src/main/java/com/github/alathra/AlathranWars/utility/Logger.java b/src/main/java/com/github/alathra/AlathranWars/utility/Logger.java
new file mode 100644
index 0000000..715de1b
--- /dev/null
+++ b/src/main/java/com/github/alathra/AlathranWars/utility/Logger.java
@@ -0,0 +1,21 @@
+package com.github.alathra.AlathranWars.utility;
+
+
+import com.github.alathra.AlathranWars.AlathranWars;
+import net.kyori.adventure.text.logger.slf4j.ComponentLogger;
+import org.jetbrains.annotations.NotNull;
+
+/**
+ * A class that provides shorthand access to {@link AlathranWars#getComponentLogger}.
+ */
+public class Logger {
+ /**
+ * Get component logger. Shorthand for:
+ *
+ * @return the component logger {@link AlathranWars#getComponentLogger}.
+ */
+ @NotNull
+ public static ComponentLogger get() {
+ return AlathranWars.getInstance().getComponentLogger();
+ }
+}
diff --git a/src/main/java/com/github/alathra/AlathranWars/utility/SQLQueries.java b/src/main/java/com/github/alathra/AlathranWars/utility/SQLQueries.java
deleted file mode 100644
index 36fb848..0000000
--- a/src/main/java/com/github/alathra/AlathranWars/utility/SQLQueries.java
+++ /dev/null
@@ -1,637 +0,0 @@
-package com.github.alathra.AlathranWars.utility;
-
-import com.github.alathra.AlathranWars.conflict.Side;
-import com.github.alathra.AlathranWars.conflict.War;
-import com.github.alathra.AlathranWars.conflict.WarManager;
-import com.github.alathra.AlathranWars.conflict.battle.siege.Siege;
-import com.github.alathra.AlathranWars.enums.BattleSide;
-import com.github.alathra.AlathranWars.enums.BattleTeam;
-import com.palmergames.bukkit.towny.TownyAPI;
-import com.palmergames.bukkit.towny.object.Nation;
-import com.palmergames.bukkit.towny.object.Town;
-import org.bukkit.Bukkit;
-import org.bukkit.OfflinePlayer;
-import org.jetbrains.annotations.Contract;
-import org.jetbrains.annotations.NotNull;
-import org.jetbrains.annotations.Nullable;
-
-import java.sql.*;
-import java.time.Instant;
-import java.util.HashSet;
-import java.util.Set;
-import java.util.UUID;
-
-/**
- * Convenience class for defining and executing SQL queries
- */
-public abstract class SQLQueries {
- public static void initDB() {
- try (final Statement statement = DB.get().createStatement()) {
- statement.addBatch("""
- CREATE TABLE IF NOT EXISTS `wars_list` (
- `uuid` uuid NOT NULL DEFAULT uuid(),
- `name` tinytext NOT NULL,
- `label` tinytext NOT NULL,
- `side1` uuid NOT NULL DEFAULT uuid(),
- `side2` uuid NOT NULL DEFAULT uuid(),
- PRIMARY KEY (`uuid`),
- KEY `side2` (`side2`),
- KEY `side1` (`side1`)
- ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_general_ci;
- """);
-
- statement.addBatch("""
- CREATE TABLE IF NOT EXISTS `wars_sides` (
- `war` uuid NOT NULL,
- `uuid` uuid NOT NULL,
- `side` tinytext NOT NULL,
- `team` tinytext NOT NULL,
- `name` tinytext NOT NULL,
- `town` uuid NOT NULL,
- `siegeGrace` timestamp NOT NULL,
- `raidGrace` timestamp NOT NULL,
- PRIMARY KEY (`uuid`),
- KEY `town` (`town`),
- KEY `war` (`war`),
- CONSTRAINT `war` FOREIGN KEY (`war`) REFERENCES `wars_list` (`uuid`) ON DELETE CASCADE ON UPDATE CASCADE
- ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_general_ci;
- """);
-
- statement.addBatch("""
- CREATE TABLE IF NOT EXISTS `wars_sides_nations` (
- `side` uuid NOT NULL,
- `nation` uuid NOT NULL,
- KEY `side_nations` (`side`),
- CONSTRAINT `side_nations` FOREIGN KEY (`side`) REFERENCES `wars_sides` (`uuid`) ON DELETE CASCADE ON UPDATE CASCADE
- ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_general_ci;
- """);
-
- statement.addBatch("""
- CREATE TABLE IF NOT EXISTS `wars_sides_nations_surrendered` (
- `side` uuid NOT NULL,
- `nation` uuid NOT NULL,
- KEY `side_nations_surrendered` (`side`),
- CONSTRAINT `side_nations_surrendered` FOREIGN KEY (`side`) REFERENCES `wars_sides` (`uuid`) ON DELETE CASCADE ON UPDATE CASCADE
- ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_general_ci;
- """);
-
- statement.addBatch("""
- CREATE TABLE IF NOT EXISTS `wars_sides_players` (
- `side` uuid NOT NULL,
- `player` uuid NOT NULL,
- KEY `side_players` (`side`),
- CONSTRAINT `side_players` FOREIGN KEY (`side`) REFERENCES `wars_sides` (`uuid`) ON DELETE CASCADE ON UPDATE CASCADE
- ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_general_ci;
- """);
-
- statement.addBatch("""
- CREATE TABLE IF NOT EXISTS `wars_sides_players_surrendered` (
- `side` uuid NOT NULL,
- `player` uuid NOT NULL,
- KEY `side_players_surrendered` (`side`),
- CONSTRAINT `side_players_surrendered` FOREIGN KEY (`side`) REFERENCES `wars_sides` (`uuid`) ON DELETE CASCADE ON UPDATE CASCADE
- ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_general_ci;
- """);
-
- statement.addBatch("""
- CREATE TABLE IF NOT EXISTS `wars_sides_towns` (
- `side` uuid NOT NULL,
- `town` uuid NOT NULL,
- KEY `side_towns` (`side`),
- CONSTRAINT `side_towns` FOREIGN KEY (`side`) REFERENCES `wars_sides` (`uuid`) ON DELETE CASCADE ON UPDATE CASCADE
- ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_general_ci;
- """);
-
- statement.addBatch("""
- CREATE TABLE IF NOT EXISTS `wars_sides_towns_surrendered` (
- `side` uuid NOT NULL,
- `town` uuid NOT NULL,
- KEY `side_towns_surrendered` (`side`),
- CONSTRAINT `side_towns_surrendered` FOREIGN KEY (`side`) REFERENCES `wars_sides` (`uuid`) ON DELETE CASCADE ON UPDATE CASCADE
- ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_general_ci;
- """);
-
- statement.addBatch("""
- CREATE TABLE IF NOT EXISTS `wars_sieges` (
- `war` uuid NOT NULL,
- `uuid` uuid NOT NULL,
- `town` uuid NOT NULL,
- `siegeLeader` uuid NOT NULL,
- `endTime` timestamp NOT NULL,
- `lastTouched` timestamp NOT NULL,
- `siegeProgress` int(11) NOT NULL,
- PRIMARY KEY (`uuid`),
- KEY `siege_war` (`war`),
- CONSTRAINT `siege_war` FOREIGN KEY (`war`) REFERENCES `wars_list` (`uuid`) ON DELETE CASCADE ON UPDATE CASCADE
- ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_general_ci;
- """);
-
- statement.addBatch("""
- CREATE TABLE IF NOT EXISTS `wars_sieges_players_attackers` (
- `siege` uuid NOT NULL,
- `player` uuid NOT NULL,
- KEY `siege_players_attackers` (`siege`),
- CONSTRAINT `siege_players_attackers` FOREIGN KEY (`siege`) REFERENCES `wars_sieges` (`uuid`) ON DELETE CASCADE ON UPDATE CASCADE
- ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_general_ci;
- """);
-
- statement.addBatch("""
- CREATE TABLE IF NOT EXISTS `wars_sieges_players_defenders` (
- `siege` uuid NOT NULL,
- `player` uuid NOT NULL,
- KEY `siege_players_defenders` (`siege`),
- CONSTRAINT `siege_players_defenders` FOREIGN KEY (`siege`) REFERENCES `wars_sieges` (`uuid`) ON DELETE CASCADE ON UPDATE CASCADE
- ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_general_ci;
- """);
-
- statement.addBatch("""
- ALTER TABLE `wars_list` ADD COLUMN `event` BIT NOT NULL DEFAULT 0 AFTER `side2`;
- """);
-
- statement.executeLargeBatch();
- } catch (SQLException e) {
- e.printStackTrace();
- }
- }
-
- public static void saveAll() {
- try (
- @NotNull Connection con = DB.get();
- PreparedStatement warStatement = con.prepareStatement("INSERT INTO `wars_list` (`uuid`, `name`, `label`, `side1`, `side2`, `event`) VALUES (?, ?, ?, ?, ?, ?) "
- + "ON DUPLICATE KEY UPDATE `name` = ?, `label` = ?, `side1` = ?, `side2` = ?, `event` = ?")
- ) {
- // Save wars
- for (@NotNull War war : WarManager.getInstance().getWars()) {
- // Insert
- warStatement.setString(1, war.getUUID().toString());
- warStatement.setString(2, war.getName());
- warStatement.setString(3, war.getLabel());
- warStatement.setString(4, war.getSide1().getUUID().toString());
- warStatement.setString(5, war.getSide2().getUUID().toString());
- warStatement.setBoolean(6, war.isEvent());
-
- // Update
- warStatement.setString(7, war.getName());
- warStatement.setString(8, war.getLabel());
- warStatement.setString(9, war.getSide1().getUUID().toString());
- warStatement.setString(10, war.getSide2().getUUID().toString());
- warStatement.setBoolean(11, war.isEvent());
-
- warStatement.executeUpdate();
-
- // Save sides
- for (@NotNull Side side : war.getSides()) {
- saveSide(con, side);
- }
-
- // Save sieges
- for (@NotNull Siege siege : war.getSieges()) {
- saveSiege(con, siege);
- }
- }
- } catch (SQLException e) {
- e.printStackTrace();
- }
- }
-
- private static void saveSide(@NotNull Connection con, @NotNull Side side) {
- try (
- PreparedStatement sideStatement = con.prepareStatement("INSERT INTO `wars_sides` (`war`, `uuid`, `side`, `team`, `name`, `town`, `siegeGrace`, `raidGrace`) VALUES (?, ?, ?, ?, ?, ?, ?, ?) "
- + "ON DUPLICATE KEY UPDATE `side` = ?, `team` = ?, `name` = ?, `town` = ?, `siegeGrace` = ?, `raidGrace` = ?")
- ) {
- // Insert
- sideStatement.setString(1, side.getWar().getUUID().toString());
- sideStatement.setString(2, side.getUUID().toString());
- sideStatement.setString(3, side.getSide().toString());
- sideStatement.setString(4, side.getTeam().toString());
- sideStatement.setString(5, side.getName());
- sideStatement.setString(6, side.getTown().getUUID().toString());
- sideStatement.setTimestamp(7, Timestamp.from(side.getSiegeGrace()));
- sideStatement.setTimestamp(8, Timestamp.from(side.getRaidGrace()));
-
- // Update
- sideStatement.setString(9, side.getSide().toString());
- sideStatement.setString(10, side.getTeam().toString());
- sideStatement.setString(11, side.getName());
- sideStatement.setString(12, side.getTown().getUUID().toString());
- sideStatement.setTimestamp(13, Timestamp.from(side.getSiegeGrace()));
- sideStatement.setTimestamp(14, Timestamp.from(side.getRaidGrace()));
-
- sideStatement.executeUpdate();
-
- saveSideNations(con, side, false);
- saveSideNations(con, side, true);
- saveSideTowns(con, side, false);
- saveSideTowns(con, side, true);
- saveSidePlayers(con, side, false);
- saveSidePlayers(con, side, true);
- } catch (SQLException e) {
- e.printStackTrace();
- }
- }
-
- private static void saveSideNations(@NotNull Connection con, @NotNull Side side, boolean surrendered) throws SQLException {
- try (
- PreparedStatement deleteStatement = con.prepareStatement("DELETE FROM `%s` WHERE `side` = ?".formatted(surrendered ? "wars_sides_nations_surrendered" : "wars_sides_nations"));
- PreparedStatement insertStatement = con.prepareStatement("INSERT INTO `%s` (`side`, `nation`) VALUES (?, ?)".formatted(surrendered ? "wars_sides_nations_surrendered" : "wars_sides_nations"))
- ) {
- try {
- // Transaction start
- con.setAutoCommit(false);
-
- // Delete old
- deleteStatement.setString(1, side.getUUID().toString());
- deleteStatement.executeUpdate();
-
- // Insert new
- for (@NotNull Nation nation : (surrendered ? side.getSurrenderedNations() : side.getNations())) {
- insertStatement.setString(1, side.getUUID().toString());
- insertStatement.setString(2, nation.getUUID().toString());
- insertStatement.executeUpdate();
- }
-
- // Transaction end
- con.commit();
- } catch (Exception e) {
- con.rollback();
- } finally {
- con.setAutoCommit(true);
- }
- }
- }
-
- private static void saveSideTowns(@NotNull Connection con, @NotNull Side side, boolean surrendered) throws SQLException {
- try (
- PreparedStatement deleteStatement = con.prepareStatement("DELETE FROM `%s` WHERE `side` = ?".formatted(surrendered ? "wars_sides_towns_surrendered" : "wars_sides_towns"));
- PreparedStatement insertStatement = con.prepareStatement("INSERT INTO `%s` (`side`, `town`) VALUES (?, ?)".formatted(surrendered ? "wars_sides_towns_surrendered" : "wars_sides_towns"))
- ) {
- try {
- // Transaction start
- con.setAutoCommit(false);
-
- // Delete old
- deleteStatement.setString(1, side.getUUID().toString());
- deleteStatement.executeUpdate();
-
- // Insert new
- for (@NotNull Town town : (surrendered ? side.getSurrenderedTowns() : side.getTowns())) {
- insertStatement.setString(1, side.getUUID().toString());
- insertStatement.setString(2, town.getUUID().toString());
- insertStatement.executeUpdate();
- }
-
- // Transaction end
- con.commit();
- } catch (Exception e) {
- con.rollback();
- } finally {
- con.setAutoCommit(true);
- }
- }
- }
-
- private static void saveSidePlayers(@NotNull Connection con, @NotNull Side side, boolean surrendered) throws SQLException {
- try (
- PreparedStatement deleteStatement = con.prepareStatement("DELETE FROM `%s` WHERE `side` = ?".formatted(surrendered ? "wars_sides_players_surrendered" : "wars_sides_players"));
- PreparedStatement insertStatement = con.prepareStatement("INSERT INTO `%s` (`side`, `player`) VALUES (?, ?)".formatted(surrendered ? "wars_sides_players_surrendered" : "wars_sides_players"))
- ) {
- try {
- // Transaction start
- con.setAutoCommit(false);
-
- // Delete old
- deleteStatement.setString(1, side.getUUID().toString());
- deleteStatement.executeUpdate();
-
- // Insert new
- for (@NotNull UUID uuid : (surrendered ? side.getSurrenderedPlayersIncludingOffline() : side.getPlayersIncludingOffline())) {
- insertStatement.setString(1, side.getUUID().toString());
- insertStatement.setString(2, uuid.toString());
- insertStatement.executeUpdate();
- }
-
- // Transaction end
- con.commit();
- } catch (Exception e) {
- con.rollback();
- } finally {
- con.setAutoCommit(true);
- }
- }
- }
-
- public static @NotNull Set loadAll() {
- @NotNull Set wars = new HashSet<>();
-
- try (
- @NotNull Connection con = DB.get();
- PreparedStatement warStatement = con.prepareStatement("SELECT * FROM `wars_list`")
- ) {
- // Load all wars
- ResultSet warsResult = warStatement.executeQuery();
-
- if (warsResult == null)
- throw new SQLException("Failed to get wars from DB");
-
- while (warsResult.next()) {
- // War data
- @NotNull UUID uuid = UUID.fromString(warsResult.getString("uuid"));
- String name = warsResult.getString("name");
- String label = warsResult.getString("label");
- @NotNull UUID side1UUID = UUID.fromString(warsResult.getString("side1"));
- @NotNull UUID side2UUID = UUID.fromString(warsResult.getString("side2"));
- @NotNull Side side1 = loadSide(con, uuid, side1UUID);
- @NotNull Side side2 = loadSide(con, uuid, side2UUID);
- boolean event = warsResult.getBoolean("event");
-
- wars.add(new War(
- uuid,
- name,
- label,
- side1,
- side2,
- new HashSet<>(),
- new HashSet<>(),
- event
- ));
- }
-
- for (War war : wars) {
- @NotNull Set sieges = loadSieges(con, war);
- war.setSieges(sieges);
- }
- } catch (SQLException e) {
- e.printStackTrace();
- }
-
- return wars;
- }
-
- @Contract("_, _, _ -> new")
- public static @NotNull Side loadSide(@NotNull Connection con, @NotNull UUID warUUID, @NotNull UUID uuid) {
- try (PreparedStatement warStatement = con.prepareStatement("SELECT * FROM `wars_sides` WHERE `war` = ? AND `uuid` = ?")) {
- // Load side
- warStatement.setString(1, warUUID.toString());
- warStatement.setString(2, uuid.toString());
- ResultSet sideResult = warStatement.executeQuery();
-
- if (sideResult == null)
- throw new SQLException("Failed to get side from DB");
-
- sideResult.next();
-
- // Side data
- @NotNull BattleSide side = BattleSide.valueOf(sideResult.getString("side"));
- @NotNull BattleTeam team = BattleTeam.valueOf(sideResult.getString("team"));
- String name = sideResult.getString("name");
- @Nullable Town town = TownyAPI.getInstance().getTown(UUID.fromString(sideResult.getString("town")));
- Instant siegeGrace = sideResult.getTimestamp("siegeGrace").toInstant();
- Instant raidGrace = sideResult.getTimestamp("raidGrace").toInstant();
-
- @NotNull Set players = loadSidePlayers(con, uuid, false);
- @NotNull Set playersSurrendered = loadSidePlayers(con, uuid, true);
- @NotNull Set nations = loadSideNations(con, uuid, false);
- @NotNull Set nationsSurrendered = loadSideNations(con, uuid, true);
- @NotNull Set towns = loadSideTowns(con, uuid, false);
- @NotNull Set townsSurrendered = loadSideTowns(con, uuid, true);
-
- return new Side(
- warUUID,
- uuid,
- town,
- side,
- team,
- name,
- towns,
- nations,
- players,
- townsSurrendered,
- nationsSurrendered,
- playersSurrendered,
- siegeGrace,
- raidGrace
- );
- } catch (SQLException e) {
- e.printStackTrace();
- throw new RuntimeException(e);
- }
- }
-
- public static @NotNull Set loadSidePlayers(@NotNull Connection con, @NotNull UUID sideUUID, boolean surrendered) {
- @NotNull Set players = new HashSet<>();
-
- try (PreparedStatement warStatement = con.prepareStatement("SELECT * FROM `%s` WHERE `side` = ?".formatted(surrendered ? "wars_sides_players_surrendered" : "wars_sides_players"))) {
- warStatement.setString(1, sideUUID.toString());
- ResultSet warsResult = warStatement.executeQuery();
-
- if (warsResult == null)
- throw new SQLException("Failed to get players from DB");
-
- while (warsResult.next()) {
- players.add(UUID.fromString(warsResult.getString("player")));
- }
- } catch (SQLException e) {
- e.printStackTrace();
- }
-
- return players;
- }
-
- public static @NotNull Set loadSideNations(@NotNull Connection con, @NotNull UUID sideUUID, boolean surrendered) {
- @NotNull Set nations = new HashSet<>();
-
- try (PreparedStatement warStatement = con.prepareStatement("SELECT * FROM `%s` WHERE `side` = ?".formatted(surrendered ? "wars_sides_nations_surrendered" : "wars_sides_nations"))) {
- warStatement.setString(1, sideUUID.toString());
- ResultSet warsResult = warStatement.executeQuery();
-
- if (warsResult == null)
- throw new SQLException("Failed to get nations from DB");
-
- while (warsResult.next()) {
- final @NotNull UUID uuid = UUID.fromString(warsResult.getString("nation"));
-
- @Nullable Nation nation = TownyAPI.getInstance().getNation(uuid);
- if (nation == null) continue;
-
- nations.add(nation);
- }
- } catch (SQLException e) {
- e.printStackTrace();
- }
-
- return nations;
- }
-
- public static @NotNull Set loadSideTowns(@NotNull Connection con, @NotNull UUID sideUUID, boolean surrendered) {
- @NotNull Set towns = new HashSet<>();
-
- try (PreparedStatement warStatement = con.prepareStatement("SELECT * FROM `%s` WHERE `side` = ?".formatted(surrendered ? "wars_sides_towns_surrendered" : "wars_sides_towns"))) {
- warStatement.setString(1, sideUUID.toString());
- ResultSet warsResult = warStatement.executeQuery();
-
- if (warsResult == null)
- throw new SQLException("Failed to get towns from DB");
-
- while (warsResult.next()) {
- final @NotNull UUID uuid = UUID.fromString(warsResult.getString("town"));
-
- @Nullable Town town = TownyAPI.getInstance().getTown(uuid);
- if (town == null) continue;
-
- towns.add(town);
- }
- } catch (SQLException e) {
- e.printStackTrace();
- }
-
- return towns;
- }
-
- public static @NotNull Set loadSieges(@NotNull Connection con, @NotNull War war) {
- @NotNull Set sieges = new HashSet<>();
-
- try (PreparedStatement siegesStatement = con.prepareStatement("SELECT * FROM `wars_sieges` WHERE `war` = ?")) {
- siegesStatement.setString(1, war.getUUID().toString());
- ResultSet siegesResults = siegesStatement.executeQuery();
-
- if (siegesResults == null)
- throw new SQLException("Failed to get sieges from DB");
-
- while (siegesResults.next()) {
- final UUID uuid = UUID.fromString(siegesResults.getString("uuid"));
- final @Nullable Town town = TownyAPI.getInstance().getTown(UUID.fromString(siegesResults.getString("town")));
- final OfflinePlayer siegeLeader = Bukkit.getOfflinePlayer(UUID.fromString(siegesResults.getString("siegeLeader")));
- final Instant endTime = siegesResults.getTimestamp("endTime").toInstant();
- final Instant lastTouched = siegesResults.getTimestamp("lastTouched").toInstant();
- final int siegeProgress = siegesResults.getInt("siegeProgress");
- final Set attackersIncludingOffline = loadSiegePlayers(con, uuid, true);
- final Set defendersIncludingOffline = loadSiegePlayers(con, uuid, false);
-
- if (town == null) continue;
-
- sieges.add(new Siege(
- war,
- uuid,
- town,
- siegeLeader,
- endTime,
- lastTouched,
- siegeProgress,
- attackersIncludingOffline,
- defendersIncludingOffline
- ));
- }
- } catch (SQLException e) {
- e.printStackTrace();
- }
-
- return sieges;
- }
-
- public static @NotNull Set loadSiegePlayers(@NotNull Connection con, @NotNull UUID siegeUUID, boolean getAttackers) {
- @NotNull Set players = new HashSet<>();
-
- try (PreparedStatement siegeStatement = con.prepareStatement("SELECT * FROM `%s` WHERE `siege` = ?".formatted(getAttackers ? "wars_sieges_players_attackers" : "wars_sieges_players_defenders"))) {
- siegeStatement.setString(1, siegeUUID.toString());
- ResultSet playersResult = siegeStatement.executeQuery();
-
- if (playersResult == null)
- throw new SQLException("Failed to get players from DB");
-
- while (playersResult.next()) {
- players.add(UUID.fromString(playersResult.getString("player")));
- }
- } catch (SQLException e) {
- e.printStackTrace();
- }
-
- return players;
- }
-
- public static void deleteWar(@NotNull War war) {
- try (
- @NotNull Connection con = DB.get();
- PreparedStatement warStatement = con.prepareStatement("DELETE FROM `wars_list` WHERE `uuid` = ?")
- ) {
- // Delete war data
- warStatement.setString(1, war.getUUID().toString());
- warStatement.executeUpdate();
- } catch (SQLException e) {
- e.printStackTrace();
- }
- }
-
- public static void deleteSiege(@NotNull Siege siege) {
- try (
- @NotNull Connection con = DB.get();
- PreparedStatement siegesStatement = con.prepareStatement("DELETE FROM `wars_sieges` WHERE `uuid` = ?")
- ) {
- // Delete siege data
- siegesStatement.setString(1, siege.getUUID().toString());
- siegesStatement.executeUpdate();
- } catch (SQLException e) {
- e.printStackTrace();
- }
- }
-
- private static void saveSiege(@NotNull Connection con, @NotNull Siege siege) {
- try (
- PreparedStatement siegeStatement = con.prepareStatement("INSERT INTO `wars_sieges` (`war`, `uuid`, `town`, `siegeLeader`, `endTime`, `lastTouched`, `siegeProgress`) VALUES (?, ?, ?, ?, ?, ?, ?) "
- + "ON DUPLICATE KEY UPDATE `war` = ?, `town` = ?, `siegeLeader` = ?, `endTime` = ?, `lastTouched` = ?, `siegeProgress` = ?")
- ) {
- // Insert
- siegeStatement.setString(1, siege.getWar().getUUID().toString());
- siegeStatement.setString(2, siege.getUUID().toString());
- siegeStatement.setString(3, siege.getTown().getUUID().toString());
- siegeStatement.setString(4, siege.getSiegeLeader().getUniqueId().toString());
- siegeStatement.setTimestamp(5, Timestamp.from(siege.getEndTime()));
- siegeStatement.setTimestamp(6, Timestamp.from(siege.getLastTouched()));
- siegeStatement.setInt(7, siege.getSiegeProgress());
-
- // Update
- siegeStatement.setString(8, siege.getWar().getUUID().toString());
- siegeStatement.setString(9, siege.getTown().getUUID().toString());
- siegeStatement.setString(10, siege.getSiegeLeader().getUniqueId().toString());
- siegeStatement.setTimestamp(11, Timestamp.from(siege.getEndTime()));
- siegeStatement.setTimestamp(12, Timestamp.from(siege.getLastTouched()));
- siegeStatement.setInt(13, siege.getSiegeProgress());
-
- siegeStatement.executeUpdate();
-
- saveSiegePlayers(con, siege, false);
- saveSiegePlayers(con, siege, true);
- } catch (SQLException e) {
- e.printStackTrace();
- }
- }
-
- private static void saveSiegePlayers(@NotNull Connection con, @NotNull Siege siege, boolean isAttacker) throws SQLException {
- try (
- PreparedStatement deleteStatement = con.prepareStatement("DELETE FROM `%s` WHERE `siege` = ?".formatted(isAttacker ? "wars_sieges_players_attackers" : "wars_sieges_players_defenders"));
- PreparedStatement insertStatement = con.prepareStatement("INSERT INTO `%s` (`siege`, `player`) VALUES (?, ?)".formatted(isAttacker ? "wars_sieges_players_attackers" : "wars_sieges_players_defenders"))
- ) {
- try {
- // Transaction start
- con.setAutoCommit(false);
-
- // Delete old
- deleteStatement.setString(1, siege.getUUID().toString());
- deleteStatement.executeUpdate();
-
- // Insert new
- for (@NotNull UUID uuid : (isAttacker ? siege.getAttackerPlayersIncludingOffline() : siege.getDefenderPlayersIncludingOffline())) {
- insertStatement.setString(1, siege.getUUID().toString());
- insertStatement.setString(2, uuid.toString());
- insertStatement.executeUpdate();
- }
-
- // Transaction end
- con.commit();
- } catch (Exception e) {
- con.rollback();
- } finally {
- con.setAutoCommit(true);
- }
- }
- }
-}
diff --git a/src/main/resources/config.yml b/src/main/resources/config.yml
index ea3caa0..e8c5d61 100644
--- a/src/main/resources/config.yml
+++ b/src/main/resources/config.yml
@@ -8,9 +8,12 @@ minimumPlayTime: 12
batteringRamEffectiveness: 10
# Database Settings
-mysql:
- enabled: false
- host: "127.0.0.1:3306" # Must include port
+db:
+ type: "h2" # Available types: "hsqldb", "h2", "mysql", "mariadb"
+ prefix: "wars_" # The table prefix
+ host: "127.0.0.1"
+ port: 3306
database: "database_name"
user: "name"
pass: "123"
+ repair: false
diff --git a/src/main/resources/db/migration/V1__Initial_Tables.sql b/src/main/resources/db/migration/V1__Initial_Tables.sql
new file mode 100644
index 0000000..a1b6b03
--- /dev/null
+++ b/src/main/resources/db/migration/V1__Initial_Tables.sql
@@ -0,0 +1,71 @@
+CREATE TABLE IF NOT EXISTS ${tablePrefix}list (
+ uuid ${uuidType} NOT NULL DEFAULT uuid(),
+ "name" TINYTEXT NOT NULL,
+ label TINYTEXT NOT NULL,
+ side1 ${uuidType} NOT NULL DEFAULT uuid(),
+ side2 ${uuidType} NOT NULL DEFAULT uuid(),
+ event TINYINT(1) NOT NULL DEFAULT 0,
+ PRIMARY KEY (uuid),
+ INDEX side2 (side2),
+ INDEX side1 (side1)
+)${tableDefaults};
+
+CREATE TABLE IF NOT EXISTS ${tablePrefix}sides (
+ war ${uuidType} NOT NULL,
+ uuid ${uuidType} NOT NULL,
+ side TINYTEXT NOT NULL,
+ team TINYTEXT NOT NULL,
+ "name" TINYTEXT NOT NULL,
+ town ${uuidType} NOT NULL,
+ siegeGrace TIMESTAMP NOT NULL,
+ raidGrace TIMESTAMP NOT NULL,
+ PRIMARY KEY (uuid),
+ INDEX town (town),
+ INDEX war (war),
+ CONSTRAINT war FOREIGN KEY (war) REFERENCES ${tablePrefix}list (uuid) ON UPDATE CASCADE ON DELETE CASCADE
+)${tableDefaults};
+
+CREATE TABLE IF NOT EXISTS ${tablePrefix}sides_nations (
+ side ${uuidType} NOT NULL,
+ nation ${uuidType} NOT NULL,
+ surrendered TINYINT(1) NOT NULL DEFAULT 0,
+ INDEX side_nations (side),
+ CONSTRAINT side_nations FOREIGN KEY (side) REFERENCES ${tablePrefix}sides (uuid) ON UPDATE CASCADE ON DELETE CASCADE
+)${tableDefaults};
+
+CREATE TABLE IF NOT EXISTS ${tablePrefix}sides_players (
+ side ${uuidType} NOT NULL,
+ player ${uuidType} NOT NULL,
+ surrendered TINYINT(1) NOT NULL DEFAULT 0,
+ INDEX side_players (side),
+ CONSTRAINT side_players FOREIGN KEY (side) REFERENCES ${tablePrefix}sides (uuid) ON UPDATE CASCADE ON DELETE CASCADE
+)${tableDefaults};
+
+CREATE TABLE IF NOT EXISTS ${tablePrefix}sides_towns (
+ side ${uuidType} NOT NULL,
+ town ${uuidType} NOT NULL,
+ surrendered TINYINT(1) NOT NULL DEFAULT 0,
+ INDEX side_towns (side),
+ CONSTRAINT side_towns FOREIGN KEY (side) REFERENCES ${tablePrefix}sides (uuid) ON UPDATE CASCADE ON DELETE CASCADE
+)${tableDefaults};
+
+CREATE TABLE IF NOT EXISTS ${tablePrefix}sieges (
+ war ${uuidType} NOT NULL,
+ uuid ${uuidType} NOT NULL,
+ town ${uuidType} NOT NULL,
+ siegeLeader ${uuidType} NOT NULL,
+ endTime TIMESTAMP NOT NULL,
+ lastTouched TIMESTAMP NOT NULL,
+ siegeProgress INT(11) NOT NULL,
+ PRIMARY KEY (uuid),
+ INDEX siege_war (war),
+ CONSTRAINT siege_war FOREIGN KEY (war) REFERENCES ${tablePrefix}list (uuid) ON UPDATE CASCADE ON DELETE CASCADE
+)${tableDefaults};
+
+CREATE TABLE IF NOT EXISTS ${tablePrefix}siege_players (
+ siege ${uuidType} NOT NULL,
+ player ${uuidType} NOT NULL,
+ team TINYINT(1) NOT NULL,
+ INDEX siege_players (siege),
+ CONSTRAINT siege_players FOREIGN KEY (siege) REFERENCES ${tablePrefix}sieges (uuid) ON UPDATE CASCADE ON DELETE CASCADE
+)${tableDefaults};