mirror of
https://github.com/darksaid98/AlathranWars.git
synced 2026-12-01 22:14:45 +00:00
refactor: prepare for raids
- Recode most classes - Add phases to battles - Pull updates from gradle-template-plugin
This commit is contained in:
1 parent
a4440c9283
commit
b1a95ed011
105 files changed
+6941
-3296
No files matched your search
@@ -1,102 +1,197 @@
|
||||
package com.github.alathra.alathranwars;
|
||||
|
||||
import com.github.alathra.alathranwars.commands.CommandManager;
|
||||
import com.github.alathra.alathranwars.commands.CommandHandler;
|
||||
import com.github.alathra.alathranwars.config.ConfigHandler;
|
||||
import com.github.alathra.alathranwars.conflict.war.WarController;
|
||||
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.database.DatabaseQueries;
|
||||
import com.github.alathra.alathranwars.database.handler.DatabaseHandler;
|
||||
import com.github.alathra.alathranwars.hook.*;
|
||||
import com.github.alathra.alathranwars.listeners.ListenerHandler;
|
||||
import net.milkbowl.vault.economy.Economy;
|
||||
import org.bukkit.plugin.RegisteredServiceProvider;
|
||||
import com.github.alathra.alathranwars.translation.TranslationManager;
|
||||
import com.github.alathra.alathranwars.updatechecker.UpdateChecker;
|
||||
import com.github.alathra.alathranwars.utility.Logger;
|
||||
import com.github.milkdrinkers.colorparser.ColorParser;
|
||||
import org.bukkit.plugin.java.JavaPlugin;
|
||||
import org.jetbrains.annotations.NotNull;
|
||||
import org.jetbrains.annotations.Nullable;
|
||||
import space.arim.morepaperlib.MorePaperLib;
|
||||
|
||||
public class AlathranWars extends JavaPlugin {
|
||||
public static @Nullable Economy econ = null;
|
||||
private static MorePaperLib paperLib;
|
||||
|
||||
private static AlathranWars instance;
|
||||
private ConfigHandler configHandler;
|
||||
private TranslationManager translationManager;
|
||||
private DatabaseHandler databaseHandler;
|
||||
private CommandHandler commandHandler;
|
||||
private ListenerHandler listenerHandler;
|
||||
private UpdateChecker updateChecker;
|
||||
|
||||
private CommandManager commandManager;
|
||||
private HookManager hookManager;
|
||||
|
||||
@SuppressWarnings("rawtypes")
|
||||
private boolean setupEconomy() {
|
||||
if (this.getServer().getPluginManager().getPlugin("Vault") == null) {
|
||||
return false;
|
||||
}
|
||||
@SuppressWarnings("unchecked") final @Nullable RegisteredServiceProvider<Economy> rsp = (RegisteredServiceProvider<Economy>) this.getServer()
|
||||
.getServicesManager().getRegistration((Class) Economy.class);
|
||||
if (rsp == null) {
|
||||
return false;
|
||||
}
|
||||
econ = rsp.getProvider();
|
||||
return econ != null;
|
||||
}
|
||||
// Hooks
|
||||
private static BStatsHook bStatsHook;
|
||||
private static VaultHook vaultHook;
|
||||
private static ProtocolLibHook protocolLibHook;
|
||||
private static PAPIHook papiHook;
|
||||
|
||||
public void onLoad() {
|
||||
instance = this;
|
||||
paperLib = new MorePaperLib(instance);
|
||||
WarController.getInstance();
|
||||
configHandler = new ConfigHandler(instance);
|
||||
databaseHandler = new DatabaseHandler(instance);
|
||||
commandManager = new CommandManager(instance);
|
||||
translationManager = new TranslationManager(instance);
|
||||
databaseHandler = new DatabaseHandler(configHandler, getComponentLogger());
|
||||
commandHandler = new CommandHandler(instance);
|
||||
listenerHandler = new ListenerHandler(instance);
|
||||
hookManager = new HookManager();
|
||||
updateChecker = new UpdateChecker();
|
||||
bStatsHook = new BStatsHook(instance);
|
||||
vaultHook = new VaultHook(instance);
|
||||
protocolLibHook = new ProtocolLibHook(instance);
|
||||
papiHook = new PAPIHook(instance);
|
||||
|
||||
configHandler.onLoad();
|
||||
translationManager.onLoad();
|
||||
databaseHandler.onLoad();
|
||||
commandManager.onLoad();
|
||||
commandHandler.onLoad();
|
||||
listenerHandler.onLoad();
|
||||
hookManager.onLoad();
|
||||
updateChecker.onLoad();
|
||||
bStatsHook.onLoad();
|
||||
vaultHook.onLoad();
|
||||
protocolLibHook.onLoad();
|
||||
papiHook.onLoad();
|
||||
}
|
||||
|
||||
public void onEnable() {
|
||||
this.saveDefaultConfig();
|
||||
new WarItemRegistry();
|
||||
setupEconomy();
|
||||
|
||||
configHandler.onEnable();
|
||||
translationManager.onEnable();
|
||||
databaseHandler.onEnable();
|
||||
commandManager.onEnable();
|
||||
commandHandler.onEnable();
|
||||
listenerHandler.onEnable();
|
||||
hookManager.onEnable();
|
||||
updateChecker.onEnable();
|
||||
bStatsHook.onEnable();
|
||||
vaultHook.onEnable();
|
||||
protocolLibHook.onEnable();
|
||||
papiHook.onEnable();
|
||||
|
||||
if (!databaseHandler.isRunning()) {
|
||||
Logger.get().warn(ColorParser.of("<yellow>Database handler failed to start. Database support has been disabled.").build());
|
||||
}
|
||||
|
||||
if (vaultHook.isVaultLoaded()) {
|
||||
Logger.get().info(ColorParser.of("<green>Vault has been found on this server. Vault support enabled.").build());
|
||||
} else {
|
||||
Logger.get().warn(ColorParser.of("<yellow>Vault is not installed on this server. Vault support has been disabled.").build());
|
||||
}
|
||||
|
||||
if (protocolLibHook.isHookLoaded()) {
|
||||
Logger.get().info(ColorParser.of("<green>ProtocolLib has been found on this server. ProtocolLib support enabled.").build());
|
||||
} else {
|
||||
Logger.get().warn(ColorParser.of("<yellow>ProtocolLib is not installed on this server. ProtocolLib support has been disabled.").build());
|
||||
}
|
||||
|
||||
WarController.getInstance().loadAll();
|
||||
}
|
||||
|
||||
public void onDisable() {
|
||||
getPaperLib().scheduling().cancelGlobalTasks();
|
||||
DatabaseQueries.saveAll();
|
||||
commandManager.onDisable();
|
||||
listenerHandler.onDisable();
|
||||
hookManager.onDisable();
|
||||
databaseHandler.onDisable();
|
||||
|
||||
configHandler.onDisable();
|
||||
translationManager.onDisable();
|
||||
databaseHandler.onDisable();
|
||||
commandHandler.onDisable();
|
||||
listenerHandler.onDisable();
|
||||
updateChecker.onDisable();
|
||||
bStatsHook.onDisable();
|
||||
vaultHook.onDisable();
|
||||
protocolLibHook.onDisable();
|
||||
papiHook.onDisable();
|
||||
}
|
||||
|
||||
/**
|
||||
* Gets plugin instance.
|
||||
*
|
||||
* @return the plugin instance
|
||||
*/
|
||||
@NotNull
|
||||
public static AlathranWars getInstance() {
|
||||
return instance;
|
||||
}
|
||||
|
||||
/**
|
||||
* Gets more paper lib instance.
|
||||
*
|
||||
* @return the more paper lib instance
|
||||
*/
|
||||
public static MorePaperLib getPaperLib() {
|
||||
return paperLib;
|
||||
}
|
||||
|
||||
/**
|
||||
* Gets data handler.
|
||||
*
|
||||
* @return the data handler
|
||||
*/
|
||||
@NotNull
|
||||
public DatabaseHandler getDataHandler() {
|
||||
return databaseHandler;
|
||||
}
|
||||
|
||||
/**
|
||||
* Gets config handler.
|
||||
*
|
||||
* @return the config handler
|
||||
*/
|
||||
@NotNull
|
||||
public ConfigHandler getConfigHandler() {
|
||||
return configHandler;
|
||||
}
|
||||
|
||||
/**
|
||||
* Gets config handler.
|
||||
*
|
||||
* @return the translation handler
|
||||
*/
|
||||
@NotNull
|
||||
public TranslationManager getTranslationManager() {
|
||||
return translationManager;
|
||||
}
|
||||
|
||||
/**
|
||||
* Gets update checker.
|
||||
*
|
||||
* @return the update checker
|
||||
*/
|
||||
@NotNull
|
||||
public UpdateChecker getUpdateChecker() {
|
||||
return updateChecker;
|
||||
}
|
||||
|
||||
/**
|
||||
* Gets bStats hook.
|
||||
*
|
||||
* @return the bStats hook
|
||||
*/
|
||||
@NotNull
|
||||
public static BStatsHook getBStatsHook() {
|
||||
return bStatsHook;
|
||||
}
|
||||
|
||||
/**
|
||||
* Gets vault hook.
|
||||
*
|
||||
* @return the vault hook
|
||||
*/
|
||||
@NotNull
|
||||
public static VaultHook getVaultHook() {
|
||||
return vaultHook;
|
||||
}
|
||||
|
||||
/**
|
||||
* Gets ProtocolLib hook.
|
||||
*
|
||||
* @return the ProtocolLib hook
|
||||
*/
|
||||
@NotNull
|
||||
public static ProtocolLibHook getProtocolLibHook() {
|
||||
return protocolLibHook;
|
||||
}
|
||||
}
|
||||
@@ -1,7 +1,7 @@
|
||||
package com.github.alathra.alathranwars.commands;
|
||||
|
||||
import com.github.alathra.alathranwars.AlathranWars;
|
||||
import com.github.alathra.alathranwars.hooks.NameColorHandler;
|
||||
import com.github.alathra.alathranwars.hook.NameColorHandler;
|
||||
import com.github.alathra.alathranwars.items.WarItemRegistry;
|
||||
import com.github.alathra.alathranwars.utility.UtilsChat;
|
||||
import com.github.milkdrinkers.colorparser.ColorParser;
|
||||
|
||||
+10
-5
@@ -4,15 +4,20 @@ import com.github.alathra.alathranwars.AlathranWars;
|
||||
import dev.jorel.commandapi.CommandAPI;
|
||||
import dev.jorel.commandapi.CommandAPIBukkitConfig;
|
||||
|
||||
public class CommandManager {
|
||||
private final AlathranWars instance;
|
||||
public class CommandHandler {
|
||||
private final AlathranWars plugin;
|
||||
|
||||
public CommandManager(AlathranWars instance) {
|
||||
this.instance = instance;
|
||||
/**
|
||||
* Instantiates the Command handler.
|
||||
*
|
||||
* @param plugin the plugin
|
||||
*/
|
||||
public CommandHandler(AlathranWars plugin) {
|
||||
this.plugin = plugin;
|
||||
}
|
||||
|
||||
public void onLoad() {
|
||||
CommandAPI.onLoad(new CommandAPIBukkitConfig(instance).shouldHookPaperReload(true).silentLogs(true));
|
||||
CommandAPI.onLoad(new CommandAPIBukkitConfig(plugin).shouldHookPaperReload(true).silentLogs(true));
|
||||
}
|
||||
|
||||
public void onEnable() {
|
||||
@@ -7,7 +7,6 @@ import com.github.alathra.alathranwars.conflict.war.WarController;
|
||||
import com.github.alathra.alathranwars.conflict.war.side.Side;
|
||||
import com.github.alathra.alathranwars.enums.CommandArgsSiege;
|
||||
import com.github.alathra.alathranwars.enums.CommandArgsWar;
|
||||
import com.github.alathra.alathranwars.hooks.TownyHook;
|
||||
import com.github.alathra.alathranwars.items.WarItemRegistry;
|
||||
import com.github.alathra.alathranwars.utility.UtilsChat;
|
||||
import com.github.milkdrinkers.colorparser.ColorParser;
|
||||
@@ -31,10 +30,7 @@ import org.jetbrains.annotations.Nullable;
|
||||
|
||||
import java.time.Duration;
|
||||
import java.time.Instant;
|
||||
import java.util.ArrayList;
|
||||
import java.util.Collections;
|
||||
import java.util.List;
|
||||
import java.util.UUID;
|
||||
import java.util.*;
|
||||
import java.util.stream.Collectors;
|
||||
import java.util.stream.Stream;
|
||||
|
||||
@@ -66,7 +62,7 @@ public class CommandUtil {
|
||||
|
||||
return TownyAPI.getInstance().getNation(argNationName);
|
||||
}).replaceSuggestions(ArgumentSuggestions.stringCollection(info -> {
|
||||
final @NotNull List<String> nationNames = TownyHook.getNations()
|
||||
final @NotNull List<String> nationNames = TownyAPI.getInstance().getNations()
|
||||
.stream()
|
||||
.map(Nation::getName)
|
||||
.sorted()
|
||||
@@ -85,7 +81,7 @@ public class CommandUtil {
|
||||
|
||||
return TownyAPI.getInstance().getTown(argTownName);
|
||||
}).replaceSuggestions(ArgumentSuggestions.stringCollection(info -> {
|
||||
final @NotNull List<String> townNames = TownyHook.getTowns()
|
||||
final @NotNull List<String> townNames = TownyAPI.getInstance().getTowns()
|
||||
.stream()
|
||||
.map(Town::getName)
|
||||
.sorted()
|
||||
@@ -107,17 +103,17 @@ public class CommandUtil {
|
||||
|
||||
@Nullable Nation nation = TownyAPI.getInstance().getNation(argNationName);
|
||||
|
||||
if (war.getNations().contains(nation) || war.getSurrenderedNations().contains(nation))
|
||||
if (war.getNations().contains(nation) || war.getNationsSurrendered().contains(nation))
|
||||
return nation;
|
||||
|
||||
throw CustomArgument.CustomArgumentException.fromAdventureComponent(ColorParser.of(UtilsChat.getPrefix() + "<red>The nation is already at war!").parseLegacy().build());
|
||||
}).replaceSuggestions(ArgumentSuggestions.stringCollection(info -> {
|
||||
final @NotNull List<String> nationNames = TownyHook.getNations()
|
||||
final @NotNull List<String> nationNames = TownyAPI.getInstance().getNations()
|
||||
.stream()
|
||||
.map(Nation::getName)
|
||||
.sorted()
|
||||
.collect(Collectors.toList());
|
||||
final @NotNull List<String> townNames = TownyHook.getTowns()
|
||||
final @NotNull List<String> townNames = TownyAPI.getInstance().getTowns()
|
||||
.stream()
|
||||
.map(Town::getName)
|
||||
.sorted()
|
||||
@@ -131,7 +127,7 @@ public class CommandUtil {
|
||||
|
||||
final @NotNull List<String> removeNames = Stream.concat( // Create a list of all nations in war
|
||||
war.getNations().stream().map(Nation::getName),
|
||||
war.getSurrenderedNations().stream().map(Nation::getName)
|
||||
war.getNationsSurrendered().stream().map(Nation::getName)
|
||||
).toList();
|
||||
|
||||
nationNames.removeAll(removeNames);
|
||||
@@ -152,12 +148,12 @@ public class CommandUtil {
|
||||
|
||||
@Nullable Town town = TownyAPI.getInstance().getTown(argTownName);
|
||||
|
||||
if (war.getTowns().contains(town) || war.getSurrenderedTowns().contains(town))
|
||||
if (war.getTowns().contains(town) || war.getTownsSurrendered().contains(town))
|
||||
return town;
|
||||
|
||||
throw CustomArgument.CustomArgumentException.fromAdventureComponent(ColorParser.of(UtilsChat.getPrefix() + "<red>The town is already at war!").parseLegacy().build());
|
||||
}).replaceSuggestions(ArgumentSuggestions.stringCollection(info -> {
|
||||
final @NotNull List<String> townNames = TownyHook.getTowns()
|
||||
final @NotNull List<String> townNames = TownyAPI.getInstance().getTowns()
|
||||
.stream()
|
||||
.map(Town::getName)
|
||||
.sorted()
|
||||
@@ -169,7 +165,7 @@ public class CommandUtil {
|
||||
|
||||
final @NotNull List<String> removeNames = Stream.concat( // Create a list of all nations & towns in war
|
||||
war.getTowns().stream().map(Town::getName),
|
||||
war.getSurrenderedTowns().stream().map(Town::getName)
|
||||
war.getTownsSurrendered().stream().map(Town::getName)
|
||||
).toList();
|
||||
|
||||
townNames.removeAll(removeNames);
|
||||
@@ -188,7 +184,7 @@ public class CommandUtil {
|
||||
if (nation == null)
|
||||
throw CustomArgument.CustomArgumentException.fromAdventureComponent(ColorParser.of(UtilsChat.getPrefix() + "<red>The nation does not exist!").parseLegacy().build());
|
||||
|
||||
if (!war.isNationInWar(nation))
|
||||
if (!war.isInWar(nation))
|
||||
throw CustomArgument.CustomArgumentException.fromAdventureComponent(ColorParser.of(UtilsChat.getPrefix() + "<red>The nation is not in that war!").parseLegacy().build());
|
||||
|
||||
return nation;
|
||||
@@ -198,7 +194,7 @@ public class CommandUtil {
|
||||
|
||||
return Stream.concat( // Create a list of all nations & towns in war
|
||||
war.getNations().stream().map(Nation::getName),
|
||||
war.getSurrenderedNations().stream().map(Nation::getName)
|
||||
war.getNationsSurrendered().stream().map(Nation::getName)
|
||||
).sorted().toList();
|
||||
}));
|
||||
}
|
||||
@@ -213,7 +209,7 @@ public class CommandUtil {
|
||||
if (town == null)
|
||||
throw CustomArgument.CustomArgumentException.fromAdventureComponent(ColorParser.of(UtilsChat.getPrefix() + "<red>The town does not exist!").parseLegacy().build());
|
||||
|
||||
if (!war.isTownInWar(town))
|
||||
if (!war.isInWar(town))
|
||||
throw CustomArgument.CustomArgumentException.fromAdventureComponent(ColorParser.of(UtilsChat.getPrefix() + "<red>The town is not in that war!").parseLegacy().build());
|
||||
|
||||
return town;
|
||||
@@ -223,7 +219,7 @@ public class CommandUtil {
|
||||
|
||||
return Stream.concat( // Create a list of all nations & towns in war
|
||||
war.getTowns().stream().map(Town::getName),
|
||||
war.getSurrenderedTowns().stream().map(Town::getName)
|
||||
war.getTownsSurrendered().stream().map(Town::getName)
|
||||
).sorted().toList();
|
||||
}));
|
||||
}
|
||||
@@ -256,12 +252,12 @@ public class CommandUtil {
|
||||
.build()
|
||||
);
|
||||
}).replaceSuggestions(ArgumentSuggestions.stringCollection(info -> {
|
||||
final @NotNull List<String> nationNames = TownyHook.getNations()
|
||||
final @NotNull List<String> nationNames = TownyAPI.getInstance().getNations()
|
||||
.stream()
|
||||
.map(Nation::getName)
|
||||
.sorted()
|
||||
.collect(Collectors.toList());
|
||||
final @NotNull List<String> townNames = TownyHook.getTowns()
|
||||
final @NotNull List<String> townNames = TownyAPI.getInstance().getTowns()
|
||||
.stream()
|
||||
.map(Town::getName)
|
||||
.sorted()
|
||||
@@ -276,10 +272,10 @@ public class CommandUtil {
|
||||
final @NotNull List<String> removeNames = Stream.concat( // Create a list of all nations & towns in war
|
||||
war.getNations().stream().map(Nation::getName),
|
||||
Stream.concat(
|
||||
war.getSurrenderedNations().stream().map(Nation::getName),
|
||||
war.getNationsSurrendered().stream().map(Nation::getName),
|
||||
Stream.concat(
|
||||
war.getTowns().stream().map(Town::getName),
|
||||
war.getSurrenderedTowns().stream().map(Town::getName)
|
||||
war.getTownsSurrendered().stream().map(Town::getName)
|
||||
)
|
||||
)
|
||||
).toList();
|
||||
@@ -301,9 +297,9 @@ public class CommandUtil {
|
||||
);
|
||||
}
|
||||
|
||||
final List<String> townNames = war.getTowns().stream().map(Town::getName).sorted().toList();
|
||||
final List<String> nationNames = war.getNations().stream().map(Nation::getName).sorted().toList();
|
||||
final List<String> playerNames = war.getPlayersIncludingOffline().stream()
|
||||
final List<String> townNames = war.getTownsAll().stream().map(Town::getName).sorted().toList();
|
||||
final List<String> nationNames = war.getNationsAll().stream().map(Nation::getName).sorted().toList();
|
||||
final List<String> playerNames = war.getPlayersAll().stream()
|
||||
.filter(offlinePlayer -> Instant.ofEpochMilli(offlinePlayer.getLastSeen()).isAfter(Instant.now().minus(Duration.ofDays(60)))) // Remove players that haven't been on in 60 days
|
||||
.filter(p -> p.getName() != null)
|
||||
.map(OfflinePlayer::getName)
|
||||
@@ -330,12 +326,12 @@ public class CommandUtil {
|
||||
return Collections.emptyList();
|
||||
}
|
||||
|
||||
final List<String> nationNames = war.getNations().stream().map(Nation::getName).sorted().toList();
|
||||
final List<String> townNames = war.getTowns().stream().map(Town::getName).sorted().toList();
|
||||
final List<String> playerNames = war.getPlayersIncludingOffline().stream()
|
||||
final List<String> nationNames = war.getNationsAll().stream().map(Nation::getName).sorted().toList();
|
||||
final List<String> townNames = war.getTownsAll().stream().map(Town::getName).sorted().toList();
|
||||
final List<String> playerNames = war.getPlayersAll().stream()
|
||||
.filter(offlinePlayer -> Instant.ofEpochMilli(offlinePlayer.getLastSeen()).isAfter(Instant.now().minus(Duration.ofDays(60)))) // Remove players that haven't been on in 60 days
|
||||
.filter(p -> p.getName() != null)
|
||||
.map(OfflinePlayer::getName)
|
||||
.filter(Objects::nonNull)
|
||||
.sorted()
|
||||
.toList();
|
||||
|
||||
@@ -358,7 +354,7 @@ public class CommandUtil {
|
||||
if (town == null)
|
||||
throw CustomArgument.CustomArgumentException.fromAdventureComponent(ColorParser.of(UtilsChat.getPrefix() + "<red>The town does not exist!").parseLegacy().build());
|
||||
|
||||
if (!war.isTownInWar(town))
|
||||
if (!war.isInWar(town))
|
||||
throw CustomArgument.CustomArgumentException.fromAdventureComponent(ColorParser.of(UtilsChat.getPrefix() + "<red>The town is not in that war!").parseLegacy().build());
|
||||
|
||||
if (checkIfSieged) {
|
||||
@@ -376,14 +372,14 @@ public class CommandUtil {
|
||||
final @NotNull List<String> townNames = new ArrayList<>();
|
||||
|
||||
if (info.sender() instanceof Player p) {
|
||||
if (war.getSide1().isPlayerOnSide(p)) {
|
||||
if (war.getSide1().isOnSide(p)) {
|
||||
townNames.addAll(war.getSide2().getTowns()
|
||||
.stream()
|
||||
.map(TownyObject::getName)
|
||||
.sorted()
|
||||
.toList()
|
||||
);
|
||||
} else if (war.getSide2().isPlayerOnSide(p)) {
|
||||
} else if (war.getSide2().isOnSide(p)) {
|
||||
townNames.addAll(war.getSide1().getTowns()
|
||||
.stream()
|
||||
.map(TownyObject::getName)
|
||||
@@ -418,13 +414,13 @@ public class CommandUtil {
|
||||
if (!(info.previousArgs().get(playerNodeName) instanceof Player player))
|
||||
throw CustomArgument.CustomArgumentException.fromAdventureComponent(ColorParser.of(UtilsChat.getPrefix() + "<red>The player does not exist!").build());
|
||||
|
||||
if (!siege.isPlayerInSiege(player))
|
||||
if (!siege.isPlayerParticipating(player))
|
||||
throw CustomArgument.CustomArgumentException.fromAdventureComponent(ColorParser.of(UtilsChat.getPrefix() + "<red>The player is already in that war.").build());
|
||||
} else {
|
||||
if (!(info.sender() instanceof Player player))
|
||||
throw CustomArgument.CustomArgumentException.fromAdventureComponent(ColorParser.of(UtilsChat.getPrefix() + "<red>Only players can execute this command!").build());
|
||||
|
||||
if (!siege.isPlayerInSiege(player))
|
||||
if (!siege.isPlayerParticipating(player))
|
||||
throw CustomArgument.CustomArgumentException.fromAdventureComponent(ColorParser.of(UtilsChat.getPrefix() + "<red>You are already in this war.").build());
|
||||
}
|
||||
}
|
||||
@@ -433,13 +429,13 @@ public class CommandUtil {
|
||||
if (!(info.previousArgs().get(playerNodeName) instanceof Player player))
|
||||
throw CustomArgument.CustomArgumentException.fromAdventureComponent(ColorParser.of(UtilsChat.getPrefix() + "<red>The player does not exist!").build());
|
||||
|
||||
if (siege.isPlayerInSiege(player))
|
||||
if (siege.isPlayerParticipating(player))
|
||||
throw CustomArgument.CustomArgumentException.fromAdventureComponent(ColorParser.of(UtilsChat.getPrefix() + "<red>The player is not in that war.").build());
|
||||
} else {
|
||||
if (!(info.sender() instanceof Player player))
|
||||
throw CustomArgument.CustomArgumentException.fromAdventureComponent(ColorParser.of(UtilsChat.getPrefix() + "<red>Only players can execute this command!").build());
|
||||
|
||||
if (siege.isPlayerInSiege(player))
|
||||
if (siege.isPlayerParticipating(player))
|
||||
throw CustomArgument.CustomArgumentException.fromAdventureComponent(ColorParser.of(UtilsChat.getPrefix() + "<red>You are not in that war.").build());
|
||||
}
|
||||
}
|
||||
@@ -462,11 +458,11 @@ public class CommandUtil {
|
||||
|
||||
if (isAdmin) {
|
||||
if (info.previousArgs().get(playerNodeName) instanceof Player player) {
|
||||
siegeNames = WarController.getInstance().getSieges().stream().filter(siege -> !siege.isPlayerInSiege(player)).map(Siege::getName).toList();
|
||||
siegeNames = WarController.getInstance().getSieges().stream().filter(siege -> !siege.isPlayerParticipating(player)).map(Siege::getName).toList();
|
||||
}
|
||||
} else {
|
||||
if (info.sender() instanceof Player player) {
|
||||
siegeNames = WarController.getInstance().getSieges().stream().filter(siege -> !siege.isPlayerInSiege(player)).map(Siege::getName).toList();
|
||||
siegeNames = WarController.getInstance().getSieges().stream().filter(siege -> !siege.isPlayerParticipating(player)).map(Siege::getName).toList();
|
||||
}
|
||||
}
|
||||
|
||||
@@ -478,11 +474,11 @@ public class CommandUtil {
|
||||
|
||||
if (isAdmin) {
|
||||
if (info.previousArgs().get(playerNodeName) instanceof Player player) {
|
||||
siegeNames = WarController.getInstance().getSieges().stream().filter(siege -> siege.isPlayerInSiege(player)).map(Siege::getName).toList();
|
||||
siegeNames = WarController.getInstance().getSieges().stream().filter(siege -> siege.isPlayerParticipating(player)).map(Siege::getName).toList();
|
||||
}
|
||||
} else {
|
||||
if (info.sender() instanceof Player player) {
|
||||
siegeNames = WarController.getInstance().getSieges().stream().filter(siege -> siege.isPlayerInSiege(player)).map(Siege::getName).toList();
|
||||
siegeNames = WarController.getInstance().getSieges().stream().filter(siege -> siege.isPlayerParticipating(player)).map(Siege::getName).toList();
|
||||
}
|
||||
}
|
||||
|
||||
@@ -503,13 +499,13 @@ public class CommandUtil {
|
||||
if (!(info.previousArgs().get(playerNodeName) instanceof Player player))
|
||||
throw CustomArgument.CustomArgumentException.fromAdventureComponent(ColorParser.of(UtilsChat.getPrefix() + "<red>The player does not exist!").parseLegacy().build());
|
||||
|
||||
if (!war.isPlayerInWar(player))
|
||||
if (!war.isInWar(player))
|
||||
throw CustomArgument.CustomArgumentException.fromAdventureComponent(ColorParser.of(UtilsChat.getPrefix() + "<red>The player is already in that war.").parseLegacy().build());
|
||||
} else {
|
||||
if (!(info.sender() instanceof Player player))
|
||||
throw CustomArgument.CustomArgumentException.fromAdventureComponent(ColorParser.of(UtilsChat.getPrefix() + "<red>Only players can execute this command!").parseLegacy().build());
|
||||
|
||||
if (!war.isPlayerInWar(player))
|
||||
if (!war.isInWar(player))
|
||||
throw CustomArgument.CustomArgumentException.fromAdventureComponent(ColorParser.of(UtilsChat.getPrefix() + "<red>You are already in this war.").parseLegacy().build());
|
||||
}
|
||||
}
|
||||
@@ -518,13 +514,13 @@ public class CommandUtil {
|
||||
if (!(info.previousArgs().get(playerNodeName) instanceof Player player))
|
||||
throw CustomArgument.CustomArgumentException.fromAdventureComponent(ColorParser.of(UtilsChat.getPrefix() + "<red>The player does not exist!").parseLegacy().build());
|
||||
|
||||
if (war.isPlayerInWar(player))
|
||||
if (war.isInWar(player))
|
||||
throw CustomArgument.CustomArgumentException.fromAdventureComponent(ColorParser.of(UtilsChat.getPrefix() + "<red>The player is not in that war.").parseLegacy().build());
|
||||
} else {
|
||||
if (!(info.sender() instanceof Player player))
|
||||
throw CustomArgument.CustomArgumentException.fromAdventureComponent(ColorParser.of(UtilsChat.getPrefix() + "<red>Only players can execute this command!").parseLegacy().build());
|
||||
|
||||
if (war.isPlayerInWar(player))
|
||||
if (war.isInWar(player))
|
||||
throw CustomArgument.CustomArgumentException.fromAdventureComponent(ColorParser.of(UtilsChat.getPrefix() + "<red>You are not in that war.").parseLegacy().build());
|
||||
}
|
||||
}
|
||||
@@ -547,11 +543,11 @@ public class CommandUtil {
|
||||
|
||||
if (isAdmin) {
|
||||
if (info.previousArgs().get(playerNodeName) instanceof Player player) {
|
||||
warNames = WarController.getInstance().getWars().stream().filter(war -> !war.isPlayerInWar(player)).map(War::getName).toList();
|
||||
warNames = WarController.getInstance().getWars().stream().filter(war -> !war.isInWar(player)).map(War::getName).toList();
|
||||
}
|
||||
} else {
|
||||
if (info.sender() instanceof Player player) {
|
||||
warNames = WarController.getInstance().getWars().stream().filter(war -> !war.isPlayerInWar(player)).map(War::getName).toList();
|
||||
warNames = WarController.getInstance().getWars().stream().filter(war -> !war.isInWar(player)).map(War::getName).toList();
|
||||
}
|
||||
}
|
||||
|
||||
@@ -563,11 +559,11 @@ public class CommandUtil {
|
||||
|
||||
if (isAdmin) {
|
||||
if (info.previousArgs().get(playerNodeName) instanceof Player player) {
|
||||
warNames = WarController.getInstance().getWars().stream().filter(war -> war.isPlayerInWar(player)).map(War::getName).toList();
|
||||
warNames = WarController.getInstance().getWars().stream().filter(war -> war.isInWar(player)).map(War::getName).toList();
|
||||
}
|
||||
} else {
|
||||
if (info.sender() instanceof Player player) {
|
||||
warNames = WarController.getInstance().getWars().stream().filter(war -> war.isPlayerInWar(player)).map(War::getName).toList();
|
||||
warNames = WarController.getInstance().getWars().stream().filter(war -> war.isInWar(player)).map(War::getName).toList();
|
||||
}
|
||||
}
|
||||
|
||||
@@ -594,13 +590,13 @@ public class CommandUtil {
|
||||
if (!(info.previousArgs().get(playerNodeName) instanceof Player player))
|
||||
throw CustomArgument.CustomArgumentException.fromAdventureComponent(ColorParser.of(UtilsChat.getPrefix() + "<red>The player does not exist!").parseLegacy().build());
|
||||
|
||||
if (side.getPlayers().contains(player))
|
||||
if (side.getPlayersOnline().contains(player))
|
||||
throw CustomArgument.CustomArgumentException.fromAdventureComponent(ColorParser.of(UtilsChat.getPrefix() + "<red>The player is already on that side.").parseLegacy().build());
|
||||
} else {
|
||||
if (!(info.sender() instanceof Player player))
|
||||
throw CustomArgument.CustomArgumentException.fromAdventureComponent(ColorParser.of(UtilsChat.getPrefix() + "<red>Only players can execute this command!").parseLegacy().build());
|
||||
|
||||
if (side.getPlayers().contains(player))
|
||||
if (side.getPlayersOnline().contains(player))
|
||||
throw CustomArgument.CustomArgumentException.fromAdventureComponent(ColorParser.of(UtilsChat.getPrefix() + "<red>You are already on that side.").parseLegacy().build());
|
||||
}
|
||||
}
|
||||
@@ -616,14 +612,14 @@ public class CommandUtil {
|
||||
if (isAdmin) {
|
||||
if (info.previousArgs().get(playerNodeName) instanceof Player player) {
|
||||
for (@NotNull Side side : war.getSides()) {
|
||||
if (!side.getPlayers().contains(player))
|
||||
if (!side.getPlayersOnline().contains(player))
|
||||
sideNames.add(side.getName());
|
||||
}
|
||||
}
|
||||
} else {
|
||||
if (info.sender() instanceof Player player) {
|
||||
for (@NotNull Side side : war.getSides()) {
|
||||
if (!side.getPlayers().contains(player))
|
||||
if (!side.getPlayersOnline().contains(player))
|
||||
sideNames.add(side.getName());
|
||||
}
|
||||
}
|
||||
@@ -655,7 +651,7 @@ public class CommandUtil {
|
||||
if (isTown && !war.getTowns().stream().map(Town::getName).toList().contains(argTargetName))
|
||||
return argTargetName;
|
||||
|
||||
if (isPlayer && !war.getPlayers().stream().map(Player::getName).toList().contains(argTargetName))
|
||||
if (isPlayer && !war.getPlayersOnline().stream().map(Player::getName).toList().contains(argTargetName))
|
||||
return argTargetName;
|
||||
|
||||
throw CustomArgument.CustomArgumentException.fromAdventureComponent(ColorParser.of(UtilsChat.getPrefix() + "<red>Invalid target.").build());
|
||||
@@ -665,7 +661,7 @@ public class CommandUtil {
|
||||
|
||||
// Get all participants in war into list
|
||||
final List<String> inWar = Stream.concat(
|
||||
war.getPlayers().stream().map(Player::getName),
|
||||
war.getPlayersOnline().stream().map(Player::getName),
|
||||
Stream.concat(
|
||||
war.getNations().stream().map(Nation::getName),
|
||||
war.getTowns().stream().map(Town::getName)
|
||||
|
||||
@@ -119,7 +119,7 @@ public class SiegeCommands {
|
||||
if (side == null)
|
||||
throw CommandAPIBukkit.failWithAdventureComponent(ColorParser.of("<red>You are not in this war.").build());
|
||||
|
||||
if (side.isPlayerSurrendered(siegeLeader))
|
||||
if (side.isSurrendered(siegeLeader))
|
||||
throw CommandAPIBukkit.failWithAdventureComponent(ColorParser.of("<red>You have surrendered and cannot participate in this war.").build());
|
||||
|
||||
if (side.isSiegeGraceActive() && !asAdmin)
|
||||
@@ -130,7 +130,7 @@ public class SiegeCommands {
|
||||
);
|
||||
|
||||
// Attacking own side
|
||||
if (side.isTownOnSide(town) && !side.isTownSurrendered(town)) {
|
||||
if (side.isOnSide(town) && !side.isSurrendered(town)) {
|
||||
if (asAdmin)
|
||||
throw CommandAPIBukkit.failWithAdventureComponent(ColorParser.of("<red>You cannot attack your own side.").build());
|
||||
else
|
||||
@@ -152,7 +152,7 @@ public class SiegeCommands {
|
||||
if (location.distance(townLocation) <= Siege.BATTLEFIELD_START_MIN_RANGE && !asAdmin)
|
||||
throw CommandAPIBukkit.failWithAdventureComponent(ColorParser.of("<red>You need to be further than <range> blocks away from the town to start a siege!").parseMinimessagePlaceholder("range", String.valueOf(Siege.BATTLEFIELD_START_MIN_RANGE)).build());
|
||||
|
||||
if ((AlathranWars.econ.getBalance(siegeLeader) < Siege.SIEGE_VICTORY_MONEY) && !asAdmin)
|
||||
if ((AlathranWars.getVaultHook().isEconomyLoaded() && AlathranWars.getVaultHook().getEconomy().getBalance(siegeLeader) < Siege.SIEGE_VICTORY_MONEY) && !asAdmin)
|
||||
throw CommandAPIBukkit.failWithAdventureComponent(ColorParser.of("<red>You need to have $<amount> to start a siege!").parseMinimessagePlaceholder("amount", String.valueOf(Siege.SIEGE_VICTORY_MONEY)).build());
|
||||
|
||||
side.setSiegeGrace();
|
||||
|
||||
@@ -5,7 +5,7 @@ import com.github.alathra.alathranwars.conflict.war.WarBuilder;
|
||||
import com.github.alathra.alathranwars.conflict.war.WarController;
|
||||
import com.github.alathra.alathranwars.conflict.war.side.Side;
|
||||
import com.github.alathra.alathranwars.conflict.war.side.SideCreationException;
|
||||
import com.github.alathra.alathranwars.hooks.NameColorHandler;
|
||||
import com.github.alathra.alathranwars.hook.NameColorHandler;
|
||||
import com.github.alathra.alathranwars.utility.UtilsChat;
|
||||
import com.github.milkdrinkers.colorparser.ColorParser;
|
||||
import com.palmergames.bukkit.towny.TownyAPI;
|
||||
@@ -249,8 +249,8 @@ public class WarCommands {
|
||||
|
||||
if (!war.isEventWar()) {
|
||||
// Join nation into war
|
||||
if (isArgNation && nation != null && !war.isNationInWar(nation) && (asAdmin || canKingJoin)) {
|
||||
side.addNation(nation);
|
||||
if (isArgNation && nation != null && !war.isInWar(nation) && (asAdmin || canKingJoin)) {
|
||||
side.add(nation);
|
||||
nation.getResidents().stream().filter(Resident::isOnline).map(Resident::getPlayer).toList().forEach(player -> NameColorHandler.getInstance().calculatePlayerColors(player));
|
||||
Bukkit.broadcast(
|
||||
ColorParser.of(
|
||||
@@ -282,8 +282,8 @@ public class WarCommands {
|
||||
}
|
||||
|
||||
// Join town into war
|
||||
if (isArgTown && town != null && !war.isTownInWar(town) && (asAdmin || canMayorJoin)) {
|
||||
side.addTown(town);
|
||||
if (isArgTown && town != null && !war.isInWar(town) && (asAdmin || canMayorJoin)) {
|
||||
side.add(town);
|
||||
town.getResidents().stream().filter(Resident::isOnline).map(Resident::getPlayer).toList().forEach(player -> NameColorHandler.getInstance().getPlayerNameColor(player));
|
||||
Bukkit.broadcast(
|
||||
ColorParser.of(
|
||||
@@ -316,9 +316,9 @@ public class WarCommands {
|
||||
}
|
||||
|
||||
// Join player into war
|
||||
if (isArgPlayer && targetPlayer != null && !war.isPlayerInWar(targetPlayer) && asAdmin) {
|
||||
if (isArgPlayer && targetPlayer != null && !war.isInWar(targetPlayer) && asAdmin) {
|
||||
targetPlayer.sendMessage(ColorParser.of(UtilsChat.getPrefix() + "You have joined the war.").build());
|
||||
side.addPlayer(targetPlayer);
|
||||
side.add(targetPlayer);
|
||||
NameColorHandler.getInstance().calculatePlayerColors(targetPlayer);
|
||||
final Title warTitle = Title.title(
|
||||
ColorParser.of("<gradient:#D72A09:#B01F03><u><b>War")
|
||||
@@ -367,10 +367,10 @@ public class WarCommands {
|
||||
final Location targetLocation = targetPlayer.getLocation();
|
||||
if (!location.getWorld().equals(targetLocation.getWorld())) continue;
|
||||
if (location.distance(targetLocation) > 25D) continue;
|
||||
if (war.isPlayerInWar(targetPlayer)) continue;
|
||||
if (war.isInWar(targetPlayer)) continue;
|
||||
|
||||
targetPlayer.sendMessage(ColorParser.of(UtilsChat.getPrefix() + "You have joined the war.").build());
|
||||
side.addPlayer(targetPlayer);
|
||||
side.add(targetPlayer);
|
||||
NameColorHandler.getInstance().calculatePlayerColors(targetPlayer);
|
||||
final Title warTitle = Title.title(
|
||||
ColorParser.of("<gradient:#D72A09:#B01F03><u><b>War")
|
||||
@@ -404,7 +404,7 @@ public class WarCommands {
|
||||
if (town == null)
|
||||
throw CommandAPIBukkit.failWithAdventureComponent(ColorParser.of("<red>You are not in a town.").build());
|
||||
|
||||
@Nullable Side side = war.getTownSide(town);
|
||||
@Nullable Side side = war.getSide(town);
|
||||
if (side == null)
|
||||
throw CommandAPIBukkit.failWithAdventureComponent(ColorParser.of("<red>You are not in that war.").build());
|
||||
|
||||
@@ -415,7 +415,7 @@ public class WarCommands {
|
||||
// Has nation surrender permission
|
||||
argPlayer.sendMessage(ColorParser.of(UtilsChat.getPrefix() + "You have surrendered the war for " + resNation.getName() + ".").build());
|
||||
Bukkit.broadcast(ColorParser.of(UtilsChat.getPrefix() + "The nation of " + resNation.getName() + " has surrendered!").build());
|
||||
war.surrenderNation(resNation);
|
||||
war.surrender(resNation);
|
||||
} else if (resTown == null) {
|
||||
// Cannot surrender nation involvement
|
||||
throw CommandAPIBukkit.failWithAdventureComponent(ColorParser.of("<red>You cannot surrender for your nation.").build());
|
||||
@@ -426,7 +426,7 @@ public class WarCommands {
|
||||
argPlayer.sendMessage(ColorParser.of(UtilsChat.getPrefix() + "You have surrendered the war for " + resTown.getName() + ".").build());
|
||||
Bukkit.broadcast(ColorParser.of(UtilsChat.getPrefix() + "The town of " + resTown.getName() + " has surrendered!").build());
|
||||
war.cancelSieges(resTown);
|
||||
war.surrenderTown(resTown);
|
||||
war.surrender(resTown);
|
||||
} else {
|
||||
// No perms
|
||||
throw CommandAPIBukkit.failWithAdventureComponent(ColorParser.of("<red>You cannot surrender war for your town.").build());
|
||||
@@ -447,26 +447,26 @@ public class WarCommands {
|
||||
Town town = TownyAPI.getInstance().getTown(uuid);
|
||||
OfflinePlayer player = Bukkit.getOfflinePlayer(uuid);
|
||||
|
||||
Side sideNation = war.getNationSide(nation);
|
||||
Side sideTown = war.getTownSide(town);
|
||||
Side sideNation = war.getSide(nation);
|
||||
Side sideTown = war.getSide(town);
|
||||
Side sidePlayer = war.getPlayerSide(uuid);
|
||||
|
||||
if (isNation && sideNation != null) {
|
||||
sideNation.kickNation(nation);
|
||||
sideNation.kick(nation);
|
||||
p.sendMessage(ColorParser.of("Target yeeted.").build());
|
||||
nation.getResidents().stream().filter(Resident::isOnline).map(Resident::getPlayer).forEach(player1 -> NameColorHandler.getInstance().calculatePlayerColors(player1));
|
||||
return;
|
||||
}
|
||||
|
||||
if (isTown && sideTown != null) {
|
||||
sideTown.kickTown(town);
|
||||
sideTown.kick(town);
|
||||
p.sendMessage(ColorParser.of("Target yeeted.").build());
|
||||
town.getResidents().stream().filter(Resident::isOnline).map(Resident::getPlayer).forEach(player1 -> NameColorHandler.getInstance().calculatePlayerColors(player1));
|
||||
return;
|
||||
}
|
||||
|
||||
if (isPlayer && sidePlayer != null) {
|
||||
sidePlayer.kickPlayer(player.getUniqueId());
|
||||
sidePlayer.kick(player.getUniqueId());
|
||||
p.sendMessage(ColorParser.of("Target yeeted.").build());
|
||||
if (player.getPlayer() != null)
|
||||
NameColorHandler.getInstance().calculatePlayerColors(player.getPlayer());
|
||||
@@ -509,9 +509,9 @@ public class WarCommands {
|
||||
for (Side side : war.getSides()) {
|
||||
msg.append("\n<white><bold>%s<reset>".formatted(side.getName()));
|
||||
msg.append("\n <grey>Score: <green>%s".formatted(side.getScore()));
|
||||
msg.append("\n <grey>Nations: <green>%s<grey>/<red>%s".formatted(side.getNations().size(), side.getNations().size() + side.getSurrenderedNations().size()));
|
||||
msg.append("\n <grey>Towns: <green>%s<grey>/<red>%s".formatted(side.getTowns().size(), side.getTowns().size() + side.getSurrenderedTowns().size()));
|
||||
msg.append("\n <grey>Players: <green>%s<grey>/<red>%s".formatted(side.getPlayersIncludingOffline().size(), side.getPlayersIncludingOffline().size() + side.getSurrenderedPlayersIncludingOffline().size()));
|
||||
msg.append("\n <grey>Nations: <green>%s<grey>/<red>%s".formatted(side.getNations().size(), side.getNations().size() + side.getNationsSurrendered().size()));
|
||||
msg.append("\n <grey>Towns: <green>%s<grey>/<red>%s".formatted(side.getTowns().size(), side.getTowns().size() + side.getTownsSurrendered().size()));
|
||||
msg.append("\n <grey>Players: <green>%s<grey>/<red>%s".formatted(side.getPlayersAll().size(), side.getPlayersAll().size() + side.getPlayersSurrendered().size()));
|
||||
msg.append("\n");
|
||||
}
|
||||
|
||||
|
||||
@@ -2,30 +2,32 @@ 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 com.github.milkdrinkers.crate.Config;
|
||||
|
||||
import javax.inject.Singleton;
|
||||
|
||||
/**
|
||||
* A class that generates/loads & provides access to a configuration file.
|
||||
* A class that generates/loads {@literal &} provides access to a configuration file.
|
||||
*/
|
||||
@Singleton
|
||||
public class ConfigHandler implements Reloadable {
|
||||
private final AlathranWars alathranWars;
|
||||
private final AlathranWars plugin;
|
||||
private Config cfg;
|
||||
private Config databaseCfg;
|
||||
|
||||
/**
|
||||
* Instantiates a new Config handler.
|
||||
*
|
||||
* @param alathranWars the plugin instance
|
||||
* @param plugin the plugin instance
|
||||
*/
|
||||
public ConfigHandler(AlathranWars alathranWars) {
|
||||
this.alathranWars = alathranWars;
|
||||
public ConfigHandler(AlathranWars plugin) {
|
||||
this.plugin = plugin;
|
||||
}
|
||||
|
||||
@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
|
||||
cfg = new Config("config", plugin.getDataFolder().getPath(), plugin.getResource("config.yml")); // Create a config file from the template in our resources folder
|
||||
databaseCfg = new Config("database", plugin.getDataFolder().getPath(), plugin.getResource("database.yml"));
|
||||
}
|
||||
|
||||
@Override
|
||||
@@ -37,11 +39,20 @@ public class ConfigHandler implements Reloadable {
|
||||
}
|
||||
|
||||
/**
|
||||
* Gets alathranWars config object.
|
||||
* Gets main config object.
|
||||
*
|
||||
* @return the alathranWars config object
|
||||
* @return the config object
|
||||
*/
|
||||
public Config getConfig() {
|
||||
return cfg;
|
||||
}
|
||||
|
||||
/**
|
||||
* Gets database config object.
|
||||
*
|
||||
* @return the config object
|
||||
*/
|
||||
public Config getDatabaseConfig() {
|
||||
return databaseCfg;
|
||||
}
|
||||
}
|
||||
@@ -2,6 +2,42 @@ package com.github.alathra.alathranwars.conflict;
|
||||
|
||||
import com.github.alathra.alathranwars.enums.ConflictType;
|
||||
|
||||
public class Conflict {
|
||||
import java.util.UUID;
|
||||
|
||||
public abstract class Conflict implements IUnique<Conflict> {
|
||||
private ConflictType conflictType;
|
||||
private final UUID uuid;
|
||||
|
||||
public Conflict(UUID uuid) {
|
||||
this.uuid = uuid;
|
||||
}
|
||||
|
||||
/**
|
||||
* @return conflict uuid
|
||||
*/
|
||||
@Override
|
||||
public UUID getUUID() {
|
||||
return uuid;
|
||||
}
|
||||
|
||||
/**
|
||||
* Equals boolean.
|
||||
*
|
||||
* @param uuid the uuid
|
||||
* @return the boolean
|
||||
*/
|
||||
@Override
|
||||
public boolean equals(UUID uuid) {
|
||||
return getUUID().equals(uuid);
|
||||
}
|
||||
|
||||
/**
|
||||
* Equals boolean.
|
||||
*
|
||||
* @param conflict the conflict
|
||||
* @return the boolean
|
||||
*/
|
||||
public boolean equals(Conflict conflict) {
|
||||
return conflict.getUUID().equals(uuid);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,18 @@
|
||||
package com.github.alathra.alathranwars.conflict;
|
||||
|
||||
import com.github.alathra.alathranwars.conflict.war.War;
|
||||
|
||||
public interface IAssociatedWar {
|
||||
/**
|
||||
* Gets the associated war with this object from the war uuid
|
||||
* @return the associated war
|
||||
*/
|
||||
War getWar();
|
||||
|
||||
/**
|
||||
* Check whether a war is associated with this class
|
||||
* @param war the war to compare with
|
||||
* @return if the war is the one associated with this object
|
||||
*/
|
||||
boolean equals(War war);
|
||||
}
|
||||
@@ -0,0 +1,27 @@
|
||||
package com.github.alathra.alathranwars.conflict;
|
||||
|
||||
import java.util.UUID;
|
||||
|
||||
public interface IUnique<T extends IUnique<T>> {
|
||||
UUID getUUID();
|
||||
|
||||
/**
|
||||
* Equals boolean.
|
||||
*
|
||||
* @param uuid the uuid
|
||||
* @return the boolean
|
||||
*/
|
||||
default boolean equals(UUID uuid) {
|
||||
return getUUID().equals(uuid);
|
||||
}
|
||||
|
||||
/**
|
||||
* Equals boolean.
|
||||
*
|
||||
* @param obj the object implementing IUnique
|
||||
* @return the boolean
|
||||
*/
|
||||
default boolean equals(T obj) {
|
||||
return getUUID().equals(obj.getUUID());
|
||||
}
|
||||
}
|
||||
+213
@@ -0,0 +1,213 @@
|
||||
package com.github.alathra.alathranwars.conflict.battle;
|
||||
|
||||
import com.github.alathra.alathranwars.conflict.war.War;
|
||||
import com.github.alathra.alathranwars.enums.battle.BattleSide;
|
||||
import com.github.alathra.alathranwars.events.battle.PlayerEnteredBattlefieldEvent;
|
||||
import com.github.alathra.alathranwars.events.battle.PlayerLeftBattlefieldEvent;
|
||||
import org.bukkit.Bukkit;
|
||||
import org.bukkit.Location;
|
||||
import org.bukkit.OfflinePlayer;
|
||||
import org.bukkit.entity.Player;
|
||||
|
||||
import java.util.*;
|
||||
import java.util.stream.Collectors;
|
||||
|
||||
/**
|
||||
* Provides methods for handling all members of a Battle
|
||||
*/
|
||||
public abstract class AbstractBattleTeamManagement {
|
||||
// SECTION Player management
|
||||
|
||||
private final List<OfflinePlayer> attackers = new ArrayList<>(); // A list of all players who are in the attackers team
|
||||
private final List<OfflinePlayer> defenders = new ArrayList<>(); // A list of all players who are in the attackers team
|
||||
|
||||
/**
|
||||
* Get all online players eligible to fight in the battle
|
||||
* @param side battle side
|
||||
* @return list of players
|
||||
*/
|
||||
public List<Player> getPlayersOnline(BattleSide side) {
|
||||
return switch (side) {
|
||||
case ATTACKER -> attackers.stream()
|
||||
.filter(OfflinePlayer::isOnline)
|
||||
.map(OfflinePlayer::getPlayer)
|
||||
.toList();
|
||||
case DEFENDER -> defenders.stream()
|
||||
.filter(OfflinePlayer::isOnline)
|
||||
.map(OfflinePlayer::getPlayer)
|
||||
.toList();
|
||||
case SPECTATOR -> Bukkit.getOnlinePlayers().stream()
|
||||
.map(OfflinePlayer::getPlayer)
|
||||
.filter(p -> !attackers.contains(p) && !defenders.contains(p))
|
||||
.toList();
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* Get all players eligible to fight in the battle
|
||||
* @param side battle side
|
||||
* @return list of players
|
||||
*/
|
||||
public List<OfflinePlayer> getPlayers(BattleSide side) {
|
||||
return switch (side) {
|
||||
case ATTACKER -> attackers;
|
||||
case DEFENDER -> defenders;
|
||||
default -> List.of();
|
||||
};
|
||||
}
|
||||
|
||||
public void addPlayer(OfflinePlayer p, BattleSide side) {
|
||||
switch (side) {
|
||||
case ATTACKER -> attackers.add(p);
|
||||
case DEFENDER -> defenders.add(p);
|
||||
}
|
||||
}
|
||||
|
||||
public void addPlayer(Player p, BattleSide side) { addPlayer(Bukkit.getOfflinePlayer(p.getUniqueId()), side); }
|
||||
|
||||
public void addPlayer(UUID uuid, BattleSide side) { addPlayer(Bukkit.getOfflinePlayer(uuid), side); }
|
||||
|
||||
public void removePlayer(OfflinePlayer p, BattleSide side) {
|
||||
switch (side) {
|
||||
case ATTACKER -> attackers.remove(p);
|
||||
case DEFENDER -> defenders.remove(p);
|
||||
}
|
||||
}
|
||||
|
||||
public void removePlayer(Player p, BattleSide side) { removePlayer(p.getUniqueId(), side); }
|
||||
|
||||
public void removePlayer(UUID uuid, BattleSide side) { removePlayer(Bukkit.getOfflinePlayer(uuid), side); }
|
||||
|
||||
// Player info methods
|
||||
|
||||
public BattleSide getPlayerBattleSide(OfflinePlayer p) {
|
||||
if (getPlayers(BattleSide.ATTACKER).contains(p))
|
||||
return BattleSide.ATTACKER;
|
||||
|
||||
if (getPlayers(BattleSide.DEFENDER).contains(p))
|
||||
return BattleSide.DEFENDER;
|
||||
|
||||
return BattleSide.SPECTATOR;
|
||||
}
|
||||
|
||||
public BattleSide getPlayerBattleSide(Player p) {
|
||||
return getPlayerBattleSide(p.getUniqueId());
|
||||
}
|
||||
|
||||
public BattleSide getPlayerBattleSide(UUID uuid) {
|
||||
return getPlayerBattleSide(Bukkit.getOfflinePlayer(uuid));
|
||||
}
|
||||
|
||||
// Misc
|
||||
|
||||
/**
|
||||
* Checks if the player is considered part of this battle
|
||||
* @param p the player
|
||||
* @return yes if they have joined the battle
|
||||
*/
|
||||
public boolean isPlayerParticipating(OfflinePlayer p) {
|
||||
return getPlayers(BattleSide.ATTACKER).contains(p) || getPlayers(BattleSide.DEFENDER).contains(p);
|
||||
}
|
||||
|
||||
/**
|
||||
* Checks if the player is considered part of this battle
|
||||
* @param p the player
|
||||
* @return yes if they have joined the battle
|
||||
*/
|
||||
public boolean isPlayerParticipating(Player p) {
|
||||
return isPlayerParticipating(p.getUniqueId());
|
||||
}
|
||||
|
||||
/**
|
||||
* Checks if the player is considered part of this battle
|
||||
* @param uuid the player uuid
|
||||
* @return yes if they have joined the battle
|
||||
*/
|
||||
public boolean isPlayerParticipating(UUID uuid) {
|
||||
return isPlayerParticipating(Bukkit.getOfflinePlayer(uuid));
|
||||
}
|
||||
|
||||
// SECTION Active player management
|
||||
|
||||
private final List<Player> activeAttackers = new ArrayList<>(); // Players in the battle zone
|
||||
private final List<Player> activeDefenders = new ArrayList<>(); // Players in the battle zone
|
||||
private final List<Player> activeSpectators = new ArrayList<>(); // Players in the battle zone
|
||||
|
||||
/**
|
||||
* Get all online players within the battlefield.
|
||||
* @param side battle side
|
||||
* @return list of players
|
||||
*/
|
||||
public List<Player> getActivePlayers(BattleSide side) {
|
||||
return switch (side) {
|
||||
case ATTACKER -> activeAttackers;
|
||||
case DEFENDER -> activeDefenders;
|
||||
case SPECTATOR -> activeSpectators;
|
||||
};
|
||||
}
|
||||
|
||||
private void addActivePlayer(Player p, BattleSide side) {
|
||||
switch (side) {
|
||||
case ATTACKER -> activeAttackers.add(p);
|
||||
case DEFENDER -> activeDefenders.add(p);
|
||||
case SPECTATOR -> activeSpectators.add(p);
|
||||
};
|
||||
}
|
||||
|
||||
private void removeActivePlayer(Player p, BattleSide side) {
|
||||
switch (side) {
|
||||
case ATTACKER -> activeAttackers.remove(p);
|
||||
case DEFENDER -> activeDefenders.remove(p);
|
||||
case SPECTATOR -> activeSpectators.remove(p);
|
||||
};
|
||||
}
|
||||
|
||||
public void calculateBattlefieldPlayers(Location location, int range, War war, Battle battle) {
|
||||
final List<Player> previousAttackersOnBattlefield = new ArrayList<>(getActivePlayers(BattleSide.ATTACKER));
|
||||
final List<Player> previousDefendersOnBattlefield = new ArrayList<>(getActivePlayers(BattleSide.DEFENDER));
|
||||
final List<Player> previousSpectatorsOnBattlefield = new ArrayList<>(getActivePlayers(BattleSide.SPECTATOR));
|
||||
|
||||
activeAttackers.clear();
|
||||
activeSpectators.addAll(getPlayersWithinRange(BattleSide.ATTACKER, location, range));
|
||||
|
||||
activeDefenders.clear();
|
||||
activeSpectators.addAll(getPlayersWithinRange(BattleSide.DEFENDER, location, range));
|
||||
|
||||
activeSpectators.clear();
|
||||
activeSpectators.addAll(getPlayersWithinRange(BattleSide.SPECTATOR, location, range));
|
||||
|
||||
// Attackers
|
||||
emitLeaving(BattleSide.ATTACKER, previousAttackersOnBattlefield, war, battle); // Emit Leaving attackers events
|
||||
emitEntering(BattleSide.ATTACKER, previousAttackersOnBattlefield, war, battle); // Emit Entering attackers events
|
||||
|
||||
// Defenders
|
||||
emitLeaving(BattleSide.DEFENDER, previousDefendersOnBattlefield, war, battle); // Emit Leaving defenders events
|
||||
emitEntering(BattleSide.DEFENDER, previousDefendersOnBattlefield, war, battle); // Emit Entering defenders events
|
||||
|
||||
// Spectators
|
||||
emitLeaving(BattleSide.SPECTATOR, previousSpectatorsOnBattlefield, war, battle); // Emit Leaving spectators events
|
||||
emitEntering(BattleSide.SPECTATOR, previousSpectatorsOnBattlefield, war, battle); // Emit Entering spectators events
|
||||
}
|
||||
|
||||
private List<Player> getPlayersWithinRange(BattleSide battleSide, Location location, int range) {
|
||||
return getPlayersOnline(battleSide).stream()
|
||||
.filter(OfflinePlayer::isOnline)
|
||||
.filter(p -> location.getWorld().equals(p.getLocation().getWorld()))
|
||||
.filter(p -> location.distance(p.getLocation()) < range)
|
||||
.toList();
|
||||
}
|
||||
|
||||
private void emitEntering(BattleSide battleSide, List<Player> previousPlayers, War war, Battle battle) {
|
||||
getActivePlayers(battleSide).stream()
|
||||
.filter(p -> p.isConnected() && !previousPlayers.contains(p))
|
||||
.collect(Collectors.toSet())
|
||||
.forEach(p -> new PlayerEnteredBattlefieldEvent(p, war, battle, battleSide).callEvent());
|
||||
}
|
||||
|
||||
private void emitLeaving(BattleSide battleSide, List<Player> previousPlayers, War war, Battle battle) {
|
||||
previousPlayers.stream()
|
||||
.filter(p -> p.isConnected() && !getActivePlayers(battleSide).contains(p))
|
||||
.collect(Collectors.toSet())
|
||||
.forEach(p -> new PlayerLeftBattlefieldEvent(p, war, battle, battleSide).callEvent());
|
||||
}
|
||||
}
|
||||
@@ -1,40 +1,58 @@
|
||||
package com.github.alathra.alathranwars.conflict.battle;
|
||||
|
||||
import com.github.alathra.alathranwars.conflict.IUnique;
|
||||
import com.github.alathra.alathranwars.conflict.war.War;
|
||||
import com.github.alathra.alathranwars.enums.battle.BattleType;
|
||||
import com.github.alathra.alathranwars.enums.battle.BattleVictoryReason;
|
||||
import org.jetbrains.annotations.NotNull;
|
||||
import org.jetbrains.annotations.ApiStatus;
|
||||
|
||||
import java.util.UUID;
|
||||
public interface Battle extends IUnique<Battle> {
|
||||
War war = null;
|
||||
|
||||
public interface Battle {
|
||||
void start(); // Initiates battle
|
||||
|
||||
void stop(); // Ends battle
|
||||
|
||||
void resume(); // Resume battle after server restart or plugin reload
|
||||
|
||||
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
|
||||
|
||||
default @NotNull UUID getUUID() {
|
||||
return uuid;
|
||||
default War getWar() {
|
||||
return war;
|
||||
}
|
||||
|
||||
/**
|
||||
* Equals boolean.
|
||||
*
|
||||
* @param uuid the uuid
|
||||
* @return the boolean
|
||||
* Starts the battle
|
||||
*/
|
||||
default boolean equals(UUID uuid) {
|
||||
return getUUID().equals(uuid);
|
||||
}
|
||||
@ApiStatus.Internal
|
||||
void start();
|
||||
|
||||
/**
|
||||
* Resumes the battle (after a server restart e.t.c.)
|
||||
*/
|
||||
@ApiStatus.Internal
|
||||
void resume();
|
||||
|
||||
/**
|
||||
* Stops the battle
|
||||
* </p>
|
||||
* Internal stop method for battles which triggers cleanup methods
|
||||
*/
|
||||
@ApiStatus.Internal
|
||||
void stop(); // Ends battle
|
||||
|
||||
/**
|
||||
* Stop a battle in favor of the attackers
|
||||
*
|
||||
* @param reason what triggered the end
|
||||
*/
|
||||
void attackersWin(BattleVictoryReason reason); // A Attacker victory
|
||||
|
||||
/**
|
||||
* Stop a battle in favor of the defenders
|
||||
*
|
||||
* @param reason what triggered the end
|
||||
*/
|
||||
void defendersWin(BattleVictoryReason reason); // A Defender victory
|
||||
|
||||
/**
|
||||
* End a battle in favor of no one
|
||||
*
|
||||
* @param reason what triggered the end
|
||||
*/
|
||||
void equalWin(BattleVictoryReason reason); // A Draw
|
||||
|
||||
/**
|
||||
* Equals boolean.
|
||||
@@ -42,7 +60,7 @@ public interface Battle {
|
||||
* @param battle the battle
|
||||
* @return the boolean
|
||||
*/
|
||||
default boolean equals(@NotNull Battle battle) {
|
||||
default boolean equals(Battle battle) {
|
||||
return getUUID().equals(battle.getUUID());
|
||||
}
|
||||
|
||||
|
||||
+98
@@ -0,0 +1,98 @@
|
||||
package com.github.alathra.alathranwars.conflict.battle.beam.betterbeam;
|
||||
|
||||
public class BetterBeam {
|
||||
/*BetterBeam() {
|
||||
PacketContainer spawnPacket = new PacketContainer(PacketType.Play.Server.SPAWN_ENTITY);
|
||||
PacketContainer metadataPacket = new PacketContainer(PacketType.Play.Server.ENTITY_METADATA);
|
||||
PacketContainer destroyPacket = new PacketContainer(PacketType.Play.Server.ENTITY_DESTROY);
|
||||
|
||||
// Required fields
|
||||
// EndCrystal entity
|
||||
// Squid entity (Made invisible)
|
||||
AlathranWars.getProtocolLibHook().getProtocolManager()
|
||||
|
||||
PacketContainer spawnCrystalPacket = new PacketContainer(PacketType.Play.Server.ENTITY_METADATA);
|
||||
PacketContainer spawnCrystalPacket = new PacketContainer(PacketType.Play.Server.ENTITY_METADATA);
|
||||
|
||||
ProtocolManager manager = AlathranWars.getProtocolLibHook().getProtocolManager();
|
||||
|
||||
Entity endcrystal;
|
||||
|
||||
endcrystal.getI
|
||||
spawnPacket.getStructures()
|
||||
|
||||
|
||||
|
||||
}
|
||||
|
||||
private void spawnEntity(Location location, Vector vector, EntityType type) {
|
||||
int entityId = 10000;
|
||||
|
||||
PacketContainer packet = new PacketContainer(PacketType.Play.Server.SPAWN_ENTITY);
|
||||
|
||||
// Crucial data, do not remove
|
||||
packet.getIntegers().write(0, entityId);
|
||||
packet.getUUIDs().write(0, UUID.randomUUID());
|
||||
packet.getEntityTypeModifier().write(0, type);
|
||||
|
||||
packet.getDoubles()
|
||||
.write(0, location.getX())
|
||||
.write(1, location.getY())
|
||||
.write(2, location.getZ());
|
||||
// -- section end --
|
||||
|
||||
// Pitch and yaw, remove this code section if you want to default to 0
|
||||
|
||||
packet.
|
||||
packet.getIntegers()
|
||||
.write(4, (int) (location.getPitch() * 256.0F / 360.0F))
|
||||
.write(5, (int) (location.getYaw() * 256.0F / 360.0F));
|
||||
|
||||
// -- section end --
|
||||
|
||||
// Send the packet to all players
|
||||
try {
|
||||
for(Player player : Bukkit.getOnlinePlayers()) {
|
||||
ProtocolLibrary.getProtocolManager().sendServerPacket(player, packet);
|
||||
}
|
||||
} catch (Exception e) {
|
||||
e.printStackTrace();
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
private void spawnLivingEntity(Location location, Vector vector, EntityType type) {
|
||||
int entityId = 10000;
|
||||
|
||||
PacketContainer packet = new PacketContainer(PacketType.Play.Server.SPAWN_ENTITY);
|
||||
|
||||
// Crucial data, do not remove
|
||||
packet.getIntegers().write(0, entityId);
|
||||
packet.getUUIDs().write(0, UUID.randomUUID());
|
||||
packet.getIntegers().write(1, (int) type.getTypeId()); // getTypeId is deprecated, you can find the actual IDs on wiki.vg/Protocol
|
||||
|
||||
packet.getDoubles()
|
||||
.write(0, location.getX())
|
||||
.write(1, location.getY())
|
||||
.write(2, location.getZ());
|
||||
// -- section end --
|
||||
|
||||
// Pitch and yaw, remove this code section if you want to default to 0
|
||||
packet.getBytes()
|
||||
.write(4, (byte) (location.getYaw() * 256.0F / 360.0F)) // yaw
|
||||
.write(5, (byte) (location.getPitch() * 256.0F / 360.0F)) // pitch
|
||||
.write(5, (byte) (location.getYaw() * 256.0F / 360.0F)); // head yaw
|
||||
|
||||
// -- section end --
|
||||
|
||||
// Send the packet to all players
|
||||
try {
|
||||
for(Player player : Bukkit.getOnlinePlayers()) {
|
||||
ProtocolLibrary.getProtocolManager().sendServerPacket(player, packet);
|
||||
}
|
||||
} catch (Exception e) {
|
||||
e.printStackTrace();
|
||||
}
|
||||
|
||||
}*/
|
||||
}
|
||||
+9
@@ -0,0 +1,9 @@
|
||||
package com.github.alathra.alathranwars.conflict.battle.phase;
|
||||
|
||||
import java.time.Instant;
|
||||
|
||||
public class BattlePhaseManager<T extends Enum<T> & IBattlePhase<T>> extends BattlePhaseManagerImpl<T> {
|
||||
public BattlePhaseManager(T phase, int progress, Instant startTime) {
|
||||
super(phase, progress, startTime);
|
||||
}
|
||||
}
|
||||
+57
@@ -0,0 +1,57 @@
|
||||
package com.github.alathra.alathranwars.conflict.battle.phase;
|
||||
|
||||
import java.time.Duration;
|
||||
import java.time.Instant;
|
||||
|
||||
public abstract class BattlePhaseManagerImpl<T extends Enum<T> & IBattlePhase<T>> implements IBattlePhaseManager<T> {
|
||||
private T phase;
|
||||
private int progress;
|
||||
private Instant startTime;
|
||||
|
||||
public BattlePhaseManagerImpl(T phase, int progress, Instant startTime) {
|
||||
this.phase = phase;
|
||||
this.progress = progress;
|
||||
this.startTime = startTime;
|
||||
}
|
||||
|
||||
@Override
|
||||
public T get() {
|
||||
return phase;
|
||||
}
|
||||
|
||||
@Override
|
||||
public void set(T phase) throws BattlePhaseSwitchException {
|
||||
this.phase = phase;
|
||||
}
|
||||
|
||||
@Override
|
||||
public int getProgress() {
|
||||
return progress;
|
||||
}
|
||||
|
||||
@Override
|
||||
public void setProgress(int val) {
|
||||
if (val > 100) { // TODO Use phase progress max here
|
||||
val = 100;
|
||||
} else if (val < 0) {
|
||||
val = 0;
|
||||
}
|
||||
|
||||
progress = val;
|
||||
}
|
||||
|
||||
@Override
|
||||
public Instant getStartTime() {
|
||||
return startTime;
|
||||
}
|
||||
|
||||
@Override
|
||||
public void setStartTime(Instant instant) {
|
||||
startTime = instant;
|
||||
}
|
||||
|
||||
@Override
|
||||
public Duration getElapsedTime() {
|
||||
return Duration.between(Instant.now(), getStartTime());
|
||||
}
|
||||
}
|
||||
+7
@@ -0,0 +1,7 @@
|
||||
package com.github.alathra.alathranwars.conflict.battle.phase;
|
||||
|
||||
public class BattlePhaseSwitchException extends RuntimeException {
|
||||
public BattlePhaseSwitchException(String message) {
|
||||
super(message);
|
||||
}
|
||||
}
|
||||
+100
@@ -0,0 +1,100 @@
|
||||
package com.github.alathra.alathranwars.conflict.battle.phase;
|
||||
|
||||
import org.jetbrains.annotations.Nullable;
|
||||
|
||||
import java.util.Arrays;
|
||||
|
||||
/**
|
||||
* Used to implement common methods in battle phase enums
|
||||
* @param <T> the Enum
|
||||
*/
|
||||
public interface IBattlePhase<T extends Enum<T> & IBattlePhase<T>> {
|
||||
int getPhaseIdentifier();
|
||||
|
||||
/**
|
||||
* Uses {@link #next(Enum)} to get the next phase
|
||||
* @return a phase enum value
|
||||
* @throws BattlePhaseSwitchException Thrown if no next phase can be found
|
||||
*/
|
||||
T next() throws BattlePhaseSwitchException;
|
||||
|
||||
/**
|
||||
* Uses {@link #previous(Enum)} to get the previous phase
|
||||
* @return a phase enum value
|
||||
* @throws BattlePhaseSwitchException Thrown if no previous phase can be found
|
||||
*/
|
||||
T previous() throws BattlePhaseSwitchException;
|
||||
|
||||
/**
|
||||
* Get the next phase after the provided one
|
||||
* @param phase a phase enum value
|
||||
* @return a phase enum value
|
||||
* @throws BattlePhaseSwitchException Thrown if no next phase can be found
|
||||
*/
|
||||
default T next(T phase) throws BattlePhaseSwitchException {
|
||||
final int currentPhase = phase.getPhaseIdentifier();
|
||||
|
||||
// Find the next enum constant by incrementing until a valid enum constant is found
|
||||
int increment = 0;
|
||||
for (int i = 1; i < 6; i++) {
|
||||
if (fromIdentifier(currentPhase + i) != null) {
|
||||
increment = i;
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
// Failed to find new phase
|
||||
if (increment == 0)
|
||||
throw new BattlePhaseSwitchException("No later phase could be found.");
|
||||
|
||||
return fromIdentifier(currentPhase + increment);
|
||||
}
|
||||
|
||||
/**
|
||||
* Get the previous phase to the provided one
|
||||
* @param phase a phase enum value
|
||||
* @return a phase enum value
|
||||
* @throws BattlePhaseSwitchException Thrown if no previous phase can be found
|
||||
*/
|
||||
default T previous(T phase) throws BattlePhaseSwitchException {
|
||||
final int currentPhase = phase.getPhaseIdentifier();
|
||||
if (currentPhase - 1 < 1)
|
||||
throw new BattlePhaseSwitchException("No previous phase could be found.");
|
||||
|
||||
// Find the previous enum constant by decrementing until a valid enum constant is found
|
||||
int decrement = 0;
|
||||
for (int i = 1; i < 6; i++) {
|
||||
if (fromIdentifier(currentPhase - i) != null) {
|
||||
decrement = i;
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
// Failed to find new phase
|
||||
if (decrement == 0)
|
||||
throw new BattlePhaseSwitchException("No previous phase could be found.");
|
||||
|
||||
return fromIdentifier(currentPhase - decrement);
|
||||
}
|
||||
|
||||
/**
|
||||
* Get a phase from the phase identifier
|
||||
* @param identifier the phase identifier
|
||||
* @return a phase enum value or null if none was found
|
||||
*/
|
||||
@Nullable
|
||||
default T fromIdentifier(final int identifier) {
|
||||
if (identifier < 1)
|
||||
return null;
|
||||
|
||||
return Arrays.stream(getDeclaringClass().getEnumConstants())
|
||||
.filter(phase -> phase.getPhaseIdentifier() == identifier)
|
||||
.findFirst()
|
||||
.orElse(null);
|
||||
}
|
||||
|
||||
/**
|
||||
* Don't override this method, it is implemented in all enums by default.
|
||||
*/
|
||||
Class<T> getDeclaringClass();
|
||||
}
|
||||
+70
@@ -0,0 +1,70 @@
|
||||
package com.github.alathra.alathranwars.conflict.battle.phase;
|
||||
|
||||
import org.jetbrains.annotations.ApiStatus;
|
||||
|
||||
import java.time.Duration;
|
||||
import java.time.Instant;
|
||||
|
||||
public interface IBattlePhaseManager<T extends Enum<T> & IBattlePhase<T>> {
|
||||
/**
|
||||
* Get the current battle phase
|
||||
* @return the phase
|
||||
*/
|
||||
T get();
|
||||
|
||||
/**
|
||||
* Set the current battle phase
|
||||
* @param phase the phase
|
||||
* @throws BattlePhaseSwitchException Thrown if unable to switch phase
|
||||
*/
|
||||
@ApiStatus.Internal
|
||||
void set(T phase) throws BattlePhaseSwitchException;
|
||||
|
||||
/**
|
||||
* Goes to the next battle phase if possible
|
||||
* @throws BattlePhaseSwitchException Thrown if unable to switch phase
|
||||
*/
|
||||
default T next() throws BattlePhaseSwitchException {
|
||||
return get().next();
|
||||
};
|
||||
|
||||
/**
|
||||
* Goes to the previous battle phase if possible
|
||||
* @throws BattlePhaseSwitchException Thrown if unable to switch phase
|
||||
*/
|
||||
default T previous() throws BattlePhaseSwitchException {
|
||||
return get().previous();
|
||||
};
|
||||
|
||||
/**
|
||||
* Get the current phase progress
|
||||
* @return integer from 0 to 100
|
||||
*/
|
||||
int getProgress();
|
||||
|
||||
/**
|
||||
* Set the current phase progress
|
||||
* @param val integer from 0 to 100
|
||||
*/
|
||||
@ApiStatus.Internal
|
||||
void setProgress(int val);
|
||||
|
||||
/**
|
||||
* Get the time at which this phase started
|
||||
* @return the instant at which this phase started
|
||||
*/
|
||||
Instant getStartTime();
|
||||
|
||||
/**
|
||||
* Set the time of when this phase started
|
||||
* @param instant the instant at which this phase started
|
||||
*/
|
||||
@ApiStatus.Internal
|
||||
void setStartTime(Instant instant);
|
||||
|
||||
/**
|
||||
* Get the duration between now and when phase started
|
||||
* @return duration between now and start time
|
||||
*/
|
||||
Duration getElapsedTime();
|
||||
}
|
||||
+36
@@ -0,0 +1,36 @@
|
||||
package com.github.alathra.alathranwars.conflict.battle.phase;
|
||||
|
||||
public enum TestBattlePhase implements IBattlePhase<TestBattlePhase> {
|
||||
INITIAL(1),
|
||||
FIGHTING(2),
|
||||
END(3);
|
||||
|
||||
// Identifiers start at 1, used to traverse between stages
|
||||
private final int phaseIdentifier;
|
||||
|
||||
TestBattlePhase(int phaseIdentifier) {
|
||||
this.phaseIdentifier = phaseIdentifier;
|
||||
}
|
||||
|
||||
public int getPhaseIdentifier() {
|
||||
return phaseIdentifier;
|
||||
}
|
||||
|
||||
public TestBattlePhase next() throws BattlePhaseSwitchException {
|
||||
return next(fromIdentifier(getPhaseIdentifier()));
|
||||
}
|
||||
|
||||
public TestBattlePhase previous() throws BattlePhaseSwitchException {
|
||||
return previous(fromIdentifier(getPhaseIdentifier()));
|
||||
}
|
||||
|
||||
@Override
|
||||
public TestBattlePhase next(TestBattlePhase phase) throws BattlePhaseSwitchException {
|
||||
return IBattlePhase.super.next(phase);
|
||||
}
|
||||
|
||||
@Override
|
||||
public TestBattlePhase previous(TestBattlePhase phase) throws BattlePhaseSwitchException {
|
||||
return IBattlePhase.super.previous(phase);
|
||||
}
|
||||
}
|
||||
+7
@@ -0,0 +1,7 @@
|
||||
package com.github.alathra.alathranwars.conflict.battle.progress;
|
||||
|
||||
public class BattleProgressManager extends BattleProgressManagerImpl {
|
||||
public BattleProgressManager(int progress, int maxProgress) {
|
||||
super(progress, maxProgress);
|
||||
}
|
||||
}
|
||||
+32
@@ -0,0 +1,32 @@
|
||||
package com.github.alathra.alathranwars.conflict.battle.progress;
|
||||
|
||||
public abstract class BattleProgressManagerImpl implements IBattleProgressManager {
|
||||
private int progress;
|
||||
private final int maxProgress;
|
||||
|
||||
public BattleProgressManagerImpl(int progress, int maxProgress) {
|
||||
this.progress = progress;
|
||||
this.maxProgress = maxProgress;
|
||||
}
|
||||
|
||||
@Override
|
||||
public int get() {
|
||||
return progress;
|
||||
}
|
||||
|
||||
@Override
|
||||
public void set(int val) {
|
||||
if (val > getMax()) {
|
||||
val = getMax();
|
||||
} else if (val < 0) {
|
||||
val = 0;
|
||||
}
|
||||
|
||||
progress = val;
|
||||
}
|
||||
|
||||
@Override
|
||||
public int getMax() {
|
||||
return maxProgress;
|
||||
}
|
||||
}
|
||||
+24
@@ -0,0 +1,24 @@
|
||||
package com.github.alathra.alathranwars.conflict.battle.progress;
|
||||
|
||||
import org.jetbrains.annotations.ApiStatus;
|
||||
|
||||
public interface IBattleProgressManager {
|
||||
/**
|
||||
* Get the current battle progress
|
||||
* @return the current progress
|
||||
*/
|
||||
int get();
|
||||
|
||||
/**
|
||||
* Set the current battle progress
|
||||
* @param val the new progress (Cannot be higher than max or lower than 0)
|
||||
*/
|
||||
@ApiStatus.Internal
|
||||
void set(int val);
|
||||
|
||||
/**
|
||||
* Get the current battles maximum progress
|
||||
* @return the maximum progress this battle can reach
|
||||
*/
|
||||
int getMax();
|
||||
}
|
||||
File diff suppressed because it is too large.
Load diff
+6
-7
@@ -19,10 +19,9 @@ import space.arim.morepaperlib.scheduling.ScheduledTask;
|
||||
import java.time.Duration;
|
||||
import java.time.Instant;
|
||||
|
||||
import static com.github.alathra.alathranwars.conflict.battle.raid.Raid.*;
|
||||
import static com.github.alathra.alathranwars.enums.CaptureProgressDirection.*;
|
||||
|
||||
public class RaidRunnable implements Runnable {
|
||||
/*public class RaidRunnable implements Runnable {
|
||||
// Settings
|
||||
private static final Duration ANNOUNCEMENT_COOLDOWN = Duration.ofMinutes(5);
|
||||
private final static int CAPTURE_RANGE = 10;
|
||||
@@ -34,11 +33,11 @@ public class RaidRunnable implements Runnable {
|
||||
private final ScheduledTask task;
|
||||
private @Nullable Laser beam;
|
||||
|
||||
/**
|
||||
*//**
|
||||
* Start a raid
|
||||
*
|
||||
* @param raid the raid
|
||||
*/
|
||||
*//*
|
||||
public RaidRunnable(@NotNull Raid raid) {
|
||||
this.raid = raid;
|
||||
|
||||
@@ -54,12 +53,12 @@ public class RaidRunnable implements Runnable {
|
||||
raid.updateDisplayBar(CONTESTED);
|
||||
}
|
||||
|
||||
/**
|
||||
*//**
|
||||
* Resume a raid at tick
|
||||
*
|
||||
* @param raid the raid
|
||||
* @param raidProgress the raid ticks
|
||||
*/
|
||||
*//*
|
||||
public RaidRunnable(@NotNull Raid raid, int raidProgress) {
|
||||
this.raid = raid;
|
||||
|
||||
@@ -257,4 +256,4 @@ public class RaidRunnable implements Runnable {
|
||||
beam = null;
|
||||
}
|
||||
}
|
||||
}
|
||||
}*/
|
||||
@@ -1,10 +1,13 @@
|
||||
package com.github.alathra.alathranwars.conflict.battle.siege;
|
||||
|
||||
import com.github.alathra.alathranwars.AlathranWars;
|
||||
import com.github.alathra.alathranwars.conflict.battle.AbstractBattleTeamManagement;
|
||||
import com.github.alathra.alathranwars.conflict.battle.Battle;
|
||||
import com.github.alathra.alathranwars.conflict.battle.phase.BattlePhaseManager;
|
||||
import com.github.alathra.alathranwars.conflict.battle.progress.BattleProgressManager;
|
||||
import com.github.alathra.alathranwars.conflict.war.War;
|
||||
import com.github.alathra.alathranwars.conflict.war.side.Side;
|
||||
import com.github.alathra.alathranwars.db.DatabaseQueries;
|
||||
import com.github.alathra.alathranwars.database.DatabaseQueries;
|
||||
import com.github.alathra.alathranwars.enums.CaptureProgressDirection;
|
||||
import com.github.alathra.alathranwars.enums.battle.*;
|
||||
import com.github.alathra.alathranwars.events.battle.BattleResultEvent;
|
||||
@@ -20,21 +23,21 @@ import org.bukkit.Bukkit;
|
||||
import org.bukkit.Location;
|
||||
import org.bukkit.OfflinePlayer;
|
||||
import org.bukkit.entity.Player;
|
||||
import org.jetbrains.annotations.ApiStatus;
|
||||
import org.jetbrains.annotations.NotNull;
|
||||
import org.jetbrains.annotations.Nullable;
|
||||
|
||||
import java.time.Duration;
|
||||
import java.time.Instant;
|
||||
import java.util.HashSet;
|
||||
import java.util.List;
|
||||
import java.util.Set;
|
||||
import java.util.UUID;
|
||||
import java.util.stream.Collectors;
|
||||
import java.util.stream.Stream;
|
||||
|
||||
/**
|
||||
* The type Siege.
|
||||
* @author darksaid98
|
||||
*/
|
||||
public class Siege implements Battle {
|
||||
public class Siege extends AbstractBattleTeamManagement implements Battle {
|
||||
public static final Duration SIEGE_DURATION = Duration.ofMinutes(60);
|
||||
public static final int MAX_SIEGE_PROGRESS_MINUTES = 8; // How many minutes attackers will need to be on point uncontested for to reach 100%
|
||||
public static final int MAX_SIEGE_PROGRESS = 60 * 10 * MAX_SIEGE_PROGRESS_MINUTES; // On reaching this, the attackers win. 10 points is added per second
|
||||
@@ -45,19 +48,15 @@ public class Siege implements Battle {
|
||||
public static final int BATTLEFIELD_START_MIN_RANGE = 75;
|
||||
public static final double SIEGE_VICTORY_MONEY = 2500.0;
|
||||
|
||||
private final @NotNull UUID uuid;
|
||||
// Battle fields
|
||||
private final UUID uuid;
|
||||
private final static BattleType battleType = BattleType.SIEGE;
|
||||
private final Set<Player> attackers = new HashSet<>(); // Players inside battlefield
|
||||
private final Set<Player> defenders = new HashSet<>(); // Players inside battlefield
|
||||
private final Set<Player> attackerPlayers = new HashSet<>();
|
||||
private final Set<Player> defenderPlayers = new HashSet<>();
|
||||
private final Set<UUID> attackerPlayersIncludingOffline = new HashSet<>();
|
||||
private final Set<UUID> defenderPlayersIncludingOffline = new HashSet<>();
|
||||
private @NotNull War war; // War which siege belongs to
|
||||
private final War war; // War which siege belongs to
|
||||
|
||||
// Misc fields
|
||||
private Instant endTime;
|
||||
private int siegeProgress = 0;
|
||||
private Instant lastTouched;
|
||||
private SiegeRunnable siegeRunnable;
|
||||
private SiegeRunnable battleRunnable;
|
||||
private Town town; // Town of the siege
|
||||
private boolean side1AreAttackers; // bool of if side1 being attacker
|
||||
private OfflinePlayer siegeLeader;
|
||||
@@ -66,6 +65,10 @@ public class Siege implements Battle {
|
||||
private @Nullable BossBar activeBossBar = null;
|
||||
private boolean stopped = false; // Used to track if the siege has been already deleted
|
||||
|
||||
// Progress / Phases
|
||||
private final BattleProgressManager progressManager; // Represents the capture progress of the capture point in this case
|
||||
private final BattlePhaseManager<SiegePhase> phaseManager; // Controls the current stage of the siege
|
||||
|
||||
/**
|
||||
* Instantiates a new Siege. Used when creating a new siege.
|
||||
*
|
||||
@@ -73,7 +76,12 @@ public class Siege implements Battle {
|
||||
* @param town the town
|
||||
* @param siegeLeader the siege leader
|
||||
*/
|
||||
public Siege(final @NotNull War war, final Town town, Player siegeLeader) {
|
||||
public Siege(
|
||||
War war,
|
||||
Town town,
|
||||
Player siegeLeader
|
||||
) {
|
||||
super();
|
||||
uuid = UUID.randomUUID();
|
||||
|
||||
endTime = Instant.now().plus(SIEGE_DURATION);
|
||||
@@ -82,17 +90,18 @@ public class Siege implements Battle {
|
||||
this.war = war;
|
||||
this.town = town;
|
||||
this.siegeLeader = siegeLeader;
|
||||
this.progressManager = new BattleProgressManager(0, MAX_SIEGE_PROGRESS);
|
||||
this.phaseManager = new BattlePhaseManager<>(SiegePhase.SIEGE, 0, Instant.now());
|
||||
|
||||
side1AreAttackers = war.getTownSide(town).getTeam().equals(BattleTeam.SIDE_2);
|
||||
side1AreAttackers = war.getSide(town).getTeam().equals(BattleTeam.SIDE_2);
|
||||
|
||||
if (getSide1AreAttackers()) {
|
||||
attackerPlayersIncludingOffline.addAll(getWar().getSide1().getPlayersIncludingOffline());
|
||||
defenderPlayersIncludingOffline.addAll(getWar().getSide2().getPlayersIncludingOffline());
|
||||
getWar().getSide1().getPlayers().forEach(p -> addPlayer(p, BattleSide.ATTACKER));
|
||||
getWar().getSide2().getPlayers().forEach(p -> addPlayer(p, BattleSide.DEFENDER));
|
||||
} else {
|
||||
attackerPlayersIncludingOffline.addAll(getWar().getSide2().getPlayersIncludingOffline());
|
||||
defenderPlayersIncludingOffline.addAll(getWar().getSide1().getPlayersIncludingOffline());
|
||||
getWar().getSide2().getPlayers().forEach(p -> addPlayer(p, BattleSide.ATTACKER));
|
||||
getWar().getSide1().getPlayers().forEach(p -> addPlayer(p, BattleSide.DEFENDER));
|
||||
}
|
||||
calculateOnlinePlayers();
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -105,36 +114,55 @@ public class Siege implements Battle {
|
||||
* @param endTime the end time
|
||||
* @param lastTouched the last touched
|
||||
* @param siegeProgress the siege progress
|
||||
* @param attackerPlayersIncludingOffline the attacker players including offline
|
||||
* @param defenderPlayersIncludingOffline the defender players including offline
|
||||
* @param attackers the attacker players including offline
|
||||
* @param defenders the defender players including offline
|
||||
*/
|
||||
public Siege(War war, @NotNull UUID uuid, Town town, OfflinePlayer siegeLeader, Instant endTime, Instant lastTouched, int siegeProgress, Set<UUID> attackerPlayersIncludingOffline, Set<UUID> defenderPlayersIncludingOffline) {
|
||||
public Siege(
|
||||
War war,
|
||||
UUID uuid,
|
||||
Town town,
|
||||
OfflinePlayer siegeLeader,
|
||||
Instant endTime,
|
||||
Instant lastTouched,
|
||||
int siegeProgress,
|
||||
Set<UUID> attackers,
|
||||
Set<UUID> defenders,
|
||||
SiegePhase phase,
|
||||
int phaseProgress,
|
||||
Instant phaseStartTime
|
||||
) {
|
||||
super();
|
||||
this.war = war;
|
||||
this.uuid = uuid;
|
||||
this.town = town;
|
||||
this.siegeLeader = siegeLeader;
|
||||
this.endTime = endTime;
|
||||
this.lastTouched = lastTouched;
|
||||
this.siegeProgress = siegeProgress;
|
||||
this.attackerPlayersIncludingOffline.addAll(attackerPlayersIncludingOffline);
|
||||
this.defenderPlayersIncludingOffline.addAll(defenderPlayersIncludingOffline);
|
||||
this.progressManager = new BattleProgressManager(siegeProgress, MAX_SIEGE_PROGRESS);
|
||||
this.phaseManager = new BattlePhaseManager<>(phase, phaseProgress, phaseStartTime);
|
||||
attackers.stream()
|
||||
.map(Bukkit::getOfflinePlayer)
|
||||
.forEach(p -> addPlayer(p, BattleSide.ATTACKER));
|
||||
defenders.stream()
|
||||
.map(Bukkit::getOfflinePlayer)
|
||||
.forEach(p -> addPlayer(p, BattleSide.DEFENDER));
|
||||
|
||||
side1AreAttackers = war.getTownSide(town).getTeam().equals(BattleTeam.SIDE_2);
|
||||
|
||||
calculateOnlinePlayers();
|
||||
side1AreAttackers = war.getSide(town).getTeam().equals(BattleTeam.SIDE_2);
|
||||
}
|
||||
|
||||
/**
|
||||
* Starts the battle
|
||||
*/
|
||||
@ApiStatus.Internal
|
||||
public void start() {
|
||||
if (!new PreBattleStartEvent(war, this, BattleType.SIEGE).callEvent()) return;
|
||||
|
||||
siegeRunnable = new SiegeRunnable(this);
|
||||
battleRunnable = new SiegeRunnable(this);
|
||||
stopped = false;
|
||||
|
||||
if (!war.isEventWar())
|
||||
AlathranWars.econ.withdrawPlayer(siegeLeader, SIEGE_VICTORY_MONEY);
|
||||
if (AlathranWars.getVaultHook().isEconomyLoaded())
|
||||
AlathranWars.getVaultHook().getEconomy().withdrawPlayer(siegeLeader, SIEGE_VICTORY_MONEY);
|
||||
|
||||
new BattleStartEvent(war, this).callEvent();
|
||||
}
|
||||
@@ -142,10 +170,11 @@ public class Siege implements Battle {
|
||||
/**
|
||||
* Resumes the battle (after a server restart e.t.c.)
|
||||
*/
|
||||
@ApiStatus.Internal
|
||||
public void resume() {
|
||||
if (!new PreBattleStartEvent(war, this, BattleType.SIEGE).callEvent()) return;
|
||||
|
||||
siegeRunnable = new SiegeRunnable(this, getSiegeProgress());
|
||||
battleRunnable = new SiegeRunnable(this, getProgressManager().get());
|
||||
stopped = false;
|
||||
|
||||
new BattleStartEvent(war, this).callEvent();
|
||||
@@ -156,10 +185,11 @@ public class Siege implements Battle {
|
||||
* </p>
|
||||
* Internal stop method for battles which triggers cleanup methods
|
||||
*/
|
||||
@ApiStatus.Internal
|
||||
public void stop() {
|
||||
if (stopped) return;
|
||||
stopped = true;
|
||||
siegeRunnable.cancel();
|
||||
battleRunnable.cancel();
|
||||
DatabaseQueries.deleteSiege(this); // TODO Run as latent event?
|
||||
war.removeSiege(this); // TODO Run as latent event?
|
||||
}
|
||||
@@ -173,7 +203,8 @@ public class Siege implements Battle {
|
||||
if (!new PreBattleResultEvent(war, this, BattleType.SIEGE, BattleVictor.ATTACKER, reason).callEvent()) return;
|
||||
|
||||
if (!war.isEventWar()) {
|
||||
AlathranWars.econ.depositPlayer(siegeLeader, SIEGE_VICTORY_MONEY);
|
||||
if (AlathranWars.getVaultHook().isEconomyLoaded())
|
||||
AlathranWars.getVaultHook().getEconomy().depositPlayer(siegeLeader, SIEGE_VICTORY_MONEY);
|
||||
double amt;
|
||||
|
||||
if (town.getAccount().getHoldingBalance() > 10000.0) {
|
||||
@@ -184,7 +215,8 @@ public class Siege implements Battle {
|
||||
amt = SIEGE_VICTORY_MONEY;
|
||||
}
|
||||
|
||||
AlathranWars.econ.depositPlayer(siegeLeader, amt);
|
||||
if (AlathranWars.getVaultHook().isEconomyLoaded())
|
||||
AlathranWars.getVaultHook().getEconomy().depositPlayer(siegeLeader, amt);
|
||||
}
|
||||
|
||||
new BattleResultEvent(war, this, BattleVictor.ATTACKER, reason).callEvent();
|
||||
@@ -230,30 +262,12 @@ public class Siege implements Battle {
|
||||
this.lastTouched = lastTouched;
|
||||
}
|
||||
|
||||
public int getSiegeProgress() {
|
||||
return siegeProgress;
|
||||
}
|
||||
|
||||
public void setSiegeProgress(int siegeProgress) {
|
||||
if (siegeProgress < 0) {
|
||||
siegeProgress = 0;
|
||||
} else if (siegeProgress > MAX_SIEGE_PROGRESS) {
|
||||
siegeProgress = MAX_SIEGE_PROGRESS;
|
||||
}
|
||||
this.siegeProgress = siegeProgress;
|
||||
public BattleProgressManager getProgressManager() {
|
||||
return progressManager;
|
||||
}
|
||||
|
||||
public float getSiegeProgressPercentage() {
|
||||
return (getSiegeProgress() * 1.0f) / MAX_SIEGE_PROGRESS;
|
||||
}
|
||||
|
||||
@NotNull
|
||||
public War getWar() {
|
||||
return war;
|
||||
}
|
||||
|
||||
public void setWar(final War war) {
|
||||
this.war = war;
|
||||
return (getProgressManager().get() * 1.0f) / MAX_SIEGE_PROGRESS;
|
||||
}
|
||||
|
||||
@NotNull
|
||||
@@ -268,7 +282,6 @@ public class Siege implements Battle {
|
||||
/**
|
||||
* Gets attacker name string
|
||||
*/
|
||||
@NotNull
|
||||
public Side getAttackerSide() {
|
||||
return getSide1AreAttackers() ? war.getSide1() : war.getSide2();
|
||||
}
|
||||
@@ -276,7 +289,6 @@ public class Siege implements Battle {
|
||||
/**
|
||||
* Gets defender name string
|
||||
*/
|
||||
@NotNull
|
||||
public Side getDefenderSide() {
|
||||
return getSide1AreAttackers() ? war.getSide2() : war.getSide1();
|
||||
}
|
||||
@@ -287,11 +299,11 @@ public class Siege implements Battle {
|
||||
if (activeBossBar == null)
|
||||
createNewDisplayBar();
|
||||
|
||||
for (@NotNull Player p : Bukkit.getOnlinePlayers()) {
|
||||
for (Player p : Bukkit.getOnlinePlayers()) {
|
||||
p.hideBossBar(activeBossBar);
|
||||
}
|
||||
|
||||
for (@Nullable Player p : this.getPlayersOnBattlefield()) {
|
||||
for (Player p : this.getPlayersOnBattlefield()) {
|
||||
if (p != null)
|
||||
p.showBossBar(activeBossBar);
|
||||
}
|
||||
@@ -341,7 +353,7 @@ public class Siege implements Battle {
|
||||
}
|
||||
|
||||
public void createNewDisplayBar() {
|
||||
final @NotNull Component text = ColorParser.of("<gray>Capture Progress: <yellow><progress> <gray>Time: <yellow><time>min")
|
||||
final Component text = ColorParser.of("<gray>Capture Progress: <yellow><progress> <gray>Time: <yellow><time>min")
|
||||
.parseMinimessagePlaceholder("progress", "%.0f%%".formatted(getSiegeProgressPercentage() * 100))
|
||||
.parseMinimessagePlaceholder("time", String.valueOf(Duration.between(Instant.now(), getEndTime()).toMinutesPart()))
|
||||
.build();
|
||||
@@ -361,7 +373,8 @@ public class Siege implements Battle {
|
||||
|
||||
// SECTION UUID
|
||||
|
||||
public @NotNull UUID getUUID() {
|
||||
@Override
|
||||
public UUID getUUID() {
|
||||
return uuid;
|
||||
}
|
||||
|
||||
@@ -378,11 +391,12 @@ public class Siege implements Battle {
|
||||
/**
|
||||
* Equals boolean.
|
||||
*
|
||||
* @param siege the siege
|
||||
* @param battle the battle
|
||||
* @return the boolean
|
||||
*/
|
||||
public boolean equals(@NotNull Siege siege) {
|
||||
return getUUID().equals(siege.getUUID());
|
||||
@Override
|
||||
public boolean equals(Battle battle) {
|
||||
return getUUID().equals(battle.getUUID());
|
||||
}
|
||||
|
||||
// SECTION BattleType
|
||||
@@ -399,7 +413,7 @@ public class Siege implements Battle {
|
||||
return homeBlock;
|
||||
}
|
||||
|
||||
public void setHomeBlock(TownBlock homeBlock) {
|
||||
public void setHomeBlock(@Nullable TownBlock homeBlock) {
|
||||
this.homeBlock = homeBlock;
|
||||
}
|
||||
|
||||
@@ -408,7 +422,7 @@ public class Siege implements Battle {
|
||||
return townSpawn;
|
||||
}
|
||||
|
||||
public void setTownSpawn(Location townSpawn) {
|
||||
public void setTownSpawn(@Nullable Location townSpawn) {
|
||||
this.townSpawn = townSpawn;
|
||||
}
|
||||
|
||||
@@ -420,29 +434,8 @@ public class Siege implements Battle {
|
||||
this.side1AreAttackers = side1AreAttackers;
|
||||
}
|
||||
|
||||
@NotNull
|
||||
public Set<Player> getPlayersOnBattlefield() {
|
||||
return Stream.concat(attackers.stream(), defenders.stream()).collect(Collectors.toSet());
|
||||
}
|
||||
|
||||
@NotNull
|
||||
public Set<Player> getAttackers() {
|
||||
return attackers;
|
||||
}
|
||||
|
||||
@NotNull
|
||||
public Set<Player> getDefenders() {
|
||||
return defenders;
|
||||
}
|
||||
|
||||
@NotNull
|
||||
public Set<Player> getAttackerPlayers() {
|
||||
return attackerPlayers;
|
||||
}
|
||||
|
||||
@NotNull
|
||||
public Set<Player> getDefenderPlayers() {
|
||||
return defenderPlayers;
|
||||
public List<Player> getPlayersOnBattlefield() {
|
||||
return Stream.concat(getActivePlayers(BattleSide.ATTACKER).stream(), getActivePlayers(BattleSide.DEFENDER).stream()).toList();
|
||||
}
|
||||
|
||||
@NotNull
|
||||
@@ -470,179 +463,9 @@ public class Siege implements Battle {
|
||||
endTime = time;
|
||||
}
|
||||
|
||||
// SECTION Player management
|
||||
// SECTION Phase Management
|
||||
|
||||
public boolean isPlayerInSiege(UUID uuid) {
|
||||
return attackerPlayersIncludingOffline.contains(uuid) || defenderPlayersIncludingOffline.contains(uuid);
|
||||
}
|
||||
|
||||
public boolean isPlayerInSiege(@NotNull Player p) {
|
||||
return isPlayerInSiege(p.getUniqueId());
|
||||
}
|
||||
|
||||
public @NotNull BattleSide getPlayerSideInSiege(UUID uuid) {
|
||||
if (attackerPlayersIncludingOffline.contains(uuid))
|
||||
return BattleSide.ATTACKER;
|
||||
|
||||
if (defenderPlayersIncludingOffline.contains(uuid))
|
||||
return BattleSide.DEFENDER;
|
||||
|
||||
return BattleSide.SPECTATOR;
|
||||
}
|
||||
|
||||
public @NotNull BattleSide getPlayerSideInSiege(@NotNull Player p) {
|
||||
return getPlayerSideInSiege(p.getUniqueId());
|
||||
}
|
||||
|
||||
public void addPlayer(@NotNull Player p, @NotNull BattleSide side) {
|
||||
addPlayer(p.getUniqueId(), side);
|
||||
}
|
||||
|
||||
public void addPlayer(@NotNull OfflinePlayer offlinePlayer, @NotNull BattleSide side) {
|
||||
if (offlinePlayer.hasPlayedBefore())
|
||||
addPlayer(offlinePlayer.getUniqueId(), side);
|
||||
}
|
||||
|
||||
public void addPlayer(@NotNull UUID uuid, @NotNull BattleSide side) {
|
||||
if (isPlayerInSiege(uuid)) return;
|
||||
|
||||
switch (side) {
|
||||
case ATTACKER -> attackerPlayersIncludingOffline.add(uuid);
|
||||
case DEFENDER -> defenderPlayersIncludingOffline.add(uuid);
|
||||
}
|
||||
|
||||
if (Bukkit.getOfflinePlayer(uuid).isOnline()) {
|
||||
final @Nullable Player p = Bukkit.getPlayer(uuid);
|
||||
addOnlinePlayer(p, side);
|
||||
}
|
||||
}
|
||||
|
||||
public void addOnlinePlayer(Player p, @NotNull BattleSide side) {
|
||||
switch (side) {
|
||||
case ATTACKER -> attackerPlayers.add(p);
|
||||
case DEFENDER -> defenderPlayers.add(p);
|
||||
}
|
||||
}
|
||||
|
||||
public void removePlayer(@NotNull Player p) {
|
||||
removePlayer(p.getUniqueId());
|
||||
}
|
||||
|
||||
public void removePlayer(@NotNull OfflinePlayer offlinePlayer) {
|
||||
if (offlinePlayer.hasPlayedBefore())
|
||||
removePlayer(offlinePlayer.getUniqueId());
|
||||
}
|
||||
|
||||
public void removePlayer(@NotNull UUID uuid) {
|
||||
if (!isPlayerInSiege(uuid)) return;
|
||||
|
||||
final @NotNull BattleSide side = getPlayerSideInSiege(uuid);
|
||||
|
||||
switch (side) {
|
||||
case ATTACKER -> attackerPlayersIncludingOffline.remove(uuid);
|
||||
case DEFENDER -> defenderPlayersIncludingOffline.remove(uuid);
|
||||
}
|
||||
|
||||
if (Bukkit.getOfflinePlayer(uuid).isOnline()) {
|
||||
final @Nullable Player p = Bukkit.getPlayer(uuid);
|
||||
removeOnlinePlayer(p, side);
|
||||
}
|
||||
}
|
||||
|
||||
public void removeOnlinePlayer(Player p, @NotNull BattleSide side) {
|
||||
switch (side) {
|
||||
case ATTACKER -> attackerPlayers.remove(p);
|
||||
case DEFENDER -> defenderPlayers.remove(p);
|
||||
}
|
||||
}
|
||||
|
||||
public Set<UUID> getAttackerPlayersIncludingOffline() {
|
||||
return attackerPlayersIncludingOffline;
|
||||
}
|
||||
|
||||
public Set<UUID> getDefenderPlayersIncludingOffline() {
|
||||
return defenderPlayersIncludingOffline;
|
||||
}
|
||||
|
||||
public void calculateOnlinePlayers() {
|
||||
final @NotNull Set<Player> onlineAttackers = attackerPlayersIncludingOffline.stream()
|
||||
.filter(uuid1 -> Bukkit.getOfflinePlayer(uuid1).isOnline())
|
||||
.map(Bukkit::getPlayer)
|
||||
.collect(Collectors.toSet());
|
||||
|
||||
attackerPlayers.clear();
|
||||
attackerPlayers.addAll(onlineAttackers);
|
||||
|
||||
final @NotNull Set<Player> onlineDefenders = defenderPlayersIncludingOffline.stream()
|
||||
.filter(uuid1 -> Bukkit.getOfflinePlayer(uuid1).isOnline())
|
||||
.map(Bukkit::getPlayer)
|
||||
.collect(Collectors.toSet());
|
||||
|
||||
defenderPlayers.clear();
|
||||
defenderPlayers.addAll(onlineDefenders);
|
||||
}
|
||||
|
||||
public void calculateBattlefieldPlayers(@NotNull Location location) {
|
||||
final Set<Player> previousAttackersOnBattlefield = new HashSet<>(attackers);
|
||||
final Set<Player> previousDefendersOnBattlefield = new HashSet<>(defenders);
|
||||
|
||||
final @NotNull Set<Player> attackersOnBattlefield = attackerPlayers.stream()
|
||||
.filter(OfflinePlayer::isOnline)
|
||||
.filter(p -> location.getWorld().equals(p.getLocation().getWorld()))
|
||||
.filter(p -> location.distance(p.getLocation()) < BATTLEFIELD_RANGE)
|
||||
.collect(Collectors.toSet());
|
||||
|
||||
attackers.clear();
|
||||
attackers.addAll(attackersOnBattlefield);
|
||||
|
||||
final @NotNull Set<Player> defendersOnBattlefield = defenderPlayers.stream()
|
||||
.filter(OfflinePlayer::isOnline)
|
||||
.filter(p -> location.getWorld().equals(p.getLocation().getWorld()))
|
||||
.filter(p -> location.distance(p.getLocation()) < BATTLEFIELD_RANGE)
|
||||
.collect(Collectors.toSet());
|
||||
|
||||
defenders.clear();
|
||||
defenders.addAll(defendersOnBattlefield);
|
||||
|
||||
// TODO Emit events for players leaving & entering the battlefield
|
||||
|
||||
// Leaving attackers
|
||||
previousAttackersOnBattlefield.stream()
|
||||
.filter(p -> p.isConnected() && !attackers.contains(p))
|
||||
.collect(Collectors.toSet())
|
||||
.forEach(p -> {
|
||||
// TODO Player left battlefield
|
||||
|
||||
}
|
||||
);
|
||||
|
||||
// Entering attackers
|
||||
attackers.stream()
|
||||
.filter(p -> p.isConnected() && !previousAttackersOnBattlefield.contains(p))
|
||||
.collect(Collectors.toSet())
|
||||
.forEach(p -> {
|
||||
// TODO Player entered battlefield
|
||||
|
||||
}
|
||||
);
|
||||
|
||||
// Leaving defenders
|
||||
previousDefendersOnBattlefield.stream()
|
||||
.filter(p -> p.isConnected() && !defenders.contains(p))
|
||||
.collect(Collectors.toSet())
|
||||
.forEach(p -> {
|
||||
// TODO Player left battlefield
|
||||
|
||||
}
|
||||
);
|
||||
|
||||
// Entering defenders
|
||||
defenders.stream()
|
||||
.filter(p -> p.isConnected() && !previousDefendersOnBattlefield.contains(p))
|
||||
.collect(Collectors.toSet())
|
||||
.forEach(p -> {
|
||||
// TODO Player entered battlefield
|
||||
}
|
||||
);
|
||||
public BattlePhaseManager<SiegePhase> getPhaseManager() {
|
||||
return phaseManager;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,41 @@
|
||||
package com.github.alathra.alathranwars.conflict.battle.siege;
|
||||
|
||||
import com.github.alathra.alathranwars.conflict.battle.phase.BattlePhaseSwitchException;
|
||||
import com.github.alathra.alathranwars.conflict.battle.phase.IBattlePhase;
|
||||
|
||||
public enum SiegePhase implements IBattlePhase<SiegePhase> {
|
||||
SIEGE(1),
|
||||
ENDING(2);
|
||||
|
||||
// Identifiers start at 1, used to traverse between stages
|
||||
private final int phaseIdentifier;
|
||||
|
||||
SiegePhase(int phaseIdentifier) {
|
||||
this.phaseIdentifier = phaseIdentifier;
|
||||
}
|
||||
|
||||
@Override
|
||||
public int getPhaseIdentifier() {
|
||||
return phaseIdentifier;
|
||||
}
|
||||
|
||||
@Override
|
||||
public SiegePhase next() throws BattlePhaseSwitchException {
|
||||
return next(fromIdentifier(getPhaseIdentifier()));
|
||||
}
|
||||
|
||||
@Override
|
||||
public SiegePhase previous() throws BattlePhaseSwitchException {
|
||||
return previous(fromIdentifier(getPhaseIdentifier()));
|
||||
}
|
||||
|
||||
@Override
|
||||
public SiegePhase next(SiegePhase phase) throws BattlePhaseSwitchException {
|
||||
return IBattlePhase.super.next(phase);
|
||||
}
|
||||
|
||||
@Override
|
||||
public SiegePhase previous(SiegePhase phase) throws BattlePhaseSwitchException {
|
||||
return IBattlePhase.super.previous(phase);
|
||||
}
|
||||
}
|
||||
+15
-12
@@ -42,7 +42,7 @@ public class SiegeRunnable implements Runnable {
|
||||
public SiegeRunnable(@NotNull Siege siege) {
|
||||
this.siege = siege;
|
||||
|
||||
siege.setSiegeProgress(0);
|
||||
siege.getProgressManager().set(0);
|
||||
|
||||
siege.setHomeBlock(siege.getTown().getHomeBlockOrNull());
|
||||
siege.setTownSpawn(siege.getTown().getSpawnOrNull());
|
||||
@@ -63,7 +63,7 @@ public class SiegeRunnable implements Runnable {
|
||||
public SiegeRunnable(@NotNull Siege siege, int siegeProgress) {
|
||||
this.siege = siege;
|
||||
|
||||
siege.setSiegeProgress(siegeProgress);
|
||||
siege.getProgressManager().set(siegeProgress);
|
||||
|
||||
siege.setHomeBlock(siege.getTown().getHomeBlockOrNull());
|
||||
siege.setTownSpawn(siege.getTown().getSpawnOrNull());
|
||||
@@ -94,11 +94,14 @@ public class SiegeRunnable implements Runnable {
|
||||
town.setSpawn(townSpawn);
|
||||
}
|
||||
|
||||
if (townSpawn == null)
|
||||
return;
|
||||
|
||||
// Render beam
|
||||
startBeam();
|
||||
|
||||
// Calculate battlefield players
|
||||
siege.calculateBattlefieldPlayers(townSpawn.toCenterLocation());
|
||||
siege.calculateBattlefieldPlayers(townSpawn.toCenterLocation(), BATTLEFIELD_RANGE, this.siege.getWar(), siege);
|
||||
|
||||
// Progress the siege
|
||||
final int attackersOnPoint = getPeopleOnPoint(townSpawn, BattleSide.ATTACKER);
|
||||
@@ -117,7 +120,7 @@ public class SiegeRunnable implements Runnable {
|
||||
}
|
||||
|
||||
// Attackers captured the town
|
||||
if (siege.getSiegeProgress() >= MAX_SIEGE_PROGRESS) {
|
||||
if (siege.getProgressManager().get() >= MAX_SIEGE_PROGRESS) {
|
||||
cancel();
|
||||
siege.attackersWin(BattleVictoryReason.OPPONENT_LOST);
|
||||
return;
|
||||
@@ -129,12 +132,12 @@ public class SiegeRunnable implements Runnable {
|
||||
|
||||
// If you have less than 5 people contesting you get (4 + excessPlayers) points per second
|
||||
if (playerOnPointDiff < 5) {
|
||||
siege.setSiegeProgress(siege.getSiegeProgress() + (4 + playerOnPointDiff));
|
||||
siege.getProgressManager().set(siege.getProgressManager().get() + (4 + playerOnPointDiff));
|
||||
} else {
|
||||
siege.setSiegeProgress(siege.getSiegeProgress() + 10);
|
||||
siege.getProgressManager().set(siege.getProgressManager().get() + 10);
|
||||
}
|
||||
}
|
||||
case DOWN -> siege.setSiegeProgress(siege.getSiegeProgress() - 10);
|
||||
case DOWN -> siege.getProgressManager().set(siege.getProgressManager().get() - 10);
|
||||
}
|
||||
|
||||
if (oldProgressDirection != progressDirection) {
|
||||
@@ -188,10 +191,10 @@ public class SiegeRunnable implements Runnable {
|
||||
oldProgressDirection = progressDirection;
|
||||
}
|
||||
|
||||
public int getPeopleOnPoint(@NotNull Location townSpawn, @NotNull BattleSide battleSide) {
|
||||
private int getPeopleOnPoint(Location townSpawn, BattleSide battleSide) {
|
||||
int onPoint = 0;
|
||||
|
||||
for (final @NotNull Player p : (battleSide.equals(BattleSide.ATTACKER) ? siege.getAttackers() : siege.getDefenders())) {
|
||||
for (final Player p : (battleSide.equals(BattleSide.ATTACKER) ? siege.getActivePlayers(BattleSide.ATTACKER) : siege.getActivePlayers(BattleSide.DEFENDER))) {
|
||||
if (p.isDead())
|
||||
continue;
|
||||
|
||||
@@ -206,7 +209,7 @@ public class SiegeRunnable implements Runnable {
|
||||
return onPoint;
|
||||
}
|
||||
|
||||
public @NotNull CaptureProgressDirection getSiegeProgressDirection(int attackersOnPoint, int defendersOnPoint) {
|
||||
private CaptureProgressDirection getSiegeProgressDirection(int attackersOnPoint, int defendersOnPoint) {
|
||||
final boolean attackersAreOnPoint = attackersOnPoint > 0;
|
||||
final boolean defendersAreOnPoint = defendersOnPoint > 0;
|
||||
|
||||
@@ -220,12 +223,12 @@ public class SiegeRunnable implements Runnable {
|
||||
|
||||
return CONTESTED;
|
||||
} else if (attackersAreOnPoint && !defendersAreOnPoint) {
|
||||
if (siege.getSiegeProgress() == MAX_SIEGE_PROGRESS)
|
||||
if (siege.getProgressManager().get() == MAX_SIEGE_PROGRESS)
|
||||
return CONTESTED;
|
||||
|
||||
return UP;
|
||||
} else {
|
||||
if (siege.getSiegeProgress() == 0)
|
||||
if (siege.getProgressManager().get() == 0)
|
||||
return UNCONTESTED;
|
||||
|
||||
// If the attackers haven't touched in a while, begin reverting progress
|
||||
|
||||
@@ -7,7 +7,7 @@ import com.github.alathra.alathranwars.conflict.battle.siege.Siege;
|
||||
import com.github.alathra.alathranwars.conflict.war.side.Side;
|
||||
import com.github.alathra.alathranwars.conflict.war.side.SideBuilder;
|
||||
import com.github.alathra.alathranwars.conflict.war.side.SideCreationException;
|
||||
import com.github.alathra.alathranwars.db.DatabaseQueries;
|
||||
import com.github.alathra.alathranwars.database.DatabaseQueries;
|
||||
import com.github.alathra.alathranwars.enums.ConflictType;
|
||||
import com.github.alathra.alathranwars.enums.WarDeleteReason;
|
||||
import com.github.alathra.alathranwars.enums.battle.BattleSide;
|
||||
@@ -17,7 +17,7 @@ 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.hooks.NameColorHandler;
|
||||
import com.github.alathra.alathranwars.hook.NameColorHandler;
|
||||
import com.github.alathra.alathranwars.utility.UtilsChat;
|
||||
import com.github.milkdrinkers.colorparser.ColorParser;
|
||||
import com.palmergames.bukkit.towny.object.Government;
|
||||
@@ -37,6 +37,7 @@ import org.jetbrains.annotations.Nullable;
|
||||
|
||||
import java.time.Duration;
|
||||
import java.util.HashSet;
|
||||
import java.util.List;
|
||||
import java.util.Set;
|
||||
import java.util.UUID;
|
||||
import java.util.stream.Collectors;
|
||||
@@ -46,7 +47,6 @@ import java.util.stream.Stream;
|
||||
* The type New war.
|
||||
*/
|
||||
public class War extends Conflict {
|
||||
private final UUID uuid;
|
||||
private final String name; // Used in commands and such, like "TidalHaven.vs.Meme"
|
||||
private final String label;
|
||||
private final ConflictType conflictType = ConflictType.WAR;
|
||||
@@ -73,7 +73,7 @@ public class War extends Conflict {
|
||||
* @param event the event
|
||||
*/
|
||||
@ApiStatus.Internal
|
||||
public War(
|
||||
War(
|
||||
UUID uuid,
|
||||
String name,
|
||||
String label,
|
||||
@@ -83,7 +83,7 @@ public class War extends Conflict {
|
||||
Set<Raid> raids,
|
||||
boolean event
|
||||
) {
|
||||
this.uuid = uuid;
|
||||
super(uuid);
|
||||
this.name = name;
|
||||
this.label = label;
|
||||
|
||||
@@ -112,14 +112,14 @@ public class War extends Conflict {
|
||||
* @throws WrapperCommandSyntaxException the wrapper command syntax exception
|
||||
*/
|
||||
@ApiStatus.Internal
|
||||
public War(
|
||||
War(
|
||||
UUID uuid,
|
||||
String label,
|
||||
Government aggressor,
|
||||
Government victim,
|
||||
boolean event
|
||||
) throws SideCreationException, WrapperCommandSyntaxException {
|
||||
this.uuid = uuid;
|
||||
super(uuid);
|
||||
this.label = label;
|
||||
|
||||
this.name = "%s.vs.%s".formatted(aggressor.getName(), victim.getName());
|
||||
@@ -127,14 +127,14 @@ public class War extends Conflict {
|
||||
throw CommandAPIBukkit.failWithAdventureComponent(ColorParser.of(UtilsChat.getPrefix() + "<red>A war already exists with that name!").build());
|
||||
|
||||
this.side1 = new SideBuilder()
|
||||
.setWarUUID(this.uuid)
|
||||
.setWarUUID(getUUID())
|
||||
.setUuid(UUID.randomUUID())
|
||||
.setLeader(aggressor)
|
||||
.setSide(BattleSide.ATTACKER)
|
||||
.setTeam(BattleTeam.SIDE_1)
|
||||
.build();
|
||||
this.side2 = new SideBuilder()
|
||||
.setWarUUID(this.uuid)
|
||||
.setWarUUID(getUUID())
|
||||
.setUuid(UUID.randomUUID())
|
||||
.setLeader(victim)
|
||||
.setSide(BattleSide.DEFENDER)
|
||||
@@ -156,15 +156,6 @@ public class War extends Conflict {
|
||||
new WarCreateEvent(this).callEvent();
|
||||
}
|
||||
|
||||
/**
|
||||
* Gets uuid of the war.
|
||||
*
|
||||
* @return the uuid
|
||||
*/
|
||||
public UUID getUUID() {
|
||||
return this.uuid;
|
||||
}
|
||||
|
||||
/**
|
||||
* Gets name of the war.
|
||||
*
|
||||
@@ -185,26 +176,6 @@ public class War extends Conflict {
|
||||
return label;
|
||||
}
|
||||
|
||||
/**
|
||||
* Compare war UUID's.
|
||||
*
|
||||
* @param uuid the uuid
|
||||
* @return the boolean
|
||||
*/
|
||||
public boolean equals(UUID uuid) {
|
||||
return this.uuid.equals(uuid);
|
||||
}
|
||||
|
||||
/**
|
||||
* Compare war by UUID's.
|
||||
*
|
||||
* @param war the war
|
||||
* @return the boolean
|
||||
*/
|
||||
public boolean equals(War war) {
|
||||
return this.uuid.equals(war.getUUID());
|
||||
}
|
||||
|
||||
/**
|
||||
* Compare war by names.
|
||||
*
|
||||
@@ -302,6 +273,8 @@ public class War extends Conflict {
|
||||
return null;
|
||||
}
|
||||
|
||||
// SECTION Battles
|
||||
|
||||
/**
|
||||
* Gets sieges in a list.
|
||||
*
|
||||
@@ -367,6 +340,32 @@ public class War extends Conflict {
|
||||
return raids;
|
||||
}
|
||||
|
||||
/**
|
||||
* Sets raids for the war.
|
||||
*
|
||||
* @param raids the raids
|
||||
*/
|
||||
@ApiStatus.Internal
|
||||
public void setRaids(Set<Raid> raids) {
|
||||
this.raids = raids;
|
||||
// TODO Raids
|
||||
// this.raids.forEach(Raid::resume);
|
||||
}
|
||||
|
||||
/**
|
||||
* Gets raid by the raid UUID.
|
||||
*
|
||||
* @param uuid the uuid
|
||||
* @return the raid
|
||||
*/
|
||||
@Nullable
|
||||
public Raid getRaid(UUID uuid) {
|
||||
return raids.stream()
|
||||
.filter(s -> s.equals(uuid))
|
||||
.findAny()
|
||||
.orElse(null);
|
||||
}
|
||||
|
||||
/**
|
||||
* Add raid to war.
|
||||
*
|
||||
@@ -404,59 +403,172 @@ public class War extends Conflict {
|
||||
* @return the boolean
|
||||
*/
|
||||
public boolean isTownUnderRaid(Town town) {
|
||||
return raids.stream().anyMatch(raid -> raid.getTown().equals(town));
|
||||
// TODO Raids
|
||||
return false;
|
||||
// return raids.stream().anyMatch(raid -> raid.getTown().equals(town));
|
||||
}
|
||||
|
||||
// SECITON Nation & Town Getters
|
||||
|
||||
/**
|
||||
* Gets all online players in the war.
|
||||
* Gets nations in the war excluding surrendered ones.
|
||||
*
|
||||
* @return the players
|
||||
* @return the nations
|
||||
*/
|
||||
@NotNull
|
||||
public Set<Player> getPlayers() {
|
||||
public Set<Nation> getNations() {
|
||||
return Stream.concat(
|
||||
getSide1().getPlayers().stream(),
|
||||
getSide2().getPlayers().stream()
|
||||
getSide1().getNations().stream(),
|
||||
getSide2().getNations().stream()
|
||||
)
|
||||
.collect(Collectors.toSet());
|
||||
}
|
||||
|
||||
/**
|
||||
* Gets all players, including offline ones in the war.
|
||||
* Gets all surrendered nations in the war.
|
||||
*
|
||||
* @return the players including offline
|
||||
* @return the surrendered nations
|
||||
*/
|
||||
@NotNull
|
||||
public Set<OfflinePlayer> getPlayersIncludingOffline() {
|
||||
public Set<Nation> getNationsSurrendered() {
|
||||
return Stream.concat(
|
||||
getSide1().getPlayersIncludingOffline().stream().map(Bukkit::getOfflinePlayer),
|
||||
getSide2().getPlayersIncludingOffline().stream().map(Bukkit::getOfflinePlayer)
|
||||
getSide1().getNationsSurrendered().stream(),
|
||||
getSide2().getNationsSurrendered().stream()
|
||||
)
|
||||
.collect(Collectors.toSet());
|
||||
}
|
||||
|
||||
/**
|
||||
* Gets all surrendered players in the war.
|
||||
* Gets all nations in the war including surrendered.
|
||||
*
|
||||
* @return the surrendered players
|
||||
* @return the all nations
|
||||
*/
|
||||
@NotNull
|
||||
public Set<OfflinePlayer> getSurrenderedPlayers() {
|
||||
public Set<Nation> getNationsAll() {
|
||||
return Stream.concat(
|
||||
getSide1().getSurrenderedPlayersIncludingOffline().stream().map(Bukkit::getOfflinePlayer),
|
||||
getSide2().getSurrenderedPlayersIncludingOffline().stream().map(Bukkit::getOfflinePlayer)
|
||||
getSide1().getNations().stream(),
|
||||
Stream.concat(
|
||||
getSide2().getNations().stream(),
|
||||
getNationsSurrendered().stream()
|
||||
)
|
||||
)
|
||||
.collect(Collectors.toSet());
|
||||
}
|
||||
|
||||
/**
|
||||
* Gets towns in the war excluding surrendered ones.
|
||||
*
|
||||
* @return the towns
|
||||
*/
|
||||
public Set<Town> getTowns() {
|
||||
return Stream.concat(
|
||||
getSide1().getTowns().stream(),
|
||||
getSide2().getTowns().stream()
|
||||
)
|
||||
.collect(Collectors.toSet());
|
||||
}
|
||||
|
||||
/**
|
||||
* Gets all surrendered towns in the war.
|
||||
*
|
||||
* @return the surrendered towns
|
||||
*/
|
||||
public Set<Town> getTownsSurrendered() {
|
||||
return Stream.concat(
|
||||
getSide1().getTownsSurrendered().stream(),
|
||||
getSide2().getTownsSurrendered().stream()
|
||||
)
|
||||
.collect(Collectors.toSet());
|
||||
}
|
||||
|
||||
/**
|
||||
* Gets all towns in the war including surrendered towns.
|
||||
*
|
||||
* @return the all towns
|
||||
*/
|
||||
public Set<Town> getTownsAll() {
|
||||
return Stream.concat(
|
||||
getSide1().getTowns().stream(),
|
||||
Stream.concat(
|
||||
getSide2().getTowns().stream(),
|
||||
getTownsSurrendered().stream()
|
||||
)
|
||||
)
|
||||
.collect(Collectors.toSet());
|
||||
}
|
||||
|
||||
// SECTION Players Getters
|
||||
|
||||
/**
|
||||
* Get all players in the war (excluding surrendered)
|
||||
* @return player list
|
||||
*/
|
||||
public List<OfflinePlayer> getPlayers() {
|
||||
return Stream.concat(
|
||||
getSide1().getPlayers().stream(),
|
||||
getSide2().getPlayers().stream()
|
||||
).toList();
|
||||
}
|
||||
|
||||
/**
|
||||
* Get all players in the war (excludes non-surrendered players)
|
||||
* @return player list
|
||||
*/
|
||||
public List<OfflinePlayer> getPlayersSurrendered() {
|
||||
return Stream.concat(
|
||||
getSide1().getPlayersSurrendered().stream(),
|
||||
getSide2().getPlayersSurrendered().stream()
|
||||
).toList();
|
||||
}
|
||||
|
||||
/**
|
||||
* Get all players in the war (includes surrendered players)
|
||||
* @return player list
|
||||
*/
|
||||
public List<OfflinePlayer> getPlayersAll() {
|
||||
return Stream.concat(getSide1().getPlayersAll().stream(), getSide2().getPlayersAll().stream()).toList();
|
||||
}
|
||||
|
||||
/**
|
||||
* Get all online players in the war (excluding surrendered)
|
||||
* @return player list
|
||||
*/
|
||||
public List<Player> getPlayersOnline() {
|
||||
return Stream.concat(
|
||||
getSide1().getPlayersOnline().stream(),
|
||||
getSide2().getPlayersOnline().stream()
|
||||
).toList();
|
||||
}
|
||||
|
||||
/**
|
||||
* Get all online players in the war (excludes non-surrendered players)
|
||||
* @return player list
|
||||
*/
|
||||
public List<Player> getPlayersSurrenderedOnline() {
|
||||
return Stream.concat(
|
||||
getSide1().getPlayersSurrenderedOnline().stream(),
|
||||
getSide2().getPlayersSurrenderedOnline().stream()
|
||||
).toList();
|
||||
}
|
||||
|
||||
/**
|
||||
* Get all online players in the war (includes surrendered players)
|
||||
* @return player list
|
||||
*/
|
||||
public List<Player> getPlayersOnlineAll() {
|
||||
return Stream.concat(
|
||||
getSide1().getPlayersOnlineAll().stream(),
|
||||
getSide2().getPlayersOnlineAll().stream()
|
||||
).toList();
|
||||
}
|
||||
|
||||
// SECTION Misc
|
||||
|
||||
/**
|
||||
* Check if player is in war.
|
||||
*
|
||||
* @param p the p
|
||||
* @return the boolean
|
||||
*/
|
||||
public boolean isPlayerInWar(Player p) {
|
||||
return side1.isPlayerOnSide(p) || side2.isPlayerOnSide(p);
|
||||
public boolean isInWar(Player p) {
|
||||
return side1.isOnSide(p) || side2.isOnSide(p);
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -465,8 +577,8 @@ public class War extends Conflict {
|
||||
* @param uuid the uuid
|
||||
* @return the boolean
|
||||
*/
|
||||
public boolean isPlayerInWar(UUID uuid) {
|
||||
return side1.isPlayerOnSide(uuid) || side2.isPlayerOnSide(uuid);
|
||||
public boolean isInWar(UUID uuid) {
|
||||
return side1.isOnSide(uuid) || side2.isOnSide(uuid);
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -488,64 +600,37 @@ public class War extends Conflict {
|
||||
*/
|
||||
@Nullable
|
||||
public Side getPlayerSide(UUID uuid) {
|
||||
if (side1.isPlayerOnSide(uuid))
|
||||
if (side1.isOnSide(uuid))
|
||||
return getSide1();
|
||||
|
||||
if (side2.isPlayerOnSide(uuid))
|
||||
if (side2.isOnSide(uuid))
|
||||
return getSide2();
|
||||
|
||||
return null;
|
||||
}
|
||||
|
||||
/**
|
||||
* Is town in war.
|
||||
* Is nation or town in war.
|
||||
*
|
||||
* @param town the town
|
||||
* @param government the nation or town
|
||||
* @return the boolean
|
||||
*/
|
||||
public boolean isTownInWar(Town town) {
|
||||
return side1.isTownOnSide(town) || side2.isTownOnSide(town);
|
||||
public boolean isInWar(Government government) {
|
||||
return side1.isOnSide(government) || side2.isOnSide(government);
|
||||
}
|
||||
|
||||
/**
|
||||
* Gets town side or null if not in war.
|
||||
* Gets nation or town side, or null if not in war.
|
||||
*
|
||||
* @param town the town
|
||||
* @param government the nation or town
|
||||
* @return the town side
|
||||
*/
|
||||
@Nullable
|
||||
public Side getTownSide(Town town) {
|
||||
if (side1.isTownOnSide(town))
|
||||
public Side getSide(Government government) {
|
||||
if (side1.isOnSide(government))
|
||||
return getSide1();
|
||||
|
||||
if (side2.isTownOnSide(town))
|
||||
return getSide2();
|
||||
|
||||
return null;
|
||||
}
|
||||
|
||||
/**
|
||||
* Is nation in war boolean.
|
||||
*
|
||||
* @param nation the nation
|
||||
* @return the boolean
|
||||
*/
|
||||
public boolean isNationInWar(Nation nation) {
|
||||
return side1.isNationOnSide(nation) || side2.isNationOnSide(nation);
|
||||
}
|
||||
|
||||
/**
|
||||
* Gets nation side or null if not in war.
|
||||
*
|
||||
* @param nation the nation
|
||||
* @return the nation side
|
||||
*/
|
||||
@Nullable
|
||||
public Side getNationSide(Nation nation) {
|
||||
if (side1.isNationOnSide(nation))
|
||||
return getSide1();
|
||||
|
||||
if (side2.isNationOnSide(nation))
|
||||
if (side2.isOnSide(government))
|
||||
return getSide2();
|
||||
|
||||
return null;
|
||||
@@ -577,7 +662,7 @@ public class War extends Conflict {
|
||||
@ApiStatus.Internal
|
||||
public void cancelSieges(Town town) {
|
||||
if (this != null) {
|
||||
Side townSide = getTownSide(town);
|
||||
Side townSide = getSide(town);
|
||||
|
||||
if (townSide == null) return;
|
||||
|
||||
@@ -594,161 +679,61 @@ public class War extends Conflict {
|
||||
}
|
||||
|
||||
/**
|
||||
* Surrender a nation and all its towns out of the war.
|
||||
* Makes a government surrender (Recursively surrenders subjects AKA nations, towns, players)
|
||||
*
|
||||
* @param nation the nation
|
||||
* @param government the government
|
||||
*/
|
||||
public void surrenderNation(Nation nation) {
|
||||
Side nationSide = getNationSide(nation);
|
||||
if (nationSide == null) return;
|
||||
public void surrender(Government government) {
|
||||
if (government instanceof Nation nation) {
|
||||
Side nationSide = getSide(nation);
|
||||
if (nationSide == null) return;
|
||||
|
||||
final @Nullable Nation occupier = nationSide.equals(getSide1()) ? getSide2().getTown().getNationOrNull() : getSide1().getTown().getNationOrNull();
|
||||
Occupation.setOccupied(nation, occupier);
|
||||
final @Nullable Nation occupier = nationSide.equals(getSide1()) ? getSide2().getTown().getNationOrNull() : getSide1().getTown().getNationOrNull();
|
||||
Occupation.setOccupied(nation, occupier);
|
||||
|
||||
nationSide.surrenderNation(nation);
|
||||
// TODO Cancel in progress sieges for towns?
|
||||
nationSide.processSurrenders();
|
||||
}
|
||||
nationSide.surrender(nation);
|
||||
// TODO Cancel in progress sieges for towns?
|
||||
nationSide.processSurrenders();
|
||||
} else if (government instanceof Town town) {
|
||||
Side townSide = getSide(town);
|
||||
if (townSide == null) return;
|
||||
|
||||
/**
|
||||
* Surrender town and all its players out of a war.
|
||||
*
|
||||
* @param town the town
|
||||
*/
|
||||
public void surrenderTown(Town town) {
|
||||
Side townSide = getTownSide(town);
|
||||
if (townSide == null) return;
|
||||
final @Nullable Nation townNation = town.getNationOrNull();
|
||||
final @Nullable Nation occupier = townSide.equals(getSide1()) ? getSide2().getTown().getNationOrNull() : getSide1().getTown().getNationOrNull();
|
||||
Occupation.setOccupied(town, occupier);
|
||||
townSide.surrender(town);
|
||||
|
||||
final @Nullable Nation townNation = town.getNationOrNull();
|
||||
final @Nullable Nation occupier = townSide.equals(getSide1()) ? getSide2().getTown().getNationOrNull() : getSide1().getTown().getNationOrNull();
|
||||
Occupation.setOccupied(town, occupier);
|
||||
townSide.surrenderTown(town);
|
||||
|
||||
if (townNation != null) {
|
||||
if (townSide.shouldNationSurrender(townNation)) {
|
||||
surrenderNation(townNation);
|
||||
if (townNation != null) {
|
||||
if (townSide.shouldSurrender(townNation)) {
|
||||
surrender(townNation);
|
||||
}
|
||||
}
|
||||
|
||||
// TODO Cancel in progress sieges for towns?
|
||||
townSide.processSurrenders();
|
||||
}
|
||||
|
||||
// TODO Cancel in progress sieges for towns?
|
||||
townSide.processSurrenders();
|
||||
}
|
||||
|
||||
/**
|
||||
* Unsurrender a nation and all its towns and players.
|
||||
* Makes a government un-surrender (Recursively un-surrenders subjects AKA nations, towns, players)
|
||||
*
|
||||
* @param nation the nation
|
||||
* @param government the government
|
||||
*/
|
||||
public void unsurrenderNation(Nation nation) {
|
||||
Side nationSide = getNationSide(nation);
|
||||
if (nationSide == null) return;
|
||||
public void unsurrender(Government government) {
|
||||
if (government instanceof Nation nation) {
|
||||
Side nationSide = getSide(nation);
|
||||
if (nationSide == null) return;
|
||||
|
||||
nationSide.unsurrenderNation(nation);
|
||||
nation.getTowns().forEach(this::unsurrenderTown);
|
||||
}
|
||||
nationSide.unsurrender(nation);
|
||||
nation.getTowns().forEach(this::unsurrender);
|
||||
} else if (government instanceof Town town) {
|
||||
Side townSide = getSide(town);
|
||||
if (townSide == null) return;
|
||||
|
||||
/**
|
||||
* Unsurrender town and all its players.
|
||||
*
|
||||
* @param town the town
|
||||
*/
|
||||
public void unsurrenderTown(Town town) {
|
||||
Side townSide = getTownSide(town);
|
||||
if (townSide == null) return;
|
||||
Occupation.removeOccupied(town);
|
||||
|
||||
Occupation.removeOccupied(town);
|
||||
|
||||
townSide.unsurrenderTown(town);
|
||||
}
|
||||
|
||||
/**
|
||||
* Gets towns in the war excluding surrendered ones.
|
||||
*
|
||||
* @return the towns
|
||||
*/
|
||||
@NotNull
|
||||
public Set<Town> getTowns() {
|
||||
return Stream.concat(
|
||||
getSide1().getTowns().stream(),
|
||||
getSide2().getTowns().stream()
|
||||
)
|
||||
.collect(Collectors.toSet());
|
||||
}
|
||||
|
||||
/**
|
||||
* Gets all towns in the war including surrendered towns.
|
||||
*
|
||||
* @return the all towns
|
||||
*/
|
||||
@NotNull
|
||||
public Set<Town> getAllTowns() {
|
||||
return Stream.concat(
|
||||
getSide1().getTowns().stream(),
|
||||
Stream.concat(
|
||||
getSide2().getTowns().stream(),
|
||||
getSurrenderedTowns().stream()
|
||||
)
|
||||
)
|
||||
.collect(Collectors.toSet());
|
||||
}
|
||||
|
||||
/**
|
||||
* Gets nations in the war excluding surrendered ones.
|
||||
*
|
||||
* @return the nations
|
||||
*/
|
||||
@NotNull
|
||||
public Set<Nation> getNations() {
|
||||
return Stream.concat(
|
||||
getSide1().getNations().stream(),
|
||||
getSide2().getNations().stream()
|
||||
)
|
||||
.collect(Collectors.toSet());
|
||||
}
|
||||
|
||||
/**
|
||||
* Gets all nations in the war including surrendered.
|
||||
*
|
||||
* @return the all nations
|
||||
*/
|
||||
@NotNull
|
||||
public Set<Nation> getAllNations() {
|
||||
return Stream.concat(
|
||||
getSide1().getNations().stream(),
|
||||
Stream.concat(
|
||||
getSide2().getNations().stream(),
|
||||
getSurrenderedNations().stream()
|
||||
)
|
||||
)
|
||||
.collect(Collectors.toSet());
|
||||
}
|
||||
|
||||
/**
|
||||
* Gets all surrendered towns in the war.
|
||||
*
|
||||
* @return the surrendered towns
|
||||
*/
|
||||
@NotNull
|
||||
public Set<Town> getSurrenderedTowns() {
|
||||
return Stream.concat(
|
||||
getSide1().getSurrenderedTowns().stream(),
|
||||
getSide2().getSurrenderedTowns().stream()
|
||||
)
|
||||
.collect(Collectors.toSet());
|
||||
}
|
||||
|
||||
/**
|
||||
* Gets all surrendered nations in the war.
|
||||
*
|
||||
* @return the surrendered nations
|
||||
*/
|
||||
@NotNull
|
||||
public Set<Nation> getSurrenderedNations() {
|
||||
return Stream.concat(
|
||||
getSide1().getSurrenderedNations().stream(),
|
||||
getSide2().getSurrenderedNations().stream()
|
||||
)
|
||||
.collect(Collectors.toSet());
|
||||
townSide.unsurrender(town);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -773,11 +758,11 @@ public class War extends Conflict {
|
||||
);
|
||||
final Sound warSound = Sound.sound(Key.key("entity.wither.spawn"), Sound.Source.VOICE, 0.5f, 1.0F);
|
||||
|
||||
side1.getPlayers().forEach(player -> {
|
||||
side1.getPlayersOnline().forEach(player -> {
|
||||
player.showTitle(warTitle);
|
||||
player.playSound(warSound);
|
||||
});
|
||||
side2.getPlayers().forEach(player -> {
|
||||
side2.getPlayersOnline().forEach(player -> {
|
||||
player.showTitle(warTitle);
|
||||
player.playSound(warSound);
|
||||
});
|
||||
@@ -806,13 +791,13 @@ public class War extends Conflict {
|
||||
return;
|
||||
|
||||
getSieges().forEach(Siege::stop);
|
||||
getAllTowns().forEach(Occupation::removeOccupied);
|
||||
getTownsAll().forEach(Occupation::removeOccupied);
|
||||
|
||||
DatabaseQueries.deleteWar(this);
|
||||
WarController.getInstance().removeWar(this);
|
||||
|
||||
// Run check after war is removed to cleanup player tags
|
||||
getPlayers().forEach(p -> NameColorHandler.getInstance().calculatePlayerColors(p));
|
||||
getPlayersOnline().forEach(p -> NameColorHandler.getInstance().calculatePlayerColors(p));
|
||||
|
||||
new WarDeleteEvent(this, reason).callEvent();
|
||||
}
|
||||
|
||||
@@ -6,43 +6,56 @@ import com.github.alathra.alathranwars.conflict.war.side.Side;
|
||||
import com.github.alathra.alathranwars.conflict.war.side.SideCreationException;
|
||||
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.Nullable;
|
||||
|
||||
import java.util.HashSet;
|
||||
import java.util.Set;
|
||||
import java.util.UUID;
|
||||
|
||||
public class WarBuilder {
|
||||
private UUID uuid;
|
||||
private String name;
|
||||
private String label;
|
||||
private @Nullable UUID uuid;
|
||||
private @Nullable String name;
|
||||
private @Nullable String label;
|
||||
private ConflictType conflictType = ConflictType.WAR;
|
||||
private boolean event = false;
|
||||
private Side side1;
|
||||
private Side side2;
|
||||
private Set<Siege> sieges = new HashSet<>();
|
||||
private Set<Raid> raids = new HashSet<>();
|
||||
private @Nullable Side side1;
|
||||
private @Nullable Side side2;
|
||||
private @Nullable Set<Siege> sieges = new HashSet<>();
|
||||
private @Nullable Set<Raid> raids = new HashSet<>();
|
||||
|
||||
private Government aggressor;
|
||||
private Government victim;
|
||||
private @Nullable Government aggressor;
|
||||
private @Nullable 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();
|
||||
}
|
||||
/**
|
||||
* Build a new war from save data
|
||||
* @return a new war
|
||||
* @throws WarCreationException exception
|
||||
*/
|
||||
public War resume() throws WarCreationException {
|
||||
if (uuid == null)
|
||||
throw new WarCreationException("Missing state uuid required to create War!");
|
||||
|
||||
if (name == null)
|
||||
throw new WarCreationException("Missing state name required to create War!");
|
||||
|
||||
if (label == null)
|
||||
throw new WarCreationException("Missing state label required to create War!");
|
||||
|
||||
if (side1 == null)
|
||||
throw new WarCreationException("Missing state side1 required to create War!");
|
||||
|
||||
if (side2 == null)
|
||||
throw new WarCreationException("Missing state side2 required to create War!");
|
||||
|
||||
if (sieges == null)
|
||||
throw new WarCreationException("Missing state sieges required to create War!");
|
||||
|
||||
if (raids == null)
|
||||
throw new WarCreationException("Missing state raids required to create War!");
|
||||
|
||||
return new War(
|
||||
uuid,
|
||||
@@ -56,9 +69,27 @@ public class WarBuilder {
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* Build a new War
|
||||
* @return a new war
|
||||
* @throws WrapperCommandSyntaxException exception
|
||||
* @throws SideCreationException exception
|
||||
*/
|
||||
public War create() throws WrapperCommandSyntaxException, SideCreationException {
|
||||
this.setUuid(UUID.randomUUID());
|
||||
|
||||
if (uuid == null)
|
||||
throw new WarCreationException("Missing state uuid required to create War!");
|
||||
|
||||
if (label == null)
|
||||
throw new WarCreationException("Missing state label required to create War!");
|
||||
|
||||
if (aggressor == null)
|
||||
throw new WarCreationException("Missing state aggressor required to create War!");
|
||||
|
||||
if (victim == null)
|
||||
throw new WarCreationException("Missing state victim required to create War!");
|
||||
|
||||
return new War(
|
||||
uuid,
|
||||
label,
|
||||
@@ -113,22 +144,6 @@ public class WarBuilder {
|
||||
return this;
|
||||
}
|
||||
|
||||
public WarBuilder setAggressorTown(Town target) {
|
||||
return this;
|
||||
}
|
||||
|
||||
public WarBuilder setAggressorNation(Nation target) {
|
||||
return this;
|
||||
}
|
||||
|
||||
public WarBuilder setVictimTown(Town target) {
|
||||
return this;
|
||||
}
|
||||
|
||||
public WarBuilder setVictimNation(Nation target) {
|
||||
return this;
|
||||
}
|
||||
|
||||
public WarBuilder setAggressor(Government aggressor) {
|
||||
this.aggressor = aggressor;
|
||||
return this;
|
||||
|
||||
@@ -3,20 +3,17 @@ package com.github.alathra.alathranwars.conflict.war;
|
||||
import com.github.alathra.alathranwars.conflict.battle.raid.Raid;
|
||||
import com.github.alathra.alathranwars.conflict.battle.siege.Siege;
|
||||
import com.github.alathra.alathranwars.conflict.war.side.Side;
|
||||
import com.github.alathra.alathranwars.db.DatabaseQueries;
|
||||
import com.github.alathra.alathranwars.database.DatabaseQueries;
|
||||
import com.palmergames.bukkit.towny.object.Government;
|
||||
import com.palmergames.bukkit.towny.object.Nation;
|
||||
import com.palmergames.bukkit.towny.object.Town;
|
||||
import org.bukkit.Bukkit;
|
||||
import org.bukkit.entity.Player;
|
||||
import org.jetbrains.annotations.ApiStatus;
|
||||
import org.jetbrains.annotations.NotNull;
|
||||
import org.jetbrains.annotations.Nullable;
|
||||
|
||||
import javax.inject.Singleton;
|
||||
import java.util.HashSet;
|
||||
import java.util.List;
|
||||
import java.util.Set;
|
||||
import java.util.UUID;
|
||||
import java.util.*;
|
||||
import java.util.stream.Collectors;
|
||||
|
||||
/**
|
||||
@@ -25,7 +22,7 @@ import java.util.stream.Collectors;
|
||||
@Singleton
|
||||
public class WarController {
|
||||
private static WarController instance;
|
||||
private @NotNull Set<War> wars = new HashSet<>();
|
||||
private Set<War> wars = new HashSet<>();
|
||||
|
||||
private WarController() {
|
||||
if (instance != null)
|
||||
@@ -37,7 +34,6 @@ public class WarController {
|
||||
*
|
||||
* @return the instance
|
||||
*/
|
||||
@NotNull
|
||||
public static WarController getInstance() {
|
||||
if (instance == null)
|
||||
instance = new WarController();
|
||||
@@ -53,12 +49,31 @@ public class WarController {
|
||||
wars = DatabaseQueries.loadAll();
|
||||
}
|
||||
|
||||
/**
|
||||
* Add a war to the war controller.
|
||||
*
|
||||
* @param war the war
|
||||
*/
|
||||
@ApiStatus.Internal
|
||||
public void addWar(War war) {
|
||||
getWars().add(war);
|
||||
}
|
||||
|
||||
/**
|
||||
* Remove a war from the war controller.
|
||||
*
|
||||
* @param war the war
|
||||
*/
|
||||
@ApiStatus.Internal
|
||||
public void removeWar(War war) {
|
||||
getWars().remove(war);
|
||||
}
|
||||
|
||||
/**
|
||||
* Gets all wars.
|
||||
*
|
||||
* @return the wars
|
||||
*/
|
||||
@NotNull
|
||||
public Set<War> getWars() {
|
||||
return wars;
|
||||
}
|
||||
@@ -92,20 +107,73 @@ public class WarController {
|
||||
}
|
||||
|
||||
/**
|
||||
* Gets side by the side UUID.
|
||||
* Is nation or town in any wars. (Includes surrendered nations & towns)
|
||||
*
|
||||
* @param government the government
|
||||
* @return the boolean
|
||||
*/
|
||||
public boolean isInAnyWars(Government government) {
|
||||
return getWars().stream()
|
||||
.anyMatch(war -> war.isInWar(government));
|
||||
}
|
||||
|
||||
/**
|
||||
* Is player in any wars. Includes if surrendered.
|
||||
*
|
||||
* @param p the p
|
||||
* @return the boolean
|
||||
*/
|
||||
public boolean isInAnyWars(Player p) {
|
||||
return isInAnyWars(p.getUniqueId());
|
||||
}
|
||||
|
||||
/**
|
||||
* Is player in any wars. Includes if surrendered.
|
||||
*
|
||||
* @param uuid the uuid
|
||||
* @return the side
|
||||
* @return the boolean
|
||||
*/
|
||||
@Nullable
|
||||
public Side getSide(UUID uuid) {
|
||||
public boolean isInAnyWars(UUID uuid) {
|
||||
return getWars().stream()
|
||||
.filter(war -> war.getSide(uuid) != null)
|
||||
.map(war -> war.getSide(uuid))
|
||||
.findAny()
|
||||
.orElse(null);
|
||||
.anyMatch(war -> war.isInWar(uuid));
|
||||
}
|
||||
|
||||
/**
|
||||
* Gets nation or town wars. (Includes surrendered nations & towns)
|
||||
*
|
||||
* @param government the government
|
||||
* @return the nation wars
|
||||
*/
|
||||
public Set<War> getWars(Government government) {
|
||||
return getWars().stream()
|
||||
.filter(war -> war.isInWar(government))
|
||||
.collect(Collectors.toSet());
|
||||
}
|
||||
|
||||
/**
|
||||
* Gets list of player wars. Includes if surrendered.
|
||||
*
|
||||
* @param p the p
|
||||
* @return the player wars
|
||||
*/
|
||||
public Set<War> getWars(Player p) {
|
||||
return getWars(p.getUniqueId());
|
||||
}
|
||||
|
||||
/**
|
||||
* Gets list of player wars. Includes if surrendered.
|
||||
*
|
||||
* @param uuid the uuid
|
||||
* @return the player wars
|
||||
*/
|
||||
public Set<War> getWars(UUID uuid) {
|
||||
return getWars().stream()
|
||||
.filter(war -> war.isInWar(uuid))
|
||||
.collect(Collectors.toSet());
|
||||
}
|
||||
|
||||
// SECTION Battles
|
||||
|
||||
/**
|
||||
* Gets siege by the siege UUID.
|
||||
*
|
||||
@@ -115,195 +183,194 @@ public class WarController {
|
||||
@Nullable
|
||||
public Siege getSiege(UUID uuid) {
|
||||
return getWars().stream()
|
||||
.filter(war -> war.getSiege(uuid) != null)
|
||||
.map(war -> war.getSiege(uuid))
|
||||
.filter(Objects::nonNull)
|
||||
.findAny()
|
||||
.orElse(null);
|
||||
}
|
||||
|
||||
/**
|
||||
* Add a war to the war controller.
|
||||
*
|
||||
* @param war the war
|
||||
*/
|
||||
@ApiStatus.Internal
|
||||
public void addWar(War war) {
|
||||
getWars().add(war);
|
||||
}
|
||||
|
||||
/**
|
||||
* Remove a war from the war controller.
|
||||
*
|
||||
* @param war the war
|
||||
*/
|
||||
@ApiStatus.Internal
|
||||
public void removeWar(War war) {
|
||||
getWars().remove(war);
|
||||
}
|
||||
|
||||
/**
|
||||
* Is player in any wars. Includes if surrendered.
|
||||
* Gets raid by the raid UUID.
|
||||
*
|
||||
* @param uuid the uuid
|
||||
* @return the raid
|
||||
*/
|
||||
@Nullable
|
||||
public Raid getRaid(UUID uuid) {
|
||||
return getWars().stream()
|
||||
.map(war -> war.getRaid(uuid))
|
||||
.filter(Objects::nonNull)
|
||||
.findAny()
|
||||
.orElse(null);
|
||||
}
|
||||
|
||||
/**
|
||||
* Is nation or town in any sieges. Includes surrendered nations/towns.
|
||||
*
|
||||
* @param government the government
|
||||
* @return the boolean
|
||||
*/
|
||||
public boolean isPlayerInAnyWars(UUID uuid) {
|
||||
return getWars().stream()
|
||||
.anyMatch(war -> war.isPlayerInWar(uuid));
|
||||
public boolean isInAnySieges(Government government) {
|
||||
if (government instanceof Nation nation) {
|
||||
return nation.getTowns().stream()
|
||||
.anyMatch(this::isInAnySieges);
|
||||
} else if (government instanceof Town town) {
|
||||
return getWars().stream()
|
||||
.anyMatch(war -> war.isInWar(town) && war.isTownUnderSiege(town));
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
/**
|
||||
* Is player in any wars. Includes if surrendered.
|
||||
* Is nation or town in any raids. Includes surrendered nations/towns.
|
||||
*
|
||||
* @param p the p
|
||||
* @param government the government
|
||||
* @return the boolean
|
||||
*/
|
||||
public boolean isPlayerInAnyWars(Player p) {
|
||||
return isPlayerInAnyWars(p.getUniqueId());
|
||||
public boolean isInAnyRaids(Government government) {
|
||||
if (government instanceof Nation nation) {
|
||||
return nation.getTowns().stream()
|
||||
.anyMatch(this::isInAnyRaids);
|
||||
} else if (government instanceof Town town) {
|
||||
return getWars().stream()
|
||||
.anyMatch(war -> war.isInWar(town) && war.isTownUnderRaid(town));
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
/**
|
||||
* Gets list of player wars. Includes if surrendered.
|
||||
* Gets a list of all active sieges.
|
||||
*
|
||||
* @param p the p
|
||||
* @return the player wars
|
||||
* @return the sieges
|
||||
*/
|
||||
public @NotNull Set<War> getPlayerWars(Player p) {
|
||||
return getPlayerWars(p.getUniqueId());
|
||||
}
|
||||
|
||||
/**
|
||||
* Gets list of player wars. Includes if surrendered.
|
||||
*
|
||||
* @param uuid the uuid
|
||||
* @return the player wars
|
||||
*/
|
||||
public @NotNull Set<War> getPlayerWars(UUID uuid) {
|
||||
public Set<Siege> getSieges() {
|
||||
return getWars().stream()
|
||||
.filter(war -> war.isPlayerInWar(uuid))
|
||||
.map(War::getSieges)
|
||||
.flatMap(Set::stream)
|
||||
.collect(Collectors.toSet());
|
||||
}
|
||||
|
||||
/**
|
||||
* Is town in any wars. Includes surrendered towns.
|
||||
* Gets nation or town sieges. Includes surrendered nation/town.
|
||||
*
|
||||
* @param town the town
|
||||
* @return the boolean
|
||||
*/
|
||||
public boolean isTownInAnyWars(Town town) {
|
||||
return getWars().stream()
|
||||
.anyMatch(war -> war.isTownInWar(town));
|
||||
}
|
||||
|
||||
/**
|
||||
* Is town in any sieges. Includes surrendered towns.
|
||||
*
|
||||
* @param town the town
|
||||
* @return the boolean
|
||||
*/
|
||||
public boolean isTownInAnySieges(Town town) {
|
||||
return getWars().stream()
|
||||
.anyMatch(war -> war.isTownInWar(town) && war.isTownUnderSiege(town));
|
||||
}
|
||||
|
||||
/**
|
||||
* Is town in any raids. Includes surrendered towns.
|
||||
*
|
||||
* @param town the town
|
||||
* @return the boolean
|
||||
*/
|
||||
public boolean isTownInAnyRaids(Town town) {
|
||||
return getWars().stream()
|
||||
.anyMatch(war -> war.isTownInWar(town) && war.isTownUnderRaid(town));
|
||||
}
|
||||
|
||||
/**
|
||||
* Is nation in any sieges. Includes surrendered nations.
|
||||
*
|
||||
* @param nation the nation
|
||||
* @return the boolean
|
||||
*/
|
||||
public boolean isNationInAnySieges(Nation nation) {
|
||||
return nation.getTowns().stream()
|
||||
.anyMatch(this::isTownInAnySieges);
|
||||
}
|
||||
|
||||
/**
|
||||
* Is nation in any raids. Includes surrendered nations.
|
||||
*
|
||||
* @param nation the nation
|
||||
* @return the boolean
|
||||
*/
|
||||
public boolean isNationInAnyRaids(Nation nation) {
|
||||
return nation.getTowns().stream()
|
||||
.anyMatch(this::isTownInAnyRaids);
|
||||
}
|
||||
|
||||
/**
|
||||
* Gets town sieges. Includes surrendered towns.
|
||||
*
|
||||
* @param town the town
|
||||
* @param government the government
|
||||
* @return the town sieges
|
||||
*/
|
||||
public @NotNull Set<Siege> getTownSieges(Town town) {
|
||||
public Set<Siege> getSieges(Government government) {
|
||||
if (government instanceof Nation nation) {
|
||||
return nation.getTowns().stream()
|
||||
.flatMap(town -> getSieges(town).stream())
|
||||
.collect(Collectors.toSet());
|
||||
} else if (government instanceof Town town) {
|
||||
return getSieges().stream()
|
||||
.filter(siege -> siege.getAttackerSide().isOnSide(town) || siege.getDefenderSide().isOnSide(town))
|
||||
.collect(Collectors.toSet());
|
||||
}
|
||||
return Set.of();
|
||||
}
|
||||
|
||||
/**
|
||||
* Gets player sieges.
|
||||
*
|
||||
* @param p the p
|
||||
* @return the player sieges
|
||||
*/
|
||||
public Set<Siege> getSieges(Player p) {
|
||||
return getSieges(p.getUniqueId());
|
||||
}
|
||||
|
||||
/**
|
||||
* Gets player sieges. Returns true for offline players.
|
||||
*
|
||||
* @param uuid the uuid
|
||||
* @return the player sieges
|
||||
*/
|
||||
public Set<Siege> getSieges(UUID uuid) {
|
||||
return getSieges().stream()
|
||||
.filter(siege -> siege.getAttackerSide().isTownOnSide(town) || siege.getDefenderSide().isTownOnSide(town))
|
||||
.filter(siege -> siege.isPlayerParticipating(uuid))
|
||||
.collect(Collectors.toSet());
|
||||
}
|
||||
|
||||
/**
|
||||
* Gets town raids. Includes surrendered towns.
|
||||
* Gets a list of all active raids.
|
||||
*
|
||||
* @param town the town
|
||||
* @return the raids
|
||||
*/
|
||||
public Set<Raid> getRaids() {
|
||||
return getWars().stream()
|
||||
.map(War::getRaids)
|
||||
.flatMap(Set::stream)
|
||||
.collect(Collectors.toSet());
|
||||
}
|
||||
|
||||
/**
|
||||
* Gets nation or town raids. Includes surrendered nation/town.
|
||||
*
|
||||
* @param government the government
|
||||
* @return the town raids
|
||||
*/
|
||||
public @NotNull Set<Raid> getTownRaids(Town town) {
|
||||
return getRaids().stream()
|
||||
.filter(raid -> raid.getAttackerSide().isTownOnSide(town) || raid.getDefenderSide().isTownOnSide(town))
|
||||
.collect(Collectors.toSet());
|
||||
public Set<Raid> getRaids(Government government) {
|
||||
// TODO Raids
|
||||
/*if (government instanceof Nation nation) {
|
||||
return nation.getTowns().stream()
|
||||
.flatMap(town -> getRaids(town).stream())
|
||||
.collect(Collectors.toSet());
|
||||
} else if (government instanceof Town town) {
|
||||
return getRaids().stream()
|
||||
.filter(raid -> raid.getAttackerSide().isOnSide(town) || raid.getDefenderSide().isOnSide(town))
|
||||
.collect(Collectors.toSet());
|
||||
}*/
|
||||
return Set.of();
|
||||
}
|
||||
|
||||
/**
|
||||
* Gets town wars. Includes surrendered towns.
|
||||
* Gets player raids.
|
||||
*
|
||||
* @param town the town
|
||||
* @return the town wars
|
||||
* @param p the p
|
||||
* @return the player raids
|
||||
*/
|
||||
public @NotNull Set<War> getTownWars(Town town) {
|
||||
return getWars().stream()
|
||||
.filter(war -> war.isTownInWar(town))
|
||||
.collect(Collectors.toSet());
|
||||
public Set<Raid> getRaids(Player p) {
|
||||
return getRaids(p.getUniqueId());
|
||||
}
|
||||
|
||||
/**
|
||||
* Is nation in any wars. Includes surrendered nations.
|
||||
* Gets player raids. Returns true for offline players.
|
||||
*
|
||||
* @param nation the nation
|
||||
* @return the boolean
|
||||
* @param uuid the uuid
|
||||
* @return the player raids
|
||||
*/
|
||||
public boolean isNationInAnyWars(Nation nation) {
|
||||
return getWars().stream()
|
||||
.anyMatch(war -> war.isNationInWar(nation));
|
||||
public Set<Raid> getRaids(UUID uuid) {
|
||||
// TODO Raids
|
||||
/*return getRaids().stream()
|
||||
.filter(raid -> raid.isPlayerInRaid(uuid))
|
||||
.collect(Collectors.toSet());*/
|
||||
return Collections.emptySet();
|
||||
}
|
||||
|
||||
// SECTION Misc
|
||||
|
||||
/**
|
||||
* Gets nation wars. Includes surrendered nations.
|
||||
* Gets side by the side UUID.
|
||||
*
|
||||
* @param nation the nation
|
||||
* @return the nation wars
|
||||
* @param uuid the uuid
|
||||
* @return the side
|
||||
*/
|
||||
public @NotNull Set<War> getNationWars(Nation nation) {
|
||||
@Nullable
|
||||
public Side getSide(UUID uuid) {
|
||||
return getWars().stream()
|
||||
.filter(war -> war.isNationInWar(nation))
|
||||
.collect(Collectors.toSet());
|
||||
.map(war -> war.getSide(uuid))
|
||||
.filter(Objects::nonNull)
|
||||
.findAny()
|
||||
.orElse(null);
|
||||
}
|
||||
|
||||
// SECTION API
|
||||
|
||||
/**
|
||||
* Gets a list of war names.
|
||||
*
|
||||
* @return the war names
|
||||
*/
|
||||
@NotNull
|
||||
public List<String> getWarNames() {
|
||||
return getWars().stream()
|
||||
.map(War::getName)
|
||||
@@ -316,7 +383,6 @@ public class WarController {
|
||||
*
|
||||
* @return the war labels
|
||||
*/
|
||||
@NotNull
|
||||
public List<String> getWarLabels() {
|
||||
return getWars().stream()
|
||||
.map(War::getLabel)
|
||||
@@ -324,81 +390,12 @@ public class WarController {
|
||||
.collect(Collectors.toList());
|
||||
}
|
||||
|
||||
/**
|
||||
* Gets a list of all active sieges.
|
||||
*
|
||||
* @return the sieges
|
||||
*/
|
||||
@NotNull
|
||||
public Set<Siege> getSieges() {
|
||||
return getWars().stream()
|
||||
.map(War::getSieges)
|
||||
.flatMap(Set::stream)
|
||||
.collect(Collectors.toSet());
|
||||
}
|
||||
|
||||
/**
|
||||
* Gets a list of all active raids.
|
||||
*
|
||||
* @return the raids
|
||||
*/
|
||||
@NotNull
|
||||
public Set<Raid> getRaids() {
|
||||
return getWars().stream()
|
||||
.map(War::getRaids)
|
||||
.flatMap(Set::stream)
|
||||
.collect(Collectors.toSet());
|
||||
}
|
||||
|
||||
/**
|
||||
* Is player in any siege.
|
||||
*
|
||||
* @param p the p
|
||||
* @return the boolean
|
||||
*/
|
||||
public boolean isPlayerInAnySiege(Player p) {
|
||||
return isPlayerInAnySiege(p.getUniqueId());
|
||||
}
|
||||
|
||||
/**
|
||||
* Is player in any siege. Returns true for offline players.
|
||||
*
|
||||
* @param uuid the uuid
|
||||
* @return the boolean
|
||||
*/
|
||||
public boolean isPlayerInAnySiege(UUID uuid) {
|
||||
return getSieges().stream()
|
||||
.anyMatch(siege -> siege.isPlayerInSiege(uuid));
|
||||
}
|
||||
|
||||
/**
|
||||
* Gets player sieges.
|
||||
*
|
||||
* @param p the p
|
||||
* @return the player sieges
|
||||
*/
|
||||
public @NotNull Set<Siege> getPlayerSieges(Player p) {
|
||||
return getPlayerSieges(p.getUniqueId());
|
||||
}
|
||||
|
||||
/**
|
||||
* Gets player sieges. Returns true for offline players.
|
||||
*
|
||||
* @param uuid the uuid
|
||||
* @return the player sieges
|
||||
*/
|
||||
public @NotNull Set<Siege> getPlayerSieges(UUID uuid) {
|
||||
return getSieges().stream()
|
||||
.filter(siege -> siege.isPlayerInSiege(uuid))
|
||||
.collect(Collectors.toSet());
|
||||
}
|
||||
|
||||
/**
|
||||
* Gets nations at war. Does not include surrendered nations.
|
||||
*
|
||||
* @return the nations at war
|
||||
*/
|
||||
public @NotNull Set<Nation> getNationsAtWar() {
|
||||
public Set<Nation> getNationsAtWar() {
|
||||
return getWars().stream()
|
||||
.map(War::getNations)
|
||||
.flatMap(Set::stream)
|
||||
@@ -410,10 +407,59 @@ public class WarController {
|
||||
*
|
||||
* @return the towns at war
|
||||
*/
|
||||
public @NotNull Set<Town> getTownsAtWar() {
|
||||
public Set<Town> getTownsAtWar() {
|
||||
return getWars().stream()
|
||||
.map(War::getTowns)
|
||||
.flatMap(Set::stream)
|
||||
.collect(Collectors.toSet());
|
||||
}
|
||||
|
||||
/**
|
||||
* Check if two sides are opposing each-other in a war
|
||||
* @param side1 a side
|
||||
* @param side2 a side
|
||||
* @return true if opposing each-other in a war
|
||||
*/
|
||||
public boolean isAtWar(Side side1, Side side2) {
|
||||
// Return early if comparing same side to prevent false positive
|
||||
if (side1.equals(side2))
|
||||
return false;
|
||||
|
||||
return side1.getWar().equals(side2.getWar());
|
||||
}
|
||||
|
||||
/**
|
||||
* Check if two governments are at war with each-other
|
||||
* @param government1 nation or town
|
||||
* @param government2 nation or town
|
||||
* @return true if governments are on opposing sides in any war
|
||||
*/
|
||||
public boolean isAtWar(Government government1, Government government2) {
|
||||
Set<War> wars1 = getWars(government1);
|
||||
Set<War> wars2 = getWars(government2);
|
||||
|
||||
/*final boolean isInSameWar = wars1.stream().anyMatch(wars2::contains);
|
||||
if (!isInSameWar)
|
||||
return false;*/
|
||||
|
||||
// Get list of common wars
|
||||
Set<War> sharedWars = wars1.stream()
|
||||
.filter(wars2::contains)
|
||||
.collect(Collectors.toSet());
|
||||
|
||||
// Iterate shared wars and check if on opposite sides
|
||||
for (War war : sharedWars) {
|
||||
Side side1 = war.getSide(government1);
|
||||
Side side2 = war.getSide(government2);
|
||||
|
||||
if (side1 == null || side2 == null)
|
||||
continue;
|
||||
|
||||
if (!isAtWar(side1, side2)) {
|
||||
return true;
|
||||
}
|
||||
}
|
||||
|
||||
return false;
|
||||
}
|
||||
}
|
||||
+546
@@ -0,0 +1,546 @@
|
||||
package com.github.alathra.alathranwars.conflict.war.side;
|
||||
|
||||
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;
|
||||
import org.bukkit.Bukkit;
|
||||
import org.bukkit.OfflinePlayer;
|
||||
import org.bukkit.entity.Player;
|
||||
|
||||
import java.util.HashSet;
|
||||
import java.util.List;
|
||||
import java.util.Set;
|
||||
import java.util.UUID;
|
||||
import java.util.stream.Stream;
|
||||
|
||||
/**
|
||||
* Provides methods for handling all members of a side
|
||||
*/
|
||||
public abstract class AbstractSideTeamManager {
|
||||
private final Set<Nation> nations = new HashSet<>(); // Collection of nations in the war (excludes surrendered)
|
||||
private final Set<Town> towns = new HashSet<>(); // Collection of towns in the war (excludes surrendered)
|
||||
private final Set<OfflinePlayer> players = new HashSet<>(); // Collection of players in the war (excludes surrendered)
|
||||
|
||||
private final Set<Nation> nationsSurrendered = new HashSet<>(); // Collection surrendered of nations in the war (excludes non-surrendered)
|
||||
private final Set<Town> townsSurrendered = new HashSet<>(); // Collection of surrendered towns in the war (excludes non-surrendered)
|
||||
private final Set<OfflinePlayer> playersSurrendered = new HashSet<>(); // Collection of surrendered players in the war (excludes non-surrendered)
|
||||
|
||||
public AbstractSideTeamManager() {}
|
||||
|
||||
public AbstractSideTeamManager(
|
||||
Set<Nation> nations,
|
||||
Set<Town> towns,
|
||||
Set<OfflinePlayer> players,
|
||||
Set<Nation> nationsSurrendered,
|
||||
Set<Town> townsSurrendered,
|
||||
Set<OfflinePlayer> playersSurrendered
|
||||
) {
|
||||
this.nations.addAll(nations);
|
||||
this.towns.addAll(towns);
|
||||
this.players.addAll(players);
|
||||
this.nationsSurrendered.addAll(nationsSurrendered);
|
||||
this.townsSurrendered.addAll(townsSurrendered);
|
||||
this.playersSurrendered.addAll(playersSurrendered);
|
||||
}
|
||||
|
||||
// SECTION Governments management
|
||||
|
||||
/**
|
||||
* Add a government to the side (Recursively adds subjects AKA towns, players)
|
||||
* @param government a government
|
||||
*/
|
||||
public void add(Government government) {
|
||||
if (government instanceof Nation nation) {
|
||||
nations.add(nation);
|
||||
nation.getTowns().forEach(this::add);
|
||||
} else if (government instanceof Town town) {
|
||||
towns.add(town);
|
||||
town.getResidents().stream()
|
||||
.map(Resident::getUUID)
|
||||
.map(Bukkit::getOfflinePlayer)
|
||||
.forEach(this::add);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Remove a government from the side (Recursively removes subjects AKA towns, players)
|
||||
* @param government a government
|
||||
*/
|
||||
public void remove(Government government) {
|
||||
if (government instanceof Nation nation) {
|
||||
nations.remove(nation);
|
||||
nation.getTowns().forEach(this::remove);
|
||||
} else if (government instanceof Town town) {
|
||||
towns.remove(town);
|
||||
town.getResidents().stream()
|
||||
.map(Resident::getUUID)
|
||||
.map(Bukkit::getOfflinePlayer)
|
||||
.forEach(this::remove);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Add a surrendered government to the side (Recursively adds subjects AKA towns, players)
|
||||
* @param government a government
|
||||
*/
|
||||
public void addSurrendered(Government government) {
|
||||
if (government instanceof Nation nation) {
|
||||
nationsSurrendered.add(nation);
|
||||
nation.getTowns().forEach(this::addSurrendered);
|
||||
} else if (government instanceof Town town) {
|
||||
townsSurrendered.add(town);
|
||||
town.getResidents().stream()
|
||||
.map(Resident::getUUID)
|
||||
.map(Bukkit::getOfflinePlayer)
|
||||
.forEach(this::addSurrendered);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Remove a surrendered government from the side (Recursively removes subjects AKA towns, players)
|
||||
* @param government a government
|
||||
*/
|
||||
public void removeSurrendered(Government government) {
|
||||
if (government instanceof Nation nation) {
|
||||
nationsSurrendered.remove(nation);
|
||||
nation.getTowns().forEach(this::removeSurrendered);
|
||||
} else if (government instanceof Town town) {
|
||||
townsSurrendered.remove(town);
|
||||
town.getResidents().stream()
|
||||
.map(Resident::getUUID)
|
||||
.map(Bukkit::getOfflinePlayer)
|
||||
.forEach(this::removeSurrendered);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Kick a government from the side (Recursively kicks subjects AKA towns, players)
|
||||
* @param government a government
|
||||
*/
|
||||
public void kick(Government government) {
|
||||
remove(government);
|
||||
removeSurrendered(government);
|
||||
}
|
||||
|
||||
// SECTION Players management
|
||||
|
||||
/**
|
||||
* Add a player to the side
|
||||
* @param p a player
|
||||
*/
|
||||
public void add(Player p) {
|
||||
add(p.getUniqueId());
|
||||
}
|
||||
|
||||
/**
|
||||
* Add a player to the side
|
||||
* @param uuid a player uuid
|
||||
*/
|
||||
public void add(UUID uuid) {
|
||||
add(Bukkit.getOfflinePlayer(uuid));
|
||||
}
|
||||
|
||||
/**
|
||||
* Add a player to the side
|
||||
* @param p a player
|
||||
*/
|
||||
public void add(OfflinePlayer p) {
|
||||
players.add(p);
|
||||
}
|
||||
|
||||
/**
|
||||
* Remove a player from the side
|
||||
* @param p a player
|
||||
*/
|
||||
public void remove(Player p) {
|
||||
remove(p.getUniqueId());
|
||||
}
|
||||
|
||||
/**
|
||||
* Remove a player from the side
|
||||
* @param uuid a player uuid
|
||||
*/
|
||||
public void remove(UUID uuid) {
|
||||
remove(Bukkit.getOfflinePlayer(uuid));
|
||||
}
|
||||
|
||||
/**
|
||||
* Remove a player from the side
|
||||
* @param p a player
|
||||
*/
|
||||
public void remove(OfflinePlayer p) {
|
||||
players.remove(p);
|
||||
}
|
||||
|
||||
/**
|
||||
* Add a surrendered player to the side
|
||||
* @param p a player
|
||||
*/
|
||||
public void addSurrendered(Player p) {
|
||||
add(p.getUniqueId());
|
||||
}
|
||||
|
||||
/**
|
||||
* Add a surrendered player to the side
|
||||
* @param uuid a player uuid
|
||||
*/
|
||||
public void addSurrendered(UUID uuid) {
|
||||
add(Bukkit.getOfflinePlayer(uuid));
|
||||
}
|
||||
|
||||
/**
|
||||
* Add a surrendered player to the side
|
||||
* @param p a player
|
||||
*/
|
||||
public void addSurrendered(OfflinePlayer p) {
|
||||
playersSurrendered.add(p);
|
||||
}
|
||||
|
||||
/**
|
||||
* Remove a surrendered player from the side
|
||||
* @param p a player
|
||||
*/
|
||||
public void removeSurrendered(Player p) {
|
||||
remove(p.getUniqueId());
|
||||
}
|
||||
|
||||
/**
|
||||
* Remove a surrendered player from the side
|
||||
* @param uuid a player uuid
|
||||
*/
|
||||
public void removeSurrendered(UUID uuid) {
|
||||
remove(Bukkit.getOfflinePlayer(uuid));
|
||||
}
|
||||
|
||||
/**
|
||||
* Remove a surrendered player from the side
|
||||
* @param p a player
|
||||
*/
|
||||
public void removeSurrendered(OfflinePlayer p) {
|
||||
playersSurrendered.remove(p);
|
||||
}
|
||||
|
||||
/**
|
||||
* Kick a player from the side
|
||||
* @param p a player
|
||||
*/
|
||||
public void kick(Player p) {
|
||||
remove(p);
|
||||
removeSurrendered(p);
|
||||
}
|
||||
|
||||
/**
|
||||
* Kick a player from the side
|
||||
* @param uuid a player uuid
|
||||
*/
|
||||
public void kick(UUID uuid) {
|
||||
remove(uuid);
|
||||
removeSurrendered(uuid);
|
||||
}
|
||||
|
||||
/**
|
||||
* Kick a player from the side
|
||||
* @param p a player
|
||||
*/
|
||||
public void kick(OfflinePlayer p) {
|
||||
remove(p);
|
||||
removeSurrendered(p);
|
||||
}
|
||||
|
||||
// SECTION Governments Getters
|
||||
|
||||
/**
|
||||
* Get nations on this side (excludes surrendered nations)
|
||||
* @return the nations
|
||||
*/
|
||||
public Set<Nation> getNations() {
|
||||
return nations;
|
||||
}
|
||||
|
||||
/**
|
||||
* Get nations on this side (excludes non-surrendered nations)
|
||||
* @return the nations
|
||||
*/
|
||||
public Set<Nation> getNationsSurrendered() {
|
||||
return nationsSurrendered;
|
||||
}
|
||||
|
||||
/**
|
||||
* Get all nations on this side (includes surrendered nations)
|
||||
* @return the nations
|
||||
*/
|
||||
public List<Nation> getNationsAll() {
|
||||
return Stream.concat(getNations().stream(), getNationsSurrendered().stream()).toList();
|
||||
}
|
||||
|
||||
/**
|
||||
* Get towns on this side (excludes surrendered towns)
|
||||
* @return the towns
|
||||
*/
|
||||
public Set<Town> getTowns() {
|
||||
return towns;
|
||||
}
|
||||
|
||||
/**
|
||||
* Get towns on this side (excludes non-surrendered towns)
|
||||
* @return the towns
|
||||
*/
|
||||
public Set<Town> getTownsSurrendered() {
|
||||
return townsSurrendered;
|
||||
}
|
||||
|
||||
/**
|
||||
* Get all towns on this side (includes surrendered towns)
|
||||
* @return the towns
|
||||
*/
|
||||
public List<Town> getTownsAll() {
|
||||
return Stream.concat(getTowns().stream(), getTownsSurrendered().stream()).toList();
|
||||
}
|
||||
|
||||
// SECTION Players Getters
|
||||
|
||||
/**
|
||||
* Get all players on this side (excluding surrendered)
|
||||
* @return player list
|
||||
*/
|
||||
public List<OfflinePlayer> getPlayers() {
|
||||
return players.stream().toList();
|
||||
}
|
||||
|
||||
/**
|
||||
* Get all players on this side (excludes non-surrendered players)
|
||||
* @return player list
|
||||
*/
|
||||
public List<OfflinePlayer> getPlayersSurrendered() {
|
||||
return playersSurrendered.stream().toList();
|
||||
}
|
||||
|
||||
/**
|
||||
* Get all players on this side (includes surrendered players)
|
||||
* @return player list
|
||||
*/
|
||||
public List<OfflinePlayer> getPlayersAll() {
|
||||
return Stream.concat(getPlayers().stream(), getPlayersSurrendered().stream()).toList();
|
||||
}
|
||||
|
||||
/**
|
||||
* Get all online players on this side (excluding surrendered)
|
||||
* @return player list
|
||||
*/
|
||||
public List<Player> getPlayersOnline() {
|
||||
return players.stream()
|
||||
.filter(OfflinePlayer::isOnline)
|
||||
.map(OfflinePlayer::getPlayer)
|
||||
.toList();
|
||||
}
|
||||
|
||||
/**
|
||||
* Get all online players on this side (excludes non-surrendered players)
|
||||
* @return player list
|
||||
*/
|
||||
public List<Player> getPlayersSurrenderedOnline() {
|
||||
return playersSurrendered.stream()
|
||||
.filter(OfflinePlayer::isOnline)
|
||||
.map(OfflinePlayer::getPlayer)
|
||||
.toList();
|
||||
}
|
||||
|
||||
/**
|
||||
* Get all online players on this side (includes surrendered players)
|
||||
* @return player list
|
||||
*/
|
||||
public List<Player> getPlayersOnlineAll() {
|
||||
return Stream.concat(getPlayersOnline().stream(), getPlayersSurrenderedOnline().stream()).toList();
|
||||
}
|
||||
|
||||
// Checks
|
||||
|
||||
/**
|
||||
* Check if a government is on this side (includes surrendered governments)
|
||||
* @param government the government
|
||||
* @return true if on side
|
||||
*/
|
||||
public boolean isOnSide(Government government) {
|
||||
if (government instanceof Nation nation) {
|
||||
return nations.contains(nation) || nationsSurrendered.contains(nation);
|
||||
} else if (government instanceof Town town) {
|
||||
return towns.contains(town) || townsSurrendered.contains(town);
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
/**
|
||||
* Check if a player is on this side (includes surrendered players)
|
||||
* @param p the player
|
||||
* @return true if on side
|
||||
*/
|
||||
public boolean isOnSide(Player p) {
|
||||
return isOnSide(p.getUniqueId());
|
||||
}
|
||||
|
||||
/**
|
||||
* Check if a player is on this side (includes surrendered players)
|
||||
* @param uuid the player uuid
|
||||
* @return true if on side
|
||||
*/
|
||||
public boolean isOnSide(UUID uuid) {
|
||||
return isOnSide(Bukkit.getOfflinePlayer(uuid));
|
||||
}
|
||||
|
||||
/**
|
||||
* Check if a player is on this side (includes surrendered players)
|
||||
* @param p the player
|
||||
* @return true if on side
|
||||
*/
|
||||
public boolean isOnSide(OfflinePlayer p) {
|
||||
return players.contains(p) || playersSurrendered.contains(p);
|
||||
}
|
||||
|
||||
/**
|
||||
* Check if a government is surrendered on this side
|
||||
* @param government the government
|
||||
* @return true if on side and surrendered
|
||||
*/
|
||||
public boolean isSurrendered(Government government) {
|
||||
if (government instanceof Nation nation) {
|
||||
return nationsSurrendered.contains(nation);
|
||||
} else if (government instanceof Town town) {
|
||||
return townsSurrendered.contains(town);
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
/**
|
||||
* Check if a player is surrendered on this side
|
||||
* @param p the player
|
||||
* @return true if on side and surrendered
|
||||
*/
|
||||
public boolean isSurrendered(Player p) {
|
||||
return isSurrendered(p.getUniqueId());
|
||||
}
|
||||
|
||||
/**
|
||||
* Check if a player is surrendered on this side
|
||||
* @param uuid the player uuid
|
||||
* @return true if on side and surrendered
|
||||
*/
|
||||
public boolean isSurrendered(UUID uuid) {
|
||||
return isSurrendered(Bukkit.getOfflinePlayer(uuid));
|
||||
}
|
||||
|
||||
/**
|
||||
* Check if a player is surrendered on this side
|
||||
* @param p the player
|
||||
* @return true if on side and surrendered
|
||||
*/
|
||||
public boolean isSurrendered(OfflinePlayer p) {
|
||||
return playersSurrendered.contains(p);
|
||||
}
|
||||
|
||||
// SECTION Surrendering
|
||||
|
||||
/**
|
||||
* Makes a government surrender (Recursively surrenders subjects AKA nations, towns, players)
|
||||
* @param government the government
|
||||
*/
|
||||
public void surrender(Government government) {
|
||||
if (isSurrendered(government))
|
||||
return;
|
||||
|
||||
if (government instanceof Nation nation) {
|
||||
remove(nation);
|
||||
addSurrendered(nation);
|
||||
} else if (government instanceof Town town) {
|
||||
remove(town);
|
||||
addSurrendered(town);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Makes a player surrender
|
||||
* @param p the player
|
||||
*/
|
||||
public void surrender(Player p) { surrender(p.getUniqueId()); }
|
||||
|
||||
/**
|
||||
* Makes a player surrender
|
||||
* @param uuid the player uuid
|
||||
*/
|
||||
public void surrender(UUID uuid) { surrender(Bukkit.getOfflinePlayer(uuid)); }
|
||||
|
||||
/**
|
||||
* Makes a player surrender
|
||||
* @param p the player
|
||||
*/
|
||||
public void surrender(OfflinePlayer p) {
|
||||
if (!isSurrendered(p))
|
||||
return;
|
||||
|
||||
remove(p);
|
||||
addSurrendered(p);
|
||||
}
|
||||
|
||||
/**
|
||||
* Makes a government un-surrender (Recursively un-surrenders subjects AKA nations, towns, players)
|
||||
* @param government the government
|
||||
*/
|
||||
public void unsurrender(Government government) {
|
||||
if (!isSurrendered(government))
|
||||
return;
|
||||
|
||||
if (government instanceof Nation nation) {
|
||||
removeSurrendered(nation);
|
||||
add(nation);
|
||||
} else if (government instanceof Town town) {
|
||||
removeSurrendered(town);
|
||||
add(town);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Makes a player un-surrender
|
||||
* @param p the player
|
||||
*/
|
||||
public void unsurrender(Player p) { unsurrender(p.getUniqueId()); }
|
||||
|
||||
/**
|
||||
* Makes a player un-surrender
|
||||
* @param uuid the player uuid
|
||||
*/
|
||||
public void unsurrender(UUID uuid) { unsurrender(Bukkit.getOfflinePlayer(uuid)); }
|
||||
|
||||
/**
|
||||
* Makes a player un-surrender
|
||||
* @param p the player
|
||||
*/
|
||||
public void unsurrender(OfflinePlayer p) {
|
||||
if (isSurrendered(p))
|
||||
return;
|
||||
|
||||
removeSurrendered(p);
|
||||
add(p);
|
||||
}
|
||||
|
||||
// SECTION Misc methods
|
||||
|
||||
/**
|
||||
* Check if this side is no longer able to continue fighting a war
|
||||
* @return true if there are no more nations or towns to participate in the war
|
||||
*/
|
||||
public boolean shouldSurrender() {
|
||||
return getNations().isEmpty() && getTowns().isEmpty();
|
||||
}
|
||||
|
||||
/**
|
||||
* Check if this nation is no longer able to continue fighting a war
|
||||
* @param nation the nation
|
||||
* @return true if there are no more un-surrendered towns from the nation to participate in the war
|
||||
*/
|
||||
public boolean shouldSurrender(Nation nation) {
|
||||
final int townsQty = nation.getNumTowns();
|
||||
final int surrenderedTownsQty = nation.getTowns().stream().filter(this::isSurrendered).mapToInt(value -> 1).sum();
|
||||
return surrenderedTownsQty == townsQty;
|
||||
|
||||
}
|
||||
}
|
||||
@@ -1,29 +1,24 @@
|
||||
package com.github.alathra.alathranwars.conflict.war.side;
|
||||
|
||||
import com.github.alathra.alathranwars.conflict.battle.siege.Siege;
|
||||
import com.github.alathra.alathranwars.conflict.IAssociatedWar;
|
||||
import com.github.alathra.alathranwars.conflict.IUnique;
|
||||
import com.github.alathra.alathranwars.conflict.war.War;
|
||||
import com.github.alathra.alathranwars.conflict.war.WarController;
|
||||
import com.github.alathra.alathranwars.enums.battle.BattleSide;
|
||||
import com.github.alathra.alathranwars.enums.battle.BattleTeam;
|
||||
import com.github.alathra.alathranwars.hooks.NameColorHandler;
|
||||
import com.github.alathra.alathranwars.hook.NameColorHandler;
|
||||
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;
|
||||
import org.bukkit.Bukkit;
|
||||
import org.bukkit.OfflinePlayer;
|
||||
import org.bukkit.entity.Player;
|
||||
import org.jetbrains.annotations.NotNull;
|
||||
import org.jetbrains.annotations.Nullable;
|
||||
import org.jetbrains.annotations.ApiStatus;
|
||||
|
||||
import java.time.Duration;
|
||||
import java.time.Instant;
|
||||
import java.util.HashSet;
|
||||
import java.util.Set;
|
||||
import java.util.UUID;
|
||||
import java.util.stream.Collectors;
|
||||
|
||||
public class Side {
|
||||
public class Side extends AbstractSideTeamManager implements IUnique<Side>, IAssociatedWar {
|
||||
private static final Duration SIEGE_COOLDOWN = Duration.ofMinutes(30);
|
||||
private static final Duration RAID_COOLDOWN = Duration.ofMinutes(30);
|
||||
private final UUID warUUID;
|
||||
@@ -33,50 +28,38 @@ public class Side {
|
||||
private final String name; // A town name
|
||||
|
||||
private final Town town; // The initiating town or capital of the nation
|
||||
private final Set<Town> towns; // A list of participating Towns
|
||||
private final Set<Nation> nations; // A list of participating Nations
|
||||
private final Set<UUID> playersIncludingOffline; // A list of all participating player UUID, (Online & Offline)
|
||||
private final @NotNull Set<Player> players; // A list of the players who are currently online
|
||||
private final Set<Town> surrenderedTowns;
|
||||
private final Set<Nation> surrenderedNations;
|
||||
private final Set<UUID> surrenderedPlayersIncludingOffline;
|
||||
private Instant siegeGrace = Instant.now().minus(SIEGE_COOLDOWN); // The time after which this side can be besieged
|
||||
private Instant raidGrace = Instant.now().minus(RAID_COOLDOWN); // The time after which this side can be raided
|
||||
|
||||
private int score = 0;
|
||||
|
||||
// Create object from DB
|
||||
public Side(
|
||||
/**
|
||||
* Instantiates a existing Side.
|
||||
* @throws SideCreationException exception
|
||||
*/
|
||||
@ApiStatus.Internal
|
||||
Side(
|
||||
UUID warUUID,
|
||||
UUID uuid,
|
||||
Government government,
|
||||
BattleSide side,
|
||||
BattleTeam team,
|
||||
String name,
|
||||
Set<Town> towns,
|
||||
Set<Nation> nations,
|
||||
Set<UUID> playersIncludingOffline,
|
||||
Set<Town> surrenderedTowns,
|
||||
Set<Nation> surrenderedNations,
|
||||
Set<UUID> surrenderedPlayersIncludingOffline,
|
||||
Set<Town> towns,
|
||||
Set<OfflinePlayer> players,
|
||||
Set<Nation> nationsSurrendered,
|
||||
Set<Town> townsSurrendered,
|
||||
Set<OfflinePlayer> playersSurrendered,
|
||||
Instant siegeGrace,
|
||||
Instant raidGrace
|
||||
) throws SideCreationException {
|
||||
super(nations, towns, players, nationsSurrendered, townsSurrendered, playersSurrendered);
|
||||
this.warUUID = warUUID;
|
||||
this.uuid = uuid;
|
||||
this.side = side;
|
||||
this.team = team;
|
||||
this.name = name;
|
||||
|
||||
this.towns = towns;
|
||||
this.nations = nations;
|
||||
this.playersIncludingOffline = playersIncludingOffline;
|
||||
this.players = new HashSet<>();
|
||||
|
||||
this.surrenderedTowns = surrenderedTowns;
|
||||
this.surrenderedNations = surrenderedNations;
|
||||
this.surrenderedPlayersIncludingOffline = surrenderedPlayersIncludingOffline;
|
||||
|
||||
this.siegeGrace = siegeGrace;
|
||||
this.raidGrace = raidGrace;
|
||||
|
||||
@@ -87,38 +70,37 @@ public class Side {
|
||||
} else {
|
||||
throw new SideCreationException("No town or nation specified!");
|
||||
}
|
||||
|
||||
calculateOnlinePlayers();
|
||||
}
|
||||
|
||||
public Side(UUID warUUID, UUID uuid, Government government, BattleSide side, BattleTeam team) throws SideCreationException {
|
||||
/**
|
||||
* Instantiates a new Side.
|
||||
* @throws SideCreationException exception
|
||||
*/
|
||||
@ApiStatus.Internal
|
||||
Side(
|
||||
UUID warUUID,
|
||||
UUID uuid,
|
||||
Government government,
|
||||
BattleSide side,
|
||||
BattleTeam team
|
||||
) throws SideCreationException {
|
||||
super();
|
||||
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);
|
||||
add(nation);
|
||||
} else if (government instanceof Town town2) {
|
||||
this.town = town2;
|
||||
addTown(town2);
|
||||
add(town2);
|
||||
} else {
|
||||
throw new SideCreationException("No town or nation specified!");
|
||||
}
|
||||
|
||||
this.name = this.town.getName();
|
||||
|
||||
calculateOnlinePlayers();
|
||||
}
|
||||
|
||||
public BattleSide getSide() {
|
||||
@@ -133,268 +115,12 @@ public class Side {
|
||||
return name;
|
||||
}
|
||||
|
||||
public Set<Nation> getNations() {
|
||||
return nations;
|
||||
}
|
||||
|
||||
public Set<Town> getTowns() {
|
||||
return towns;
|
||||
}
|
||||
|
||||
public Set<UUID> getPlayersIncludingOffline() {
|
||||
return playersIncludingOffline;
|
||||
}
|
||||
|
||||
public @NotNull Set<Player> getPlayers() {
|
||||
return players;
|
||||
}
|
||||
|
||||
public Set<Town> getSurrenderedTowns() {
|
||||
return surrenderedTowns;
|
||||
}
|
||||
|
||||
public Set<Nation> getSurrenderedNations() {
|
||||
return surrenderedNations;
|
||||
}
|
||||
|
||||
public Set<UUID> getSurrenderedPlayersIncludingOffline() {
|
||||
return surrenderedPlayersIncludingOffline;
|
||||
}
|
||||
|
||||
// Participant management
|
||||
|
||||
public boolean isTownOnSide(Town town) {
|
||||
return towns.contains(town) || surrenderedTowns.contains(town);
|
||||
}
|
||||
|
||||
public boolean isNationOnSide(Nation nation) {
|
||||
return nations.contains(nation) || surrenderedNations.contains(nation);
|
||||
}
|
||||
|
||||
public boolean isTownSurrendered(Town town) {
|
||||
return surrenderedTowns.contains(town);
|
||||
}
|
||||
|
||||
public boolean isNationSurrendered(Nation nation) {
|
||||
return surrenderedNations.contains(nation);
|
||||
}
|
||||
|
||||
public void addTown(Town town) {
|
||||
if (isTownOnSide(town)) return;
|
||||
|
||||
towns.add(town);
|
||||
|
||||
town.getResidents().forEach((Resident resident) -> addPlayer(resident.getUUID()));
|
||||
}
|
||||
|
||||
public void addNation(Nation nation) {
|
||||
if (isNationOnSide(nation)) return;
|
||||
|
||||
nations.add(nation);
|
||||
|
||||
nation.getTowns().forEach(this::addTown);
|
||||
}
|
||||
|
||||
public void removeTown(Town town) {
|
||||
if (!isTownOnSide(town)) return;
|
||||
|
||||
towns.remove(town);
|
||||
|
||||
town.getResidents().forEach((Resident resident) -> removePlayer(resident.getUUID()));
|
||||
}
|
||||
|
||||
public void removeNation(Nation nation) {
|
||||
if (!isNationOnSide(nation)) return;
|
||||
|
||||
nations.remove(nation);
|
||||
|
||||
nation.getTowns().forEach(this::removeTown);
|
||||
}
|
||||
|
||||
public void surrenderTown(Town town) {
|
||||
if (isTownSurrendered(town)) return;
|
||||
|
||||
removeTown(town);
|
||||
|
||||
surrenderedTowns.add(town);
|
||||
|
||||
town.getResidents().forEach((Resident resident) -> surrenderPlayer(resident.getUUID()));
|
||||
}
|
||||
|
||||
public void surrenderNation(Nation nation) {
|
||||
if (isNationSurrendered(nation)) return;
|
||||
|
||||
removeNation(nation);
|
||||
|
||||
surrenderedNations.add(nation);
|
||||
|
||||
nation.getTowns().forEach(this::surrenderTown);
|
||||
}
|
||||
|
||||
public void unsurrenderTown(Town town) {
|
||||
if (!isTownSurrendered(town)) return;
|
||||
|
||||
addTown(town);
|
||||
|
||||
surrenderedTowns.remove(town);
|
||||
|
||||
town.getResidents().forEach((Resident resident) -> unsurrenderPlayer(resident.getUUID()));
|
||||
}
|
||||
|
||||
public void unsurrenderNation(Nation nation) {
|
||||
if (!isNationSurrendered(nation)) return;
|
||||
|
||||
addNation(nation);
|
||||
|
||||
surrenderedNations.remove(nation);
|
||||
|
||||
nation.getTowns().forEach(this::unsurrenderTown);
|
||||
}
|
||||
|
||||
public void kickTown(Town town) {
|
||||
towns.remove(town);
|
||||
surrenderedTowns.remove(town);
|
||||
|
||||
town.getResidents().forEach(resident -> kickPlayer(resident.getUUID()));
|
||||
}
|
||||
|
||||
public void kickNation(Nation nation) {
|
||||
nations.remove(nation);
|
||||
surrenderedNations.remove(nation);
|
||||
|
||||
nation.getTowns().forEach(this::kickTown);
|
||||
}
|
||||
|
||||
public boolean isPlayerOnSide(Player p) {
|
||||
return isPlayerOnSide(p.getUniqueId());
|
||||
}
|
||||
|
||||
public boolean isPlayerOnSide(UUID uuid) {
|
||||
return playersIncludingOffline.contains(uuid) || surrenderedPlayersIncludingOffline.contains(uuid);
|
||||
}
|
||||
|
||||
public boolean isPlayerSurrendered(Player p) {
|
||||
return isPlayerSurrendered(p.getUniqueId());
|
||||
}
|
||||
|
||||
public boolean isPlayerSurrendered(UUID uuid) {
|
||||
return surrenderedPlayersIncludingOffline.contains(uuid);
|
||||
}
|
||||
|
||||
public void addPlayer(Player p) {
|
||||
addPlayer(p.getUniqueId());
|
||||
}
|
||||
|
||||
public void addPlayer(OfflinePlayer offlinePlayer) {
|
||||
if (offlinePlayer.hasPlayedBefore())
|
||||
addPlayer(offlinePlayer.getUniqueId());
|
||||
}
|
||||
|
||||
public void addPlayer(UUID uuid) {
|
||||
if (isPlayerOnSide(uuid)) return;
|
||||
|
||||
playersIncludingOffline.add(uuid);
|
||||
if (getWar() != null) { // We need to check this as on side creation War doesn't exist
|
||||
for (Siege siege : getWar().getSieges()) {
|
||||
if (siege.getAttackerSide().equals(this)) {
|
||||
siege.addPlayer(uuid, BattleSide.ATTACKER);
|
||||
} else {
|
||||
siege.addPlayer(uuid, BattleSide.DEFENDER);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
if (Bukkit.getOfflinePlayer(uuid).isOnline()) {
|
||||
final @Nullable Player p = Bukkit.getPlayer(uuid);
|
||||
addOnlinePlayer(p);
|
||||
}
|
||||
}
|
||||
|
||||
public void addOnlinePlayer(Player p) {
|
||||
players.add(p);
|
||||
}
|
||||
|
||||
public void removePlayer(Player p) {
|
||||
removePlayer(p.getUniqueId());
|
||||
}
|
||||
|
||||
public void removePlayer(OfflinePlayer offlinePlayer) {
|
||||
if (offlinePlayer.hasPlayedBefore())
|
||||
removePlayer(offlinePlayer.getUniqueId());
|
||||
}
|
||||
|
||||
public void removePlayer(UUID uuid) {
|
||||
if (!isPlayerOnSide(uuid)) return;
|
||||
|
||||
playersIncludingOffline.remove(uuid);
|
||||
if (getWar() != null) { // We need to check this as on side creation War doesn't exist
|
||||
for (Siege siege : getWar().getSieges()) {
|
||||
if (siege.getAttackerSide().equals(this)) {
|
||||
siege.removePlayer(uuid);
|
||||
} else {
|
||||
siege.removePlayer(uuid);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
if (Bukkit.getOfflinePlayer(uuid).isOnline()) {
|
||||
final @Nullable Player p = Bukkit.getPlayer(uuid);
|
||||
removeOnlinePlayer(p);
|
||||
}
|
||||
}
|
||||
|
||||
public void kickPlayer(UUID uuid) {
|
||||
removePlayer(uuid);
|
||||
surrenderedPlayersIncludingOffline.remove(uuid);
|
||||
}
|
||||
|
||||
public void removeOnlinePlayer(Player p) {
|
||||
players.remove(p);
|
||||
}
|
||||
|
||||
public void surrenderPlayer(Player p) {
|
||||
surrenderPlayer(p.getUniqueId());
|
||||
}
|
||||
|
||||
public void surrenderPlayer(UUID uuid) {
|
||||
if (isPlayerSurrendered(uuid)) return;
|
||||
|
||||
removePlayer(uuid);
|
||||
surrenderedPlayersIncludingOffline.add(uuid);
|
||||
applyNameTags();
|
||||
}
|
||||
|
||||
public void unsurrenderPlayer(Player p) {
|
||||
unsurrenderPlayer(p.getUniqueId());
|
||||
}
|
||||
|
||||
public void unsurrenderPlayer(UUID uuid) {
|
||||
if (!isPlayerSurrendered(uuid)) return;
|
||||
|
||||
addPlayer(uuid);
|
||||
surrenderedPlayersIncludingOffline.remove(uuid);
|
||||
applyNameTags();
|
||||
}
|
||||
|
||||
public void calculateOnlinePlayers() {
|
||||
final Set<Player> onlinePlayers = getPlayersIncludingOffline().stream()
|
||||
.filter(uuid -> Bukkit.getOfflinePlayer(uuid).isOnline())
|
||||
.map(Bukkit::getPlayer)
|
||||
.collect(Collectors.toSet());
|
||||
|
||||
this.players.clear();
|
||||
this.players.addAll(onlinePlayers);
|
||||
|
||||
applyNameTags();
|
||||
}
|
||||
|
||||
public void applyNameTags() {
|
||||
players.forEach(p -> NameColorHandler.getInstance().getPlayerNameColor(p));
|
||||
surrenderedPlayersIncludingOffline.stream()
|
||||
.filter((UUID uuid) -> Bukkit.getPlayer(uuid) != null)
|
||||
.map(Bukkit::getPlayer)
|
||||
.toList()
|
||||
.forEach(p -> NameColorHandler.getInstance().calculatePlayerColors(p));
|
||||
getPlayersOnlineAll().forEach(
|
||||
player -> NameColorHandler.getInstance().calculatePlayerColors(player)
|
||||
);
|
||||
}
|
||||
|
||||
// Graces
|
||||
@@ -447,12 +173,14 @@ public class Side {
|
||||
|
||||
// Comparators & UUID
|
||||
|
||||
public boolean equals(UUID uuid) {
|
||||
return this.uuid.equals(uuid);
|
||||
@Override
|
||||
public UUID getUUID() {
|
||||
return uuid;
|
||||
}
|
||||
|
||||
public boolean equals(War war) {
|
||||
return this.warUUID.equals(war.getUUID());
|
||||
@Override
|
||||
public boolean equals(UUID uuid) {
|
||||
return getUUID().equals(uuid);
|
||||
}
|
||||
|
||||
public boolean equals(Side side) {
|
||||
@@ -463,13 +191,16 @@ public class Side {
|
||||
return this.name.equals(sideName);
|
||||
}
|
||||
|
||||
public UUID getUUID() {
|
||||
return this.uuid;
|
||||
// Associated war
|
||||
|
||||
@Override
|
||||
public boolean equals(War war) {
|
||||
return this.warUUID.equals(war.getUUID());
|
||||
}
|
||||
|
||||
@Nullable
|
||||
@Override
|
||||
public War getWar() {
|
||||
return WarController.getInstance().getWar(warUUID); // The war must exist, or this object wouldn't
|
||||
return WarController.getInstance().getWar(warUUID);
|
||||
}
|
||||
|
||||
public void processSurrenders() {
|
||||
@@ -483,26 +214,53 @@ public class Side {
|
||||
getWar().defeat(this);
|
||||
}
|
||||
|
||||
private boolean shouldSurrender() {
|
||||
return nations.isEmpty() && towns.isEmpty();
|
||||
}
|
||||
|
||||
public boolean shouldNationSurrender(Nation nation) {
|
||||
final int townsQty = nation.getNumTowns();
|
||||
// List<Town> towns = nation.getTowns();
|
||||
|
||||
final int surrenderedTownsQty = nation.getTowns().stream().filter(this::isTownSurrendered).mapToInt(value -> 1).sum();
|
||||
|
||||
/*int surrenderedTownsQty = 0;
|
||||
for (Town town : towns) {
|
||||
if (isTownSurrendered(town))
|
||||
surrenderedTownsQty++;
|
||||
}*/
|
||||
|
||||
return surrenderedTownsQty == townsQty;
|
||||
}
|
||||
|
||||
public Town getTown() {
|
||||
return town;
|
||||
}
|
||||
|
||||
// Player management
|
||||
|
||||
@Override
|
||||
public void add(OfflinePlayer p) {
|
||||
super.add(p);
|
||||
|
||||
// Add player to battles
|
||||
getWar().getSieges().forEach(siege -> {
|
||||
if (siege.getAttackerSide().equals(this)) {
|
||||
siege.addPlayer(p, BattleSide.ATTACKER);
|
||||
} else if (siege.getDefenderSide().equals(this)) {
|
||||
siege.addPlayer(p, BattleSide.DEFENDER);
|
||||
}
|
||||
});
|
||||
// TODO Raids
|
||||
/*getWar().getRaids().forEach(raid -> {
|
||||
if (raid.getAttackerSide().equals(this)) {
|
||||
raid.addPlayer(p, BattleSide.ATTACKER);
|
||||
} else if (raid.getDefenderSide().equals(this)) {
|
||||
raid.addPlayer(p, BattleSide.DEFENDER);
|
||||
}
|
||||
});*/
|
||||
}
|
||||
|
||||
@Override
|
||||
public void remove(OfflinePlayer p) {
|
||||
super.remove(p);
|
||||
|
||||
// Remove player from battles
|
||||
getWar().getSieges().forEach(siege -> {
|
||||
if (siege.getAttackerSide().equals(this)) {
|
||||
siege.removePlayer(p, BattleSide.ATTACKER);
|
||||
} else if (siege.getDefenderSide().equals(this)) {
|
||||
siege.removePlayer(p, BattleSide.DEFENDER);
|
||||
}
|
||||
});
|
||||
// TODO Raids
|
||||
/*getWar().getRaids().forEach(raid -> {
|
||||
if (raid.getAttackerSide().equals(this)) {
|
||||
raid.removePlayer(p, BattleSide.ATTACKER);
|
||||
} else if (raid.getDefenderSide().equals(this)) {
|
||||
raid.removePlayer(p, BattleSide.DEFENDER);
|
||||
}
|
||||
});*/
|
||||
}
|
||||
}
|
||||
@@ -5,55 +5,86 @@ 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.Bukkit;
|
||||
import org.bukkit.OfflinePlayer;
|
||||
import org.jetbrains.annotations.NotNull;
|
||||
import org.jetbrains.annotations.Nullable;
|
||||
|
||||
import java.time.Instant;
|
||||
import java.util.Set;
|
||||
import java.util.UUID;
|
||||
import java.util.stream.Collectors;
|
||||
|
||||
public class SideBuilder {
|
||||
private UUID warUUID;
|
||||
private UUID uuid;
|
||||
private BattleSide side;
|
||||
private BattleTeam team;
|
||||
private String name;
|
||||
private @Nullable UUID warUUID;
|
||||
private @Nullable UUID uuid;
|
||||
private @Nullable BattleSide side;
|
||||
private @Nullable BattleTeam team;
|
||||
private @Nullable String name;
|
||||
|
||||
private Government government;
|
||||
private @Nullable Government government;
|
||||
|
||||
private Set<Town> towns;
|
||||
private Set<Nation> nations;
|
||||
private Set<UUID> playersIncludingOffline;
|
||||
private Set<Town> surrenderedTowns;
|
||||
private Set<Nation> surrenderedNations;
|
||||
private Set<UUID> surrenderedPlayersIncludingOffline;
|
||||
private Instant siegeGrace;
|
||||
private Instant raidGrace;
|
||||
private @Nullable Set<Nation> nations;
|
||||
private @Nullable Set<Town> towns;
|
||||
private @Nullable Set<OfflinePlayer> players;
|
||||
|
||||
private @Nullable Set<Nation> nationsSurrendered;
|
||||
private @Nullable Set<Town> townsSurrendered;
|
||||
private @Nullable Set<OfflinePlayer> playersSurrendered;
|
||||
|
||||
private @Nullable Instant siegeGrace;
|
||||
private @Nullable Instant raidGrace;
|
||||
|
||||
public SideBuilder() {
|
||||
}
|
||||
|
||||
/**
|
||||
* Build a new side from save data
|
||||
* @return a new side
|
||||
* @throws SideCreationException exception
|
||||
*/
|
||||
public Side rebuild() 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");
|
||||
// TODO Cleanup this shit
|
||||
if (warUUID == null || uuid == null
|
||||
) throw new IllegalStateException("Missing state to create Side 1.2");
|
||||
if (warUUID == null)
|
||||
throw new SideCreationException("Missing state warUUID required to create Side!");
|
||||
|
||||
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 (uuid == null)
|
||||
throw new SideCreationException("Missing state uuid required to create Side!");
|
||||
|
||||
if (team == null || name == null ||
|
||||
towns == null || nations == null
|
||||
) throw new IllegalStateException("Missing state to create Side 1");
|
||||
if (government == null)
|
||||
throw new SideCreationException("Missing state government required to create Side!");
|
||||
|
||||
if (playersIncludingOffline == null ||
|
||||
surrenderedTowns == null || surrenderedNations == null || surrenderedPlayersIncludingOffline == null ||
|
||||
siegeGrace == null || raidGrace == null
|
||||
) throw new IllegalStateException("Missing state to create Side 2");
|
||||
if (side == null)
|
||||
throw new SideCreationException("Missing state side required to create Side!");
|
||||
|
||||
if (team == null)
|
||||
throw new SideCreationException("Missing state team required to create Side!");
|
||||
|
||||
if (name == null)
|
||||
throw new SideCreationException("Missing state name required to create Side!");
|
||||
|
||||
if (towns == null)
|
||||
throw new SideCreationException("Missing state towns required to create Side!");
|
||||
|
||||
if (nations == null)
|
||||
throw new SideCreationException("Missing state nations required to create Side!");
|
||||
|
||||
if (players == null)
|
||||
throw new SideCreationException("Missing state players required to create Side!");
|
||||
|
||||
if (townsSurrendered == null)
|
||||
throw new SideCreationException("Missing state townsSurrendered required to create Side!");
|
||||
|
||||
if (nationsSurrendered == null)
|
||||
throw new SideCreationException("Missing state nationsSurrendered required to create Side!");
|
||||
|
||||
if (playersSurrendered == null)
|
||||
throw new SideCreationException("Missing state playersSurrendered required to create Side!");
|
||||
|
||||
if (siegeGrace == null)
|
||||
throw new SideCreationException("Missing state siegeGrace required to create Side!");
|
||||
|
||||
if (raidGrace == null)
|
||||
throw new SideCreationException("Missing state raidGrace required to create Side!");
|
||||
|
||||
return new Side(
|
||||
warUUID,
|
||||
@@ -62,20 +93,37 @@ public class SideBuilder {
|
||||
side,
|
||||
team,
|
||||
name,
|
||||
towns,
|
||||
nations,
|
||||
playersIncludingOffline,
|
||||
surrenderedTowns,
|
||||
surrenderedNations,
|
||||
surrenderedPlayersIncludingOffline,
|
||||
towns,
|
||||
players,
|
||||
nationsSurrendered,
|
||||
townsSurrendered,
|
||||
playersSurrendered,
|
||||
siegeGrace,
|
||||
raidGrace
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* Build a new Side
|
||||
* @return a new side
|
||||
* @throws SideCreationException exception
|
||||
*/
|
||||
public Side build() throws SideCreationException {
|
||||
if (warUUID == null || uuid == null || government == null || side == null || team == null)
|
||||
throw new IllegalStateException("Missing state to create new Side");
|
||||
if (warUUID == null)
|
||||
throw new SideCreationException("Missing state warUUID required to create Side!");
|
||||
|
||||
if (uuid == null)
|
||||
throw new SideCreationException("Missing state uuid required to create Side!");
|
||||
|
||||
if (government == null)
|
||||
throw new SideCreationException("Missing state government required to create Side!");
|
||||
|
||||
if (side == null)
|
||||
throw new SideCreationException("Missing state side required to create Side!");
|
||||
|
||||
if (team == null)
|
||||
throw new SideCreationException("Missing state team required to create Side!");
|
||||
|
||||
return new Side(
|
||||
warUUID,
|
||||
@@ -116,33 +164,33 @@ public class SideBuilder {
|
||||
return this;
|
||||
}
|
||||
|
||||
public SideBuilder setTowns(Set<Town> towns) {
|
||||
this.towns = towns;
|
||||
return this;
|
||||
}
|
||||
|
||||
public SideBuilder setNations(Set<Nation> nations) {
|
||||
this.nations = nations;
|
||||
return this;
|
||||
}
|
||||
|
||||
public SideBuilder setPlayersIncludingOffline(Set<UUID> playersIncludingOffline) {
|
||||
this.playersIncludingOffline = playersIncludingOffline;
|
||||
public SideBuilder setTowns(Set<Town> towns) {
|
||||
this.towns = towns;
|
||||
return this;
|
||||
}
|
||||
|
||||
public SideBuilder setSurrenderedTowns(Set<Town> surrenderedTowns) {
|
||||
this.surrenderedTowns = surrenderedTowns;
|
||||
public SideBuilder setPlayers(@NotNull Set<UUID> players) {
|
||||
this.players = players.stream().map(Bukkit::getOfflinePlayer).collect(Collectors.toSet());
|
||||
return this;
|
||||
}
|
||||
|
||||
public SideBuilder setSurrenderedNations(Set<Nation> surrenderedNations) {
|
||||
this.surrenderedNations = surrenderedNations;
|
||||
public SideBuilder setNationsSurrendered(Set<Nation> nationsSurrendered) {
|
||||
this.nationsSurrendered = nationsSurrendered;
|
||||
return this;
|
||||
}
|
||||
|
||||
public SideBuilder setSurrenderedPlayersIncludingOffline(Set<UUID> surrenderedPlayersIncludingOffline) {
|
||||
this.surrenderedPlayersIncludingOffline = surrenderedPlayersIncludingOffline;
|
||||
public SideBuilder setTownsSurrendered(Set<Town> townsSurrendered) {
|
||||
this.townsSurrendered = townsSurrendered;
|
||||
return this;
|
||||
}
|
||||
|
||||
public SideBuilder setPlayersSurrendered(@NotNull Set<UUID> playersSurrendered) {
|
||||
this.playersSurrendered = playersSurrendered.stream().map(Bukkit::getOfflinePlayer).collect(Collectors.toSet());
|
||||
return this;
|
||||
}
|
||||
|
||||
|
||||
+114
-133
@@ -1,9 +1,11 @@
|
||||
package com.github.alathra.alathranwars.db;
|
||||
package com.github.alathra.alathranwars.database;
|
||||
|
||||
import com.github.alathra.alathranwars.conflict.battle.siege.Siege;
|
||||
import com.github.alathra.alathranwars.conflict.battle.siege.SiegePhase;
|
||||
import com.github.alathra.alathranwars.conflict.war.War;
|
||||
import com.github.alathra.alathranwars.conflict.war.WarBuilder;
|
||||
import com.github.alathra.alathranwars.conflict.war.WarController;
|
||||
import com.github.alathra.alathranwars.conflict.war.WarCreationException;
|
||||
import com.github.alathra.alathranwars.conflict.war.side.Side;
|
||||
import com.github.alathra.alathranwars.conflict.war.side.SideBuilder;
|
||||
import com.github.alathra.alathranwars.conflict.war.side.SideCreationException;
|
||||
@@ -24,10 +26,8 @@ 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.time.Instant;
|
||||
import java.time.LocalDateTime;
|
||||
import java.time.ZoneOffset;
|
||||
@@ -35,47 +35,13 @@ import java.util.HashSet;
|
||||
import java.util.Set;
|
||||
import java.util.UUID;
|
||||
|
||||
import static com.github.alathra.alathranwars.db.schema.Tables.*;
|
||||
import static com.github.alathra.alathranwars.database.schema.Tables.*;
|
||||
import static com.github.alathra.alathranwars.database.QueryUtil.*;
|
||||
|
||||
/**
|
||||
* 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() {
|
||||
@@ -86,27 +52,20 @@ public abstract class DatabaseQueries {
|
||||
|
||||
for (War war : WarController.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.isEventWar() ? (byte) 1 : (byte) 0)
|
||||
.insertInto(LIST, LIST.UUID, LIST.NAME, LIST.LABEL, LIST.SIDE1, LIST.SIDE2, LIST.EVENT)
|
||||
.values(
|
||||
DatabaseQueries.convertUUIDToBytes(war.getUUID()),
|
||||
fromUUIDToBytes(war.getUUID()),
|
||||
war.getName(),
|
||||
war.getLabel(),
|
||||
DatabaseQueries.convertUUIDToBytes(war.getSide1().getUUID()),
|
||||
DatabaseQueries.convertUUIDToBytes(war.getSide2().getUUID()),
|
||||
fromUUIDToBytes(war.getSide1().getUUID()),
|
||||
fromUUIDToBytes(war.getSide2().getUUID()),
|
||||
war.isEventWar() ? (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()))
|
||||
.set(LIST.SIDE1, fromUUIDToBytes(war.getSide1().getUUID()))
|
||||
.set(LIST.SIDE2, fromUUIDToBytes(war.getSide2().getUUID()))
|
||||
.execute();
|
||||
|
||||
// Save sides
|
||||
@@ -129,14 +88,14 @@ public abstract class DatabaseQueries {
|
||||
DSLContext context = DB.getContext(con);
|
||||
|
||||
context
|
||||
.insertInto(SIDES, SIDES.WAR, SIDES.UUID, SIDES.SIDE, SIDES.TEAM, SIDES.NAME, SIDES.TOWN, SIDES.SIEGEGRACE, SIDES.RAIDGRACE)
|
||||
.insertInto(SIDES, SIDES.WAR, SIDES.UUID, SIDES.SIDE, SIDES.TEAM, SIDES.NAME, SIDES.TOWN, SIDES.SIEGE_GRACE, SIDES.RAID_GRACE)
|
||||
.values(
|
||||
convertUUIDToBytes(side.getWar().getUUID()),
|
||||
convertUUIDToBytes(side.getUUID()),
|
||||
fromUUIDToBytes(side.getWar().getUUID()),
|
||||
fromUUIDToBytes(side.getUUID()),
|
||||
side.getSide().toString(),
|
||||
side.getTeam().toString(),
|
||||
side.getName(),
|
||||
convertUUIDToBytes(side.getTown().getUUID()),
|
||||
fromUUIDToBytes(side.getTown().getUUID()),
|
||||
LocalDateTime.ofInstant(side.getSiegeGrace(), ZoneOffset.UTC),
|
||||
LocalDateTime.ofInstant(side.getRaidGrace(), ZoneOffset.UTC)
|
||||
)
|
||||
@@ -144,9 +103,9 @@ public abstract class DatabaseQueries {
|
||||
.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))
|
||||
.set(SIDES.TOWN, fromUUIDToBytes(side.getTown().getUUID()))
|
||||
.set(SIDES.SIEGE_GRACE, LocalDateTime.ofInstant(side.getSiegeGrace(), ZoneOffset.UTC))
|
||||
.set(SIDES.RAID_GRACE, LocalDateTime.ofInstant(side.getRaidGrace(), ZoneOffset.UTC))
|
||||
.execute();
|
||||
|
||||
saveSideNations(con, side);
|
||||
@@ -159,27 +118,27 @@ public abstract class DatabaseQueries {
|
||||
|
||||
public static void saveSideNations(Connection con, Side side) {
|
||||
try {
|
||||
transactionWrapper(con, (connection, context) -> {
|
||||
transaction(con, (connection, context) -> {
|
||||
context
|
||||
.deleteFrom(SIDES_NATIONS)
|
||||
.where(SIDES_NATIONS.SIDE.equal(convertUUIDToBytes(side.getUUID())))
|
||||
.where(SIDES_NATIONS.SIDE.equal(fromUUIDToBytes(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()),
|
||||
fromUUIDToBytes(side.getUUID()),
|
||||
fromUUIDToBytes(nation.getUUID()),
|
||||
(byte) 0
|
||||
)
|
||||
.execute();
|
||||
}
|
||||
|
||||
for (Nation nation : side.getSurrenderedNations()) {
|
||||
for (Nation nation : side.getNationsSurrendered()) {
|
||||
context.insertInto(SIDES_NATIONS, SIDES_NATIONS.SIDE, SIDES_NATIONS.NATION, SIDES_NATIONS.SURRENDERED)
|
||||
.values(
|
||||
convertUUIDToBytes(side.getUUID()),
|
||||
convertUUIDToBytes(nation.getUUID()),
|
||||
fromUUIDToBytes(side.getUUID()),
|
||||
fromUUIDToBytes(nation.getUUID()),
|
||||
(byte) 1
|
||||
)
|
||||
.execute();
|
||||
@@ -192,27 +151,27 @@ public abstract class DatabaseQueries {
|
||||
|
||||
public static void saveSideTowns(Connection con, Side side) {
|
||||
try {
|
||||
transactionWrapper(con, (connection, context) -> {
|
||||
transaction(con, (connection, context) -> {
|
||||
context
|
||||
.deleteFrom(SIDES_TOWNS)
|
||||
.where(SIDES_TOWNS.SIDE.equal(convertUUIDToBytes(side.getUUID())))
|
||||
.where(SIDES_TOWNS.SIDE.equal(fromUUIDToBytes(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()),
|
||||
fromUUIDToBytes(side.getUUID()),
|
||||
fromUUIDToBytes(town.getUUID()),
|
||||
(byte) 0
|
||||
)
|
||||
.execute();
|
||||
}
|
||||
|
||||
for (Town town : side.getSurrenderedTowns()) {
|
||||
for (Town town : side.getTownsSurrendered()) {
|
||||
context.insertInto(SIDES_TOWNS, SIDES_TOWNS.SIDE, SIDES_TOWNS.TOWN, SIDES_TOWNS.SURRENDERED)
|
||||
.values(
|
||||
convertUUIDToBytes(side.getUUID()),
|
||||
convertUUIDToBytes(town.getUUID()),
|
||||
fromUUIDToBytes(side.getUUID()),
|
||||
fromUUIDToBytes(town.getUUID()),
|
||||
(byte) 1
|
||||
)
|
||||
.execute();
|
||||
@@ -225,27 +184,27 @@ public abstract class DatabaseQueries {
|
||||
|
||||
public static void saveSidePlayers(Connection con, Side side) {
|
||||
try {
|
||||
transactionWrapper(con, (connection, context) -> {
|
||||
transaction(con, (connection, context) -> {
|
||||
context
|
||||
.deleteFrom(SIDES_PLAYERS)
|
||||
.where(SIDES_PLAYERS.SIDE.equal(convertUUIDToBytes(side.getUUID())))
|
||||
.where(SIDES_PLAYERS.SIDE.equal(fromUUIDToBytes(side.getUUID())))
|
||||
.execute();
|
||||
|
||||
for (UUID uuid : side.getPlayersIncludingOffline()) {
|
||||
for (OfflinePlayer p : side.getPlayersAll()) {
|
||||
context.insertInto(SIDES_PLAYERS, SIDES_PLAYERS.SIDE, SIDES_PLAYERS.PLAYER, SIDES_PLAYERS.SURRENDERED)
|
||||
.values(
|
||||
convertUUIDToBytes(side.getUUID()),
|
||||
convertUUIDToBytes(uuid),
|
||||
fromUUIDToBytes(side.getUUID()),
|
||||
fromUUIDToBytes(p.getUniqueId()),
|
||||
(byte) 0
|
||||
)
|
||||
.execute();
|
||||
}
|
||||
|
||||
for (UUID uuid : side.getSurrenderedPlayersIncludingOffline()) {
|
||||
for (OfflinePlayer p : side.getPlayersSurrendered()) {
|
||||
context.insertInto(SIDES_PLAYERS, SIDES_PLAYERS.SIDE, SIDES_PLAYERS.PLAYER, SIDES_PLAYERS.SURRENDERED)
|
||||
.values(
|
||||
convertUUIDToBytes(side.getUUID()),
|
||||
convertUUIDToBytes(uuid),
|
||||
fromUUIDToBytes(side.getUUID()),
|
||||
fromUUIDToBytes(p.getUniqueId()),
|
||||
(byte) 1
|
||||
)
|
||||
.execute();
|
||||
@@ -260,23 +219,29 @@ public abstract class DatabaseQueries {
|
||||
try {
|
||||
DSLContext context = DB.getContext(con);
|
||||
|
||||
context.insertInto(SIEGES, SIEGES.WAR, SIEGES.UUID, SIEGES.TOWN, SIEGES.SIEGELEADER, SIEGES.ENDTIME, SIEGES.LASTTOUCHED, SIEGES.SIEGEPROGRESS)
|
||||
context.insertInto(SIEGES, SIEGES.WAR, SIEGES.UUID, SIEGES.TOWN, SIEGES.SIEGE_LEADER, SIEGES.END_TIME, SIEGES.LAST_TOUCHED, SIEGES.SIEGE_PROGRESS, SIEGES.PHASE_CURRENT, SIEGES.PHASE_PROGRESS, SIEGES.PHASE_START_TIME)
|
||||
.values(
|
||||
convertUUIDToBytes(siege.getWar().getUUID()),
|
||||
convertUUIDToBytes(siege.getUUID()),
|
||||
convertUUIDToBytes(siege.getTown().getUUID()),
|
||||
convertUUIDToBytes(siege.getSiegeLeader().getUniqueId()),
|
||||
fromUUIDToBytes(siege.getWar().getUUID()),
|
||||
fromUUIDToBytes(siege.getUUID()),
|
||||
fromUUIDToBytes(siege.getTown().getUUID()),
|
||||
fromUUIDToBytes(siege.getSiegeLeader().getUniqueId()),
|
||||
LocalDateTime.ofInstant(siege.getEndTime(), ZoneOffset.UTC),
|
||||
LocalDateTime.ofInstant(siege.getLastTouched(), ZoneOffset.UTC),
|
||||
siege.getSiegeProgress()
|
||||
siege.getProgressManager().get(),
|
||||
siege.getPhaseManager().get().name(),
|
||||
siege.getPhaseManager().getProgress(),
|
||||
LocalDateTime.ofInstant(siege.getPhaseManager().getStartTime(), ZoneOffset.UTC)
|
||||
)
|
||||
.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())
|
||||
.set(SIEGES.WAR, fromUUIDToBytes(siege.getWar().getUUID()))
|
||||
.set(SIEGES.TOWN, fromUUIDToBytes(siege.getTown().getUUID()))
|
||||
.set(SIEGES.SIEGE_LEADER, fromUUIDToBytes(siege.getSiegeLeader().getUniqueId()))
|
||||
.set(SIEGES.END_TIME, LocalDateTime.ofInstant(siege.getEndTime(), ZoneOffset.UTC))
|
||||
.set(SIEGES.LAST_TOUCHED, LocalDateTime.ofInstant(siege.getLastTouched(), ZoneOffset.UTC))
|
||||
.set(SIEGES.SIEGE_PROGRESS, siege.getProgressManager().get())
|
||||
.set(SIEGES.PHASE_CURRENT, siege.getPhaseManager().get().name())
|
||||
.set(SIEGES.PHASE_PROGRESS, siege.getPhaseManager().getProgress())
|
||||
.set(SIEGES.PHASE_START_TIME, LocalDateTime.ofInstant(siege.getPhaseManager().getStartTime(), ZoneOffset.UTC))
|
||||
.execute();
|
||||
|
||||
saveSiegePlayers(con, siege);
|
||||
@@ -287,27 +252,27 @@ public abstract class DatabaseQueries {
|
||||
|
||||
public static void saveSiegePlayers(Connection con, Siege siege) {
|
||||
try {
|
||||
transactionWrapper(con, (connection, context) -> {
|
||||
transaction(con, (connection, context) -> {
|
||||
context
|
||||
.deleteFrom(SIEGE_PLAYERS)
|
||||
.where(SIEGE_PLAYERS.SIEGE.equal(convertUUIDToBytes(siege.getUUID())))
|
||||
.where(SIEGE_PLAYERS.SIEGE.equal(fromUUIDToBytes(siege.getUUID())))
|
||||
.execute();
|
||||
|
||||
for (UUID uuid : siege.getAttackerPlayersIncludingOffline()) {
|
||||
for (UUID uuid : siege.getPlayers(BattleSide.ATTACKER).stream().map(OfflinePlayer::getUniqueId).toList()) {
|
||||
context.insertInto(SIEGE_PLAYERS, SIEGE_PLAYERS.SIEGE, SIEGE_PLAYERS.PLAYER, SIEGE_PLAYERS.TEAM)
|
||||
.values(
|
||||
convertUUIDToBytes(siege.getUUID()),
|
||||
convertUUIDToBytes(uuid),
|
||||
fromUUIDToBytes(siege.getUUID()),
|
||||
fromUUIDToBytes(uuid),
|
||||
(byte) 0
|
||||
)
|
||||
.execute();
|
||||
}
|
||||
|
||||
for (UUID uuid : siege.getDefenderPlayersIncludingOffline()) {
|
||||
for (UUID uuid : siege.getPlayers(BattleSide.DEFENDER).stream().map(OfflinePlayer::getUniqueId).toList()) {
|
||||
context.insertInto(SIEGE_PLAYERS, SIEGE_PLAYERS.SIEGE, SIEGE_PLAYERS.PLAYER, SIEGE_PLAYERS.TEAM)
|
||||
.values(
|
||||
convertUUIDToBytes(siege.getUUID()),
|
||||
convertUUIDToBytes(uuid),
|
||||
fromUUIDToBytes(siege.getUUID()),
|
||||
fromUUIDToBytes(uuid),
|
||||
(byte) 1
|
||||
)
|
||||
.execute();
|
||||
@@ -332,14 +297,14 @@ public abstract class DatabaseQueries {
|
||||
.fetch();
|
||||
|
||||
for (Record r : result) {
|
||||
UUID uuid = convertBytesToUUID(r.get(LIST.UUID));
|
||||
UUID uuid = fromBytesToUUID(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)));
|
||||
@Nullable Side side1 = loadSide(con, uuid, fromBytesToUUID(r.get(LIST.SIDE1)));
|
||||
@Nullable Side side2 = loadSide(con, uuid, fromBytesToUUID(r.get(LIST.SIDE2)));
|
||||
boolean event = r.get(LIST.EVENT, Boolean.class);
|
||||
|
||||
wars.add( // TODO IllegalStateException
|
||||
wars.add(
|
||||
new WarBuilder()
|
||||
.setUuid(uuid)
|
||||
.setName(name)
|
||||
@@ -359,6 +324,8 @@ public abstract class DatabaseQueries {
|
||||
}
|
||||
} catch (SQLException | DataAccessException e) {
|
||||
Logger.get().error("SQL Query threw an error!", e);
|
||||
} catch (WarCreationException e) {
|
||||
Logger.get().error("Failed to re-create war from database!", e);
|
||||
}
|
||||
|
||||
return wars;
|
||||
@@ -371,8 +338,8 @@ public abstract class DatabaseQueries {
|
||||
|
||||
Record r = context.select()
|
||||
.from(SIDES)
|
||||
.where(SIDES.WAR.equal(convertUUIDToBytes(warUUID)))
|
||||
.and(SIDES.UUID.equal(convertUUIDToBytes(uuid)))
|
||||
.where(SIDES.WAR.equal(fromUUIDToBytes(warUUID)))
|
||||
.and(SIDES.UUID.equal(fromUUIDToBytes(uuid)))
|
||||
.fetchOne();
|
||||
|
||||
if (r == null) return null;
|
||||
@@ -381,23 +348,23 @@ public abstract class DatabaseQueries {
|
||||
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);
|
||||
@Nullable Town town = TownyAPI.getInstance().getTown(fromBytesToUUID(r.get(SIDES.TOWN)));
|
||||
Instant siegeGrace = r.get(SIDES.SIEGE_GRACE).toInstant(ZoneOffset.UTC);
|
||||
Instant raidGrace = r.get(SIDES.RAID_GRACE).toInstant(ZoneOffset.UTC);
|
||||
|
||||
// Load players
|
||||
Set<UUID> players = new HashSet<>();
|
||||
Set<UUID> playersSurrendered = new HashSet<>();
|
||||
Result<Record> resultPlayers = context.select()
|
||||
.from(SIDES_PLAYERS)
|
||||
.where(SIDES_PLAYERS.SIDE.equal(convertUUIDToBytes(uuid)))
|
||||
.where(SIDES_PLAYERS.SIDE.equal(fromUUIDToBytes(uuid)))
|
||||
.fetch();
|
||||
resultPlayers.forEach(
|
||||
record -> {
|
||||
if (record.get(SIDES_PLAYERS.SURRENDERED).equals((byte) 0)) {
|
||||
players.add(convertBytesToUUID(record.get(SIDES_PLAYERS.PLAYER)));
|
||||
players.add(fromBytesToUUID(record.get(SIDES_PLAYERS.PLAYER)));
|
||||
} else {
|
||||
playersSurrendered.add(convertBytesToUUID(record.get(SIDES_PLAYERS.PLAYER)));
|
||||
playersSurrendered.add(fromBytesToUUID(record.get(SIDES_PLAYERS.PLAYER)));
|
||||
}
|
||||
}
|
||||
);
|
||||
@@ -407,11 +374,11 @@ public abstract class DatabaseQueries {
|
||||
Set<Nation> nationsSurrendered = new HashSet<>();
|
||||
Result<Record> resultNations = context.select()
|
||||
.from(SIDES_NATIONS)
|
||||
.where(SIDES_NATIONS.SIDE.equal(convertUUIDToBytes(uuid)))
|
||||
.where(SIDES_NATIONS.SIDE.equal(fromUUIDToBytes(uuid)))
|
||||
.fetch();
|
||||
resultNations.forEach(
|
||||
record -> {
|
||||
final UUID identifier = convertBytesToUUID(record.get(SIDES_NATIONS.NATION));
|
||||
final UUID identifier = fromBytesToUUID(record.get(SIDES_NATIONS.NATION));
|
||||
if (record.get(SIDES_NATIONS.SURRENDERED).equals((byte) 0)) {
|
||||
@Nullable Nation nation = TownyAPI.getInstance().getNation(identifier);
|
||||
if (nation != null)
|
||||
@@ -429,11 +396,11 @@ public abstract class DatabaseQueries {
|
||||
Set<Town> townsSurrendered = new HashSet<>();
|
||||
Result<Record> resultTowns = context.select()
|
||||
.from(SIDES_TOWNS)
|
||||
.where(SIDES_TOWNS.SIDE.equal(convertUUIDToBytes(uuid)))
|
||||
.where(SIDES_TOWNS.SIDE.equal(fromUUIDToBytes(uuid)))
|
||||
.fetch();
|
||||
resultTowns.forEach(
|
||||
record -> {
|
||||
final UUID identifier = convertBytesToUUID(record.get(SIDES_TOWNS.TOWN));
|
||||
final UUID identifier = fromBytesToUUID(record.get(SIDES_TOWNS.TOWN));
|
||||
if (record.get(SIDES_TOWNS.SURRENDERED).equals((byte) 0)) {
|
||||
@Nullable Town town2 = TownyAPI.getInstance().getTown(identifier);
|
||||
if (town2 != null)
|
||||
@@ -455,10 +422,10 @@ public abstract class DatabaseQueries {
|
||||
.setName(name)
|
||||
.setTowns(towns)
|
||||
.setNations(nations)
|
||||
.setPlayersIncludingOffline(players)
|
||||
.setSurrenderedTowns(townsSurrendered)
|
||||
.setSurrenderedNations(nationsSurrendered)
|
||||
.setSurrenderedPlayersIncludingOffline(playersSurrendered)
|
||||
.setPlayers(players)
|
||||
.setTownsSurrendered(townsSurrendered)
|
||||
.setNationsSurrendered(nationsSurrendered)
|
||||
.setPlayersSurrendered(playersSurrendered)
|
||||
.setSiegeGrace(siegeGrace)
|
||||
.setRaidGrace(raidGrace)
|
||||
.rebuild();
|
||||
@@ -476,33 +443,44 @@ public abstract class DatabaseQueries {
|
||||
|
||||
Result<Record> result = context.select()
|
||||
.from(SIEGES)
|
||||
.where(SIEGES.WAR.equal(convertUUIDToBytes(war.getUUID())))
|
||||
.where(SIEGES.WAR.equal(fromUUIDToBytes(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);
|
||||
UUID uuid = fromBytesToUUID(r.get(SIEGES.UUID));
|
||||
@Nullable Town town = TownyAPI.getInstance().getTown(fromBytesToUUID(r.get(SIEGES.TOWN)));
|
||||
OfflinePlayer siegeLeader = Bukkit.getOfflinePlayer(fromBytesToUUID(r.get(SIEGES.SIEGE_LEADER)));
|
||||
Instant endTime = r.get(SIEGES.END_TIME).toInstant(ZoneOffset.UTC);
|
||||
Instant lastTouched = r.get(SIEGES.LAST_TOUCHED).toInstant(ZoneOffset.UTC);
|
||||
int siegeProgress = r.get(SIEGES.SIEGE_PROGRESS);
|
||||
Set<UUID> attackersIncludingOffline = new HashSet<>();
|
||||
Set<UUID> defendersIncludingOffline = new HashSet<>();
|
||||
|
||||
Result<Record> resultPlayers = context.select()
|
||||
.from(SIEGE_PLAYERS)
|
||||
.where(SIEGE_PLAYERS.SIEGE.equal(convertUUIDToBytes(uuid)))
|
||||
.where(SIEGE_PLAYERS.SIEGE.equal(fromUUIDToBytes(uuid)))
|
||||
.fetch();
|
||||
resultPlayers.forEach(
|
||||
record -> {
|
||||
if (record.get(SIEGE_PLAYERS.TEAM).equals((byte) 0)) {
|
||||
attackersIncludingOffline.add(convertBytesToUUID(record.get(SIEGE_PLAYERS.PLAYER)));
|
||||
attackersIncludingOffline.add(fromBytesToUUID(record.get(SIEGE_PLAYERS.PLAYER)));
|
||||
} else {
|
||||
defendersIncludingOffline.add(convertBytesToUUID(record.get(SIEGE_PLAYERS.PLAYER)));
|
||||
defendersIncludingOffline.add(fromBytesToUUID(record.get(SIEGE_PLAYERS.PLAYER)));
|
||||
}
|
||||
}
|
||||
);
|
||||
|
||||
SiegePhase phase;
|
||||
try {
|
||||
phase = SiegePhase.valueOf(r.get(SIEGES.PHASE_CURRENT));
|
||||
} catch (IllegalArgumentException e) {
|
||||
phase = SiegePhase.SIEGE;
|
||||
}
|
||||
int phaseProgress = r.get(SIEGES.PHASE_PROGRESS);
|
||||
Instant phaseStartTime = r.get(SIEGES.PHASE_START_TIME).toInstant(ZoneOffset.UTC);
|
||||
|
||||
|
||||
|
||||
sieges.add(new Siege(
|
||||
war,
|
||||
uuid,
|
||||
@@ -512,7 +490,10 @@ public abstract class DatabaseQueries {
|
||||
lastTouched,
|
||||
siegeProgress,
|
||||
attackersIncludingOffline,
|
||||
defendersIncludingOffline
|
||||
defendersIncludingOffline,
|
||||
phase,
|
||||
phaseProgress,
|
||||
phaseStartTime
|
||||
));
|
||||
}
|
||||
} catch (DataAccessException e) {
|
||||
@@ -532,7 +513,7 @@ public abstract class DatabaseQueries {
|
||||
|
||||
context
|
||||
.deleteFrom(LIST)
|
||||
.where(LIST.UUID.equal(convertUUIDToBytes(war.getUUID())))
|
||||
.where(LIST.UUID.equal(fromUUIDToBytes(war.getUUID())))
|
||||
.execute();
|
||||
} catch (SQLException | DataAccessException e) {
|
||||
Logger.get().error("SQL Query threw an error!", e);
|
||||
@@ -547,7 +528,7 @@ public abstract class DatabaseQueries {
|
||||
|
||||
context
|
||||
.deleteFrom(SIEGES)
|
||||
.where(SIEGES.UUID.equal(convertUUIDToBytes(siege.getUUID())))
|
||||
.where(SIEGES.UUID.equal(fromUUIDToBytes(siege.getUUID())))
|
||||
.execute();
|
||||
} catch (SQLException | DataAccessException e) {
|
||||
Logger.get().error("SQL Query threw an error!", e);
|
||||
+87
-82
@@ -1,11 +1,13 @@
|
||||
package com.github.alathra.alathranwars.db;
|
||||
package com.github.alathra.alathranwars.database;
|
||||
|
||||
import com.mysql.cj.jdbc.MysqlDataSource;
|
||||
import com.mysql.jdbc.Driver;
|
||||
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 org.sqlite.JDBC;
|
||||
import org.sqlite.SQLiteDataSource;
|
||||
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
@@ -15,38 +17,35 @@ import java.util.Map;
|
||||
*/
|
||||
public enum DatabaseType {
|
||||
/**
|
||||
* HSQLDB database type.
|
||||
*/
|
||||
HSQLDB("HSQLDB", org.hsqldb.jdbcDriver.class.getName(), JDBCDataSource.class.getName(), "hsqldb", ';', ';'),
|
||||
/**
|
||||
* H2 Database Engine database type.
|
||||
* SQLite database type.
|
||||
*/
|
||||
H2("H2", org.h2.Driver.class.getName(), JdbcDataSource.class.getName(), "h2", ';', ';'),
|
||||
SQLITE("SQLite", JDBC.class.getName(), SQLiteDataSource.class.getName(), "sqlite", '?', '&'),
|
||||
/**
|
||||
* MySQL database type.
|
||||
*/
|
||||
MYSQL("MySQL", com.mysql.jdbc.Driver.class.getName(), MysqlDataSource.class.getName(), "mysql", '?', '&'),
|
||||
MYSQL("MySQL", 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;
|
||||
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;
|
||||
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;
|
||||
}
|
||||
this.jdbcPropertyPrefix = jdbcPropertyPrefix;
|
||||
this.jdbcPropertySeparator = jdbcPropertySeparator;
|
||||
}
|
||||
|
||||
/**
|
||||
* Gets driver name.
|
||||
@@ -109,14 +108,14 @@ public enum DatabaseType {
|
||||
* @return the string
|
||||
*/
|
||||
public String formatJdbcConnectionProperties(Map<String, Object> properties) {
|
||||
if (properties.isEmpty()) return "";
|
||||
if (properties.isEmpty()) return "";
|
||||
|
||||
List<String> connectionProperties = properties.entrySet().stream()
|
||||
.map(map -> "%s=%s".formatted(map.getKey(), map.getValue()))
|
||||
.toList();
|
||||
|
||||
return jdbcPropertyPrefix + String.join(Character.toString(jdbcPropertySeparator), connectionProperties);
|
||||
}
|
||||
return String.join(Character.toString(getJdbcPropertySeparator()), connectionProperties);
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
@@ -131,7 +130,6 @@ public enum DatabaseType {
|
||||
if (type.equals(prefix.toLowerCase())) {
|
||||
return type;
|
||||
}
|
||||
;
|
||||
}
|
||||
|
||||
return null;
|
||||
@@ -169,25 +167,13 @@ public enum DatabaseType {
|
||||
*/
|
||||
public SQLDialect getSQLDialect() {
|
||||
return switch (this) {
|
||||
case HSQLDB -> SQLDialect.HSQLDB;
|
||||
case H2 -> SQLDialect.H2;
|
||||
case SQLITE -> SQLDialect.SQLITE;
|
||||
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.
|
||||
*
|
||||
@@ -195,49 +181,69 @@ public enum DatabaseType {
|
||||
*/
|
||||
public String getTableDefaults() {
|
||||
return switch (this) {
|
||||
case H2, HSQLDB -> "";
|
||||
case H2, SQLITE -> "";
|
||||
case MARIADB, MYSQL -> " CHARACTER SET utf8mb4 COLLATE utf8mb4_bin";
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* Gets uuid type for this DatabaseType.
|
||||
* Gets connection properties for this DatabaseType.
|
||||
*
|
||||
* @return the uuid type
|
||||
* @return the connection properties
|
||||
*/
|
||||
public String getUuidType() {
|
||||
return switch (this) {
|
||||
case HSQLDB -> "UUID";
|
||||
case H2, MARIADB, MYSQL -> "BINARY(16)";
|
||||
};
|
||||
}
|
||||
public String getDefaultConnectionProperties() {
|
||||
return getJdbcPropertyPrefix() + switch (this) {
|
||||
case H2 -> DatabaseType.H2.formatJdbcConnectionProperties(
|
||||
Map.of(
|
||||
"AUTO_SERVER", "TRUE",
|
||||
"MODE", "MYSQL", // MySQL support mode
|
||||
"CASE_INSENSITIVE_IDENTIFIERS", "TRUE",
|
||||
"IGNORECASE", "TRUE"
|
||||
)
|
||||
);
|
||||
case SQLITE -> "";
|
||||
case MYSQL -> DatabaseType.MYSQL.formatJdbcConnectionProperties(
|
||||
Map.of(
|
||||
// Base settings
|
||||
"useUnicode", true,
|
||||
"characterEncoding", "UTF-8",
|
||||
|
||||
/**
|
||||
* Gets inet type for this DatabaseType.
|
||||
*
|
||||
* @return the inet type
|
||||
*/
|
||||
public String getInetType() {
|
||||
return "VARBINARY(16)";
|
||||
}
|
||||
// Performance improvements
|
||||
"defaultFetchSize", 1000,
|
||||
|
||||
/**
|
||||
* Gets binary type for this DatabaseType.
|
||||
*
|
||||
* @return the binary type
|
||||
*/
|
||||
public String getBinaryType() {
|
||||
return "BLOB";
|
||||
}
|
||||
// Help debug in case of deadlock
|
||||
"includeInnodbStatusInDeadlockExceptions", true,
|
||||
"includeThreadDumpInDeadlockExceptions", true,
|
||||
|
||||
/**
|
||||
* 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";
|
||||
// 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 MARIADB -> DatabaseType.MARIADB.formatJdbcConnectionProperties(
|
||||
Map.of(
|
||||
// Base settings
|
||||
"useUnicode", true,
|
||||
"characterEncoding", "UTF-8",
|
||||
|
||||
// Performance improvements
|
||||
"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
|
||||
)
|
||||
);
|
||||
};
|
||||
}
|
||||
|
||||
@@ -248,7 +254,17 @@ public enum DatabaseType {
|
||||
*/
|
||||
public String getConnectionInitSql() {
|
||||
return switch (this) {
|
||||
case HSQLDB -> "SET DATABASE TRANSACTION CONTROL MVLOCKS;";
|
||||
case SQLITE, 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");
|
||||
case MARIADB -> "SET NAMES utf8mb4 COLLATE utf8mb4_bin; " + setSqlModes(
|
||||
// MariaDB defaults
|
||||
"STRICT_TRANS_TABLES",
|
||||
@@ -261,17 +277,6 @@ public enum DatabaseType {
|
||||
"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");
|
||||
};
|
||||
}
|
||||
|
||||
@@ -0,0 +1,75 @@
|
||||
package com.github.alathra.alathranwars.database;
|
||||
|
||||
import com.github.alathra.alathranwars.utility.DB;
|
||||
import org.jooq.DSLContext;
|
||||
import org.jooq.exception.DataAccessException;
|
||||
|
||||
import java.nio.ByteBuffer;
|
||||
import java.sql.Connection;
|
||||
import java.sql.SQLException;
|
||||
import java.sql.Savepoint;
|
||||
import java.util.UUID;
|
||||
|
||||
/**
|
||||
* Convenience class containing utility methods for querying databases.
|
||||
*/
|
||||
public abstract class QueryUtil {
|
||||
/**
|
||||
* Used in {@link #transaction(Connection, LambdaInterface)}.
|
||||
*/
|
||||
public interface LambdaInterface {
|
||||
void execute(Connection connection, DSLContext dslContext) throws SQLException, DataAccessException;
|
||||
}
|
||||
|
||||
/**
|
||||
* A quick wrapper for creating a transaction. The changes executed in the lambda context ar rolled back if any error occurs.
|
||||
* @param con A SQL connection
|
||||
* @param lambda A lambda method which defines what code to execute
|
||||
* @throws SQLException Exception
|
||||
* @throws DataAccessException Exception
|
||||
*/
|
||||
public static void transaction(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);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Convert uuid to an array of bytes.
|
||||
*
|
||||
* @param uuid the uuid
|
||||
* @return the byte array
|
||||
*/
|
||||
public static byte[] fromUUIDToBytes(UUID uuid) {
|
||||
ByteBuffer bb = ByteBuffer.wrap(new byte[16]);
|
||||
bb.putLong(uuid.getMostSignificantBits());
|
||||
bb.putLong(uuid.getLeastSignificantBits());
|
||||
return bb.array();
|
||||
}
|
||||
|
||||
/**
|
||||
* Convert byte array to uuid.
|
||||
*
|
||||
* @param bytes the byte array
|
||||
* @return the uuid
|
||||
*/
|
||||
public static UUID fromBytesToUUID(byte[] bytes) {
|
||||
ByteBuffer byteBuffer = ByteBuffer.wrap(bytes);
|
||||
long high = byteBuffer.getLong();
|
||||
long low = byteBuffer.getLong();
|
||||
return new UUID(high, low);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,282 @@
|
||||
package com.github.alathra.alathranwars.database.config;
|
||||
|
||||
import com.github.alathra.alathranwars.database.DatabaseType;
|
||||
import com.github.milkdrinkers.crate.Config;
|
||||
import org.jetbrains.annotations.Nullable;
|
||||
import org.jetbrains.annotations.TestOnly;
|
||||
|
||||
import java.nio.file.Path;
|
||||
import java.util.Map;
|
||||
import java.util.Optional;
|
||||
|
||||
/**
|
||||
* The type Database config.
|
||||
*/
|
||||
public class DatabaseConfig {
|
||||
// Essential details
|
||||
private final DatabaseType databaseType;
|
||||
private String tablePrefix;
|
||||
|
||||
// Connection details
|
||||
private final @Nullable Path path;
|
||||
private final String host;
|
||||
private final int port;
|
||||
private final String database;
|
||||
private final String username;
|
||||
private final String password;
|
||||
|
||||
private final boolean repair;
|
||||
|
||||
// Pool options
|
||||
private final int maxPoolSize;
|
||||
private final int minIdle;
|
||||
private final long maxLifeTime;
|
||||
private final long keepAliveTime;
|
||||
private final long connectionTimeout;
|
||||
|
||||
// JDBC properties
|
||||
private final Map<String, Object> connectionProperties;
|
||||
|
||||
/**
|
||||
* Instantiates a new Database config.
|
||||
*
|
||||
* @param databaseType the database type
|
||||
* @param tablePrefix the table prefix
|
||||
* @param path the path
|
||||
* @param host the host
|
||||
* @param port the port
|
||||
* @param database the database
|
||||
* @param username the username
|
||||
* @param password the password
|
||||
* @param repair the repair
|
||||
* @param maxPoolSize the max pool size
|
||||
* @param minIdle the min idle
|
||||
* @param maxLifeTime the max life time
|
||||
* @param keepAliveTime the keep alive time
|
||||
* @param connectionTimeout the connection timeout
|
||||
* @param connectionProperties the connection properties
|
||||
*/
|
||||
DatabaseConfig(
|
||||
DatabaseType databaseType,
|
||||
String tablePrefix,
|
||||
@Nullable Path path,
|
||||
String host,
|
||||
int port,
|
||||
String database,
|
||||
String username,
|
||||
String password,
|
||||
boolean repair,
|
||||
int maxPoolSize,
|
||||
int minIdle,
|
||||
long maxLifeTime,
|
||||
long keepAliveTime,
|
||||
long connectionTimeout,
|
||||
Map<String, Object> connectionProperties
|
||||
) {
|
||||
this.databaseType = databaseType;
|
||||
this.tablePrefix = tablePrefix;
|
||||
this.path = path;
|
||||
this.host = host;
|
||||
this.port = port;
|
||||
this.database = database;
|
||||
this.username = username;
|
||||
this.password = password;
|
||||
this.repair = repair;
|
||||
this.maxPoolSize = maxPoolSize;
|
||||
this.minIdle = minIdle;
|
||||
this.maxLifeTime = maxLifeTime;
|
||||
this.keepAliveTime = keepAliveTime;
|
||||
this.connectionTimeout = connectionTimeout;
|
||||
this.connectionProperties = connectionProperties;
|
||||
}
|
||||
|
||||
/**
|
||||
* Gets database type.
|
||||
*
|
||||
* @return the database type
|
||||
*/
|
||||
public DatabaseType getDatabaseType() {
|
||||
return databaseType;
|
||||
}
|
||||
|
||||
/**
|
||||
* Gets path.
|
||||
*
|
||||
* @return the path
|
||||
*/
|
||||
public Optional<Path> getPath() {
|
||||
return Optional.ofNullable(path);
|
||||
}
|
||||
|
||||
/**
|
||||
* Sets table prefix.
|
||||
*
|
||||
* @param tablePrefix the table prefix
|
||||
*/
|
||||
@TestOnly
|
||||
public void setTablePrefix(String tablePrefix) {
|
||||
this.tablePrefix = tablePrefix;
|
||||
}
|
||||
|
||||
/**
|
||||
* Gets table prefix.
|
||||
*
|
||||
* @return the table prefix
|
||||
*/
|
||||
public String getTablePrefix() {
|
||||
return tablePrefix;
|
||||
}
|
||||
|
||||
/**
|
||||
* Gets host.
|
||||
*
|
||||
* @return the host
|
||||
*/
|
||||
public String getHost() {
|
||||
return host;
|
||||
}
|
||||
|
||||
/**
|
||||
* Gets port.
|
||||
*
|
||||
* @return the port
|
||||
*/
|
||||
public int getPort() {
|
||||
return port;
|
||||
}
|
||||
|
||||
/**
|
||||
* Gets database.
|
||||
*
|
||||
* @return the database
|
||||
*/
|
||||
public String getDatabase() {
|
||||
return database;
|
||||
}
|
||||
|
||||
/**
|
||||
* Gets username.
|
||||
*
|
||||
* @return the username
|
||||
*/
|
||||
public String getUsername() {
|
||||
return username;
|
||||
}
|
||||
|
||||
/**
|
||||
* Gets password.
|
||||
*
|
||||
* @return the password
|
||||
*/
|
||||
public String getPassword() {
|
||||
return password;
|
||||
}
|
||||
|
||||
/**
|
||||
* Is repair boolean.
|
||||
*
|
||||
* @return the boolean
|
||||
*/
|
||||
public boolean isRepair() {
|
||||
return repair;
|
||||
}
|
||||
|
||||
/**
|
||||
* Gets max pool size.
|
||||
*
|
||||
* @return the max pool size
|
||||
*/
|
||||
public int getMaxPoolSize() {
|
||||
return maxPoolSize;
|
||||
}
|
||||
|
||||
/**
|
||||
* Gets min idle.
|
||||
*
|
||||
* @return the min idle
|
||||
*/
|
||||
public int getMinIdle() {
|
||||
return minIdle;
|
||||
}
|
||||
|
||||
/**
|
||||
* Gets max life time.
|
||||
*
|
||||
* @return the max life time
|
||||
*/
|
||||
public long getMaxLifeTime() {
|
||||
return maxLifeTime;
|
||||
}
|
||||
|
||||
/**
|
||||
* Gets keep alive time.
|
||||
*
|
||||
* @return the keep alive time
|
||||
*/
|
||||
public long getKeepAliveTime() {
|
||||
return keepAliveTime;
|
||||
}
|
||||
|
||||
/**
|
||||
* Gets connection timeout.
|
||||
*
|
||||
* @return the connection timeout
|
||||
*/
|
||||
public long getConnectionTimeout() {
|
||||
return connectionTimeout;
|
||||
}
|
||||
|
||||
/**
|
||||
* Gets connection properties.
|
||||
*
|
||||
* @return the connection properties
|
||||
*/
|
||||
public String getConnectionProperties() {
|
||||
return getDatabaseType().formatJdbcConnectionProperties(connectionProperties).isEmpty() ? "" : getDatabaseType().getJdbcPropertySeparator() + getDatabaseType().formatJdbcConnectionProperties(connectionProperties);
|
||||
}
|
||||
|
||||
/**
|
||||
* Gets database config from file.
|
||||
*
|
||||
* @param cfg the cfg
|
||||
* @return the database config from file
|
||||
*/
|
||||
public static DatabaseConfig getDatabaseConfigFromFile(Config cfg) {
|
||||
String databaseType = cfg.getString("database.type");
|
||||
String tablePrefix = cfg.getString("database.table-prefix");
|
||||
|
||||
String host = cfg.getString("database.host");
|
||||
Integer port = cfg.getInt("database.port");
|
||||
String database = cfg.getString("database.database");
|
||||
String username = cfg.getString("database.username");
|
||||
String password = cfg.getString("database.password");
|
||||
|
||||
boolean repair = cfg.getBoolean("database.advanced.repair");
|
||||
|
||||
Integer maxPoolSize = cfg.getInt("database.advanced.connection-pool.max-pool-size");
|
||||
Integer minIdle = cfg.getInt("database.advanced.connection-pool.min-idle");
|
||||
Long maxLifeTime = cfg.getLong("database.advanced.connection-pool.max-lifetime");
|
||||
Long keepAliveTime = cfg.getLong("database.advanced.connection-pool.keepalive-time");
|
||||
Long connectionTimeout = cfg.getLong("database.advanced.connection-pool.connection-timeout");
|
||||
|
||||
Map<String, Object> connectionProperties = cfg.getMapParameterized("database.advanced.connection-properties");
|
||||
|
||||
return new DatabaseConfigBuilder()
|
||||
.withDatabaseType(databaseType)
|
||||
.withTablePrefix(tablePrefix)
|
||||
.withPath(Path.of(cfg.getFilePath()).getParent())
|
||||
.withHost(host)
|
||||
.withPort(port)
|
||||
.withDatabase(database)
|
||||
.withUsername(username)
|
||||
.withPassword(password)
|
||||
.withRepair(repair)
|
||||
.withMaxPoolSize(maxPoolSize)
|
||||
.withMinIdle(minIdle)
|
||||
.withMaxLifeTime(maxLifeTime)
|
||||
.withKeepAliveTime(keepAliveTime)
|
||||
.withConnectionTimeout(connectionTimeout)
|
||||
.withConnectionProperties(connectionProperties)
|
||||
.build();
|
||||
}
|
||||
}
|
||||
+264
@@ -0,0 +1,264 @@
|
||||
package com.github.alathra.alathranwars.database.config;
|
||||
|
||||
import com.github.alathra.alathranwars.database.DatabaseType;
|
||||
import org.jetbrains.annotations.Nullable;
|
||||
|
||||
import java.nio.file.Path;
|
||||
import java.util.HashMap;
|
||||
import java.util.Map;
|
||||
|
||||
/**
|
||||
* The type Database config builder.
|
||||
*/
|
||||
public class DatabaseConfigBuilder {
|
||||
private @Nullable DatabaseType databaseType;
|
||||
private @Nullable String tablePrefix;
|
||||
|
||||
private @Nullable Path path;
|
||||
private @Nullable String host;
|
||||
private @Nullable Integer port;
|
||||
private @Nullable String database;
|
||||
private @Nullable String username;
|
||||
private @Nullable String password;
|
||||
|
||||
private @Nullable Boolean repair;
|
||||
|
||||
private @Nullable Integer maxPoolSize;
|
||||
private @Nullable Integer minIdle;
|
||||
private @Nullable Long maxLifeTime;
|
||||
private @Nullable Long keepAliveTime;
|
||||
private @Nullable Long connectionTimeout;
|
||||
|
||||
private @Nullable Map<String, Object> connectionProperties;
|
||||
|
||||
/**
|
||||
* With database type database config builder.
|
||||
*
|
||||
* @param vendorPrefix the vendor prefix
|
||||
* @return the database config builder
|
||||
*/
|
||||
public DatabaseConfigBuilder withDatabaseType(String vendorPrefix) {
|
||||
this.databaseType = DatabaseType.getDatabaseTypeFromJdbcPrefix(vendorPrefix.toLowerCase());
|
||||
return this;
|
||||
}
|
||||
|
||||
/**
|
||||
* With table prefix database config builder.
|
||||
*
|
||||
* @param tablePrefix the table prefix
|
||||
* @return the database config builder
|
||||
*/
|
||||
public DatabaseConfigBuilder withTablePrefix(String tablePrefix) {
|
||||
this.tablePrefix = tablePrefix;
|
||||
return this;
|
||||
}
|
||||
|
||||
/**
|
||||
* With path database config builder.
|
||||
*
|
||||
* @param path the path
|
||||
* @return the database config builder
|
||||
*/
|
||||
public DatabaseConfigBuilder withPath(Path path) {
|
||||
this.path = path;
|
||||
return this;
|
||||
}
|
||||
|
||||
/**
|
||||
* With host database config builder.
|
||||
*
|
||||
* @param host the host
|
||||
* @return the database config builder
|
||||
*/
|
||||
public DatabaseConfigBuilder withHost(String host) {
|
||||
this.host = host;
|
||||
return this;
|
||||
}
|
||||
|
||||
/**
|
||||
* With port database config builder.
|
||||
*
|
||||
* @param port the port
|
||||
* @return the database config builder
|
||||
*/
|
||||
public DatabaseConfigBuilder withPort(Integer port) {
|
||||
this.port = port;
|
||||
return this;
|
||||
}
|
||||
|
||||
/**
|
||||
* With database database config builder.
|
||||
*
|
||||
* @param database the database
|
||||
* @return the database config builder
|
||||
*/
|
||||
public DatabaseConfigBuilder withDatabase(String database) {
|
||||
this.database = database;
|
||||
return this;
|
||||
}
|
||||
|
||||
/**
|
||||
* With username database config builder.
|
||||
*
|
||||
* @param username the username
|
||||
* @return the database config builder
|
||||
*/
|
||||
public DatabaseConfigBuilder withUsername(String username) {
|
||||
this.username = username;
|
||||
return this;
|
||||
}
|
||||
|
||||
/**
|
||||
* With password database config builder.
|
||||
*
|
||||
* @param password the password
|
||||
* @return the database config builder
|
||||
*/
|
||||
public DatabaseConfigBuilder withPassword(String password) {
|
||||
this.password = password;
|
||||
return this;
|
||||
}
|
||||
|
||||
/**
|
||||
* With repair database config builder.
|
||||
*
|
||||
* @param repair the repair
|
||||
* @return the database config builder
|
||||
*/
|
||||
public DatabaseConfigBuilder withRepair(boolean repair) {
|
||||
this.repair = repair;
|
||||
return this;
|
||||
}
|
||||
|
||||
/**
|
||||
* With max pool size database config builder.
|
||||
*
|
||||
* @param maxPoolSize the max pool size
|
||||
* @return the database config builder
|
||||
*/
|
||||
public DatabaseConfigBuilder withMaxPoolSize(Integer maxPoolSize) {
|
||||
this.maxPoolSize = maxPoolSize;
|
||||
return this;
|
||||
}
|
||||
|
||||
/**
|
||||
* With min idle database config builder.
|
||||
*
|
||||
* @param minIdle the min idle
|
||||
* @return the database config builder
|
||||
*/
|
||||
public DatabaseConfigBuilder withMinIdle(Integer minIdle) {
|
||||
this.minIdle = minIdle;
|
||||
return this;
|
||||
}
|
||||
|
||||
/**
|
||||
* With max life time database config builder.
|
||||
*
|
||||
* @param maxLifeTime the max life time
|
||||
* @return the database config builder
|
||||
*/
|
||||
public DatabaseConfigBuilder withMaxLifeTime(Long maxLifeTime) {
|
||||
this.maxLifeTime = maxLifeTime;
|
||||
return this;
|
||||
}
|
||||
|
||||
/**
|
||||
* With keep alive time database config builder.
|
||||
*
|
||||
* @param keepAliveTime the keep alive time
|
||||
* @return the database config builder
|
||||
*/
|
||||
public DatabaseConfigBuilder withKeepAliveTime(Long keepAliveTime) {
|
||||
this.keepAliveTime = keepAliveTime;
|
||||
return this;
|
||||
}
|
||||
|
||||
/**
|
||||
* With connection timeout database config builder.
|
||||
*
|
||||
* @param connectionTimeout the connection timeout
|
||||
* @return the database config builder
|
||||
*/
|
||||
public DatabaseConfigBuilder withConnectionTimeout(Long connectionTimeout) {
|
||||
this.connectionTimeout = connectionTimeout;
|
||||
return this;
|
||||
}
|
||||
|
||||
/**
|
||||
* With connection properties database config builder.
|
||||
*
|
||||
* @param connectionProperties the connection properties
|
||||
* @return the database config builder
|
||||
*/
|
||||
public DatabaseConfigBuilder withConnectionProperties(Map<String, Object> connectionProperties) {
|
||||
this.connectionProperties = connectionProperties;
|
||||
return this;
|
||||
}
|
||||
|
||||
/**
|
||||
* Build database config.
|
||||
*
|
||||
* @return the database config
|
||||
*/
|
||||
public DatabaseConfig build() {
|
||||
if (databaseType == null)
|
||||
databaseType = DatabaseType.SQLITE;
|
||||
|
||||
if (tablePrefix == null)
|
||||
tablePrefix = "";
|
||||
|
||||
if (host == null)
|
||||
host = "localhost";
|
||||
|
||||
if (port == null)
|
||||
port = 3306;
|
||||
|
||||
if (database == null)
|
||||
database = "database_name";
|
||||
|
||||
if (username == null)
|
||||
username = "root";
|
||||
|
||||
if (password == null)
|
||||
password = "";
|
||||
|
||||
if (repair == null)
|
||||
repair = false;
|
||||
|
||||
if (maxPoolSize == null)
|
||||
maxPoolSize = 10;
|
||||
|
||||
if (minIdle == null)
|
||||
minIdle = 10;
|
||||
|
||||
if (maxLifeTime == null)
|
||||
maxLifeTime = 180_000L;
|
||||
|
||||
if (keepAliveTime == null)
|
||||
keepAliveTime = 60_000L;
|
||||
|
||||
if (connectionTimeout == null)
|
||||
connectionTimeout = 20_000L;
|
||||
|
||||
if (connectionProperties == null) {
|
||||
connectionProperties = new HashMap<>();
|
||||
|
||||
if (databaseType.equals(DatabaseType.MYSQL) || databaseType.equals(DatabaseType.MARIADB)) {
|
||||
connectionProperties.putIfAbsent("useSSL", "false");
|
||||
connectionProperties.putIfAbsent("cachePrepStmts", true);
|
||||
connectionProperties.putIfAbsent("prepStmtCacheSize", 250);
|
||||
connectionProperties.putIfAbsent("prepStmtCacheSqlLimit", 2048L);
|
||||
connectionProperties.putIfAbsent("useServerPrepStmts", true);
|
||||
connectionProperties.putIfAbsent("useLocalSessionState", true);
|
||||
connectionProperties.putIfAbsent("rewriteBatchedStatements", true);
|
||||
connectionProperties.putIfAbsent("cacheResultSetMetadata", true);
|
||||
connectionProperties.putIfAbsent("cacheServerConfiguration", true);
|
||||
connectionProperties.putIfAbsent("elideSetAutoCommits", true);
|
||||
connectionProperties.putIfAbsent("maintainTimeStats", false);
|
||||
}
|
||||
}
|
||||
|
||||
return new DatabaseConfig(databaseType, tablePrefix, path, host, port, database, username, password, repair, maxPoolSize, minIdle, maxLifeTime, keepAliveTime, connectionTimeout, connectionProperties);
|
||||
}
|
||||
}
|
||||
+34
@@ -0,0 +1,34 @@
|
||||
package com.github.alathra.alathranwars.database.exception;
|
||||
|
||||
/**
|
||||
* Database initialization exception is thrown during database initialization.
|
||||
*/
|
||||
public class DatabaseInitializationException extends RuntimeException {
|
||||
/**
|
||||
* Instantiates a new Database initialization exception.
|
||||
*
|
||||
* @param t the throwable
|
||||
*/
|
||||
public DatabaseInitializationException(Throwable t) {
|
||||
super(t);
|
||||
}
|
||||
|
||||
/**
|
||||
* Instantiates a new Database initialization exception.
|
||||
*
|
||||
* @param s the message
|
||||
* @param t the throwable
|
||||
*/
|
||||
public DatabaseInitializationException(String s, Throwable t) {
|
||||
super(s, t);
|
||||
}
|
||||
|
||||
/**
|
||||
* Instantiates a new Database initialization exception.
|
||||
*
|
||||
* @param s the message
|
||||
*/
|
||||
public DatabaseInitializationException(String s) {
|
||||
super(s);
|
||||
}
|
||||
}
|
||||
+15
@@ -0,0 +1,15 @@
|
||||
package com.github.alathra.alathranwars.database.exception;
|
||||
|
||||
/**
|
||||
* Database migration exception is thrown whenever a Flyway migration fails.
|
||||
*/
|
||||
public class DatabaseMigrationException extends Exception {
|
||||
/**
|
||||
* Instantiates a new Database migration exception.
|
||||
*
|
||||
* @param t the throwable
|
||||
*/
|
||||
public DatabaseMigrationException(Throwable t) {
|
||||
super(t);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,249 @@
|
||||
package com.github.alathra.alathranwars.database.handler;
|
||||
|
||||
import com.zaxxer.hikari.HikariDataSource;
|
||||
import com.github.alathra.alathranwars.Reloadable;
|
||||
import com.github.alathra.alathranwars.config.ConfigHandler;
|
||||
import com.github.alathra.alathranwars.database.DatabaseType;
|
||||
import com.github.alathra.alathranwars.database.config.DatabaseConfig;
|
||||
import com.github.alathra.alathranwars.database.exception.DatabaseInitializationException;
|
||||
import com.github.alathra.alathranwars.database.exception.DatabaseMigrationException;
|
||||
import com.github.alathra.alathranwars.database.jooq.JooqContext;
|
||||
import com.github.alathra.alathranwars.database.migration.MigrationHandler;
|
||||
import com.github.alathra.alathranwars.database.pool.ConnectionPoolFactory;
|
||||
import org.jetbrains.annotations.NotNull;
|
||||
import org.jetbrains.annotations.Nullable;
|
||||
import org.slf4j.Logger;
|
||||
|
||||
import java.sql.Connection;
|
||||
import java.sql.DatabaseMetaData;
|
||||
import java.sql.SQLException;
|
||||
|
||||
/**
|
||||
* Class that handles HikariCP connection pool, jOOQ and Flyway migrations.
|
||||
*/
|
||||
public class DatabaseHandler implements Reloadable {
|
||||
private JooqContext jooqContext;
|
||||
private HikariDataSource connectionPool;
|
||||
private @Nullable DatabaseConfig databaseConfig = null;
|
||||
private @Nullable ConfigHandler configHandler = null;
|
||||
private final Logger logger;
|
||||
private boolean isRunning = false;
|
||||
|
||||
/**
|
||||
* Instantiates a new Database handler.
|
||||
*
|
||||
* @param configHandler the config handler
|
||||
* @param logger the logger
|
||||
*/
|
||||
public DatabaseHandler(@NotNull ConfigHandler configHandler, Logger logger) {
|
||||
this.configHandler = configHandler;
|
||||
this.logger = logger;
|
||||
}
|
||||
|
||||
/**
|
||||
* Instantiates a new Database handler.
|
||||
*
|
||||
* @param databaseConfig the database config
|
||||
* @param logger the logger
|
||||
*/
|
||||
public DatabaseHandler(@NotNull DatabaseConfig databaseConfig, Logger logger) {
|
||||
this.databaseConfig = databaseConfig;
|
||||
this.logger = logger;
|
||||
}
|
||||
|
||||
/**
|
||||
* On plugin load.
|
||||
*/
|
||||
@Override
|
||||
public void onLoad() {
|
||||
try {
|
||||
// Load database config from file, or use provided databaseConfig from constructor
|
||||
if (configHandler != null)
|
||||
this.databaseConfig = DatabaseConfig.getDatabaseConfigFromFile(configHandler.getDatabaseConfig());
|
||||
|
||||
// Start connection pool
|
||||
startup();
|
||||
} catch (DatabaseInitializationException e) {
|
||||
logger.error("[DB] Database initialization error: {}", e.getMessage());
|
||||
} finally {
|
||||
if (!isRunning()) {
|
||||
logger.warn("[DB] Error while initializing database. Functionality will be limited.");
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* On plugin enable.
|
||||
*/
|
||||
@Override
|
||||
public void onEnable() {
|
||||
}
|
||||
|
||||
/**
|
||||
* On plugin disable.
|
||||
*/
|
||||
@Override
|
||||
public void onDisable() {
|
||||
if (!isRunning())
|
||||
return;
|
||||
|
||||
try {
|
||||
shutdown();
|
||||
} catch (Exception e) {
|
||||
logger.error("[DB] Error while shutting down database:", e);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns if the database is setup and functioning properly.
|
||||
*
|
||||
* @return the boolean
|
||||
*/
|
||||
public boolean isRunning() {
|
||||
return isRunning;
|
||||
}
|
||||
|
||||
/**
|
||||
* Gets database.
|
||||
*
|
||||
* @return the database
|
||||
*/
|
||||
public DatabaseType getDB() {
|
||||
return getDatabaseConfig().getDatabaseType();
|
||||
}
|
||||
|
||||
/**
|
||||
* Gets jooq context.
|
||||
*
|
||||
* @return the jooq context
|
||||
*/
|
||||
public JooqContext getJooqContext() {
|
||||
return jooqContext;
|
||||
}
|
||||
|
||||
/**
|
||||
* Gets connection pool.
|
||||
*
|
||||
* @return the connection pool
|
||||
*/
|
||||
public HikariDataSource getConnectionPool() {
|
||||
return connectionPool;
|
||||
}
|
||||
|
||||
/**
|
||||
* Gets database config.
|
||||
*
|
||||
* @return the database config
|
||||
*/
|
||||
public DatabaseConfig getDatabaseConfig() {
|
||||
if (databaseConfig == null)
|
||||
throw new IllegalStateException("Database config is still null but was accessed in getDB!");
|
||||
|
||||
return databaseConfig;
|
||||
}
|
||||
|
||||
/**
|
||||
* Gets a connection from the connection pool.
|
||||
*
|
||||
* @return the connection
|
||||
* @throws SQLException the sql exception
|
||||
*/
|
||||
@NotNull
|
||||
public Connection getConnection() throws SQLException {
|
||||
if (connectionPool == null)
|
||||
throw new SQLException("[DB] Unable to getConnection a connection from the pool. (connectionPool is null)");
|
||||
|
||||
final Connection connection = connectionPool.getConnection();
|
||||
if (connection == null)
|
||||
throw new SQLException("[DB] Unable to getConnection a connection from the pool. (connectionPool#getConnection returned null)");
|
||||
|
||||
return connection;
|
||||
}
|
||||
|
||||
/**
|
||||
* Creates a connection pool using HikariCP and executes Flyway migrations using jOOQ.
|
||||
*/
|
||||
public void startup() throws DatabaseInitializationException {
|
||||
if (databaseConfig == null)
|
||||
throw new DatabaseInitializationException("Attempted to start a database connection pool but database config is null!");
|
||||
|
||||
if (connectionPool != null)
|
||||
throw new DatabaseInitializationException("Attempted to create a new database connection pool while running! (connectionPool is not null)");
|
||||
|
||||
// Initialize connection pool
|
||||
connectionPool = ConnectionPoolFactory.create(
|
||||
databaseConfig,
|
||||
logger
|
||||
);
|
||||
|
||||
// Check if using invalid database type (Note, these cases throw in the previous method)
|
||||
try (Connection connection = connectionPool.getConnection()) {
|
||||
DatabaseMetaData databaseMetaData = connection.getMetaData();
|
||||
String vendorVersionName = databaseMetaData.getDatabaseProductVersion().toLowerCase();
|
||||
|
||||
if (vendorVersionName.contains("mariadb") && getDB().equals(DatabaseType.MYSQL)) {
|
||||
throw new RuntimeException("Attempted to connect to a mariadb database using mysql as database type! (Please change the type to mariadb in database.yml)");
|
||||
} else if (vendorVersionName.contains("mysql") && getDB().equals(DatabaseType.MARIADB)) {
|
||||
throw new RuntimeException("Attempted to connect to a mysql database using mariadb as database type! (Please change the type to mysql in database.yml)");
|
||||
}
|
||||
} catch (Throwable t) {
|
||||
throw new DatabaseInitializationException(t.getMessage());
|
||||
}
|
||||
|
||||
// Disable JOOQ nonsense
|
||||
System.setProperty("org.jooq.no-logo", "true");
|
||||
System.setProperty("org.jooq.no-tips", "true");
|
||||
|
||||
// Setup JOOQ
|
||||
jooqContext = new JooqContext(
|
||||
databaseConfig.getDatabaseType().getSQLDialect(),
|
||||
databaseConfig.getTablePrefix()
|
||||
);
|
||||
|
||||
// Migrate with Flyway
|
||||
migrate();
|
||||
|
||||
isRunning = true;
|
||||
}
|
||||
|
||||
/**
|
||||
* Closes the connection pool.
|
||||
*/
|
||||
public void shutdown() {
|
||||
if (!isRunning())
|
||||
return;
|
||||
|
||||
logger.info("[DB] Shutting down database pool...");
|
||||
|
||||
if (connectionPool == null) {
|
||||
logger.error("[DB] Skipped closing database pool because the connection pool is null. Was there a previous error which needs to be fixed? Check your logs!");
|
||||
return;
|
||||
}
|
||||
|
||||
if (connectionPool.isClosed()) {
|
||||
logger.error("[DB] Skipped closing database pool: connection is already closed.");
|
||||
return;
|
||||
}
|
||||
|
||||
connectionPool.close();
|
||||
connectionPool = null;
|
||||
isRunning = false;
|
||||
|
||||
logger.info("[DB] Closed database pool.");
|
||||
}
|
||||
|
||||
/**
|
||||
* Execute database migrations with Flyway.
|
||||
*/
|
||||
private void migrate() throws DatabaseInitializationException {
|
||||
try {
|
||||
new MigrationHandler(
|
||||
connectionPool,
|
||||
databaseConfig
|
||||
)
|
||||
.migrate();
|
||||
} catch (DatabaseMigrationException e) {
|
||||
throw new DatabaseInitializationException("Failed to migrate database schemas to new version! Please backup your database and report the issue.", e);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,103 @@
|
||||
package com.github.alathra.alathranwars.database.jooq;
|
||||
|
||||
import com.github.alathra.alathranwars.database.config.DatabaseConfig;
|
||||
import org.jetbrains.annotations.TestOnly;
|
||||
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 Pattern MATCH_ALL_EXCEPT_INFORMATION_SCHEMA = Pattern.compile("^(?!INFORMATION_SCHEMA)(.*?)$");
|
||||
private static final Pattern MATCH_ALL = Pattern.compile("^(.*?)$");
|
||||
private final SQLDialect dialect;
|
||||
private final String replacement; //
|
||||
|
||||
/**
|
||||
* Instantiates a new Jooq context.
|
||||
*
|
||||
* @param databaseConfig the database config
|
||||
*/
|
||||
@TestOnly
|
||||
public JooqContext(DatabaseConfig databaseConfig) {
|
||||
this.dialect = databaseConfig.getDatabaseType().getSQLDialect();
|
||||
this.replacement = "%s$0".formatted(databaseConfig.getTablePrefix());
|
||||
}
|
||||
|
||||
/**
|
||||
* Instantiates a new Jooq context.
|
||||
*
|
||||
* @param dialect the getSQLDialect
|
||||
* @param tablePrefix the prefix to add in front of tables
|
||||
*/
|
||||
public JooqContext(SQLDialect dialect, String tablePrefix) {
|
||||
this.dialect = dialect;
|
||||
this.replacement = "%s$0".formatted(tablePrefix);
|
||||
}
|
||||
|
||||
/**
|
||||
* 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)
|
||||
)
|
||||
)
|
||||
);
|
||||
}
|
||||
}
|
||||
+14
-22
@@ -1,7 +1,7 @@
|
||||
package com.github.alathra.alathranwars.db.flyway;
|
||||
package com.github.alathra.alathranwars.database.migration;
|
||||
|
||||
import com.github.alathra.alathranwars.db.DatabaseType;
|
||||
import com.github.milkdrinkers.Crate.Config;
|
||||
import com.github.alathra.alathranwars.database.config.DatabaseConfig;
|
||||
import com.github.alathra.alathranwars.database.exception.DatabaseMigrationException;
|
||||
import org.flywaydb.core.Flyway;
|
||||
import org.flywaydb.core.api.ClassProvider;
|
||||
import org.flywaydb.core.api.FlywayException;
|
||||
@@ -14,45 +14,37 @@ import java.util.Map;
|
||||
/**
|
||||
* Handles Flyway migrations.
|
||||
*/
|
||||
public class DatabaseMigrationHandler {
|
||||
public class MigrationHandler {
|
||||
// List of Java migrations
|
||||
private final List<Class<? extends JavaMigration>> migrations = List.of(
|
||||
// V3__Example.class
|
||||
);
|
||||
|
||||
private final Config config;
|
||||
private final DataSource dataSource;
|
||||
private final DatabaseType databaseType;
|
||||
private final DatabaseConfig databaseConfig;
|
||||
private Flyway flyway;
|
||||
|
||||
/**
|
||||
* Instantiates a new Database migration handler.
|
||||
*
|
||||
* @param config the config
|
||||
* @param dataSource the data source
|
||||
* @param databaseType the database type
|
||||
* @param databaseConfig the database config
|
||||
*/
|
||||
public DatabaseMigrationHandler(Config config, DataSource dataSource, DatabaseType databaseType) {
|
||||
this.config = config;
|
||||
public MigrationHandler(DataSource dataSource, DatabaseConfig databaseConfig) {
|
||||
this.dataSource = dataSource;
|
||||
this.databaseType = databaseType;
|
||||
this.databaseConfig = databaseConfig;
|
||||
initializeFlywayInstance();
|
||||
}
|
||||
|
||||
private void initializeFlywayInstance() {
|
||||
final ClassProvider<JavaMigration> javaMigrationClassProvider = new FlywayMigrationsProvider(migrations);
|
||||
final String SQL_TABLE_PREFIX = config.getOrDefault("db.prefix", "example_");
|
||||
final ClassProvider<JavaMigration> javaMigrationClassProvider = new MigrationProvider(migrations);
|
||||
final Map<String, String> 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()
|
||||
"tablePrefix", databaseConfig.getTablePrefix()
|
||||
);
|
||||
|
||||
this.flyway = Flyway
|
||||
.configure(getClass().getClassLoader())
|
||||
.loggers("slf4j")
|
||||
.baselineOnMigrate(true)
|
||||
.baselineVersion("0.0")
|
||||
.validateMigrationNaming(true)
|
||||
@@ -62,7 +54,7 @@ public class DatabaseMigrationHandler {
|
||||
"classpath:database-migrations",
|
||||
"db/migration"
|
||||
)
|
||||
.table(SQL_TABLE_PREFIX + "schema_history") // Configure tables and migrations
|
||||
.table(databaseConfig.getTablePrefix() + "schema_history") // Configure tables and migrations
|
||||
.placeholders(SQL_PLACEHOLDERS)
|
||||
.load();
|
||||
}
|
||||
@@ -92,7 +84,7 @@ public class DatabaseMigrationHandler {
|
||||
*/
|
||||
public void repair() throws DatabaseMigrationException {
|
||||
try {
|
||||
if (config.getOrDefault("db.repair", false))
|
||||
if (databaseConfig.isRepair())
|
||||
this.flyway.repair();
|
||||
} catch (FlywayException e) {
|
||||
throw new DatabaseMigrationException(e);
|
||||
+11
-3
@@ -1,4 +1,4 @@
|
||||
package com.github.alathra.alathranwars.db.flyway;
|
||||
package com.github.alathra.alathranwars.database.migration;
|
||||
|
||||
import org.flywaydb.core.api.ClassProvider;
|
||||
import org.flywaydb.core.api.migration.JavaMigration;
|
||||
@@ -6,10 +6,18 @@ import org.flywaydb.core.api.migration.JavaMigration;
|
||||
import java.util.Collection;
|
||||
import java.util.List;
|
||||
|
||||
public record FlywayMigrationsProvider(
|
||||
/**
|
||||
* Flyway migrations provider. Convenience/utility record for using Java migrations with Flyway.
|
||||
*/
|
||||
public record MigrationProvider(
|
||||
List<Class<? extends JavaMigration>> migrations
|
||||
) implements ClassProvider<JavaMigration> {
|
||||
public FlywayMigrationsProvider(List<Class<? extends JavaMigration>> migrations) {
|
||||
/**
|
||||
* Instantiates a new Flyway migrations provider.
|
||||
*
|
||||
* @param migrations the migrations
|
||||
*/
|
||||
public MigrationProvider(List<Class<? extends JavaMigration>> migrations) {
|
||||
this.migrations = List.copyOf(migrations);
|
||||
}
|
||||
|
||||
+34
@@ -0,0 +1,34 @@
|
||||
package com.github.alathra.alathranwars.database.migration.migrations;
|
||||
|
||||
import com.github.alathra.alathranwars.utility.DB;
|
||||
import org.flywaydb.core.api.migration.BaseJavaMigration;
|
||||
import org.flywaydb.core.api.migration.Context;
|
||||
import org.jooq.DSLContext;
|
||||
|
||||
import static org.jooq.impl.DSL.field;
|
||||
import static org.jooq.impl.DSL.table;
|
||||
import static org.jooq.impl.SQLDataType.VARCHAR;
|
||||
|
||||
/**
|
||||
* Example Java Flyway migration using jOOQ.
|
||||
*/
|
||||
public class V3__Example extends BaseJavaMigration {
|
||||
@Override
|
||||
public void migrate(final Context flywayContext) throws Exception {
|
||||
try {
|
||||
final DSLContext context = DB.getContext(flywayContext.getConnection());
|
||||
|
||||
context
|
||||
.alterTable(table("test"))
|
||||
.addColumn(field("memes", VARCHAR((32))))
|
||||
.execute();
|
||||
|
||||
context
|
||||
.alterTableIfExists(table("test"))
|
||||
.addColumnIfNotExists(field("column_name", VARCHAR(32).notNull()/*.defaultValue("default")*/))
|
||||
.execute();
|
||||
} catch (Exception e) {
|
||||
// Logger.pool().error(e.getMessage());
|
||||
}
|
||||
}
|
||||
}
|
||||
+88
@@ -0,0 +1,88 @@
|
||||
package com.github.alathra.alathranwars.database.pool;
|
||||
|
||||
import com.zaxxer.hikari.HikariConfig;
|
||||
import com.github.alathra.alathranwars.database.DatabaseType;
|
||||
import com.github.alathra.alathranwars.database.config.DatabaseConfig;
|
||||
import com.github.alathra.alathranwars.database.config.DatabaseConfigBuilder;
|
||||
import com.github.alathra.alathranwars.database.exception.DatabaseInitializationException;
|
||||
|
||||
import java.nio.file.Path;
|
||||
import java.util.Optional;
|
||||
|
||||
import static com.github.alathra.alathranwars.database.DatabaseType.*;
|
||||
|
||||
public abstract class ConnectionPoolConfigFactory {
|
||||
public static HikariConfig get() throws DatabaseInitializationException {
|
||||
return get(new DatabaseConfigBuilder().build());
|
||||
}
|
||||
|
||||
public static HikariConfig get(DatabaseConfig config) throws DatabaseInitializationException {
|
||||
HikariConfig hikariConfig = new HikariConfig();
|
||||
|
||||
final DatabaseType databaseType = config.getDatabaseType();
|
||||
|
||||
// Create RDBMS specific jdbc url
|
||||
final String jdbcUrl = switch (databaseType) {
|
||||
case SQLITE, H2 -> {
|
||||
final Optional<Path> path = config.getPath();
|
||||
if (path.isEmpty())
|
||||
throw new DatabaseInitializationException("Path was null when setting up database!");
|
||||
|
||||
final String fileName = databaseType.equals(SQLITE) ? "database.sqlite" : "database";
|
||||
|
||||
yield "jdbc:%s:file:%s%s".formatted(
|
||||
databaseType.getJdbcPrefix(),
|
||||
path.get().resolve(fileName).toAbsolutePath(),
|
||||
databaseType.getDefaultConnectionProperties()
|
||||
);
|
||||
}
|
||||
case MYSQL, MARIADB -> {
|
||||
yield "jdbc:%s://%s:%s/%s%s%s".formatted(
|
||||
databaseType.getJdbcPrefix(),
|
||||
config.getHost(),
|
||||
config.getPort(),
|
||||
config.getDatabase(),
|
||||
databaseType.getDefaultConnectionProperties(),
|
||||
config.getConnectionProperties()
|
||||
);
|
||||
}
|
||||
};
|
||||
|
||||
// Set username & password
|
||||
switch (databaseType) {
|
||||
case SQLITE, H2 -> {
|
||||
hikariConfig.setUsername("sa");
|
||||
hikariConfig.setPassword("");
|
||||
}
|
||||
case MYSQL, MARIADB -> {
|
||||
hikariConfig.setUsername(config.getUsername());
|
||||
hikariConfig.setPassword(config.getPassword());
|
||||
}
|
||||
}
|
||||
|
||||
// Set pool configuration
|
||||
hikariConfig.setMaximumPoolSize(config.getMaxPoolSize());
|
||||
hikariConfig.setMinimumIdle(config.getMinIdle());
|
||||
hikariConfig.setMaxLifetime(config.getMaxLifeTime());
|
||||
hikariConfig.setKeepaliveTime(config.getKeepAliveTime());
|
||||
hikariConfig.setConnectionTimeout(config.getConnectionTimeout());
|
||||
|
||||
// Set database driver class and jdbc url
|
||||
try {
|
||||
Class.forName(databaseType.getDataSourceClassName());
|
||||
} catch (ClassNotFoundException e) {
|
||||
throw new DatabaseInitializationException("Failed to initialise jdbc driver!", e);
|
||||
}
|
||||
hikariConfig.setDataSourceClassName(databaseType.getDataSourceClassName());
|
||||
hikariConfig.addDataSourceProperty("url", jdbcUrl);
|
||||
|
||||
// Misc pool configuration
|
||||
hikariConfig.setPoolName("%s-hikari".formatted(databaseType.getJdbcPrefix()));
|
||||
hikariConfig.setAutoCommit(true);
|
||||
hikariConfig.setTransactionIsolation("TRANSACTION_REPEATABLE_READ");
|
||||
hikariConfig.setIsolateInternalQueries(true);
|
||||
hikariConfig.setConnectionInitSql(databaseType.getConnectionInitSql());
|
||||
|
||||
return hikariConfig;
|
||||
}
|
||||
}
|
||||
+19
@@ -0,0 +1,19 @@
|
||||
package com.github.alathra.alathranwars.database.pool;
|
||||
|
||||
import com.zaxxer.hikari.HikariConfig;
|
||||
import com.zaxxer.hikari.HikariDataSource;
|
||||
import com.github.alathra.alathranwars.database.config.DatabaseConfig;
|
||||
import com.github.alathra.alathranwars.database.exception.DatabaseInitializationException;
|
||||
import org.slf4j.Logger;
|
||||
|
||||
public abstract class ConnectionPoolFactory {
|
||||
public static HikariDataSource create(DatabaseConfig databaseConfig, Logger logger) throws DatabaseInitializationException {
|
||||
try {
|
||||
HikariConfig hikariConfig = ConnectionPoolConfigFactory.get(databaseConfig);
|
||||
|
||||
return new HikariDataSource(hikariConfig);
|
||||
} catch (Throwable t) {
|
||||
throw new DatabaseInitializationException("Failed to initialize database pool during startup. Are you using the correct database type?");
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1,303 +0,0 @@
|
||||
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.");
|
||||
}
|
||||
}
|
||||
-7
@@ -1,7 +0,0 @@
|
||||
package com.github.alathra.alathranwars.db.flyway;
|
||||
|
||||
public class DatabaseMigrationException extends Exception {
|
||||
public DatabaseMigrationException(Throwable t) {
|
||||
super(t);
|
||||
}
|
||||
}
|
||||
@@ -1,22 +0,0 @@
|
||||
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());
|
||||
}*/
|
||||
}
|
||||
}
|
||||
@@ -1,93 +0,0 @@
|
||||
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);
|
||||
}
|
||||
}
|
||||
+49
@@ -0,0 +1,49 @@
|
||||
package com.github.alathra.alathranwars.events.battle;
|
||||
|
||||
import com.github.alathra.alathranwars.conflict.battle.Battle;
|
||||
import com.github.alathra.alathranwars.conflict.war.War;
|
||||
import com.github.alathra.alathranwars.enums.battle.BattleSide;
|
||||
import org.bukkit.entity.Player;
|
||||
import org.bukkit.event.Event;
|
||||
import org.bukkit.event.HandlerList;
|
||||
import org.jetbrains.annotations.NotNull;
|
||||
|
||||
public class PlayerEnteredBattlefieldEvent extends Event {
|
||||
private static final HandlerList HANDLER_LIST = new HandlerList();
|
||||
private final Player player;
|
||||
private final War war;
|
||||
private final Battle battle;
|
||||
private final BattleSide battleSide;
|
||||
|
||||
public PlayerEnteredBattlefieldEvent(Player player, War war, Battle battle, BattleSide battleSide) {
|
||||
this.player = player;
|
||||
this.war = war;
|
||||
this.battle = battle;
|
||||
this.battleSide = battleSide;
|
||||
}
|
||||
|
||||
@Override
|
||||
public @NotNull HandlerList getHandlers() {
|
||||
return HANDLER_LIST;
|
||||
}
|
||||
|
||||
public static HandlerList getHandlerList() {
|
||||
return HANDLER_LIST;
|
||||
}
|
||||
|
||||
public Player getPlayer() {
|
||||
return player;
|
||||
}
|
||||
|
||||
public War getWar() {
|
||||
return war;
|
||||
}
|
||||
|
||||
public Battle getBattle() {
|
||||
return battle;
|
||||
}
|
||||
|
||||
public BattleSide getBattleSide() {
|
||||
return battleSide;
|
||||
}
|
||||
}
|
||||
+49
@@ -0,0 +1,49 @@
|
||||
package com.github.alathra.alathranwars.events.battle;
|
||||
|
||||
import com.github.alathra.alathranwars.conflict.battle.Battle;
|
||||
import com.github.alathra.alathranwars.conflict.war.War;
|
||||
import com.github.alathra.alathranwars.enums.battle.BattleSide;
|
||||
import org.bukkit.entity.Player;
|
||||
import org.bukkit.event.Event;
|
||||
import org.bukkit.event.HandlerList;
|
||||
import org.jetbrains.annotations.NotNull;
|
||||
|
||||
public class PlayerLeftBattlefieldEvent extends Event {
|
||||
private static final HandlerList HANDLER_LIST = new HandlerList();
|
||||
private final Player player;
|
||||
private final War war;
|
||||
private final Battle battle;
|
||||
private final BattleSide battleSide;
|
||||
|
||||
public PlayerLeftBattlefieldEvent(Player player, War war, Battle battle, BattleSide battleSide) {
|
||||
this.player = player;
|
||||
this.war = war;
|
||||
this.battle = battle;
|
||||
this.battleSide = battleSide;
|
||||
}
|
||||
|
||||
@Override
|
||||
public @NotNull HandlerList getHandlers() {
|
||||
return HANDLER_LIST;
|
||||
}
|
||||
|
||||
public static HandlerList getHandlerList() {
|
||||
return HANDLER_LIST;
|
||||
}
|
||||
|
||||
public Player getPlayer() {
|
||||
return player;
|
||||
}
|
||||
|
||||
public War getWar() {
|
||||
return war;
|
||||
}
|
||||
|
||||
public Battle getBattle() {
|
||||
return battle;
|
||||
}
|
||||
|
||||
public BattleSide getBattleSide() {
|
||||
return battleSide;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,56 @@
|
||||
package com.github.alathra.alathranwars.hook;
|
||||
|
||||
import com.github.alathra.alathranwars.Reloadable;
|
||||
import org.bukkit.Bukkit;
|
||||
import org.bukkit.plugin.Plugin;
|
||||
|
||||
public abstract class AbstractPluginHook<T> implements Reloadable {
|
||||
private final String pluginName;
|
||||
private T pluginHook;
|
||||
|
||||
public AbstractPluginHook(String pluginName) {
|
||||
this.pluginName = pluginName;
|
||||
}
|
||||
|
||||
@Override
|
||||
public void onLoad() {
|
||||
}
|
||||
|
||||
@Override
|
||||
public void onEnable() {
|
||||
if (!Bukkit.getPluginManager().isPluginEnabled(pluginName))
|
||||
return;
|
||||
|
||||
setHook(Bukkit.getPluginManager().getPlugin(pluginName));
|
||||
}
|
||||
|
||||
@Override
|
||||
public void onDisable() {
|
||||
setHook(null);
|
||||
}
|
||||
|
||||
/**
|
||||
* Check if this plugin hook is loaded and ready for use.
|
||||
* @return whether this plugin hook is loaded or not
|
||||
*/
|
||||
public boolean isHookLoaded() {
|
||||
return pluginHook != null;
|
||||
}
|
||||
|
||||
/**
|
||||
* Gets plugin. Should only be used following {@link #isHookLoaded()}.
|
||||
*
|
||||
* @return plugin instance
|
||||
*/
|
||||
public T getHook() {
|
||||
if (!isHookLoaded())
|
||||
throw new IllegalStateException("Attempted to access a plugin hook for plugin (%s) when it is unavailable!".formatted(pluginName));
|
||||
|
||||
return pluginHook;
|
||||
}
|
||||
|
||||
@SuppressWarnings("unchecked")
|
||||
private void setHook(Plugin plugin) {
|
||||
this.pluginHook = (T) plugin;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,75 @@
|
||||
package com.github.alathra.alathranwars.hook;
|
||||
|
||||
import com.github.alathra.alathranwars.AlathranWars;
|
||||
import com.github.alathra.alathranwars.Reloadable;
|
||||
import org.bstats.bukkit.Metrics;
|
||||
import org.jetbrains.annotations.ApiStatus;
|
||||
import org.jetbrains.annotations.Nullable;
|
||||
|
||||
/**
|
||||
* A hook to interface with <a href="https://github.com/Bastian/bstats-metrics">BStats</a>.
|
||||
*/
|
||||
public class BStatsHook implements Reloadable {
|
||||
private final static int BSTATS_ID = 23308;
|
||||
private final AlathranWars plugin;
|
||||
private @Nullable Metrics hook;
|
||||
|
||||
/**
|
||||
* Instantiates a new BStats hook.
|
||||
*
|
||||
* @param plugin the plugin instance
|
||||
*/
|
||||
public BStatsHook(AlathranWars plugin) {
|
||||
this.plugin = plugin;
|
||||
}
|
||||
|
||||
@Override
|
||||
public void onLoad() {
|
||||
}
|
||||
|
||||
@Override
|
||||
public void onEnable() {
|
||||
// Catch startup errors for bstats
|
||||
try {
|
||||
setHook(new Metrics(plugin, BSTATS_ID));
|
||||
} catch (Exception ignored) {
|
||||
setHook(null);
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
public void onDisable() {
|
||||
getHook().shutdown();
|
||||
setHook(null);
|
||||
}
|
||||
|
||||
/**
|
||||
* Check if the BStats hook is loaded and ready for use.
|
||||
* @return whether the BStats metrics hook is loaded or not
|
||||
*/
|
||||
public boolean isHookLoaded() {
|
||||
return hook != null;
|
||||
}
|
||||
|
||||
/**
|
||||
* Gets BStats metrics instance. Should only be used following {@link #isHookLoaded()}.
|
||||
*
|
||||
* @return instance
|
||||
*/
|
||||
public Metrics getHook() {
|
||||
if (!isHookLoaded())
|
||||
throw new IllegalStateException("Attempted to access BStats metrics instance hook when it is unavailable!");
|
||||
|
||||
return hook;
|
||||
}
|
||||
|
||||
/**
|
||||
* Sets the BStats metrics instance.
|
||||
*
|
||||
* @param hook The BStats metrics instance {@link Metrics}
|
||||
*/
|
||||
@ApiStatus.Internal
|
||||
private void setHook(@Nullable Metrics hook) {
|
||||
this.hook = hook;
|
||||
}
|
||||
}
|
||||
+6
-6
@@ -1,4 +1,4 @@
|
||||
package com.github.alathra.alathranwars.hooks;
|
||||
package com.github.alathra.alathranwars.hook;
|
||||
|
||||
import com.github.alathra.alathranwars.conflict.war.War;
|
||||
import com.github.alathra.alathranwars.conflict.war.WarController;
|
||||
@@ -27,23 +27,23 @@ public class NameColorHandler {
|
||||
}
|
||||
|
||||
public void calculatePlayerColors(Player p) {
|
||||
if (!WarController.getInstance().isPlayerInAnyWars(p)) {
|
||||
if (!WarController.getInstance().isInAnyWars(p)) {
|
||||
playerColor.remove(p);
|
||||
playerInitial.remove(p);
|
||||
return;
|
||||
}
|
||||
|
||||
Optional<War> war = WarController.getInstance().getPlayerWars(p).stream().findFirst();
|
||||
Optional<War> war = WarController.getInstance().getWars(p).stream().findFirst();
|
||||
|
||||
if (war.isEmpty())
|
||||
return;
|
||||
|
||||
final boolean isPlayerSurrendered = war.get().getSide1().isPlayerSurrendered(p) || war.get().getSide2().isPlayerSurrendered(p);
|
||||
final boolean isPlayerSurrendered = war.get().getSide1().isSurrendered(p) || war.get().getSide2().isSurrendered(p);
|
||||
|
||||
if (isPlayerSurrendered)
|
||||
return;
|
||||
|
||||
final boolean isSideOne = war.get().getSide1().isPlayerOnSide(p);
|
||||
final boolean isSideOne = war.get().getSide1().isOnSide(p);
|
||||
|
||||
if (isSideOne) {
|
||||
playerColor.put(p, "<red>");
|
||||
@@ -55,7 +55,7 @@ public class NameColorHandler {
|
||||
|
||||
public boolean isPlayerUsingModifiedName(Player p) {
|
||||
calculatePlayerColors(p);
|
||||
return WarController.getInstance().isPlayerInAnyWars(p);
|
||||
return WarController.getInstance().isInAnyWars(p);
|
||||
}
|
||||
|
||||
public String getPlayerTabNameColor(Player p) {
|
||||
@@ -0,0 +1,72 @@
|
||||
package com.github.alathra.alathranwars.hook;
|
||||
|
||||
import com.github.alathra.alathranwars.AlathranWars;
|
||||
import me.clip.placeholderapi.expansion.PlaceholderExpansion;
|
||||
import org.bukkit.entity.Player;
|
||||
import org.jetbrains.annotations.NotNull;
|
||||
import org.jetbrains.annotations.Nullable;
|
||||
|
||||
public class PAPIExpansion extends PlaceholderExpansion {
|
||||
private final AlathranWars plugin;
|
||||
private final NameColorHandler colorHandler;
|
||||
|
||||
public PAPIExpansion(AlathranWars plugin, NameColorHandler colorHandler) {
|
||||
this.plugin = plugin;
|
||||
this.colorHandler = colorHandler;
|
||||
}
|
||||
|
||||
@Override
|
||||
public @Nullable String getRequiredPlugin() {
|
||||
return "AlathranWars";
|
||||
}
|
||||
|
||||
@Override
|
||||
@SuppressWarnings("UnstableApiUsage")
|
||||
public @NotNull String getIdentifier() {
|
||||
return plugin.getPluginMeta().getName().replace(' ', '_').toLowerCase();
|
||||
}
|
||||
|
||||
@Override
|
||||
@SuppressWarnings("UnstableApiUsage")
|
||||
public @NotNull String getAuthor() {
|
||||
return String.join(", ", plugin.getPluginMeta().getAuthors());
|
||||
}
|
||||
|
||||
@Override
|
||||
@SuppressWarnings("UnstableApiUsage")
|
||||
public @NotNull String getVersion() {
|
||||
return plugin.getPluginMeta().getVersion();
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean persist() {
|
||||
return true; // This needs to be true, or PlaceholderAPI will unregister the expansion during a plugin reload.
|
||||
}
|
||||
|
||||
@Override
|
||||
public @Nullable String onPlaceholderRequest(Player p, @NotNull String params) {
|
||||
return switch (params) {
|
||||
case "player_tablist" -> {
|
||||
if (colorHandler.isPlayerUsingModifiedName(p))
|
||||
yield colorHandler.getPlayerTabNameColor(p) + "%essentials_nickname_stripped%";
|
||||
yield "%essentials_nickname%";
|
||||
}
|
||||
case "player_nametag" -> {
|
||||
if (colorHandler.isPlayerUsingModifiedName(p))
|
||||
yield colorHandler.getPlayerNameColor(p) + "%essentials_nickname_stripped%";
|
||||
yield "%essentials_nickname%";
|
||||
}
|
||||
case "player_tablist_maquillage" -> {
|
||||
if (colorHandler.isPlayerUsingModifiedName(p))
|
||||
yield colorHandler.getPlayerTabNameColor(p) + "%essentials_nickname_stripped%";
|
||||
yield "%maquillage_namecolor_essentialsnick%";
|
||||
}
|
||||
case "player_nametag_maquillage" -> {
|
||||
if (colorHandler.isPlayerUsingModifiedName(p))
|
||||
yield colorHandler.getPlayerNameColor(p) + "%essentials_nickname_stripped%";
|
||||
yield "%maquillage_namecolor_essentialsnick%";
|
||||
}
|
||||
default -> null;
|
||||
};
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,44 @@
|
||||
package com.github.alathra.alathranwars.hook;
|
||||
|
||||
import com.github.alathra.alathranwars.AlathranWars;
|
||||
import com.github.alathra.alathranwars.Reloadable;
|
||||
import org.bukkit.Bukkit;
|
||||
|
||||
/**
|
||||
* A hook to interface with <a href="https://wiki.placeholderapi.com/">PlaceholderAPI</a>.
|
||||
*/
|
||||
public class PAPIHook implements Reloadable {
|
||||
private final AlathranWars plugin;
|
||||
private final static String pluginName = "PlaceholderAPI";
|
||||
private PAPIExpansion PAPIExpansion;
|
||||
|
||||
/**
|
||||
* Instantiates a new PlaceholderAPI hook.
|
||||
*
|
||||
* @param plugin the plugin instance
|
||||
*/
|
||||
public PAPIHook(AlathranWars plugin) {
|
||||
this.plugin = plugin;
|
||||
}
|
||||
|
||||
@Override
|
||||
public void onLoad() {
|
||||
}
|
||||
|
||||
@Override
|
||||
public void onEnable() {
|
||||
if (!Bukkit.getPluginManager().isPluginEnabled(pluginName))
|
||||
return;
|
||||
|
||||
PAPIExpansion = new PAPIExpansion(plugin, NameColorHandler.getInstance());
|
||||
}
|
||||
|
||||
@Override
|
||||
public void onDisable() {
|
||||
if (!Bukkit.getPluginManager().isPluginEnabled(pluginName))
|
||||
return;
|
||||
|
||||
PAPIExpansion.unregister();
|
||||
PAPIExpansion = null;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,105 @@
|
||||
package com.github.alathra.alathranwars.hook;
|
||||
|
||||
import com.comphenix.protocol.ProtocolLibrary;
|
||||
import com.comphenix.protocol.ProtocolManager;
|
||||
import com.comphenix.protocol.scheduler.ProtocolScheduler;
|
||||
import com.github.alathra.alathranwars.AlathranWars;
|
||||
import com.github.alathra.alathranwars.Reloadable;
|
||||
import org.bukkit.Bukkit;
|
||||
import org.jetbrains.annotations.ApiStatus;
|
||||
import org.jetbrains.annotations.Nullable;
|
||||
|
||||
/**
|
||||
* A hook to interface with <a href="https://github.com/dmulloy2/ProtocolLib">ProtocolLib</a>.
|
||||
*/
|
||||
public class ProtocolLibHook implements Reloadable {
|
||||
private final AlathranWars plugin;
|
||||
private final static String pluginName = "ProtocolLib";
|
||||
private @Nullable ProtocolManager protocolManager;
|
||||
private @Nullable ProtocolScheduler protocolScheduler;
|
||||
|
||||
/**
|
||||
* Instantiates a new ProtocolLib hook.
|
||||
*
|
||||
* @param plugin the plugin instance
|
||||
*/
|
||||
public ProtocolLibHook(AlathranWars plugin) {
|
||||
this.plugin = plugin;
|
||||
}
|
||||
|
||||
@Override
|
||||
public void onLoad() {
|
||||
}
|
||||
|
||||
@Override
|
||||
public void onEnable() {
|
||||
if (!Bukkit.getPluginManager().isPluginEnabled(pluginName))
|
||||
return;
|
||||
|
||||
setProtocolManager(ProtocolLibrary.getProtocolManager());
|
||||
setProtocolScheduler(ProtocolLibrary.getScheduler());
|
||||
}
|
||||
|
||||
@Override
|
||||
public void onDisable() {
|
||||
if (!Bukkit.getPluginManager().isPluginEnabled(pluginName))
|
||||
return;
|
||||
|
||||
setProtocolScheduler(null);
|
||||
setProtocolManager(null);
|
||||
}
|
||||
|
||||
/**
|
||||
* Check if the ProtocolLib hook is loaded and ready for use.
|
||||
* @return whether the ProtocolLib hook is loaded or not
|
||||
*/
|
||||
public boolean isHookLoaded() {
|
||||
return protocolManager != null &&
|
||||
!protocolManager.isClosed() &&
|
||||
protocolScheduler != null;
|
||||
}
|
||||
|
||||
/**
|
||||
* Gets ProtocolManager instance. Should only be used following {@link #isHookLoaded()}.
|
||||
*
|
||||
* @return instance
|
||||
*/
|
||||
public ProtocolManager getProtocolManager() {
|
||||
if (!isHookLoaded())
|
||||
throw new IllegalStateException("Attempted to access ProtocolLib hook when it is unavailable!");
|
||||
|
||||
return protocolManager;
|
||||
}
|
||||
|
||||
/**
|
||||
* Sets the ProtocolManager instance.
|
||||
*
|
||||
* @param protocolManager The ProtocolLib ProtocolManager instance {@link ProtocolManager}
|
||||
*/
|
||||
@ApiStatus.Internal
|
||||
private void setProtocolManager(@Nullable ProtocolManager protocolManager) {
|
||||
this.protocolManager = protocolManager;
|
||||
}
|
||||
|
||||
/**
|
||||
* Gets ProtocolScheduler instance. Should only be used following {@link #isHookLoaded()}.
|
||||
*
|
||||
* @return instance
|
||||
*/
|
||||
public ProtocolScheduler getProtocolScheduler() {
|
||||
if (!isHookLoaded())
|
||||
throw new IllegalStateException("Attempted to access ProtocolLib hook when it is unavailable!");
|
||||
|
||||
return protocolScheduler;
|
||||
}
|
||||
|
||||
/**
|
||||
* Sets the ProtocolScheduler instance.
|
||||
*
|
||||
* @param hook The ProtocolLib ProtocolScheduler instance {@link ProtocolScheduler}
|
||||
*/
|
||||
@ApiStatus.Internal
|
||||
private void setProtocolScheduler(@Nullable ProtocolScheduler hook) {
|
||||
this.protocolScheduler = hook;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,150 @@
|
||||
package com.github.alathra.alathranwars.hook;
|
||||
|
||||
import com.github.alathra.alathranwars.AlathranWars;
|
||||
import com.github.alathra.alathranwars.Reloadable;
|
||||
import net.milkbowl.vault.chat.Chat;
|
||||
import net.milkbowl.vault.economy.Economy;
|
||||
import net.milkbowl.vault.permission.Permission;
|
||||
import org.bukkit.plugin.RegisteredServiceProvider;
|
||||
import org.jetbrains.annotations.ApiStatus;
|
||||
import org.jetbrains.annotations.Nullable;
|
||||
|
||||
/**
|
||||
* A hook to interface with the <a href="https://github.com/MilkBowl/VaultAPI">Vault API</a>.
|
||||
*/
|
||||
public class VaultHook implements Reloadable {
|
||||
private final AlathranWars plugin;
|
||||
private @Nullable RegisteredServiceProvider<Economy> rspEconomy;
|
||||
private @Nullable RegisteredServiceProvider<Permission> rspPermissions;
|
||||
private @Nullable RegisteredServiceProvider<Chat> rspChat;
|
||||
|
||||
/**
|
||||
* Instantiates a new Vault hook.
|
||||
*
|
||||
* @param plugin the plugin instance
|
||||
*/
|
||||
public VaultHook(AlathranWars plugin) {
|
||||
this.plugin = plugin;
|
||||
}
|
||||
|
||||
@Override
|
||||
public void onLoad() {
|
||||
}
|
||||
|
||||
@Override
|
||||
public void onEnable() {
|
||||
if (!isVaultLoaded()) return;
|
||||
|
||||
setEconomy(plugin.getServer().getServicesManager().getRegistration(Economy.class));
|
||||
setPermissions(plugin.getServer().getServicesManager().getRegistration(Permission.class));
|
||||
setChat(plugin.getServer().getServicesManager().getRegistration(Chat.class));
|
||||
}
|
||||
|
||||
@Override
|
||||
public void onDisable() {
|
||||
if (!isVaultLoaded()) return;
|
||||
|
||||
setEconomy(null);
|
||||
setPermissions(null);
|
||||
setChat(null);
|
||||
}
|
||||
|
||||
/**
|
||||
* Check if Vault is present on the server.
|
||||
*
|
||||
* @return the boolean
|
||||
*/
|
||||
public boolean isVaultLoaded() {
|
||||
return plugin.getServer().getPluginManager().isPluginEnabled("Vault");
|
||||
}
|
||||
|
||||
/**
|
||||
* Check if a vault economy plugin is loaded.
|
||||
*
|
||||
* @return boolean
|
||||
*/
|
||||
public boolean isEconomyLoaded() {
|
||||
return rspEconomy != null && getEconomy() != null;
|
||||
}
|
||||
|
||||
/**
|
||||
* Gets vault economy instance. Should only be used after {@link #isEconomyLoaded()}.
|
||||
*
|
||||
* @return vault instance
|
||||
*/
|
||||
public Economy getEconomy() {
|
||||
if (rspEconomy == null)
|
||||
throw new NullPointerException("The plugin tried to use Vault without it being loaded. Use the VaultHook#isVaultLoaded method before using vault methods.");
|
||||
return rspEconomy.getProvider();
|
||||
}
|
||||
|
||||
/**
|
||||
* Sets the vault economy service provider.
|
||||
*
|
||||
* @param rsp The service provider providing {@link Economy}
|
||||
*/
|
||||
@ApiStatus.Internal
|
||||
public void setEconomy(@Nullable RegisteredServiceProvider<Economy> rsp) {
|
||||
this.rspEconomy = rsp;
|
||||
}
|
||||
|
||||
/**
|
||||
* Check if a vault permissions plugin is loaded.
|
||||
*
|
||||
* @return boolean
|
||||
*/
|
||||
public boolean isPermissionsLoaded() {
|
||||
return rspPermissions != null && getPermissions() != null;
|
||||
}
|
||||
|
||||
/**
|
||||
* Gets vault permissions instance. Should only be used after {@link #isPermissionsLoaded()}.
|
||||
*
|
||||
* @return vault instance
|
||||
*/
|
||||
public Permission getPermissions() {
|
||||
if (rspPermissions == null)
|
||||
throw new NullPointerException("The plugin tried to use Vault without it being loaded. Use the VaultHook#isVaultLoaded method before using vault methods.");
|
||||
return rspPermissions.getProvider();
|
||||
}
|
||||
|
||||
/**
|
||||
* Sets the vault permissions service provider.
|
||||
*
|
||||
* @param rsp The service provider providing {@link Permission}
|
||||
*/
|
||||
@ApiStatus.Internal
|
||||
public void setPermissions(@Nullable RegisteredServiceProvider<Permission> rsp) {
|
||||
this.rspPermissions = rsp;
|
||||
}
|
||||
|
||||
/**
|
||||
* Check if a vault chat plugin is loaded.
|
||||
*
|
||||
* @return boolean
|
||||
*/
|
||||
public boolean isChatLoaded() {
|
||||
return rspChat != null && getChat() != null;
|
||||
}
|
||||
|
||||
/**
|
||||
* Gets vault Chat instance. Should only be used after {@link #isChatLoaded()}.
|
||||
*
|
||||
* @return vault instance
|
||||
*/
|
||||
public Chat getChat() {
|
||||
if (rspChat == null)
|
||||
throw new NullPointerException("The plugin tried to use Vault without it being loaded. Use the VaultHook#isVaultLoaded method before using vault methods.");
|
||||
return rspChat.getProvider();
|
||||
}
|
||||
|
||||
/**
|
||||
* Sets the vault Chat service provider.
|
||||
*
|
||||
* @param rsp The service provider providing {@link Chat}
|
||||
*/
|
||||
@ApiStatus.Internal
|
||||
public void setChat(@Nullable RegisteredServiceProvider<Chat> rsp) {
|
||||
this.rspChat = rsp;
|
||||
}
|
||||
}
|
||||
@@ -1,20 +0,0 @@
|
||||
package com.github.alathra.alathranwars.hooks;
|
||||
|
||||
import com.github.alathra.alathranwars.Reloadable;
|
||||
|
||||
public class HookManager implements Reloadable {
|
||||
private final PAPIHook papi = new PAPIHook();
|
||||
|
||||
public void onLoad() {
|
||||
papi.onLoad();
|
||||
}
|
||||
|
||||
public void onEnable() {
|
||||
TownyHook.init();
|
||||
papi.onEnable();
|
||||
}
|
||||
|
||||
public void onDisable() {
|
||||
papi.onDisable();
|
||||
}
|
||||
}
|
||||
@@ -1,71 +0,0 @@
|
||||
package com.github.alathra.alathranwars.hooks;
|
||||
|
||||
import com.github.alathra.alathranwars.AlathranWars;
|
||||
import me.clip.placeholderapi.expansion.PlaceholderExpansion;
|
||||
import org.bukkit.entity.Player;
|
||||
import org.jetbrains.annotations.NotNull;
|
||||
import org.jetbrains.annotations.Nullable;
|
||||
|
||||
public class PAPIExpansion extends PlaceholderExpansion {
|
||||
private final AlathranWars plugin;
|
||||
private final NameColorHandler colorHandler;
|
||||
|
||||
public PAPIExpansion(AlathranWars plugin, NameColorHandler colorHandler) {
|
||||
this.plugin = plugin;
|
||||
this.colorHandler = colorHandler;
|
||||
}
|
||||
|
||||
@Override
|
||||
public @Nullable String getRequiredPlugin() {
|
||||
return "AlathranWars";
|
||||
}
|
||||
|
||||
@Override
|
||||
public @NotNull String getIdentifier() {
|
||||
return "alathranwars";
|
||||
}
|
||||
|
||||
@Override
|
||||
public @NotNull String getAuthor() {
|
||||
return String.join(", ", plugin.getPluginMeta().getAuthors());
|
||||
}
|
||||
|
||||
@Override
|
||||
public @NotNull String getVersion() {
|
||||
return plugin.getPluginMeta().getVersion();
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean persist() {
|
||||
return true;
|
||||
}
|
||||
|
||||
@Override
|
||||
public @Nullable String onPlaceholderRequest(Player p, @NotNull String params) {
|
||||
if (params.equals("player_tablist")) {
|
||||
if (colorHandler.isPlayerUsingModifiedName(p))
|
||||
return colorHandler.getPlayerTabNameColor(p) + "%essentials_nickname_stripped%";
|
||||
return "%essentials_nickname%";
|
||||
}
|
||||
|
||||
if (params.equals("player_nametag")) {
|
||||
if (colorHandler.isPlayerUsingModifiedName(p))
|
||||
return colorHandler.getPlayerNameColor(p) + "%essentials_nickname_stripped%";
|
||||
return "%essentials_nickname%";
|
||||
}
|
||||
|
||||
if (params.equals("player_tablist_maquillage")) {
|
||||
if (colorHandler.isPlayerUsingModifiedName(p))
|
||||
return colorHandler.getPlayerTabNameColor(p) + "%essentials_nickname_stripped%";
|
||||
return "%maquillage_namecolor_essentialsnick%";
|
||||
}
|
||||
|
||||
if (params.equals("player_nametag_maquillage")) {
|
||||
if (colorHandler.isPlayerUsingModifiedName(p))
|
||||
return colorHandler.getPlayerNameColor(p) + "%essentials_nickname_stripped%";
|
||||
return "%maquillage_namecolor_essentialsnick%";
|
||||
}
|
||||
|
||||
return null;
|
||||
}
|
||||
}
|
||||
@@ -1,27 +0,0 @@
|
||||
package com.github.alathra.alathranwars.hooks;
|
||||
|
||||
import com.github.alathra.alathranwars.AlathranWars;
|
||||
import com.github.alathra.alathranwars.Reloadable;
|
||||
import org.bukkit.Bukkit;
|
||||
|
||||
public class PAPIHook implements Reloadable {
|
||||
private PAPIExpansion papiExpansion;
|
||||
|
||||
@Override
|
||||
public void onLoad() {
|
||||
}
|
||||
|
||||
@Override
|
||||
public void onEnable() {
|
||||
if (Bukkit.getPluginManager().isPluginEnabled("PlaceholderAPI")) {
|
||||
papiExpansion = new PAPIExpansion(AlathranWars.getInstance(), NameColorHandler.getInstance());
|
||||
papiExpansion.register();
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
public void onDisable() {
|
||||
if (papiExpansion != null && papiExpansion.isRegistered())
|
||||
papiExpansion.unregister();
|
||||
}
|
||||
}
|
||||
@@ -1,29 +0,0 @@
|
||||
package com.github.alathra.alathranwars.hooks;
|
||||
|
||||
import com.palmergames.bukkit.towny.TownyAPI;
|
||||
import com.palmergames.bukkit.towny.object.Nation;
|
||||
import com.palmergames.bukkit.towny.object.Town;
|
||||
|
||||
import javax.inject.Singleton;
|
||||
import java.util.List;
|
||||
|
||||
@Singleton
|
||||
public class TownyHook {
|
||||
private static boolean enabled = false;
|
||||
private static TownyAPI townyAPI;
|
||||
|
||||
public static void init() {
|
||||
if (enabled) return;
|
||||
|
||||
townyAPI = TownyAPI.getInstance();
|
||||
enabled = true;
|
||||
}
|
||||
|
||||
public static List<Town> getTowns() {
|
||||
return townyAPI.getTowns();
|
||||
}
|
||||
|
||||
public static List<Nation> getNations() {
|
||||
return townyAPI.getNations();
|
||||
}
|
||||
}
|
||||
@@ -148,7 +148,7 @@ public class CommandsListener implements Listener {
|
||||
Prevent players from teleporting during a siege
|
||||
*/
|
||||
|
||||
for (Siege siege : WarController.getInstance().getPlayerSieges(p)) {
|
||||
for (Siege siege : WarController.getInstance().getSieges(p)) {
|
||||
//payment check
|
||||
if (args.length >= 2) {
|
||||
//parse what we have, remove the starting sslash
|
||||
|
||||
@@ -2,10 +2,10 @@ package com.github.alathra.alathranwars.listeners;
|
||||
|
||||
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.*;
|
||||
import com.github.alathra.alathranwars.listeners.war.NationListener;
|
||||
import com.github.alathra.alathranwars.listeners.war.PlayerJoinListener;
|
||||
import com.github.alathra.alathranwars.listeners.war.PlayerQuitListener;
|
||||
import com.github.alathra.alathranwars.listeners.war.TownListener;
|
||||
import org.bukkit.Bukkit;
|
||||
|
||||
@@ -13,10 +13,15 @@ import org.bukkit.Bukkit;
|
||||
* A class to handle registration of event listeners.
|
||||
*/
|
||||
public class ListenerHandler implements Reloadable {
|
||||
private final AlathranWars instance;
|
||||
private final AlathranWars plugin;
|
||||
|
||||
public ListenerHandler(AlathranWars instance) {
|
||||
this.instance = instance;
|
||||
/**
|
||||
* Instantiates a the Listener handler.
|
||||
*
|
||||
* @param plugin the plugin instance
|
||||
*/
|
||||
public ListenerHandler(AlathranWars plugin) {
|
||||
this.plugin = plugin;
|
||||
}
|
||||
|
||||
@Override
|
||||
@@ -26,30 +31,33 @@ public class ListenerHandler implements Reloadable {
|
||||
@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);
|
||||
plugin.getServer().getPluginManager().registerEvents(new BlockBreakPlaceListener(), plugin);
|
||||
plugin.getServer().getPluginManager().registerEvents(new PlayerDeathListener(), plugin);
|
||||
if (Bukkit.getServer().getPluginManager().isPluginEnabled("Graves"))
|
||||
instance.getServer().getPluginManager().registerEvents(new PlayerGraveListener(), instance);
|
||||
plugin.getServer().getPluginManager().registerEvents(new PlayerGraveListener(), plugin);
|
||||
if (Bukkit.getServer().getPluginManager().isPluginEnabled("HeadsPlus"))
|
||||
instance.getServer().getPluginManager().registerEvents(new PlayerHeadsPlusListener(), instance);
|
||||
plugin.getServer().getPluginManager().registerEvents(new PlayerHeadsPlusListener(), plugin);
|
||||
if (Bukkit.getServer().getPluginManager().isPluginEnabled("GSit"))
|
||||
instance.getServer().getPluginManager().registerEvents(new PlayerSitListener(), instance);
|
||||
instance.getServer().getPluginManager().registerEvents(new ItemUseListener(), instance);
|
||||
instance.getServer().getPluginManager().registerEvents(new PlayerDamageEntityListener(), instance);
|
||||
plugin.getServer().getPluginManager().registerEvents(new PlayerSitListener(), plugin);
|
||||
plugin.getServer().getPluginManager().registerEvents(new ItemUseListener(), plugin);
|
||||
plugin.getServer().getPluginManager().registerEvents(new PlayerDamageEntityListener(), plugin);
|
||||
|
||||
// Battles
|
||||
instance.getServer().getPluginManager().registerEvents(new SiegeListener(), instance);
|
||||
plugin.getServer().getPluginManager().registerEvents(new SiegeListener(), plugin);
|
||||
|
||||
// Wars
|
||||
instance.getServer().getPluginManager().registerEvents(new NationListener(), instance);
|
||||
instance.getServer().getPluginManager().registerEvents(new TownListener(), instance);
|
||||
instance.getServer().getPluginManager().registerEvents(new PlayerJoinListener(), instance);
|
||||
instance.getServer().getPluginManager().registerEvents(new com.github.alathra.alathranwars.listeners.war.PlayerQuitListener(), instance);
|
||||
plugin.getServer().getPluginManager().registerEvents(new NationListener(), plugin);
|
||||
plugin.getServer().getPluginManager().registerEvents(new TownListener(), plugin);
|
||||
plugin.getServer().getPluginManager().registerEvents(new PlayerJoinListener(), plugin);
|
||||
plugin.getServer().getPluginManager().registerEvents(new PlayerQuitListener(), plugin);
|
||||
|
||||
plugin.getServer().getPluginManager().registerEvents(new CommandsListener(), plugin);
|
||||
|
||||
// Misc
|
||||
plugin.getServer().getPluginManager().registerEvents(new UpdateCheckListener(), plugin);
|
||||
if (Bukkit.getServer().getPluginManager().isPluginEnabled("Vault")) // TODO Check if hook enabled
|
||||
plugin.getServer().getPluginManager().registerEvents(new VaultListener(), plugin);
|
||||
|
||||
instance.getServer().getPluginManager().registerEvents(new CommandsListener(), instance);
|
||||
instance.getServer().getPluginManager().registerEvents(new PlayerInteractListener(), instance);
|
||||
}
|
||||
|
||||
@Override
|
||||
|
||||
@@ -0,0 +1,45 @@
|
||||
package com.github.alathra.alathranwars.listeners;
|
||||
|
||||
import com.github.milkdrinkers.colorparser.ColorParser;
|
||||
import com.github.alathra.alathranwars.AlathranWars;
|
||||
import com.github.alathra.alathranwars.translation.Translation;
|
||||
import com.github.alathra.alathranwars.updatechecker.SemanticVersion;
|
||||
import com.github.alathra.alathranwars.updatechecker.UpdateChecker;
|
||||
import com.github.alathra.alathranwars.utility.Cfg;
|
||||
import org.bukkit.event.EventHandler;
|
||||
import org.bukkit.event.Listener;
|
||||
import org.bukkit.event.player.PlayerJoinEvent;
|
||||
|
||||
/**
|
||||
* Sends an update message to operators if there's a plugin update available
|
||||
*/
|
||||
public class UpdateCheckListener implements Listener {
|
||||
@EventHandler
|
||||
@SuppressWarnings("unused")
|
||||
public void onPlayerJoin(PlayerJoinEvent e) {
|
||||
if (AlathranWars.getInstance().getUpdateChecker().isLatest())
|
||||
return;
|
||||
|
||||
if (!Cfg.get().getOrDefault("update-checker.enable", true) || !Cfg.get().getOrDefault("update-checker.op", true))
|
||||
return;
|
||||
|
||||
if (!e.getPlayer().isOp())
|
||||
return;
|
||||
|
||||
String pluginName = AlathranWars.getInstance().getUpdateChecker().getPluginName();
|
||||
SemanticVersion latestVersion = AlathranWars.getInstance().getUpdateChecker().getLatestVersion();
|
||||
SemanticVersion currentVersion = AlathranWars.getInstance().getUpdateChecker().getCurrentVersion();
|
||||
|
||||
if (latestVersion == null || currentVersion == null)
|
||||
return;
|
||||
|
||||
e.getPlayer().sendMessage(
|
||||
ColorParser.of(Translation.of("update-checker.update-found-player"))
|
||||
.parseMinimessagePlaceholder("plugin_name", pluginName)
|
||||
.parseMinimessagePlaceholder("version_current", currentVersion.getVersionFull())
|
||||
.parseMinimessagePlaceholder("version_latest", latestVersion.getVersionFull())
|
||||
.parseMinimessagePlaceholder("download_link", UpdateChecker.LATEST_RELEASE)
|
||||
.build()
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,34 @@
|
||||
package com.github.alathra.alathranwars.listeners;
|
||||
|
||||
import com.github.alathra.alathranwars.AlathranWars;
|
||||
import net.milkbowl.vault.chat.Chat;
|
||||
import net.milkbowl.vault.economy.Economy;
|
||||
import net.milkbowl.vault.permission.Permission;
|
||||
import org.bukkit.event.EventHandler;
|
||||
import org.bukkit.event.Listener;
|
||||
import org.bukkit.event.server.ServiceRegisterEvent;
|
||||
import org.bukkit.plugin.RegisteredServiceProvider;
|
||||
|
||||
/**
|
||||
* Event Listener for the Vault Hook {@link com.github.alathra.alathranwars.hook.VaultHook}.
|
||||
*/
|
||||
public class VaultListener implements Listener {
|
||||
/**
|
||||
* Update the Vault hooks RegisteredServiceProviders in {@link com.github.alathra.alathranwars.hook.VaultHook}. <br>This ensures the Vault hook is lazily loaded and working properly, even on reloads.
|
||||
*
|
||||
* @param e event
|
||||
*/
|
||||
@SuppressWarnings("unchecked")
|
||||
@EventHandler
|
||||
public void onServiceRegisterEvent(ServiceRegisterEvent e) {
|
||||
RegisteredServiceProvider<?> rsp = e.getProvider();
|
||||
Object rspProvider = rsp.getProvider();
|
||||
if (rspProvider instanceof Economy) {
|
||||
AlathranWars.getVaultHook().setEconomy((RegisteredServiceProvider<Economy>) rsp);
|
||||
} else if (rspProvider instanceof Permission) {
|
||||
AlathranWars.getVaultHook().setPermissions((RegisteredServiceProvider<Permission>) rsp);
|
||||
} else if (rspProvider instanceof Chat) {
|
||||
AlathranWars.getVaultHook().setChat((RegisteredServiceProvider<Chat>) rsp);
|
||||
}
|
||||
}
|
||||
}
|
||||
-189
@@ -1,189 +0,0 @@
|
||||
package com.github.alathra.alathranwars.listeners.items;
|
||||
|
||||
import com.github.alathra.alathranwars.AlathranWars;
|
||||
import com.github.alathra.alathranwars.conflict.battle.siege.Siege;
|
||||
import com.github.alathra.alathranwars.conflict.war.WarController;
|
||||
import com.github.alathra.alathranwars.items.WarItemRegistry;
|
||||
import com.github.alathra.alathranwars.utility.UtilsChat;
|
||||
import com.github.milkdrinkers.colorparser.ColorParser;
|
||||
import com.palmergames.bukkit.towny.object.TownBlock;
|
||||
import com.palmergames.bukkit.towny.object.WorldCoord;
|
||||
import org.bukkit.Location;
|
||||
import org.bukkit.Material;
|
||||
import org.bukkit.block.Block;
|
||||
import org.bukkit.block.data.Bisected;
|
||||
import org.bukkit.block.data.type.Door;
|
||||
import org.bukkit.entity.Player;
|
||||
import org.bukkit.event.EventHandler;
|
||||
import org.bukkit.event.EventPriority;
|
||||
import org.bukkit.event.Listener;
|
||||
import org.bukkit.event.block.Action;
|
||||
import org.bukkit.event.player.PlayerInteractEvent;
|
||||
import org.bukkit.event.player.PlayerItemDamageEvent;
|
||||
import org.bukkit.inventory.ItemStack;
|
||||
import org.jetbrains.annotations.NotNull;
|
||||
import org.jetbrains.annotations.Nullable;
|
||||
|
||||
import javax.annotation.Nonnull;
|
||||
import java.util.HashMap;
|
||||
import java.util.HashSet;
|
||||
import java.util.Map;
|
||||
import java.util.Set;
|
||||
|
||||
public class PlayerInteractListener implements Listener {
|
||||
|
||||
//predefined foor materials
|
||||
private static final Set<Material> doors = new HashSet<>();
|
||||
|
||||
static {
|
||||
doors.add(Material.ACACIA_DOOR);
|
||||
doors.add(Material.BIRCH_DOOR);
|
||||
doors.add(Material.CRIMSON_DOOR);
|
||||
doors.add(Material.DARK_OAK_DOOR);
|
||||
doors.add(Material.IRON_DOOR);
|
||||
doors.add(Material.JUNGLE_DOOR);
|
||||
doors.add(Material.MANGROVE_DOOR);
|
||||
doors.add(Material.OAK_DOOR);
|
||||
doors.add(Material.SPRUCE_DOOR);
|
||||
doors.add(Material.WARPED_DOOR);
|
||||
}
|
||||
|
||||
//map of broken doors
|
||||
public final @NotNull Map<Location, Long> brokenDoors = new HashMap<>();
|
||||
|
||||
/**
|
||||
* @param event event
|
||||
* @author DunnoConz
|
||||
* @author AubriTheHuman
|
||||
*/
|
||||
@EventHandler(priority = EventPriority.LOWEST)
|
||||
public void onPlayerInteract(final @NotNull PlayerInteractEvent event) {
|
||||
@NotNull Player player = event.getPlayer();
|
||||
@NotNull Action action = event.getAction();
|
||||
|
||||
if (action == Action.LEFT_CLICK_BLOCK) {
|
||||
@Nullable Block clicked = event.getClickedBlock();
|
||||
@NotNull ItemStack item = player.getInventory().getItemInMainHand();
|
||||
if (clicked != null) {
|
||||
if (doors.contains(clicked.getType())) { // left click + any door types
|
||||
@NotNull Door door = (Door) clicked.getBlockData();
|
||||
// lock door in the opposite position
|
||||
if (item.equals(WarItemRegistry.getInstance().getOrNull("ram"))) {
|
||||
boolean inSiegeOrRaid = false;
|
||||
//siege check
|
||||
for (@NotNull Siege s : WarController.getInstance().getSieges()) {
|
||||
for (@NotNull TownBlock townBlock : s.getTown().getTownBlocks()) {
|
||||
if (WorldCoord.parseWorldCoord(clicked).equals(townBlock.getWorldCoord())) {
|
||||
// if we find one, just end no need to continue
|
||||
inSiegeOrRaid = true;
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
//if it wasnt in a siege, then
|
||||
/*if (!inSiegeOrRaid) {
|
||||
for (OldRaid r : RaidData.getRaids()) {
|
||||
for (TownBlock townBlock : r.getRaidedTown().getTownBlocks()) {
|
||||
if (WorldCoord.parseWorldCoord(clicked).equals(townBlock.getWorldCoord())) {
|
||||
// if we find one, just end no need to continue
|
||||
inSiegeOrRaid = true;
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
}*/
|
||||
|
||||
if (inSiegeOrRaid) {
|
||||
|
||||
// Returns if already broken.
|
||||
if (doorBroken(clicked, door)) {
|
||||
player.sendMessage(ColorParser.of(UtilsChat.getPrefix() + "<red>The door is already broken!").parseLegacy().build());
|
||||
event.setCancelled(true);
|
||||
return;
|
||||
}
|
||||
player.sendMessage(ColorParser.of(UtilsChat.getPrefix() + "<yellow>Break it down alright!").parseLegacy().build());
|
||||
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);
|
||||
} else {
|
||||
player.sendMessage(ColorParser.of(UtilsChat.getPrefix() + "<red>This item can only be used in a siege or raid!").parseLegacy().build());
|
||||
}
|
||||
event.setCancelled(true);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@EventHandler(priority = EventPriority.HIGHEST)
|
||||
public void onPlayerRClick(final @NotNull PlayerItemDamageEvent event) {
|
||||
@NotNull ItemStack item = event.getItem();
|
||||
if (item.equals(WarItemRegistry.getInstance().getOrNull("ram"))) {
|
||||
event.setCancelled(true);
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* @param event event
|
||||
* @author DunnoConz
|
||||
* @author AubriTheHuman
|
||||
*/
|
||||
@EventHandler(priority = EventPriority.LOWEST)
|
||||
public void onPlayerRClick(final @NotNull PlayerInteractEvent event) {
|
||||
@NotNull Player player = event.getPlayer();
|
||||
@NotNull Action action = event.getAction();
|
||||
@Nullable Block clicked = event.getClickedBlock();
|
||||
@NotNull ItemStack item = player.getInventory().getItemInMainHand();
|
||||
if (action == Action.RIGHT_CLICK_BLOCK) {
|
||||
if (clicked != null) {
|
||||
if (doors.contains(clicked.getType())) {
|
||||
@NotNull Door door = (Door) clicked.getBlockData();
|
||||
if (doorBroken(clicked, door)) {
|
||||
player.sendMessage(ColorParser.of(UtilsChat.getPrefix() + "Door is broken!").parseLegacy().build());
|
||||
event.setCancelled(true);
|
||||
|
||||
return;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
if (item.equals(WarItemRegistry.getInstance().getOrNull("ram"))) {
|
||||
if (clicked != null) {
|
||||
if (clicked.getType().name().equals("GRASS_BLOCK")
|
||||
|| clicked.getType().name().equals("DIRT")
|
||||
|| clicked.getType().name().equals("COARSE_DIRT")
|
||||
|| clicked.getType().name().equals("ROOTED_DIRT")
|
||||
|| clicked.getType().name().equals("DIRT_PATH")) {
|
||||
event.setCancelled(true);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private @NotNull Location getDoorPos(@NotNull Block clicked, @NotNull Door door) {
|
||||
if (door.getHalf() == Bisected.Half.BOTTOM) {
|
||||
return clicked.getLocation().clone();
|
||||
} else if (door.getHalf() == Bisected.Half.TOP) {
|
||||
return clicked.getLocation().subtract(0.0, 1.0, 0.0).clone();
|
||||
}
|
||||
return clicked.getLocation().clone();
|
||||
}
|
||||
|
||||
private boolean doorBroken(@Nonnull Block clicked, @NotNull Door door) {
|
||||
if (door.getHalf() == Bisected.Half.BOTTOM) {
|
||||
if (brokenDoors.get(clicked.getLocation()) != null) {
|
||||
return brokenDoors.get(clicked.getLocation()) > System.currentTimeMillis();
|
||||
}
|
||||
} else if (door.getHalf() == Bisected.Half.TOP) {
|
||||
if (brokenDoors.get(clicked.getLocation().subtract(0.0, 1.0D, 0.0)) != null) {
|
||||
return brokenDoors.get(clicked.getLocation().subtract(0.0, 1.0D, 0.0)) > System.currentTimeMillis();
|
||||
}
|
||||
}
|
||||
return false;
|
||||
}
|
||||
}
|
||||
+2
-2
@@ -88,7 +88,7 @@ public class BlockBreakPlaceListener implements Listener {
|
||||
if (!Utils.isOnSiegeBattlefield(e.getPlayer(), siege)) return;
|
||||
|
||||
final boolean isInsideTownClaims = e.hasTownBlock();
|
||||
final boolean isDefender = siege.getPlayerSideInSiege(e.getPlayer()).equals(BattleSide.DEFENDER);
|
||||
final boolean isDefender = siege.getPlayerBattleSide(e.getPlayer()).equals(BattleSide.DEFENDER);
|
||||
|
||||
// Allow destroying beds anywhere
|
||||
if (DESTROY_GLOBAL.contains(e.getMaterial())) {
|
||||
@@ -122,7 +122,7 @@ public class BlockBreakPlaceListener implements Listener {
|
||||
if (!Utils.isOnSiegeBattlefield(e.getPlayer(), siege)) return;
|
||||
|
||||
final boolean isInsideClaims = e.hasTownBlock();
|
||||
final boolean isDefender = siege.getPlayerSideInSiege(e.getPlayer()).equals(BattleSide.DEFENDER);
|
||||
final boolean isDefender = siege.getPlayerBattleSide(e.getPlayer()).equals(BattleSide.DEFENDER);
|
||||
|
||||
final boolean isDefenderAllowed = (!isInsideClaims || !e.getTownBlock().isOutpost()) && isDefender; // Defenders can build on the battlefield and in towns
|
||||
final boolean isAttackerAllowed = (!isInsideClaims || e.getTownBlock().isOutpost()) && !isDefender; // Attackers can build on the battlefield and in outposts
|
||||
|
||||
+2
-2
@@ -62,7 +62,7 @@ public class PlayerDeathListener implements Listener {
|
||||
|
||||
if (!Utils.isOnSiegeBattlefield(victim, siege)) return;
|
||||
|
||||
if (siege.isPlayerInSiege(victim) && siege.isPlayerInSiege(attacker)) {
|
||||
if (siege.isPlayerParticipating(victim) && siege.isPlayerParticipating(attacker)) {
|
||||
siegeKill(e);
|
||||
} else {
|
||||
oocKill(e);
|
||||
@@ -80,7 +80,7 @@ public class PlayerDeathListener implements Listener {
|
||||
|
||||
if (!Utils.isOnSiegeBattlefield(victim, siege)) return;
|
||||
|
||||
if (siege.isPlayerInSiege(victim)) {
|
||||
if (siege.isPlayerParticipating(victim)) {
|
||||
siegeKill(e);
|
||||
} else {
|
||||
oocKill(e);
|
||||
|
||||
@@ -1,23 +0,0 @@
|
||||
package com.github.alathra.alathranwars.listeners.siege;
|
||||
|
||||
import com.github.alathra.alathranwars.conflict.battle.siege.Siege;
|
||||
import com.github.alathra.alathranwars.conflict.war.WarController;
|
||||
import com.github.alathra.alathranwars.enums.battle.BattleSide;
|
||||
import org.bukkit.entity.Player;
|
||||
import org.bukkit.event.EventHandler;
|
||||
import org.bukkit.event.Listener;
|
||||
import org.bukkit.event.player.PlayerJoinEvent;
|
||||
import org.jetbrains.annotations.NotNull;
|
||||
|
||||
public class PlayerJoinListener implements Listener {
|
||||
@EventHandler
|
||||
private void onPlayerJoin(@NotNull PlayerJoinEvent e) {
|
||||
final @NotNull Player p = e.getPlayer();
|
||||
if (WarController.getInstance().isPlayerInAnySiege(p)) {
|
||||
for (@NotNull Siege siege : WarController.getInstance().getPlayerSieges(p)) {
|
||||
final @NotNull BattleSide side = siege.getPlayerSideInSiege(p);
|
||||
siege.addOnlinePlayer(p, side);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1,23 +0,0 @@
|
||||
package com.github.alathra.alathranwars.listeners.siege;
|
||||
|
||||
import com.github.alathra.alathranwars.conflict.battle.siege.Siege;
|
||||
import com.github.alathra.alathranwars.conflict.war.WarController;
|
||||
import com.github.alathra.alathranwars.enums.battle.BattleSide;
|
||||
import org.bukkit.entity.Player;
|
||||
import org.bukkit.event.EventHandler;
|
||||
import org.bukkit.event.Listener;
|
||||
import org.bukkit.event.player.PlayerQuitEvent;
|
||||
import org.jetbrains.annotations.NotNull;
|
||||
|
||||
public class PlayerQuitListener implements Listener {
|
||||
@EventHandler
|
||||
private void onPlayerQuit(@NotNull PlayerQuitEvent e) {
|
||||
final @NotNull Player p = e.getPlayer();
|
||||
if (WarController.getInstance().isPlayerInAnySiege(p)) {
|
||||
for (@NotNull Siege siege : WarController.getInstance().getPlayerSieges(p)) {
|
||||
final @NotNull BattleSide side = siege.getPlayerSideInSiege(p);
|
||||
siege.removeOnlinePlayer(p, side);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -3,6 +3,7 @@ package com.github.alathra.alathranwars.listeners.siege;
|
||||
import com.github.alathra.alathranwars.conflict.battle.siege.Siege;
|
||||
import com.github.alathra.alathranwars.conflict.war.War;
|
||||
import com.github.alathra.alathranwars.conflict.war.side.Side;
|
||||
import com.github.alathra.alathranwars.enums.battle.BattleSide;
|
||||
import com.github.alathra.alathranwars.enums.battle.BattleType;
|
||||
import com.github.alathra.alathranwars.enums.battle.BattleVictoryReason;
|
||||
import com.github.alathra.alathranwars.events.battle.BattleResultEvent;
|
||||
@@ -61,12 +62,13 @@ public class SiegeListener implements Listener {
|
||||
TITLE_TIMES
|
||||
);
|
||||
|
||||
siege.getDefenderPlayers().forEach(player -> {
|
||||
|
||||
siege.getActivePlayers(BattleSide.DEFENDER).forEach(player -> {
|
||||
player.showTitle(defTitle);
|
||||
player.playSound(SOUND_GOATHORNS.get(new Random().nextInt(1, SOUND_GOATHORNS.size())));
|
||||
});
|
||||
|
||||
siege.getAttackerPlayers().forEach(player -> {
|
||||
siege.getActivePlayers(BattleSide.ATTACKER).forEach(player -> {
|
||||
player.showTitle(attTitle);
|
||||
player.playSound(SOUND_GOATHORNS.get(new Random().nextInt(1, SOUND_GOATHORNS.size())));
|
||||
});
|
||||
@@ -116,11 +118,11 @@ public class SiegeListener implements Listener {
|
||||
.build(),
|
||||
TITLE_TIMES
|
||||
);
|
||||
siege.getAttackers().forEach(player -> {
|
||||
siege.getActivePlayers(BattleSide.ATTACKER).forEach(player -> {
|
||||
player.showTitle(vicAttackTitle);
|
||||
player.playSound(SOUND_VICTORY);
|
||||
});
|
||||
siege.getDefenders().forEach(player -> {
|
||||
siege.getActivePlayers(BattleSide.DEFENDER).forEach(player -> {
|
||||
player.showTitle(losAttackTitle);
|
||||
player.playSound(SOUND_DEFEAT);
|
||||
});
|
||||
@@ -158,11 +160,11 @@ public class SiegeListener implements Listener {
|
||||
.build(),
|
||||
TITLE_TIMES
|
||||
);
|
||||
siege.getAttackers().forEach(player -> {
|
||||
siege.getActivePlayers(BattleSide.ATTACKER).forEach(player -> {
|
||||
player.showTitle(vicDefendTitle);
|
||||
player.playSound(SOUND_DEFEAT);
|
||||
});
|
||||
siege.getDefenders().forEach(player -> {
|
||||
siege.getActivePlayers(BattleSide.DEFENDER).forEach(player -> {
|
||||
player.showTitle(losDefendTitle);
|
||||
player.playSound(SOUND_VICTORY);
|
||||
});
|
||||
@@ -183,11 +185,11 @@ public class SiegeListener implements Listener {
|
||||
.build(),
|
||||
TITLE_TIMES
|
||||
);
|
||||
siege.getAttackers().forEach(player -> {
|
||||
siege.getActivePlayers(BattleSide.ATTACKER).forEach(player -> {
|
||||
player.showTitle(drawTitle);
|
||||
player.playSound(SOUND_DEFEAT);
|
||||
});
|
||||
siege.getDefenders().forEach(player -> {
|
||||
siege.getActivePlayers(BattleSide.DEFENDER).forEach(player -> {
|
||||
player.showTitle(drawTitle);
|
||||
player.playSound(SOUND_DEFEAT);
|
||||
});
|
||||
@@ -213,19 +215,19 @@ public class SiegeListener implements Listener {
|
||||
if (war.isEventWar()) return;
|
||||
|
||||
Town town = siege.getTown();
|
||||
Side townSide = war.getTownSide(town);
|
||||
Side townSide = war.getSide(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);
|
||||
if (townSide.isSurrendered(town)) {
|
||||
war.unsurrender(town);
|
||||
}
|
||||
} else { // Occupation siege
|
||||
if (!townSide.isTownSurrendered(town)) {
|
||||
war.surrenderTown(town);
|
||||
if (!townSide.isSurrendered(town)) {
|
||||
war.surrender(town);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -3,7 +3,7 @@ package com.github.alathra.alathranwars.listeners.war;
|
||||
import com.github.alathra.alathranwars.conflict.war.War;
|
||||
import com.github.alathra.alathranwars.conflict.war.WarController;
|
||||
import com.github.alathra.alathranwars.conflict.war.side.Side;
|
||||
import com.github.alathra.alathranwars.hooks.NameColorHandler;
|
||||
import com.github.alathra.alathranwars.hook.NameColorHandler;
|
||||
import com.palmergames.bukkit.towny.event.NationAddTownEvent;
|
||||
import com.palmergames.bukkit.towny.event.NationPreRenameEvent;
|
||||
import com.palmergames.bukkit.towny.event.nation.NationPreMergeEvent;
|
||||
@@ -23,7 +23,7 @@ public class NationListener implements Listener {
|
||||
private void onRename(NationPreRenameEvent e) {
|
||||
Nation nation = e.getNation();
|
||||
|
||||
if (WarController.getInstance().isNationInAnyWars(nation)) {
|
||||
if (WarController.getInstance().isInAnyWars(nation)) {
|
||||
e.setCancelMessage("You can't rename a nation while it's in a war.");
|
||||
e.setCancelled(true);
|
||||
}
|
||||
@@ -35,26 +35,26 @@ public class NationListener implements Listener {
|
||||
Town town = e.getTown();
|
||||
|
||||
// Add town to all nation wars
|
||||
for (War war : WarController.getInstance().getNationWars(nation)) {
|
||||
Side side = war.getNationSide(nation);
|
||||
for (War war : WarController.getInstance().getWars(nation)) {
|
||||
Side side = war.getSide(nation);
|
||||
if (side == null) continue;
|
||||
|
||||
side.addTown(town);
|
||||
side.add(town);
|
||||
}
|
||||
|
||||
// TODO Add nation to towns' wars
|
||||
for (War war : WarController.getInstance().getTownWars(town)) {
|
||||
Side side = war.getTownSide(town);
|
||||
for (War war : WarController.getInstance().getWars(town)) {
|
||||
Side side = war.getSide(town);
|
||||
if (side == null) continue;
|
||||
|
||||
side.addNation(nation);
|
||||
side.add(nation);
|
||||
}
|
||||
|
||||
for (War war : WarController.getInstance().getNationWars(nation)) {
|
||||
Side side = war.getNationSide(nation);
|
||||
for (War war : WarController.getInstance().getWars(nation)) {
|
||||
Side side = war.getSide(nation);
|
||||
if (side == null) continue;
|
||||
|
||||
side.getPlayers().forEach(p -> NameColorHandler.getInstance().calculatePlayerColors(p));
|
||||
side.getPlayersOnline().forEach(p -> NameColorHandler.getInstance().calculatePlayerColors(p));
|
||||
}
|
||||
}
|
||||
|
||||
@@ -68,7 +68,7 @@ public class NationListener implements Listener {
|
||||
Nation nation = e.getRemainingNation();
|
||||
Nation nation1 = e.getNation();
|
||||
|
||||
if (WarController.getInstance().isNationInAnyWars(nation) || WarController.getInstance().isNationInAnyWars(nation1)) {
|
||||
if (WarController.getInstance().isInAnyWars(nation) || WarController.getInstance().isInAnyWars(nation1)) {
|
||||
e.setCancelMessage("You can't merge nations while they are in a war.");
|
||||
e.setCancelled(true);
|
||||
}
|
||||
|
||||
+3
-18
@@ -1,30 +1,15 @@
|
||||
package com.github.alathra.alathranwars.listeners.war;
|
||||
|
||||
import com.github.alathra.alathranwars.conflict.war.War;
|
||||
import com.github.alathra.alathranwars.conflict.war.WarController;
|
||||
import com.github.alathra.alathranwars.conflict.war.side.Side;
|
||||
import com.github.alathra.alathranwars.hooks.NameColorHandler;
|
||||
import com.github.alathra.alathranwars.hook.NameColorHandler;
|
||||
import org.bukkit.entity.Player;
|
||||
import org.bukkit.event.EventHandler;
|
||||
import org.bukkit.event.Listener;
|
||||
import org.bukkit.event.player.PlayerJoinEvent;
|
||||
import org.jetbrains.annotations.NotNull;
|
||||
import org.jetbrains.annotations.Nullable;
|
||||
|
||||
public class PlayerJoinListener implements Listener {
|
||||
@EventHandler
|
||||
private void onPlayerJoin(@NotNull PlayerJoinEvent e) {
|
||||
final @NotNull Player p = e.getPlayer();
|
||||
if (WarController.getInstance().isPlayerInAnyWars(p)) {
|
||||
for (@NotNull War war : WarController.getInstance().getWars()) {
|
||||
if (war.isPlayerInWar(p)) {
|
||||
@Nullable Side side = war.getPlayerSide(p);
|
||||
if (side != null) {
|
||||
side.addOnlinePlayer(p);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
private void onPlayerJoin(PlayerJoinEvent e) {
|
||||
Player p = e.getPlayer();
|
||||
NameColorHandler.getInstance().calculatePlayerColors(p);
|
||||
}
|
||||
}
|
||||
+3
-18
@@ -1,30 +1,15 @@
|
||||
package com.github.alathra.alathranwars.listeners.war;
|
||||
|
||||
import com.github.alathra.alathranwars.conflict.war.War;
|
||||
import com.github.alathra.alathranwars.conflict.war.WarController;
|
||||
import com.github.alathra.alathranwars.conflict.war.side.Side;
|
||||
import com.github.alathra.alathranwars.hooks.NameColorHandler;
|
||||
import com.github.alathra.alathranwars.hook.NameColorHandler;
|
||||
import org.bukkit.entity.Player;
|
||||
import org.bukkit.event.EventHandler;
|
||||
import org.bukkit.event.Listener;
|
||||
import org.bukkit.event.player.PlayerQuitEvent;
|
||||
import org.jetbrains.annotations.NotNull;
|
||||
import org.jetbrains.annotations.Nullable;
|
||||
|
||||
public class PlayerQuitListener implements Listener {
|
||||
@EventHandler
|
||||
private void onPlayerQuit(@NotNull PlayerQuitEvent e) {
|
||||
final @NotNull Player p = e.getPlayer();
|
||||
if (WarController.getInstance().isPlayerInAnyWars(p)) {
|
||||
for (@NotNull War war : WarController.getInstance().getWars()) {
|
||||
if (war.isPlayerInWar(p)) {
|
||||
@Nullable Side side = war.getPlayerSide(p);
|
||||
if (side != null) {
|
||||
side.removeOnlinePlayer(p);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
private void onPlayerQuit(PlayerQuitEvent e) {
|
||||
Player p = e.getPlayer();
|
||||
NameColorHandler.getInstance().calculatePlayerColors(p);
|
||||
}
|
||||
}
|
||||
@@ -3,7 +3,7 @@ package com.github.alathra.alathranwars.listeners.war;
|
||||
import com.github.alathra.alathranwars.conflict.war.War;
|
||||
import com.github.alathra.alathranwars.conflict.war.WarController;
|
||||
import com.github.alathra.alathranwars.conflict.war.side.Side;
|
||||
import com.github.alathra.alathranwars.hooks.NameColorHandler;
|
||||
import com.github.alathra.alathranwars.hook.NameColorHandler;
|
||||
import com.github.milkdrinkers.colorparser.ColorParser;
|
||||
import com.palmergames.bukkit.towny.event.TownAddResidentEvent;
|
||||
import com.palmergames.bukkit.towny.event.TownPreRenameEvent;
|
||||
@@ -23,7 +23,7 @@ public class TownListener implements Listener {
|
||||
private void onRename(TownPreRenameEvent e) {
|
||||
Town town = e.getTown();
|
||||
|
||||
if (WarController.getInstance().isTownInAnyWars(town)) {
|
||||
if (WarController.getInstance().isInAnyWars(town)) {
|
||||
e.setCancelMessage("You can't rename a town while it's in a war.");
|
||||
e.setCancelled(true);
|
||||
}
|
||||
@@ -35,7 +35,7 @@ public class TownListener implements Listener {
|
||||
private void onSpawnMove(TownSetSpawnEvent e) {
|
||||
Town town = e.getTown();
|
||||
|
||||
if (WarController.getInstance().isTownInAnyWars(town)) {
|
||||
if (WarController.getInstance().isInAnyWars(town)) {
|
||||
e.setCancelMessage("You can't move your town spawn while the town is in a war.");
|
||||
e.setCancelled(true);
|
||||
}
|
||||
@@ -47,10 +47,10 @@ public class TownListener implements Listener {
|
||||
Player p = e.getResident().getPlayer();
|
||||
if (p == null) return;
|
||||
|
||||
for (War war : WarController.getInstance().getTownWars(town)) {
|
||||
Side side = war.getTownSide(town);
|
||||
for (War war : WarController.getInstance().getWars(town)) {
|
||||
Side side = war.getSide(town);
|
||||
if (side == null) continue;
|
||||
side.addPlayer(p);
|
||||
side.add(p);
|
||||
|
||||
final Title warTitle = Title.title(
|
||||
ColorParser.of("<gradient:#D72A09:#B01F03><u><b>War")
|
||||
@@ -75,10 +75,10 @@ public class TownListener implements Listener {
|
||||
Player p = e.getResident().getPlayer();
|
||||
if (p == null) return;
|
||||
|
||||
for (War war : WarController.getInstance().getTownWars(town)) {
|
||||
Side side = war.getTownSide(town);
|
||||
for (War war : WarController.getInstance().getWars(town)) {
|
||||
Side side = war.getSide(town);
|
||||
if (side == null) continue;
|
||||
side.removePlayer(p);
|
||||
side.remove(p);
|
||||
}
|
||||
|
||||
NameColorHandler.getInstance().calculatePlayerColors(p);
|
||||
@@ -90,10 +90,10 @@ public class TownListener implements Listener {
|
||||
Player p = e.getKickedResident().getPlayer();
|
||||
if (p == null) return;
|
||||
|
||||
for (War war : WarController.getInstance().getTownWars(town)) {
|
||||
Side side = war.getTownSide(town);
|
||||
for (War war : WarController.getInstance().getWars(town)) {
|
||||
Side side = war.getSide(town);
|
||||
if (side == null) continue;
|
||||
side.removePlayer(p);
|
||||
side.remove(p);
|
||||
}
|
||||
|
||||
NameColorHandler.getInstance().calculatePlayerColors(p);
|
||||
@@ -125,7 +125,7 @@ public class TownListener implements Listener {
|
||||
Town town = e.getRemainingTown();
|
||||
Town town2 = e.getSuccumbingTown();
|
||||
|
||||
if (WarController.getInstance().isTownInAnyWars(town) || WarController.getInstance().isTownInAnyWars(town2)) {
|
||||
if (WarController.getInstance().isInAnyWars(town) || WarController.getInstance().isInAnyWars(town2)) {
|
||||
e.setCancelMessage("You can't merge towns while they are in a war.");
|
||||
e.setCancelled(true);
|
||||
}
|
||||
@@ -140,11 +140,11 @@ public class TownListener implements Listener {
|
||||
private void onRuin(TownRuinedEvent e) {
|
||||
Town town = e.getTown();
|
||||
|
||||
for (War war : WarController.getInstance().getTownWars(town)) {
|
||||
Side side = war.getTownSide(town);
|
||||
for (War war : WarController.getInstance().getWars(town)) {
|
||||
Side side = war.getSide(town);
|
||||
if (side == null) continue;
|
||||
war.unsurrenderTown(town);
|
||||
side.removeTown(town);
|
||||
war.unsurrender(town);
|
||||
side.remove(town);
|
||||
side.processSurrenders();
|
||||
}
|
||||
}
|
||||
|
||||
@@ -0,0 +1,6 @@
|
||||
package com.github.alathra.alathranwars.translation;
|
||||
|
||||
import com.github.milkdrinkers.crate.Config;
|
||||
|
||||
record InternalTranslation(String translationName, Config translation) {
|
||||
}
|
||||
@@ -0,0 +1,177 @@
|
||||
package com.github.alathra.alathranwars.translation;
|
||||
|
||||
import com.github.alathra.alathranwars.AlathranWars;
|
||||
import org.jetbrains.annotations.Nullable;
|
||||
|
||||
import java.util.Collections;
|
||||
import java.util.List;
|
||||
import java.util.Objects;
|
||||
|
||||
/**
|
||||
* Utility class for interacting with the Translations of the plugin.
|
||||
*/
|
||||
public class Translation {
|
||||
private static @Nullable AlathranWars plugin;
|
||||
private static @Nullable TranslationManager translationManager;
|
||||
private static boolean isUsingDefault = false; // Is the loaded translation the fallback translation
|
||||
|
||||
/**
|
||||
* Internal method that ensures all static fields have been initialized.
|
||||
*/
|
||||
private static void init() {
|
||||
if (plugin == null)
|
||||
plugin = AlathranWars.getInstance();
|
||||
|
||||
if (translationManager == null)
|
||||
translationManager = plugin.getTranslationManager();
|
||||
}
|
||||
|
||||
/**
|
||||
* Protected method run when the translation are reloaded to cache static fields.
|
||||
*/
|
||||
protected static void reload() {
|
||||
if (plugin == null || translationManager == null)
|
||||
return;
|
||||
|
||||
if (translationManager.getLoadedTranslation() != null && translationManager.getDefaultTranslation() != null)
|
||||
isUsingDefault = Objects.equals(translationManager.getLoadedTranslation().translationName(), translationManager.getDefaultTranslation().translationName());
|
||||
}
|
||||
|
||||
/**
|
||||
* Fetch a string from the translations by its key.
|
||||
* <br/>
|
||||
* Fetches from the translation specified by the user.
|
||||
* If that fails, fetches from the default translation.
|
||||
* If that fails, returns the default value.
|
||||
* <br/>
|
||||
*
|
||||
* @param key The key to the translation
|
||||
* @return a string value
|
||||
* @apiNote Internally this executes {@link #of(String, String)} with "" as def.
|
||||
*/
|
||||
public static String of(final String key) {
|
||||
return of(key, "");
|
||||
}
|
||||
|
||||
/**
|
||||
* Fetch a string from the translations by its key.
|
||||
* <br/>
|
||||
* Fetches from the translation specified by the user.
|
||||
* If that fails, fetches from the default translation.
|
||||
* If that fails, returns the default value.
|
||||
* <br/>
|
||||
*
|
||||
* @param key The key to the translation
|
||||
* @param def The default value to return if no valid value was found
|
||||
* @return a string value
|
||||
*/
|
||||
public static String of(final String key, final String def) {
|
||||
init();
|
||||
|
||||
if (plugin == null || translationManager == null)
|
||||
return def;
|
||||
|
||||
// Translations not loaded, return default
|
||||
if (translationManager.getLoadedTranslation() == null)
|
||||
return def;
|
||||
|
||||
if (isUsingDefault) {
|
||||
// Translations not loaded, return default
|
||||
if (translationManager.getDefaultTranslation() == null)
|
||||
return def;
|
||||
|
||||
return translationManager.getDefaultTranslation().translation().getOrDefault(
|
||||
key,
|
||||
def
|
||||
);
|
||||
} else {
|
||||
return translationManager.getLoadedTranslation().translation().getOrDefault(
|
||||
key,
|
||||
translationManager.getDefaultTranslation() != null ? translationManager.getDefaultTranslation().translation().getOrDefault(key, def) : def
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Fetch a list of strings from the translations by its key.
|
||||
* <br/>
|
||||
* Fetches from the translation specified by the user.
|
||||
* If that fails, fetches from the default translation.
|
||||
* If that fails, returns the default value.
|
||||
* <br/>
|
||||
*
|
||||
* @param key The key to the translation
|
||||
* @return a list of strings
|
||||
*/
|
||||
public static List<String> ofList(final String key) {
|
||||
init();
|
||||
|
||||
if (plugin == null || translationManager == null)
|
||||
return Collections.emptyList();
|
||||
|
||||
// Translations not loaded, return default
|
||||
if (translationManager.getLoadedTranslation() == null)
|
||||
return Collections.emptyList();
|
||||
|
||||
final List<String> result = translationManager.getLoadedTranslation().translation().getStringList(key);
|
||||
|
||||
if (isUsingDefault) {
|
||||
// Translations not loaded, return default
|
||||
if (translationManager.getDefaultTranslation() == null)
|
||||
return Collections.emptyList();
|
||||
|
||||
return translationManager.getDefaultTranslation().translation().getStringList(key);
|
||||
} else {
|
||||
return !result.isEmpty() ? result : translationManager.getDefaultTranslation() != null ? translationManager.getDefaultTranslation().translation().getStringList(key) : Collections.emptyList();
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Fetch a list of strings from the translations by its key.
|
||||
* <br/>
|
||||
* Fetches from the translation specified by the user.
|
||||
* If that fails, fetches from the default translation.
|
||||
* If that fails, returns the default value.
|
||||
* <br/>
|
||||
*
|
||||
* @param key The key to the translation
|
||||
* @param def The default value to return if no valid value was found
|
||||
* @return a list of strings
|
||||
*/
|
||||
public static List<String> ofList(final String key, final List<String> def) {
|
||||
init();
|
||||
|
||||
if (plugin == null || translationManager == null)
|
||||
return Collections.emptyList();
|
||||
|
||||
// Translations not loaded, return default
|
||||
if (translationManager.getLoadedTranslation() == null)
|
||||
return Collections.emptyList();
|
||||
|
||||
final List<String> loadedResult = translationManager.getLoadedTranslation().translation().getStringList(key);
|
||||
|
||||
if (isUsingDefault) {
|
||||
return !loadedResult.isEmpty() ? loadedResult : def;
|
||||
} else {
|
||||
final List<String> defaultResult = translationManager.getDefaultTranslation() != null ? translationManager.getDefaultTranslation().translation().getStringList(key) : def;
|
||||
|
||||
return !loadedResult.isEmpty() ? loadedResult : !defaultResult.isEmpty() ? defaultResult : def;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns a list of all entries in the translation file.
|
||||
*
|
||||
* @return list of strings
|
||||
*/
|
||||
public static List<String> getAllKeys() {
|
||||
if (plugin == null || translationManager == null)
|
||||
return Collections.emptyList();
|
||||
|
||||
// Translations not loaded, return default
|
||||
if (translationManager.getLoadedTranslation() == null)
|
||||
return Collections.emptyList();
|
||||
|
||||
return translationManager.getLoadedTranslation().translation().keySet().stream().toList();
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,220 @@
|
||||
package com.github.alathra.alathranwars.translation;
|
||||
|
||||
import com.github.milkdrinkers.Crate.shaded.snakeyaml.snakeyaml.Yaml;
|
||||
import com.github.milkdrinkers.colorparser.ColorParser;
|
||||
import com.github.milkdrinkers.crate.Config;
|
||||
import com.github.milkdrinkers.crate.ConfigBuilder;
|
||||
import com.github.milkdrinkers.crate.internal.FileData;
|
||||
import com.github.milkdrinkers.crate.internal.provider.CrateProviders;
|
||||
import com.github.milkdrinkers.crate.internal.settings.ConfigSetting;
|
||||
import com.github.milkdrinkers.crate.internal.settings.DataType;
|
||||
import com.github.milkdrinkers.crate.internal.settings.ReloadSetting;
|
||||
import com.github.alathra.alathranwars.AlathranWars;
|
||||
import com.github.alathra.alathranwars.Reloadable;
|
||||
import com.github.alathra.alathranwars.utility.FileUtils;
|
||||
import com.github.alathra.alathranwars.utility.Logger;
|
||||
import org.jetbrains.annotations.Nullable;
|
||||
|
||||
import java.io.BufferedReader;
|
||||
import java.io.InputStream;
|
||||
import java.io.InputStreamReader;
|
||||
import java.nio.charset.StandardCharsets;
|
||||
import java.nio.file.Path;
|
||||
import java.util.Map;
|
||||
|
||||
/**
|
||||
* A class that generates/loads {@literal &} provides access to all translation files.
|
||||
*/
|
||||
public class TranslationManager implements Reloadable {
|
||||
private final AlathranWars plugin;
|
||||
private static final String DEFAULT_TRANSLATION = "en-US";
|
||||
private static final String DEFAULT_DIR = "translations";
|
||||
private static final String RESOURCE_DIR = "translations";
|
||||
|
||||
private InternalTranslation defaultInternalTranslation; // Always DEFAULT_LOCALE
|
||||
private InternalTranslation loadedInternalTranslation; // The translation requested by the user, or fallback if it couldn't be loaded
|
||||
|
||||
/**
|
||||
* Instantiates a new TranslationManager.
|
||||
*
|
||||
* @param plugin the plugin instance
|
||||
*/
|
||||
public TranslationManager(AlathranWars plugin) {
|
||||
this.plugin = plugin;
|
||||
}
|
||||
|
||||
/**
|
||||
* On plugin load.
|
||||
*/
|
||||
@Override
|
||||
public void onLoad() {
|
||||
}
|
||||
|
||||
/**
|
||||
* On plugin enable.
|
||||
*/
|
||||
@Override
|
||||
public void onEnable() {
|
||||
final Path translationsPath = plugin.getDataFolder().toPath().resolve(DEFAULT_DIR);
|
||||
|
||||
// Create DEFAULT_DIR if not exists
|
||||
if (!translationsPath.toFile().exists()) {
|
||||
try {
|
||||
if (!translationsPath.toFile().mkdirs())
|
||||
throw new IllegalStateException("Failed to create %s directory!".formatted(DEFAULT_DIR));
|
||||
} catch (Exception ignored) {
|
||||
Logger.get().error(ColorParser.of("<red>Failed to create %s directory when loading plugin!".formatted(DEFAULT_DIR)).build());
|
||||
}
|
||||
}
|
||||
|
||||
// Extract shipped locale files from .jar into DEFAULT_DIR
|
||||
extractDefaultTranslations();
|
||||
loadTranslations();
|
||||
}
|
||||
|
||||
/**
|
||||
* On plugin disable.
|
||||
*/
|
||||
@Override
|
||||
public void onDisable() {
|
||||
}
|
||||
|
||||
/**
|
||||
* On plugin reload.
|
||||
*/
|
||||
public void onReload() {
|
||||
if (getLoadedTranslation() != null && getDefaultTranslation() != null) {
|
||||
loadTranslations();
|
||||
Translation.reload();
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Load a translation file into memory.
|
||||
* If the translation file does not exist, a blank file will be created.
|
||||
* If the requested translation file also exists on the classpath, the defaults will be copied over.
|
||||
*
|
||||
* @param translationName the file name excluding file extension
|
||||
* @return a {@link InternalTranslation} object
|
||||
*/
|
||||
private InternalTranslation loadTranslation(final String translationName) {
|
||||
// Log that the requested translation doesn't exist
|
||||
if (!exists(translationName))
|
||||
Logger.get().warn("Translation file %s.yml does not exist. Creating blank file and using fallback %s.yml!".formatted(translationName, DEFAULT_TRANSLATION));
|
||||
|
||||
Config translationConfig = new Config(translationName, plugin.getDataFolder().toPath().resolve(DEFAULT_DIR).toString());
|
||||
|
||||
// Create & load file with defaults from input-stream if there is one
|
||||
translationConfig.setReloadSetting(ReloadSetting.MANUALLY);
|
||||
|
||||
return new InternalTranslation(translationName, translationConfig);
|
||||
}
|
||||
|
||||
/**
|
||||
* Check if a translation file exists.
|
||||
*
|
||||
* @param translationName the file name excluding file extension
|
||||
* @return boolean
|
||||
*/
|
||||
private boolean exists(final String translationName) {
|
||||
Path translationsPath = plugin.getDataFolder().toPath().resolve(DEFAULT_DIR);
|
||||
Path translationPath = translationsPath.resolve(translationName + ".yml");
|
||||
|
||||
if (!translationsPath.toFile().exists())
|
||||
return false;
|
||||
|
||||
return translationPath.toFile().exists();
|
||||
}
|
||||
|
||||
/**
|
||||
* Loads the user defined translation and fallback into memory.
|
||||
*/
|
||||
private void loadTranslations() {
|
||||
final String requestedTranslation = plugin.getConfigHandler().getConfig().getOrSetDefault("translation", DEFAULT_TRANSLATION);
|
||||
|
||||
defaultInternalTranslation = loadTranslation(DEFAULT_TRANSLATION); // Load default translation, used as fallback
|
||||
if (requestedTranslation.equals(DEFAULT_TRANSLATION)) { // Load requested translation or point to default object
|
||||
loadedInternalTranslation = defaultInternalTranslation;
|
||||
} else {
|
||||
loadedInternalTranslation = loadTranslation(plugin.getConfigHandler().getConfig().getOrSetDefault("translation", DEFAULT_TRANSLATION)); // Loads the requested translation
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Extracts any translations that exist in the jar and updates old ones with missing default entries.
|
||||
*/
|
||||
private void extractDefaultTranslations() {
|
||||
try {
|
||||
final Path translationsResourcePath = Path.of(RESOURCE_DIR);
|
||||
final Path translationsPath = plugin.getDataFolder().toPath().resolve(DEFAULT_DIR);
|
||||
|
||||
for (String fileName : FileUtils.resourceListFiles(translationsResourcePath)) {
|
||||
|
||||
// If file already exists, add missing entries (Add new language strings)
|
||||
if (exists(FileUtils.stripExtension(fileName))) {
|
||||
try (InputStream stream = plugin.getResource(RESOURCE_DIR + "/" + fileName)) {
|
||||
if (stream == null) {
|
||||
Logger.get().error(ColorParser.of("<red>Failed to read translation %s from resources when loading plugin! Translation is null.".formatted(fileName)).build());
|
||||
continue;
|
||||
}
|
||||
|
||||
// Load translation file so it can be appended to
|
||||
final Config translationConfig = ConfigBuilder.fromPath(FileUtils.stripExtension(fileName), translationsPath.toString())
|
||||
.setConfigSetting(ConfigSetting.PRESERVE_COMMENTS)
|
||||
.setReloadSetting(ReloadSetting.MANUALLY)
|
||||
.setDataType(DataType.SORTED)
|
||||
.create();
|
||||
|
||||
final Yaml yaml = new Yaml(CrateProviders.yamlLoaderOptions());
|
||||
|
||||
// Copy missing entries from inputStream to config
|
||||
try (
|
||||
final InputStreamReader isr = new InputStreamReader(stream, StandardCharsets.UTF_8);
|
||||
final BufferedReader reader = new BufferedReader(isr)
|
||||
) {
|
||||
final Map<String, Object> data = yaml.load(reader);
|
||||
final FileData newData = new FileData(data, DataType.SORTED);
|
||||
|
||||
for (String key : newData.keySet()) {
|
||||
if (!translationConfig.contains(key))
|
||||
translationConfig.set(key, newData.get(key));
|
||||
}
|
||||
|
||||
translationConfig.forceReload(); // Apply file changes
|
||||
}
|
||||
} catch (Exception e) {
|
||||
Logger.get().warn(ColorParser.of("<red>Failed to apply new translation updates to %s when loading plugin!".formatted(fileName)).build());
|
||||
}
|
||||
continue;
|
||||
}
|
||||
|
||||
// Copy file from classpath into directory
|
||||
FileUtils.extractResource(translationsResourcePath.resolve(fileName), translationsPath.resolve(fileName), true);
|
||||
}
|
||||
} catch (Exception e) {
|
||||
Logger.get().warn(ColorParser.of("<red>Failed to extract and update default translations when loading plugin!").build());
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Get the loaded translation.
|
||||
*
|
||||
* @return a {@link InternalTranslation} object or null if not loaded
|
||||
* @implNote Only used internally in {@link Translation}
|
||||
*/
|
||||
@Nullable
|
||||
InternalTranslation getLoadedTranslation() {
|
||||
return loadedInternalTranslation;
|
||||
}
|
||||
|
||||
/**
|
||||
* Get the loaded default translation.
|
||||
*
|
||||
* @return a {@link InternalTranslation} object or null if not loaded
|
||||
* @implNote Only used internally in {@link Translation}
|
||||
*/
|
||||
@Nullable
|
||||
InternalTranslation getDefaultTranslation() {
|
||||
return defaultInternalTranslation;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,334 @@
|
||||
package com.github.alathra.alathranwars.updatechecker;
|
||||
|
||||
import org.jetbrains.annotations.Nullable;
|
||||
|
||||
import java.util.Optional;
|
||||
import java.util.regex.Matcher;
|
||||
import java.util.regex.Pattern;
|
||||
|
||||
/**
|
||||
* The type Semantic version.
|
||||
*/
|
||||
public class SemanticVersion {
|
||||
private final static Pattern SEMVER_REGEX = Pattern.compile("^(?<major>0|[1-9]\\d*)\\.(?<minor>0|[1-9]\\d*)\\.(?<patch>0|[1-9]\\d*)(?:-(?<prerelease>(?:0|[1-9]\\d*|\\d*[a-zA-Z-][0-9a-zA-Z-]*)(?:\\.(?:0|[1-9]\\d*|\\d*[a-zA-Z-][0-9a-zA-Z-]*))*))?(?:\\+(?<meta>[0-9a-zA-Z-]+(?:\\.[0-9a-zA-Z-]+)*))?$");
|
||||
|
||||
// Base fields
|
||||
private final long major; // The Major version
|
||||
private final long minor; // The Minor version
|
||||
private final long patch; // The Patch version
|
||||
private final String preRelease; // The pre-release data like "SNAPSHOT-1" or "RC-3"
|
||||
private final String meta; // The build-metadata
|
||||
|
||||
// Generated fields
|
||||
private final String version; // The version consisting of only Major.Minor.Patch
|
||||
private final String versionFull; // The entire version string
|
||||
private final boolean isReleaseCandidate; // Whether this is a pre-release
|
||||
private final boolean isSnapshot; // Whether this is a pre-release
|
||||
|
||||
/**
|
||||
* Creates a SemanticVersion object from a version string
|
||||
* </p>
|
||||
* @param versionString the string to parse version from
|
||||
* @throws NullPointerException thrown when major, minor or patch version are missing
|
||||
* @throws IllegalStateException thrown when the previous match operation failed
|
||||
* @throws IllegalArgumentException thrown when regex groups cant be found
|
||||
*/
|
||||
private SemanticVersion(String versionString) throws NullPointerException, IllegalStateException, IllegalArgumentException {
|
||||
// Strip preceding version "V" in version
|
||||
if (versionString.toUpperCase().startsWith("V"))
|
||||
versionString = versionString.substring(1);
|
||||
|
||||
// Grab version details from string
|
||||
final Matcher matcher = SEMVER_REGEX.matcher(versionString);
|
||||
if (!matcher.matches())
|
||||
throw new NullPointerException("Version could not be parsed from version string when constructing SemanticVersion object.");
|
||||
|
||||
final Optional<Long> major = Optional.ofNullable(matcher.group("major")).map(Long::parseLong);
|
||||
final Optional<Long> minor = Optional.ofNullable(matcher.group("minor")).map(Long::parseLong);
|
||||
final Optional<Long> patch = Optional.ofNullable(matcher.group("patch")).map(Long::parseLong);
|
||||
final Optional<String> preRelease = Optional.ofNullable(matcher.group("prerelease"));
|
||||
final Optional<String> meta = Optional.ofNullable(matcher.group("meta"));
|
||||
|
||||
// Check for missing data
|
||||
if (major.isEmpty())
|
||||
throw new NullPointerException("Major version could not be parsed from version string when constructing SemanticVersion object.");
|
||||
|
||||
if (minor.isEmpty())
|
||||
throw new NullPointerException("Major version could not be parsed from version string when constructing SemanticVersion object.");
|
||||
|
||||
if (patch.isEmpty())
|
||||
throw new NullPointerException("Major version could not be parsed from version string when constructing SemanticVersion object.");
|
||||
|
||||
// Base fields
|
||||
this.major = major.get();
|
||||
this.minor = minor.get();
|
||||
this.patch = patch.get();
|
||||
this.preRelease = preRelease.orElse("");
|
||||
this.meta = meta.orElse("");
|
||||
|
||||
// Generated fields
|
||||
this.version = concatenateVersionString(this.major, this.minor, this.patch);
|
||||
this.versionFull = concatenateVersionFullString(this.major, this.minor, this.patch, this.preRelease, this.meta);
|
||||
this.isReleaseCandidate = versionFull.contains("-RC");
|
||||
this.isSnapshot = versionFull.contains("-SNAPSHOT");
|
||||
}
|
||||
|
||||
/**
|
||||
* Create a SemanticVersion object from a version string
|
||||
*
|
||||
* @param version a string containing a semantic version
|
||||
* @return SemanticVersion or null
|
||||
*/
|
||||
public static @Nullable SemanticVersion of(String version) {
|
||||
try {
|
||||
return new SemanticVersion(version);
|
||||
} catch (NullPointerException | IllegalStateException | IllegalArgumentException e) {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* Of semantic version.
|
||||
*
|
||||
* @param major the major version
|
||||
* @param minor the minor version
|
||||
* @param patch the patch version
|
||||
* @param preRelease the pre-release version
|
||||
* @param meta the build-meta
|
||||
* @return the semantic version
|
||||
*/
|
||||
public static @Nullable SemanticVersion of(long major, long minor, long patch, String preRelease, String meta) {
|
||||
return SemanticVersion.of(concatenateVersionFullString(major, minor, patch, preRelease, meta));
|
||||
}
|
||||
|
||||
/**
|
||||
* Contains version comparison results.
|
||||
*/
|
||||
public enum VersionCheckResult {
|
||||
/**
|
||||
* Newer version check result.
|
||||
*/
|
||||
NEWER,
|
||||
/**
|
||||
* Equal version check result.
|
||||
*/
|
||||
EQUAL,
|
||||
/**
|
||||
* Older version check result.
|
||||
*/
|
||||
OLDER
|
||||
}
|
||||
|
||||
/**
|
||||
* Check if two versions are the same.
|
||||
*
|
||||
* @param newVersion the new version
|
||||
* @param oldVersion the old version
|
||||
* @return if newVersion is same as oldVersion
|
||||
*/
|
||||
public static boolean isEqual(SemanticVersion newVersion, SemanticVersion oldVersion) {
|
||||
return compare(newVersion, oldVersion).equals(VersionCheckResult.EQUAL);
|
||||
}
|
||||
|
||||
/**
|
||||
* Check if one version is newer.
|
||||
*
|
||||
* @param newVersion the new version
|
||||
* @param oldVersion the old version
|
||||
* @return if newVersion is newer
|
||||
*/
|
||||
public static boolean isNewer(SemanticVersion newVersion, SemanticVersion oldVersion) {
|
||||
return compare(newVersion, oldVersion).equals(VersionCheckResult.NEWER);
|
||||
}
|
||||
|
||||
/**
|
||||
* Check if one version is older.
|
||||
*
|
||||
* @param newVersion the new version
|
||||
* @param oldVersion the old version
|
||||
* @return if newVersion is older
|
||||
*/
|
||||
public static boolean isOlder(SemanticVersion newVersion, SemanticVersion oldVersion) {
|
||||
return compare(newVersion, oldVersion).equals(VersionCheckResult.OLDER);
|
||||
}
|
||||
|
||||
/**
|
||||
* Check if one version is newer or same.
|
||||
*
|
||||
* @param newVersion the new version
|
||||
* @param oldVersion the old version
|
||||
* @return if newVersion is newer or equal to
|
||||
*/
|
||||
public static boolean isNewerOrEqual(SemanticVersion newVersion, SemanticVersion oldVersion) {
|
||||
return isNewer(newVersion, oldVersion) || isEqual(newVersion, oldVersion);
|
||||
}
|
||||
|
||||
/**
|
||||
* Check if one version is older or same.
|
||||
*
|
||||
* @param newVersion the new version
|
||||
* @param oldVersion the old version
|
||||
* @return if newVersion is older or equal to
|
||||
*/
|
||||
public static boolean isOlderOrEqual(SemanticVersion newVersion, SemanticVersion oldVersion) {
|
||||
return isOlder(newVersion, oldVersion) || isEqual(newVersion, oldVersion);
|
||||
}
|
||||
|
||||
/**
|
||||
* Compare major, minor and patch version.
|
||||
*
|
||||
* @param newVersion the new version
|
||||
* @param oldVersion the old version
|
||||
* @return the version check result
|
||||
*/
|
||||
public static VersionCheckResult compare(SemanticVersion newVersion, SemanticVersion oldVersion) {
|
||||
double majorChange = newVersion.getMajor() - oldVersion.getMajor();
|
||||
double minorChange = newVersion.getMinor() - oldVersion.getMinor();
|
||||
double patchChange = newVersion.getPatch() - oldVersion.getPatch();
|
||||
|
||||
// If there are any changes in versioning we know whether the version is newer or not
|
||||
if (majorChange != 0)
|
||||
return majorChange < 0 ? VersionCheckResult.OLDER : VersionCheckResult.NEWER;
|
||||
|
||||
if (minorChange != 0)
|
||||
return minorChange < 0 ? VersionCheckResult.OLDER : VersionCheckResult.NEWER;
|
||||
|
||||
if (patchChange != 0)
|
||||
return patchChange < 0 ? VersionCheckResult.OLDER : VersionCheckResult.NEWER;
|
||||
|
||||
return compareMetadata(newVersion, oldVersion);
|
||||
}
|
||||
|
||||
/**
|
||||
* Compare build-metadata version.
|
||||
*
|
||||
* @param newVersion the new version
|
||||
* @param oldVersion the old version
|
||||
* @return the version check result
|
||||
*/
|
||||
public static VersionCheckResult compareMetadata(SemanticVersion newVersion, SemanticVersion oldVersion) {
|
||||
if (newVersion.isReleaseCandidate() && oldVersion.isReleaseCandidate()) {
|
||||
// Compare release candidate build number
|
||||
long rcBuild1 = Long.parseLong(newVersion.getPreRelease().substring(3));
|
||||
long rcBuild2 = Long.parseLong(oldVersion.getPreRelease().substring(3));
|
||||
|
||||
if (rcBuild1 == rcBuild2)
|
||||
return VersionCheckResult.EQUAL;
|
||||
|
||||
return rcBuild1 > rcBuild2 ? VersionCheckResult.NEWER : VersionCheckResult.OLDER;
|
||||
} else if (newVersion.isReleaseCandidate()) {
|
||||
return VersionCheckResult.NEWER;
|
||||
}
|
||||
|
||||
if (newVersion.isSnapshot() && oldVersion.isSnapshot()) {
|
||||
// Compare snapshot build number
|
||||
long snapshotBuild1 = Long.parseLong(newVersion.getPreRelease().substring(9));
|
||||
long snapshotBuild2 = Long.parseLong(oldVersion.getPreRelease().substring(9));
|
||||
|
||||
if (snapshotBuild1 == snapshotBuild2)
|
||||
return VersionCheckResult.EQUAL;
|
||||
|
||||
return snapshotBuild1 > snapshotBuild2 ? VersionCheckResult.NEWER : VersionCheckResult.OLDER;
|
||||
} else if (newVersion.isSnapshot()) {
|
||||
return VersionCheckResult.NEWER;
|
||||
}
|
||||
|
||||
return VersionCheckResult.EQUAL;
|
||||
}
|
||||
|
||||
/**
|
||||
* Gets major version.
|
||||
*
|
||||
* @return the major
|
||||
*/
|
||||
public long getMajor() {
|
||||
return major;
|
||||
}
|
||||
|
||||
/**
|
||||
* Gets minor minor.
|
||||
*
|
||||
* @return the minor
|
||||
*/
|
||||
public long getMinor() {
|
||||
return minor;
|
||||
}
|
||||
|
||||
/**
|
||||
* Gets patch version.
|
||||
*
|
||||
* @return the patch
|
||||
*/
|
||||
public long getPatch() {
|
||||
return patch;
|
||||
}
|
||||
|
||||
/**
|
||||
* Gets pre-release version.
|
||||
*
|
||||
* @return the pre release
|
||||
*/
|
||||
public String getPreRelease() {
|
||||
return preRelease;
|
||||
}
|
||||
|
||||
/**
|
||||
* Gets build-metadata.
|
||||
*
|
||||
* @return the metadata
|
||||
*/
|
||||
public String getMeta() {
|
||||
return meta;
|
||||
}
|
||||
|
||||
/**
|
||||
* Gets the simple Semantic version string containing only: major, minor and patch.
|
||||
*
|
||||
* @return the version
|
||||
*/
|
||||
public String getVersion() {
|
||||
return version;
|
||||
}
|
||||
|
||||
/**
|
||||
* Gets the full Semantic version string containing: major, minor, patch, pre-release and build-metadata.
|
||||
*
|
||||
* @return the full version
|
||||
*/
|
||||
public String getVersionFull() {
|
||||
return versionFull;
|
||||
}
|
||||
|
||||
/**
|
||||
* Is this version a release candidate.
|
||||
*
|
||||
* @return the boolean
|
||||
*/
|
||||
public boolean isReleaseCandidate() {
|
||||
return isReleaseCandidate;
|
||||
}
|
||||
|
||||
/**
|
||||
* Is this version a snapshot.
|
||||
*
|
||||
* @return the boolean
|
||||
*/
|
||||
public boolean isSnapshot() {
|
||||
return isSnapshot;
|
||||
}
|
||||
|
||||
/**
|
||||
* Concatenates to a Semantic versioning string
|
||||
*/
|
||||
private static String concatenateVersionString(long major, long minor, long patch) {
|
||||
return "%s.%s.%s".formatted(major, minor, patch);
|
||||
}
|
||||
|
||||
/**
|
||||
* Concatenates to a full Semantic versioning string
|
||||
*/
|
||||
private static String concatenateVersionFullString(long major, long minor, long patch, String preRelease, String meta) {
|
||||
return "%s%s%s".formatted(concatenateVersionString(major, minor, patch), (preRelease.isEmpty() ? "" : "-" + preRelease), (meta.isEmpty() ? "" : "+" + meta));
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,195 @@
|
||||
package com.github.alathra.alathranwars.updatechecker;
|
||||
|
||||
import com.github.milkdrinkers.colorparser.ColorParser;
|
||||
import com.google.gson.JsonObject;
|
||||
import com.google.gson.JsonParser;
|
||||
import com.github.alathra.alathranwars.AlathranWars;
|
||||
import com.github.alathra.alathranwars.Reloadable;
|
||||
import com.github.alathra.alathranwars.translation.Translation;
|
||||
import com.github.alathra.alathranwars.utility.Cfg;
|
||||
import com.github.alathra.alathranwars.utility.Logger;
|
||||
import org.jetbrains.annotations.Nullable;
|
||||
|
||||
import java.io.BufferedReader;
|
||||
import java.io.InputStream;
|
||||
import java.io.InputStreamReader;
|
||||
import java.net.URI;
|
||||
import java.net.http.HttpClient;
|
||||
import java.net.http.HttpRequest;
|
||||
import java.net.http.HttpResponse;
|
||||
import java.nio.charset.StandardCharsets;
|
||||
import java.time.Duration;
|
||||
|
||||
/**
|
||||
* The type Update checker.
|
||||
*/
|
||||
public class UpdateChecker implements Reloadable {
|
||||
// Options
|
||||
private final static String GITHUB_USER = "Alathra"; // The GitHub user/organization name
|
||||
private final static String GITHUB_REPO = "AlathranWars"; // The GitHub repository
|
||||
public final static String LATEST_RELEASE = "https://github.com/%s/%s/releases/latest".formatted(GITHUB_USER, GITHUB_REPO);
|
||||
public final static String LATEST_RELEASE_API = "https://api.github.com/repos/%s/%s/releases/latest".formatted(GITHUB_USER, GITHUB_REPO);
|
||||
|
||||
// Data
|
||||
private boolean isLatest = true;
|
||||
private @Nullable String pluginName;
|
||||
private @Nullable SemanticVersion currentVersion;
|
||||
private @Nullable SemanticVersion latestVersion;
|
||||
|
||||
/**
|
||||
* On plugin load.
|
||||
*/
|
||||
@Override
|
||||
public void onLoad() {
|
||||
}
|
||||
|
||||
/**
|
||||
* On plugin enable.
|
||||
*/
|
||||
@Override
|
||||
@SuppressWarnings("UnstableApiUsage")
|
||||
public void onEnable() {
|
||||
setPluginName(AlathranWars.getInstance().getPluginMeta().getName());
|
||||
setCurrentVersion(SemanticVersion.of(AlathranWars.getInstance().getPluginMeta().getVersion()));
|
||||
performUpdateCheck();
|
||||
}
|
||||
|
||||
/**
|
||||
* On plugin disable.
|
||||
*/
|
||||
@Override
|
||||
public void onDisable() {
|
||||
}
|
||||
|
||||
private void performUpdateCheck() {
|
||||
final boolean shouldLog = Cfg.get().getOrDefault("update-checker.enable", true) && Cfg.get().getOrDefault("update-checker.console", true);
|
||||
|
||||
try {
|
||||
HttpClient httpClient = HttpClient.newHttpClient();
|
||||
|
||||
HttpRequest req = HttpRequest.newBuilder()
|
||||
.uri(URI.create(LATEST_RELEASE_API))
|
||||
.timeout(Duration.ofSeconds(10))
|
||||
.build();
|
||||
|
||||
httpClient
|
||||
.sendAsync(req, HttpResponse.BodyHandlers.ofInputStream())
|
||||
.whenComplete((resp, err) -> {
|
||||
if (err != null) {
|
||||
if (shouldLog)
|
||||
Logger.get().warn(ColorParser.of(Translation.of("update-checker.update-failed")).parseMinimessagePlaceholder("error", err.getMessage()).build());
|
||||
return;
|
||||
}
|
||||
setLatestVersion(parseLatestVersion(resp.body()));
|
||||
checkVersion();
|
||||
});
|
||||
} catch (Exception err) {
|
||||
if (shouldLog)
|
||||
Logger.get().warn(ColorParser.of(Translation.of("update-checker.update-failed")).parseMinimessagePlaceholder("error", err.getMessage()).build());
|
||||
}
|
||||
}
|
||||
|
||||
private @Nullable SemanticVersion parseLatestVersion(InputStream inputStream) {
|
||||
try (BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream, StandardCharsets.UTF_8))) {
|
||||
final JsonObject json = JsonParser.parseReader(reader).getAsJsonObject();
|
||||
final String ver = json.getAsJsonPrimitive("tag_name").getAsString().toUpperCase();
|
||||
return SemanticVersion.of(ver);
|
||||
} catch (Exception e) {
|
||||
throw new RuntimeException("Failed to parse version JSON response.");
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Compare the current and latest.
|
||||
*/
|
||||
public void checkVersion() {
|
||||
if (pluginName == null)
|
||||
return;
|
||||
if (currentVersion == null)
|
||||
return;
|
||||
if (latestVersion == null)
|
||||
return;
|
||||
|
||||
final boolean shouldLog = Cfg.get().getOrDefault("update-checker.enable", true) && Cfg.get().getOrDefault("update-checker.console", true);
|
||||
|
||||
if (SemanticVersion.isNewer(latestVersion, currentVersion)) {
|
||||
setLatest(false);
|
||||
|
||||
if (!shouldLog)
|
||||
return;
|
||||
|
||||
Logger.get().info(
|
||||
ColorParser.of(Translation.of("update-checker.update-found-console"))
|
||||
.parseMinimessagePlaceholder("plugin_name", pluginName)
|
||||
.parseMinimessagePlaceholder("version_current", currentVersion.getVersionFull())
|
||||
.parseMinimessagePlaceholder("version_latest", latestVersion.getVersionFull())
|
||||
.parseMinimessagePlaceholder("download_link", LATEST_RELEASE)
|
||||
.build()
|
||||
);
|
||||
|
||||
} else if (SemanticVersion.isOlderOrEqual(latestVersion, currentVersion) || SemanticVersion.isEqual(latestVersion, currentVersion)) {
|
||||
setLatest(true);
|
||||
|
||||
if (!shouldLog)
|
||||
return;
|
||||
|
||||
Logger.get().info(
|
||||
ColorParser.of(Translation.of("update-checker.running-latest"))
|
||||
.parseMinimessagePlaceholder("plugin_name", pluginName)
|
||||
.build()
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns if the plugins is of the latest version.
|
||||
*
|
||||
* @return the boolean
|
||||
*/
|
||||
public boolean isLatest() {
|
||||
return isLatest;
|
||||
}
|
||||
|
||||
private void setLatest(boolean latest) {
|
||||
isLatest = latest;
|
||||
}
|
||||
|
||||
/**
|
||||
* Gets the plugin name.
|
||||
*
|
||||
* @return the plugin name
|
||||
*/
|
||||
public @Nullable String getPluginName() {
|
||||
return pluginName;
|
||||
}
|
||||
|
||||
private void setPluginName(@Nullable String pluginName) {
|
||||
this.pluginName = pluginName;
|
||||
}
|
||||
|
||||
/**
|
||||
* Gets current version of the plugin.
|
||||
*
|
||||
* @return the current version or null if it failed parse from the plugin.yml
|
||||
*/
|
||||
public @Nullable SemanticVersion getCurrentVersion() {
|
||||
return currentVersion;
|
||||
}
|
||||
|
||||
private void setCurrentVersion(@Nullable SemanticVersion currentVersion) {
|
||||
this.currentVersion = currentVersion;
|
||||
}
|
||||
|
||||
/**
|
||||
* Gets latest version.
|
||||
*
|
||||
* @return the latest version or null if it failed to fetch from github
|
||||
*/
|
||||
public @Nullable SemanticVersion getLatestVersion() {
|
||||
return latestVersion;
|
||||
}
|
||||
|
||||
private void setLatestVersion(@Nullable SemanticVersion latestVersion) {
|
||||
this.latestVersion = latestVersion;
|
||||
}
|
||||
}
|
||||
@@ -2,7 +2,7 @@ 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 com.github.milkdrinkers.crate.Config;
|
||||
import org.jetbrains.annotations.NotNull;
|
||||
|
||||
/**
|
||||
@@ -11,6 +11,8 @@ import org.jetbrains.annotations.NotNull;
|
||||
public abstract class Cfg {
|
||||
/**
|
||||
* Convenience method for {@link ConfigHandler#getConfig} to getConnection {@link Config}
|
||||
*
|
||||
* @return the config
|
||||
*/
|
||||
@NotNull
|
||||
public static Config get() {
|
||||
|
||||
@@ -1,9 +1,9 @@
|
||||
package com.github.alathra.alathranwars.utility;
|
||||
|
||||
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 com.github.alathra.alathranwars.database.DatabaseType;
|
||||
import com.github.alathra.alathranwars.database.handler.DatabaseHandler;
|
||||
import com.github.alathra.alathranwars.database.jooq.JooqContext;
|
||||
import org.jetbrains.annotations.NotNull;
|
||||
import org.jooq.DSLContext;
|
||||
|
||||
@@ -16,6 +16,9 @@ import java.sql.SQLException;
|
||||
public abstract class DB {
|
||||
/**
|
||||
* Convenience method for {@link DatabaseHandler#getConnection} to getConnection {@link Connection}
|
||||
*
|
||||
* @return the connection
|
||||
* @throws SQLException the sql exception
|
||||
*/
|
||||
@NotNull
|
||||
public static Connection getConnection() throws SQLException {
|
||||
@@ -24,6 +27,9 @@ public abstract class DB {
|
||||
|
||||
/**
|
||||
* Convenience method for {@link JooqContext#createContext(Connection)} to getConnection {@link DSLContext}
|
||||
*
|
||||
* @param con the con
|
||||
* @return the context
|
||||
*/
|
||||
@NotNull
|
||||
public static DSLContext getContext(Connection con) {
|
||||
@@ -32,6 +38,8 @@ public abstract class DB {
|
||||
|
||||
/**
|
||||
* Convenience method for {@link DatabaseHandler#getDB()} to getConnection {@link DatabaseType}
|
||||
*
|
||||
* @return the database
|
||||
*/
|
||||
public static DatabaseType getDB() {
|
||||
return AlathranWars.getInstance().getDataHandler().getDB();
|
||||
|
||||
@@ -0,0 +1,195 @@
|
||||
package com.github.alathra.alathranwars.utility;
|
||||
|
||||
import com.github.alathra.alathranwars.AlathranWars;
|
||||
import org.jetbrains.annotations.NotNull;
|
||||
|
||||
import java.io.File;
|
||||
import java.io.IOException;
|
||||
import java.io.InputStream;
|
||||
import java.net.URISyntaxException;
|
||||
import java.net.URL;
|
||||
import java.nio.file.*;
|
||||
import java.util.Collections;
|
||||
import java.util.Set;
|
||||
import java.util.stream.Collectors;
|
||||
import java.util.stream.Stream;
|
||||
|
||||
/**
|
||||
* A class that provides a plethora of useful file utilities.
|
||||
*/
|
||||
public abstract class FileUtils {
|
||||
// Parent
|
||||
|
||||
/**
|
||||
* Gets the parent dir of the provided path
|
||||
*
|
||||
* @param path Path to file or directory
|
||||
* @return Parent dir path as string
|
||||
*/
|
||||
public static Path getParentDirPath(@NotNull final Path path) {
|
||||
return getParentDirPath(path.toFile()).toPath();
|
||||
}
|
||||
|
||||
/**
|
||||
* Gets the parent dir of the provided path
|
||||
*
|
||||
* @param file File representing a file or directory
|
||||
* @return Parent dir path as string
|
||||
*/
|
||||
public static File getParentDirPath(@NotNull final File file) {
|
||||
return new File(getParentDirPath(file.getAbsolutePath()));
|
||||
}
|
||||
|
||||
/**
|
||||
* Gets the parent dir of the provided path
|
||||
*
|
||||
* @param path Path to file or directory
|
||||
* @return Parent dir path as string
|
||||
*/
|
||||
public static String getParentDirPath(@NotNull final String path) {
|
||||
final boolean endsWithSeparator = path.endsWith(File.separator);
|
||||
final int index = endsWithSeparator ? path.length() - 2 : path.length() - 1;
|
||||
|
||||
return path.substring(0, path.lastIndexOf(File.separatorChar, index));
|
||||
}
|
||||
|
||||
// File extensions
|
||||
|
||||
/**
|
||||
* Get the file extension from the given path
|
||||
*
|
||||
* @param path a path to a file or directory
|
||||
* @return a file extension or "" if none was found
|
||||
*/
|
||||
public static String getExtension(@NotNull final Path path) {
|
||||
return getExtension(path.getFileName().toString());
|
||||
}
|
||||
|
||||
/**
|
||||
* Get the file extension from the given file
|
||||
*
|
||||
* @param file a file representing a file or directory
|
||||
* @return a file extension or "" if none was found
|
||||
*/
|
||||
public static String getExtension(@NotNull final File file) {
|
||||
return getExtension(file.getName());
|
||||
}
|
||||
|
||||
/**
|
||||
* Get the file extension from the given string
|
||||
*
|
||||
* @param path a string representing a file or directory
|
||||
* @return a file extension or "" if none was found
|
||||
*/
|
||||
public static String getExtension(@NotNull final String path) {
|
||||
return path.lastIndexOf(".") > 0
|
||||
? path.substring(path.lastIndexOf(".") + 1)
|
||||
: "";
|
||||
}
|
||||
|
||||
/**
|
||||
* Strips file extension from the given path resulting in the file or directory name
|
||||
*
|
||||
* @param path a path to a file or directory
|
||||
* @return a name stripped of file extension
|
||||
*/
|
||||
public static String stripExtension(@NotNull final Path path) {
|
||||
return stripExtension(path.getFileName().toString());
|
||||
}
|
||||
|
||||
/**
|
||||
* Strips file extension from the given file resulting in the file or directory name
|
||||
*
|
||||
* @param file a file representing a file or directory
|
||||
* @return a name stripped of file extension
|
||||
*/
|
||||
public static String stripExtension(@NotNull final File file) {
|
||||
return stripExtension(file.getName());
|
||||
}
|
||||
|
||||
/**
|
||||
* Strips file extension from the given path/file/string resulting in the file or directory name
|
||||
*
|
||||
* @param fileName a filename
|
||||
* @return a name stripped of file extension
|
||||
*/
|
||||
public static String stripExtension(@NotNull final String fileName) {
|
||||
if (!fileName.contains(".")) {
|
||||
return fileName;
|
||||
}
|
||||
|
||||
return fileName.substring(0, fileName.lastIndexOf("."));
|
||||
}
|
||||
|
||||
// Resource
|
||||
|
||||
/**
|
||||
* Copy a file from the plugin jar to targetPath.
|
||||
*
|
||||
* @param resourcePath A relative path pointing to a file/directory in the jar
|
||||
* @param targetPath A path pointing to a file/directory in the jar
|
||||
* @param overwrite Whether to overwrite the file if it already exists
|
||||
* @throws IOException O
|
||||
*/
|
||||
public static void extractResource(
|
||||
@NotNull final Path resourcePath,
|
||||
@NotNull final Path targetPath,
|
||||
@NotNull final boolean overwrite
|
||||
) throws IOException {
|
||||
// Check if path is absolute which breaks our relative path navigation below
|
||||
if (resourcePath.isAbsolute())
|
||||
throw new IllegalStateException("Directory path is absolute.");
|
||||
|
||||
final File targetDir = getParentDirPath(targetPath.toFile());
|
||||
|
||||
// Ensure target directory exists
|
||||
if (!targetDir.exists())
|
||||
if (!targetDir.mkdirs())
|
||||
throw new IllegalStateException("Failed to create directories.");
|
||||
|
||||
// Overwrite check
|
||||
if (targetPath.toFile().exists() && !overwrite)
|
||||
return;
|
||||
|
||||
try (
|
||||
InputStream stream = AlathranWars.getInstance().getResource(resourcePath.toString().replace('\\', '/'))
|
||||
) {
|
||||
if (stream == null)
|
||||
throw new IllegalStateException("Input stream is null.");
|
||||
|
||||
Files.copy(stream, targetPath, StandardCopyOption.REPLACE_EXISTING);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns a list of all files found in a directory located in the plugin jar.
|
||||
*
|
||||
* @param resourcePath A relative path pointing to a directory in the jar
|
||||
* @return A list of all files (excluding directories)
|
||||
* @throws URISyntaxException Thrown when jar cannot be accessed
|
||||
* @throws IOException Thrown when jar cannot be accessed
|
||||
* @throws IllegalStateException Misc errors
|
||||
*/
|
||||
public static Set<String> resourceListFiles(
|
||||
@NotNull final Path resourcePath
|
||||
) throws URISyntaxException, IOException, IllegalStateException {
|
||||
// Check if path is absolute which breaks our relative path navigation below
|
||||
if (resourcePath.isAbsolute())
|
||||
throw new IllegalStateException("Directory path is absolute.");
|
||||
|
||||
final URL url = AlathranWars.getInstance().getClass().getResource("");
|
||||
|
||||
// Check access to the jar
|
||||
if (url == null)
|
||||
throw new IllegalStateException("Cannot access jar.");
|
||||
|
||||
try (
|
||||
final FileSystem fs = FileSystems.newFileSystem(url.toURI(), Collections.emptyMap());
|
||||
final Stream<Path> pathStream = Files.list(fs.getRootDirectories().iterator().next().resolve(resourcePath.toString()))
|
||||
) {
|
||||
return pathStream
|
||||
.map(path -> path.getFileName().toString())
|
||||
.collect(Collectors.toSet());
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1,42 +0,0 @@
|
||||
package com.github.alathra.alathranwars.utility;
|
||||
|
||||
import com.github.alathra.alathranwars.conflict.war.WarController;
|
||||
import org.jetbrains.annotations.NotNull;
|
||||
import org.jetbrains.annotations.Nullable;
|
||||
|
||||
import java.util.UUID;
|
||||
|
||||
/**
|
||||
* Convenience class for generating UUID for different things in the plugin
|
||||
*/
|
||||
public abstract class UUIDUtil {
|
||||
public static @NotNull UUID generateWarUUID() {
|
||||
@NotNull UUID uuid = UUID.randomUUID();
|
||||
|
||||
while (WarController.getInstance().getWar(uuid) != null) {
|
||||
uuid = UUID.randomUUID();
|
||||
}
|
||||
|
||||
return uuid;
|
||||
}
|
||||
|
||||
public static @NotNull UUID generateSideUUID(@Nullable UUID previousSideUUID) {
|
||||
@NotNull UUID uuid = UUID.randomUUID();
|
||||
|
||||
while (WarController.getInstance().getSide(uuid) != null || uuid == previousSideUUID) {
|
||||
uuid = UUID.randomUUID();
|
||||
}
|
||||
|
||||
return uuid;
|
||||
}
|
||||
|
||||
public static @NotNull UUID generateSiegeUUID() {
|
||||
@NotNull UUID uuid = UUID.randomUUID();
|
||||
|
||||
while (WarController.getInstance().getSiege(uuid) != null) {
|
||||
uuid = UUID.randomUUID();
|
||||
}
|
||||
|
||||
return uuid;
|
||||
}
|
||||
}
|
||||
@@ -199,7 +199,7 @@ public abstract class Utils {
|
||||
// TODO Implement usage in siege commands to make siege optional argument
|
||||
public static @Nullable Siege getClosestSiege(Player p, boolean checkIfInSiege) {
|
||||
Set<Siege> sieges = checkIfInSiege
|
||||
? WarController.getInstance().getSieges().stream().filter(siege -> siege.isPlayerInSiege(p)).collect(Collectors.toSet())
|
||||
? WarController.getInstance().getSieges().stream().filter(siege -> siege.isPlayerParticipating(p)).collect(Collectors.toSet())
|
||||
: WarController.getInstance().getSieges();
|
||||
|
||||
@Nullable Siege siegeResult = null;
|
||||
|
||||
Reference in new issue
Block a user