diff --git a/src/main/java/net/cytonic/cytosis/CytonicNetwork.java b/src/main/java/net/cytonic/cytosis/CytonicNetwork.java index fd64132b..f59d5340 100644 --- a/src/main/java/net/cytonic/cytosis/CytonicNetwork.java +++ b/src/main/java/net/cytonic/cytosis/CytonicNetwork.java @@ -2,6 +2,7 @@ import lombok.Getter; import net.cytonic.cytosis.data.RedisDatabase; + import java.util.HashSet; import java.util.Set; import java.util.UUID; @@ -14,6 +15,17 @@ public class CytonicNetwork { private final Set networkPlayers = new HashSet<>(); private final Set networkPlayerUUIDs = new HashSet<>(); + /** + * The default constructor + */ + public CytonicNetwork() { + } + + /** + * Imports online player data from redis + * + * @param redisDatabase The redis instance + */ public void importDataFromRedis(RedisDatabase redisDatabase) { networkPlayers.clear(); networkPlayerUUIDs.clear(); @@ -21,11 +33,21 @@ public void importDataFromRedis(RedisDatabase redisDatabase) { networkPlayerUUIDs.addAll(redisDatabase.getOnlineUUIDs()); } + /** + * Adds a player to the cache + * @param name The player's name + * @param uuid The player's UUID + */ public void addPlayer(String name, UUID uuid) { networkPlayers.add(name); networkPlayerUUIDs.add(uuid); } + /** + * Removes the player from the cache + * @param name The player's name + * @param uuid The player's UUID + */ public void removePlayer(String name, UUID uuid) { networkPlayers.remove(name); networkPlayerUUIDs.remove(uuid); diff --git a/src/main/java/net/cytonic/cytosis/Cytosis.java b/src/main/java/net/cytonic/cytosis/Cytosis.java index ed45ae80..43bf7fdc 100644 --- a/src/main/java/net/cytonic/cytosis/Cytosis.java +++ b/src/main/java/net/cytonic/cytosis/Cytosis.java @@ -33,13 +33,25 @@ import net.minestom.server.network.ConnectionManager; import net.minestom.server.permission.Permission; import org.jetbrains.annotations.Nullable; + import java.util.*; + import static net.cytonic.cytosis.utils.MiniMessageTemplate.MM; +/** + * The main class for Cytosis + */ @Getter -public class Cytosis { +public final class Cytosis { + /** + * the instance ID is used to identify the server + */ public static final String SERVER_ID = generateID(); + /** + * The version of Cytosis + */ + public static final String VERSION = "0.1"; // manager stuff @Getter private static MinecraftServer minecraftServer; @@ -78,10 +90,16 @@ public class Cytosis { private static SideboardManager sideboardManager; @Getter private static NPCManager npcManager; - public static final String VERSION = "0.1"; - private static List FLAGS; + private Cytosis() { + } + + /** + * The entry point for the Minecraft Server + * + * @param args Runtime flags + */ public static void main(String[] args) { FLAGS = List.of(args); long start = System.currentTimeMillis(); @@ -135,12 +153,23 @@ public static void main(String[] args) { }); } + /** + * Gets the players currently on THIS instance + * + * @return a set of players + */ public static Set getOnlinePlayers() { Set players = new HashSet<>(); instanceManager.getInstances().forEach(instance -> players.addAll(instance.getPlayers())); return players; } + /** + * Gets the player if they are on THIS instance, by USERNAME + * + * @param username The name to fetch the player by + * @return The optional holding the player if they exist + */ public static Optional getPlayer(String username) { Player target = null; for (Player onlinePlayer : getOnlinePlayers()) @@ -162,19 +191,35 @@ public static Optional getPlayer(UUID uuid) { return Optional.ofNullable(target); } + /** + * Gives a player all permissions + * + * @param player to grant all permissions to + */ public static void opPlayer(Player player) { player.addPermission(new Permission("*")); // give them every permission } + /** + * Removes the '*' permission from a player + * + * @param player The player to remove the '*' permission from + */ public static void deopPlayer(Player player) { player.removePermission("*"); // remove every permission } + /** + * Sets up Mojang Authentication + */ public static void mojangAuth() { Logger.info("Initializing Mojang Authentication"); MojangAuth.init(); //VERY IMPORTANT! (This is online mode!) } + /** + * Loads the world based on the settings + */ public static void loadWorld() { if (CytosisSettings.SERVER_WORLD_NAME.isEmpty()) { Logger.info("Generating basic world"); @@ -195,6 +240,11 @@ public static void loadWorld() { }); } + /** + * Completes nonessential startup tasks for the server + * + * @param start The time the server started + */ public static void completeNonEssentialTasks(long start) { Logger.info("Initializing database"); databaseManager = new DatabaseManager(); @@ -299,6 +349,13 @@ public static void completeNonEssentialTasks(long start) { } + /** + * Generates a random Server ID: + *

+ * TODO: make a check for existing server ids + * + * @return a random Server ID + */ private static String generateID() { //todo: make a check for existing server ids StringBuilder id = new StringBuilder("Cytosis-"); @@ -311,6 +368,13 @@ private static String generateID() { return id.toString(); } + /** + * Gets the Raw ID of the server + *

+ * For example, Cytosis-a1234b would return a1234b + * + * @return The raw ID + */ public static String getRawID() { return Cytosis.SERVER_ID.replace("Cytosis-", ""); } diff --git a/src/main/java/net/cytonic/cytosis/auditlog/Category.java b/src/main/java/net/cytonic/cytosis/auditlog/Category.java index 2147be6c..4783fe26 100644 --- a/src/main/java/net/cytonic/cytosis/auditlog/Category.java +++ b/src/main/java/net/cytonic/cytosis/auditlog/Category.java @@ -1,10 +1,31 @@ package net.cytonic.cytosis.auditlog; +/** + * An enum for the different audit log categories + */ public enum Category { + /** + * A player ban + */ BAN, + /** + * A player unban + */ UNBAN, + /** + * A player mute + */ MUTE, + /** + * A player unmute + */ UNMUTE, + /** + * A player IP ban + */ IPBAN, + /** + * A player IP unban + */ IPUNBAN } \ No newline at end of file diff --git a/src/main/java/net/cytonic/cytosis/auditlog/Entry.java b/src/main/java/net/cytonic/cytosis/auditlog/Entry.java index 656933bc..5f694eb8 100644 --- a/src/main/java/net/cytonic/cytosis/auditlog/Entry.java +++ b/src/main/java/net/cytonic/cytosis/auditlog/Entry.java @@ -2,5 +2,13 @@ import java.util.UUID; +/** + * A class representing an entry in the audit log + * + * @param uuid The UUID of the player + * @param actor The UUID of the actor who caused the entry + * @param category The cateory of the entry + * @param reason The reason for the entry + */ public record Entry(UUID uuid, UUID actor, Category category, String reason) { } \ No newline at end of file diff --git a/src/main/java/net/cytonic/cytosis/commands/ChatChannelCommand.java b/src/main/java/net/cytonic/cytosis/commands/ChatChannelCommand.java index 9581b3ec..5d0f81bf 100644 --- a/src/main/java/net/cytonic/cytosis/commands/ChatChannelCommand.java +++ b/src/main/java/net/cytonic/cytosis/commands/ChatChannelCommand.java @@ -9,8 +9,14 @@ import net.minestom.server.command.builder.suggestion.SuggestionEntry; import net.minestom.server.entity.Player; +/** + * A class that handles the chat channel command + */ public class ChatChannelCommand extends Command { + /** + * Creates the command + */ public ChatChannelCommand() { super("chat"); setDefaultExecutor((sender, _) -> sender.sendMessage(Component.text("You must specify a channel!", NamedTextColor.RED))); diff --git a/src/main/java/net/cytonic/cytosis/commands/CommandHandler.java b/src/main/java/net/cytonic/cytosis/commands/CommandHandler.java index ca7a7cec..36fba68a 100644 --- a/src/main/java/net/cytonic/cytosis/commands/CommandHandler.java +++ b/src/main/java/net/cytonic/cytosis/commands/CommandHandler.java @@ -4,21 +4,31 @@ import net.cytonic.cytosis.commands.moderation.BanCommand; import net.minestom.server.command.CommandManager; import net.minestom.server.entity.Player; + import java.util.Scanner; import java.util.concurrent.Executors; import java.util.concurrent.ScheduledExecutorService; import java.util.concurrent.TimeUnit; +/** + * A class that handles the commands, their execution, and allegedly a console. + */ public class CommandHandler { private final ScheduledExecutorService worker; private final Scanner CONSOLE_IN = new Scanner(System.in); private final Object consoleLock = new Object(); + /** + * Creates a command handler and sets up the worker + */ public CommandHandler() { this.worker = Executors.newSingleThreadScheduledExecutor(Thread.ofVirtual().name("CytosisConsoleWorker").factory()); } + /** + * Registers the default Cytosis commands + */ public void registerCytosisCommands() { CommandManager cm = Cytosis.getCommandManager(); cm.register(new GamemodeCommand()); @@ -28,11 +38,19 @@ public void registerCytosisCommands() { cm.register(new StopCommand()); } + /** + * Sends a packet to the player to recalculate command permissions + * + * @param player The player to send the packet to + */ @SuppressWarnings("UnstableApiUsage") public void recalculateCommands(Player player) { player.sendPacket(Cytosis.getCommandManager().createDeclareCommandsPacket(player)); } + /** + * Sets up the console so commands can be executed from there + */ public void setupConsole() { worker.scheduleAtFixedRate(() -> { if (CONSOLE_IN.hasNext()) { diff --git a/src/main/java/net/cytonic/cytosis/commands/GamemodeCommand.java b/src/main/java/net/cytonic/cytosis/commands/GamemodeCommand.java index 4e0ec15c..ebebf068 100644 --- a/src/main/java/net/cytonic/cytosis/commands/GamemodeCommand.java +++ b/src/main/java/net/cytonic/cytosis/commands/GamemodeCommand.java @@ -9,8 +9,14 @@ import net.minestom.server.entity.GameMode; import net.minestom.server.entity.Player; +/** + * The class representing the gamemode command + */ public class GamemodeCommand extends Command { + /** + * Creates a new command and sets up the consumers and execution logic + */ public GamemodeCommand() { super("gamemode", "gm"); setCondition((sender, _) -> sender.hasPermission("cytosis.commands.gamemode")); diff --git a/src/main/java/net/cytonic/cytosis/commands/RankCommand.java b/src/main/java/net/cytonic/cytosis/commands/RankCommand.java index 83f53563..cc12c38e 100644 --- a/src/main/java/net/cytonic/cytosis/commands/RankCommand.java +++ b/src/main/java/net/cytonic/cytosis/commands/RankCommand.java @@ -15,8 +15,14 @@ import static net.cytonic.cytosis.utils.MiniMessageTemplate.MM; +/** + * A command that allows players to change another player's rank + */ public class RankCommand extends Command { + /** + * A command that allows authorized users to change player ranks + */ public RankCommand() { super("rank"); setCondition((sender, _) -> sender.hasPermission("cytosis.commands.rank")); diff --git a/src/main/java/net/cytonic/cytosis/commands/StopCommand.java b/src/main/java/net/cytonic/cytosis/commands/StopCommand.java index 03b864ea..3520e645 100644 --- a/src/main/java/net/cytonic/cytosis/commands/StopCommand.java +++ b/src/main/java/net/cytonic/cytosis/commands/StopCommand.java @@ -3,8 +3,14 @@ import net.minestom.server.MinecraftServer; import net.minestom.server.command.builder.Command; +/** + * A class representing the stop command + */ public class StopCommand extends Command { + /** + * A simple command to stop the server + */ public StopCommand() { super("stop"); setCondition((sender, _) -> sender.hasPermission("cytosis.commands.stop")); diff --git a/src/main/java/net/cytonic/cytosis/commands/moderation/BanCommand.java b/src/main/java/net/cytonic/cytosis/commands/moderation/BanCommand.java index d68679ee..fb8cb9a1 100644 --- a/src/main/java/net/cytonic/cytosis/commands/moderation/BanCommand.java +++ b/src/main/java/net/cytonic/cytosis/commands/moderation/BanCommand.java @@ -20,7 +20,13 @@ import static net.cytonic.cytosis.utils.MiniMessageTemplate.MM; +/** + * A command that allows authorized players to ban players. + */ public class BanCommand extends Command { + /** + * Creates the command and sets the consumers + */ public BanCommand() { super("ban"); setCondition((sender, _) -> sender.hasPermission("cytosis.commands.moderation.ban")); diff --git a/src/main/java/net/cytonic/cytosis/config/CytosisSettings.java b/src/main/java/net/cytonic/cytosis/config/CytosisSettings.java index 5a47c409..83a661c0 100644 --- a/src/main/java/net/cytonic/cytosis/config/CytosisSettings.java +++ b/src/main/java/net/cytonic/cytosis/config/CytosisSettings.java @@ -1,49 +1,132 @@ package net.cytonic.cytosis.config; import net.cytonic.cytosis.logging.Logger; - import net.cytonic.cytosis.utils.PosSerializer; import net.minestom.server.coordinate.Pos; + import java.util.Map; /** * This class is used to store all the cached configuration values. */ -public class CytosisSettings { +public final class CytosisSettings { + /** + * Defualt constructor + */ + private CytosisSettings() { + } + // Logging + /** + * Should the server log player joins + */ public static boolean LOG_PLAYER_JOINS = true; + /** + * Should the server log player quits + */ public static boolean LOG_PLAYER_QUITS = true; + /** + * Should the server log player commands + */ public static boolean LOG_PLAYER_COMMANDS = true; + /** + * Should the server log player chat messages + */ public static boolean LOG_PLAYER_CHAT = true; // Database + /** + * Should the server use the database + */ public static boolean DATABASE_ENABLED = true; + /** + * Database username + */ public static String DATABASE_USER = ""; + /** + * Database password + */ public static String DATABASE_PASSWORD = ""; + /** + * Hostname of the database server + */ public static String DATABASE_HOST = ""; + /** + * Database port + */ public static int DATABASE_PORT = 3306; + /** + * Name of the database to use + */ public static String DATABASE_NAME = ""; + /** + * Use SSL? + */ public static boolean DATABASE_USE_SSL = false; // server + /** + * Should Cytosis run in proxy mode? + */ public static boolean SERVER_PROXY_MODE = false; - public static String SERVER_SECRET = ""; + /** + * The velocity forwarding secret + */ + public static String SERVER_SECRET = "cannot-be-empty"; + /** + * The port to start on + */ public static int SERVER_PORT = 25565; + /** + * The name of the world to load from the database + */ public static String SERVER_WORLD_NAME = ""; + /** + * The pos for players to spawn at + */ public static Pos SERVER_SPAWN_POS = new Pos(0, 1, 0); - // RabbitMQ + + /** + * Should Cytosis use RabbitMQ? + */ public static boolean RABBITMQ_ENABLED = false; + /** + * hostname of the RabbitMQ server + */ public static String RABBITMQ_HOST = ""; + /** + * RabbitMQ Password + */ public static String RABBITMQ_PASSWORD = ""; + /** + * RabbitMQ server username + */ public static String RABBITMQ_USERNAME = ""; + /** + * The port to connect to RabbitMQ on + */ public static int RABBITMQ_PORT = 5672; //Redis + /** + * The redis port + */ public static int REDIS_PORT = 6379; + /** + * The redis hostname + */ public static String REDIS_HOST = ""; + /** + * The redis password + */ public static String REDIS_PASSWORD = ""; + /** + * Loads the config from a config map + * + * @param config The config map of key value pairs + */ public static void inportConfig(Map config) { Logger.info("Importing config!"); config.forEach((key, value) -> { @@ -93,6 +176,9 @@ private static int toInt(Object key) { return Integer.parseInt(key.toString()); } + /** + * Load settings from environment variables + */ public static void loadEnvironmentVariables() { Logger.info("Loading environment variables!"); // logging @@ -143,6 +229,9 @@ public static void loadEnvironmentVariables() { if (!(System.getenv("REDIS_PASSWORD") == null)) REDIS_PASSWORD = System.getenv("REDIS_PASSWORD"); } + /** + * Load settings from command args (System Properties) + */ public static void loadCommandArgs() { Logger.info("Loading command args!"); // logging diff --git a/src/main/java/net/cytonic/cytosis/data/DatabaseManager.java b/src/main/java/net/cytonic/cytosis/data/DatabaseManager.java index b05bd8be..d0d33856 100644 --- a/src/main/java/net/cytonic/cytosis/data/DatabaseManager.java +++ b/src/main/java/net/cytonic/cytosis/data/DatabaseManager.java @@ -5,19 +5,34 @@ import java.util.concurrent.CompletableFuture; +/** + * A class managing databases + */ @Getter public class DatabaseManager { private MysqlDatabase mysqlDatabase; private RedisDatabase redisDatabase; + /** + * The default constructor + */ public DatabaseManager() {} + /** + * Disconnects from the databases + */ public void shutdown() { mysqlDatabase.disconnect(); + redisDatabase.disconnect(); Logger.info("Good night!"); } + /** + * Sets up the databases by creating tables and creating connections + * + * @return A future that completes once all databases are connected + */ public CompletableFuture setupDatabases() { CompletableFuture future = new CompletableFuture<>(); Logger.info("Connecting to MySQL Database."); diff --git a/src/main/java/net/cytonic/cytosis/data/DatabaseTemplate.java b/src/main/java/net/cytonic/cytosis/data/DatabaseTemplate.java index 114d0485..15ea260b 100644 --- a/src/main/java/net/cytonic/cytosis/data/DatabaseTemplate.java +++ b/src/main/java/net/cytonic/cytosis/data/DatabaseTemplate.java @@ -5,13 +5,23 @@ import java.sql.ResultSet; import java.util.concurrent.CompletableFuture; +/** + * A class providing utility StringTemplates for the database + */ public final class DatabaseTemplate { private DatabaseTemplate() { } + + /** + * Queries the database with the specified SQL string + */ @SuppressWarnings("preview") public static final StringTemplate.Processor, RuntimeException> QUERY = stringTemplate -> Cytosis.getDatabaseManager().getMysqlDatabase().query(STR.process(stringTemplate)); + /** + * Updates the database with the specified SQL string + */ @SuppressWarnings("preview") public static final StringTemplate.Processor, RuntimeException> UPDATE = stringTemplate -> Cytosis.getDatabaseManager().getMysqlDatabase().update(STR.process(stringTemplate)); diff --git a/src/main/java/net/cytonic/cytosis/data/MysqlDatabase.java b/src/main/java/net/cytonic/cytosis/data/MysqlDatabase.java index eb5f6a5b..520b385a 100644 --- a/src/main/java/net/cytonic/cytosis/data/MysqlDatabase.java +++ b/src/main/java/net/cytonic/cytosis/data/MysqlDatabase.java @@ -24,6 +24,9 @@ import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; +/** + * A class handling Cytosis database transactions + */ public class MysqlDatabase { private final ExecutorService worker; @@ -35,6 +38,9 @@ public class MysqlDatabase { private final boolean ssl; private Connection connection; + /** + * Creates and initializes a new MysqlDatabase + */ public MysqlDatabase() { this.worker = Executors.newSingleThreadExecutor(Thread.ofVirtual().name("CytosisDatabaseWorker").uncaughtExceptionHandler((t, e) -> Logger.error(STR."An uncaught exception occoured on the thread: \{t.getName()}", e)).factory()); this.host = CytosisSettings.DATABASE_HOST; @@ -50,10 +56,19 @@ public MysqlDatabase() { } } + /** + * Checks if the database is connected + * + * @return if the database is connected + */ public boolean isConnected() { return (connection != null); } + /** + * connects to the database + * @return a future that completes when the connection is successful + */ public CompletableFuture connect() { CompletableFuture future = new CompletableFuture<>(); worker.submit(() -> { @@ -72,6 +87,9 @@ public CompletableFuture connect() { return future; } + /** + * Disconnects from the database server + */ public void disconnect() { worker.submit(() -> { if (isConnected()) { @@ -85,6 +103,9 @@ public void disconnect() { }); } + /** + * Creates the database tables + */ public void createTables() { createChatTable(); createRanksTable(); @@ -96,10 +117,17 @@ public void createTables() { createAuditLogTable(); } + /** + * Gets the connection + * @return the connection to the database + */ private Connection getConnection() { return connection; } + /** + * Creates the chat messages table + */ private void createChatTable() { worker.submit(() -> { if (isConnected()) { @@ -114,6 +142,9 @@ private void createChatTable() { }); } + /** + * Creates the ranks table + */ private void createRanksTable() { worker.submit(() -> { if (isConnected()) { @@ -128,6 +159,9 @@ private void createRanksTable() { }); } + /** + * Creates the bans table + */ private void createBansTable() { worker.submit(() -> { if (isConnected()) { @@ -142,6 +176,9 @@ private void createBansTable() { }); } + /** + * Creates the player data table + */ private void createPlayersTable() { worker.submit(() -> { if (isConnected()) { @@ -156,6 +193,9 @@ private void createPlayersTable() { }); } + /** + * Creates the world table + */ public void createWorldTable() { worker.submit(() -> { if (isConnected()) { @@ -190,6 +230,9 @@ private void createChatChannelsTable() { }); } + /** + * Create the player join logging table + */ private void createPlayerJoinsTable() { worker.submit(() -> { if (isConnected()) { @@ -258,6 +301,7 @@ public CompletableFuture getPlayerRank(@NotNull final UUID uuid) { * @param uuid The player's UUID * @param rank The player's rank constant * @throws IllegalStateException if the database isn't connected + * @return a future that completes when the update is complete */ public CompletableFuture setPlayerRank(UUID uuid, PlayerRank rank) { if (!isConnected()) @@ -277,6 +321,11 @@ public CompletableFuture setPlayerRank(UUID uuid, PlayerRank rank) { return future; } + /** + * Add a chat message to the log + * @param uuid The UUID of the sender + * @param message The message to log + */ public void addChat(UUID uuid, String message) { worker.submit(() -> { PreparedStatement ps; @@ -291,6 +340,11 @@ public void addChat(UUID uuid, String message) { }); } + /** + * Adds an auditlog entry + * @param entry The entry to add + * @return a future that completes when the entry is added + */ public CompletableFuture addAuditLogEntry(Entry entry) { if (!isConnected()) throw new IllegalStateException("The database must be connected to add an auditlog entry."); CompletableFuture future = new CompletableFuture<>(); @@ -312,6 +366,13 @@ public CompletableFuture addAuditLogEntry(Entry entry) { return future; } + /** + * Bans a player + * @param uuid the player to ban + * @param reason The reason to ban the player + * @param toExpire When the ban expires + * @return a future that completes when the player is banned + */ public CompletableFuture banPlayer(UUID uuid, String reason, Instant toExpire) { CompletableFuture future = new CompletableFuture<>(); @@ -372,6 +433,11 @@ public CompletableFuture isBanned(UUID uuid) { return future; } + /** + * Finds a player's UUID by name + * @param name the player's name + * @return a future that completes with the player's UUID + */ public CompletableFuture findUUIDByName(String name) { if (!isConnected()) throw new IllegalStateException("The database must be connected."); CompletableFuture future = new CompletableFuture<>(); @@ -393,6 +459,11 @@ public CompletableFuture findUUIDByName(String name) { return future; } + /** + * Adds a or updates a player's name in the data + * @param player The player to update + * @return a future that completes when the update is complete + */ public CompletableFuture addPlayer(Player player) { if (!isConnected()) throw new IllegalStateException("The database must be connected."); CompletableFuture future = new CompletableFuture<>(); @@ -412,6 +483,11 @@ public CompletableFuture addPlayer(Player player) { return future; } + /** + * Unbans a player + * @param uuid the player to unban + * @return a future that completes when the player is unbanned + */ public CompletableFuture unbanPlayer(UUID uuid) { if (!isConnected()) throw new IllegalStateException("The database must be connected."); CompletableFuture future = new CompletableFuture<>(); @@ -429,6 +505,11 @@ public CompletableFuture unbanPlayer(UUID uuid) { return future; } + /** + * Sets a player's chat channel + * @param uuid the player + * @param chatChannel the chat channel to select + */ public void setChatChannel(UUID uuid, ChatChannel chatChannel) { worker.submit(() -> { if (!isConnected()) @@ -445,6 +526,11 @@ public void setChatChannel(UUID uuid, ChatChannel chatChannel) { }); } + /** + * Gets a player's chat channel + * @param uuid the player + * @return a future that completes with the player's chat channel + */ public CompletableFuture getChatChannel(@NotNull final UUID uuid) { CompletableFuture future = new CompletableFuture<>(); if (!isConnected()) diff --git a/src/main/java/net/cytonic/cytosis/data/RedisDatabase.java b/src/main/java/net/cytonic/cytosis/data/RedisDatabase.java index cd9967ad..9a78d2e9 100644 --- a/src/main/java/net/cytonic/cytosis/data/RedisDatabase.java +++ b/src/main/java/net/cytonic/cytosis/data/RedisDatabase.java @@ -4,6 +4,7 @@ import net.cytonic.cytosis.config.CytosisSettings; import net.cytonic.cytosis.logging.Logger; import redis.clients.jedis.*; + import java.util.HashSet; import java.util.Set; import java.util.UUID; @@ -15,10 +16,10 @@ */ public class RedisDatabase extends JedisPubSub { - public static final String ONLINE_PLAYER_NAME_KEY = "online_player_names"; - public static final String ONLINE_PLAYER_UUID_KEY = "online_player_uuids"; - public static final String PLAYER_STATUS_CHANNEL = "player_status"; - public static final String SERVER_SHUTDOWN_KEY = "server_shutdown"; + private final String ONLINE_PLAYER_NAME_KEY = "online_player_names"; + private final String ONLINE_PLAYER_UUID_KEY = "online_player_uuids"; + private final String PLAYER_STATUS_CHANNEL = "player_status"; + private final String SERVER_SHUTDOWN_KEY = "server_shutdown"; private final Jedis jedis; private final ExecutorService worker = Executors.newSingleThreadExecutor(Thread.ofVirtual().name("CytosisRedisWorker").factory()); @Getter @@ -42,6 +43,9 @@ public RedisDatabase() { worker.submit(() -> jedis.subscribe(this, PLAYER_STATUS_CHANNEL)); } + /** + * Sends a server shutdown message to the redis server + */ public void sendShutdownMessage() { jedis.set(SERVER_SHUTDOWN_KEY, ""); } @@ -66,6 +70,9 @@ public void onMessage(String channel, String message) { } } + /** + * Disconnects from the redis server + */ public void disconnect() { jedis.disconnect(); } diff --git a/src/main/java/net/cytonic/cytosis/data/enums/BanReason.java b/src/main/java/net/cytonic/cytosis/data/enums/BanReason.java index 4ec72bd3..a4df2c05 100644 --- a/src/main/java/net/cytonic/cytosis/data/enums/BanReason.java +++ b/src/main/java/net/cytonic/cytosis/data/enums/BanReason.java @@ -2,19 +2,47 @@ import lombok.Getter; +/** + * The reasons a player could be banned + */ @Getter public enum BanReason { + /** + * Cheating or hacking + */ CHEATING("Cheating/Hacking"), + /** + * A skin or cape that is not allowed + */ INAPROPRIATE_COSMETICS("Using a skin, cape, or other inappropriate cosmetics"), + /** + * Building something that violates the terms of service + */ INAPROPRIATE_BUILDING("Building a structure that violates our terms of service"), + /** + * Used when an accounts security is compromised + */ SECURITY("This account is suspended due to security concerns"), + /** + * Used for severe chat infractions + */ SEVERE_CHAT_INFRACTION("Severe chat infractions"), + /** + * Abusing bugs or exploits + */ EXPLOITING("Exploiting bugs or defects to your advantage"), - SCAMMING("Violating our terms of service by attempting to scam another player"), - ; + /** + * Scamming another user + */ + SCAMMING("Violating our terms of service by attempting to scam another player"); private final String reason; + /** + * A constructor for BanReason + * + * @param reason The reason shown to the player + */ BanReason(String reason) { this.reason = reason; } diff --git a/src/main/java/net/cytonic/cytosis/data/enums/ChatChannel.java b/src/main/java/net/cytonic/cytosis/data/enums/ChatChannel.java index ba6378fb..a38d6cd0 100644 --- a/src/main/java/net/cytonic/cytosis/data/enums/ChatChannel.java +++ b/src/main/java/net/cytonic/cytosis/data/enums/ChatChannel.java @@ -4,14 +4,38 @@ import net.kyori.adventure.text.Component; import net.kyori.adventure.text.format.NamedTextColor; +/** + * This enum holds all chat channels + */ @Getter public enum ChatChannel { + /** + * Public, single-server chat + */ ALL(Component.empty()), + /** + * Not implementated; Private messages between two players + */ PRIVATE_MESSAGE(Component.empty()), + /** + * Not implementated; Party chat + */ PARTY(Component.text("Party > ", NamedTextColor.GOLD)), + /** + * Not implementated; League chat + */ LEAGUE(Component.text("League > ", NamedTextColor.DARK_PURPLE)), + /** + * A chat channel broadcast to mods on every server + */ MOD(Component.text("Mod > ", NamedTextColor.DARK_GREEN)), + /** + * A chat channel broadcast to admins on every server + */ ADMIN(Component.text("Admin > ", NamedTextColor.DARK_RED)), + /** + * A chat channel broadcast to all staff on every server + */ STAFF(Component.text("Staff > ", NamedTextColor.LIGHT_PURPLE)); private final Component prefix; diff --git a/src/main/java/net/cytonic/cytosis/data/enums/KickReason.java b/src/main/java/net/cytonic/cytosis/data/enums/KickReason.java index cec16ec7..ed89314a 100644 --- a/src/main/java/net/cytonic/cytosis/data/enums/KickReason.java +++ b/src/main/java/net/cytonic/cytosis/data/enums/KickReason.java @@ -2,17 +2,32 @@ import lombok.Getter; +/** + * An enum holding data about kick reasons + */ @Getter public enum KickReason { + /** + * Kicked for being banned + */ BANNED(false), + /** + * Kicked for an internal error + */ INTERNAL_ERROR(true), - INVALID_WORLD(true), - ; + /** + * Kicked due to a world validation issue + */ + INVALID_WORLD(true); private final boolean rescuable; + /** + * Creates a new KickReason + * + * @param rescuable if a proxy should try to rescue a player, or terminate connection completely + */ KickReason(boolean rescuable) { this.rescuable = rescuable; } - } \ No newline at end of file diff --git a/src/main/java/net/cytonic/cytosis/data/enums/NPCInteractType.java b/src/main/java/net/cytonic/cytosis/data/enums/NPCInteractType.java index a3332b14..16f77d4a 100644 --- a/src/main/java/net/cytonic/cytosis/data/enums/NPCInteractType.java +++ b/src/main/java/net/cytonic/cytosis/data/enums/NPCInteractType.java @@ -1,6 +1,15 @@ package net.cytonic.cytosis.data.enums; +/** + * An enum holding data about NPC interactions + */ public enum NPCInteractType { + /** + * Left-clicking an NPC + */ ATTACK, + /** + * Right-clicking an NPC + */ INTERACT } diff --git a/src/main/java/net/cytonic/cytosis/events/EventHandler.java b/src/main/java/net/cytonic/cytosis/events/EventHandler.java index 7b6eeb04..9c769ec9 100644 --- a/src/main/java/net/cytonic/cytosis/events/EventHandler.java +++ b/src/main/java/net/cytonic/cytosis/events/EventHandler.java @@ -41,6 +41,11 @@ public EventHandler(GlobalEventHandler globalHandler) { GLOBAL_HANDLER = globalHandler; } + /** + * Initializes the event handler. + * + * @throws IllegalStateException if the event handler has already been initialized. + */ public void init() { if (initialized) throw new IllegalStateException("The event handler has already been initialized!"); setupInternalListeners(); @@ -88,6 +93,11 @@ public void registerListeners(EventListener... listeners) { } } + /** + * Handles the specified event + * @param event The event object + * @param The type of the event + */ public void handleEvent(T event) { List> matchingListeners = new ArrayList<>(); for (EventListener listener : NAMESPACED_HANDLERS.values()) { @@ -104,6 +114,10 @@ public void handleEvent(T event) { } } + /** + * Regisers a custom event class to implement a listener for it + * @param clazz The event class + */ public void registerCustomEvent(Class clazz) { GLOBAL_HANDLER.addListener(clazz, this::handleEvent); } diff --git a/src/main/java/net/cytonic/cytosis/events/EventListener.java b/src/main/java/net/cytonic/cytosis/events/EventListener.java index b65df981..d1960a93 100644 --- a/src/main/java/net/cytonic/cytosis/events/EventListener.java +++ b/src/main/java/net/cytonic/cytosis/events/EventListener.java @@ -6,6 +6,11 @@ import java.util.function.Consumer; +/** + * A class that represents an event listener. It contains information about the event class, priority, and consumer. + * + * @param The event class type + */ @Getter public class EventListener { private final Class eventClass; diff --git a/src/main/java/net/cytonic/cytosis/events/ServerEventListeners.java b/src/main/java/net/cytonic/cytosis/events/ServerEventListeners.java index 42272006..0a7436e9 100644 --- a/src/main/java/net/cytonic/cytosis/events/ServerEventListeners.java +++ b/src/main/java/net/cytonic/cytosis/events/ServerEventListeners.java @@ -17,8 +17,21 @@ import static net.cytonic.cytosis.utils.MiniMessageTemplate.MM; -public class ServerEventListeners { +/** + * A class that registers Cytosis required server events + */ +public final class ServerEventListeners { + /** + * Default constructor + */ + private ServerEventListeners() { + // do nothing + } + + /** + * Adds Cytosis required server events + */ public static void initServerEvents() { Logger.info("Registering player configuration event."); Cytosis.getEventHandler().registerListener(new EventListener<>("core:player-configuration", true, 1, AsyncPlayerConfigurationEvent.class, (event -> { diff --git a/src/main/java/net/cytonic/cytosis/events/ranks/RankChangeEvent.java b/src/main/java/net/cytonic/cytosis/events/ranks/RankChangeEvent.java index 364f0bb5..8859ed24 100644 --- a/src/main/java/net/cytonic/cytosis/events/ranks/RankChangeEvent.java +++ b/src/main/java/net/cytonic/cytosis/events/ranks/RankChangeEvent.java @@ -6,6 +6,9 @@ import net.minestom.server.event.trait.CancellableEvent; import net.minestom.server.event.trait.PlayerEvent; +/** + * An event that is fired when a player's rank changes + */ @Getter public class RankChangeEvent implements PlayerEvent, CancellableEvent { private boolean canceled; @@ -13,6 +16,13 @@ public class RankChangeEvent implements PlayerEvent, CancellableEvent { private final PlayerRank oldRank; private final Player player; + /** + * Creates a new event + * + * @param newRank The new rank + * @param oldRank The old rank + * @param player The player + */ public RankChangeEvent(PlayerRank newRank, PlayerRank oldRank, Player player) { this.newRank = newRank; this.oldRank = oldRank; diff --git a/src/main/java/net/cytonic/cytosis/events/ranks/RankSetupEvent.java b/src/main/java/net/cytonic/cytosis/events/ranks/RankSetupEvent.java index a85f4df4..dd706c2d 100644 --- a/src/main/java/net/cytonic/cytosis/events/ranks/RankSetupEvent.java +++ b/src/main/java/net/cytonic/cytosis/events/ranks/RankSetupEvent.java @@ -6,6 +6,9 @@ import net.minestom.server.event.trait.CancellableEvent; import net.minestom.server.event.trait.PlayerEvent; +/** + * An event that is fired when a player's rank is setup + */ @Getter public class RankSetupEvent implements PlayerEvent, CancellableEvent { @@ -13,6 +16,12 @@ public class RankSetupEvent implements PlayerEvent, CancellableEvent { private final PlayerRank rank; private boolean canceled; + /** + * Creates a new event object + * + * @param player the player + * @param rank the rank + */ public RankSetupEvent(Player player, PlayerRank rank) { this.player = player; this.rank = rank; diff --git a/src/main/java/net/cytonic/cytosis/files/FileManager.java b/src/main/java/net/cytonic/cytosis/files/FileManager.java index ec35fd4f..6788f632 100644 --- a/src/main/java/net/cytonic/cytosis/files/FileManager.java +++ b/src/main/java/net/cytonic/cytosis/files/FileManager.java @@ -5,6 +5,7 @@ import org.tomlj.Toml; import org.tomlj.TomlParseResult; import org.tomlj.TomlTable; + import java.io.*; import java.nio.file.Path; import java.util.HashMap; @@ -13,11 +14,17 @@ import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; +/** + * A class handling IO and files + */ public class FileManager { private static final Path CONFIG_PATH = Path.of("config.toml"); private final ExecutorService worker; + /** + * The default constructor that initializes the worker thread + */ public FileManager() { this.worker = Executors.newSingleThreadExecutor(Thread.ofVirtual().name("CytosisIOWorker").uncaughtExceptionHandler((t, e) -> Logger.error(STR."An uncaught exception occoured on the thread: \{t.getName()}", e)).factory()); } diff --git a/src/main/java/net/cytonic/cytosis/logging/Color.java b/src/main/java/net/cytonic/cytosis/logging/Color.java index baa29422..6aeee816 100644 --- a/src/main/java/net/cytonic/cytosis/logging/Color.java +++ b/src/main/java/net/cytonic/cytosis/logging/Color.java @@ -5,86 +5,264 @@ */ package net.cytonic.cytosis.logging; +/** + * Represents different colors that can be used for text formatting. + */ public enum Color { - //Color end string, color reset + /** + * Color end string, color reset + */ RESET("\033[0m"), - // Regular Colors. Normal color, no bold, background color etc. + /** + * Regular Colors. Normal color, no bold, background color etc. + */ BLACK("\033[0;30m"), // BLACK + /** + * Regular Colors. Normal color, no bold, background color etc. + */ RED("\033[0;31m"), // RED + /** + * Regular Colors. Normal color, no bold, background color etc. + */ GREEN("\033[0;32m"), // GREEN + /** + * Regular Colors. Normal color, no bold, background color etc. + */ YELLOW("\033[0;33m"), // YELLOW + /** + * Regular Colors. Normal color, no bold, background color etc. + */ BLUE("\033[0;34m"), // BLUE + /** + * Regular Colors. Normal color, no bold, background color etc. + */ MAGENTA("\033[0;35m"), // MAGENTA + /** + * Regular Colors. Normal color, no bold, background color etc. + */ CYAN("\033[0;36m"), // CYAN + /** + * Regular Colors. Normal color, no bold, background color etc. + */ WHITE("\033[0;37m"), // WHITE - // Bold + /** + * Bold Colors + */ BLACK_BOLD("\033[1;30m"), // BLACK + /** + * Bold Colors + */ + /** + * Bold Colors + */ RED_BOLD("\033[1;31m"), // RED + /** + * Bold Colors + */ GREEN_BOLD("\033[1;32m"), // GREEN + /** + * Bold Colors + */ YELLOW_BOLD("\033[1;33m"), // YELLOW + /** + * Bold Colors + */ BLUE_BOLD("\033[1;34m"), // BLUE + /** + * Bold Colors + */ MAGENTA_BOLD("\033[1;35m"), // MAGENTA + /** + * Bold Colors + */ CYAN_BOLD("\033[1;36m"), // CYAN + /** + * Bold Colors + */ WHITE_BOLD("\033[1;37m"), // WHITE - // Underline + /** + * Underlined Colors + */ BLACK_UNDERLINED("\033[4;30m"), // BLACK + /** + * Underlined Colors + */ RED_UNDERLINED("\033[4;31m"), // RED + /** + * Underlined Colors + */ GREEN_UNDERLINED("\033[4;32m"), // GREEN + /** + * Underlined Colors + */ YELLOW_UNDERLINED("\033[4;33m"), // YELLOW + /** + * Underlined Colors + */ BLUE_UNDERLINED("\033[4;34m"), // BLUE + /** + * Underlined Colors + */ MAGENTA_UNDERLINED("\033[4;35m"), // MAGENTA + /** + * Underlined Colors + */ CYAN_UNDERLINED("\033[4;36m"), // CYAN + /** + * Underlined Colors + */ WHITE_UNDERLINED("\033[4;37m"), // WHITE - // Background + /** + * Background colors + */ BLACK_BACKGROUND("\033[40m"), // BLACK + /** + * Background colors + */ RED_BACKGROUND("\033[41m"), // RED + /** + * Background colors + */ GREEN_BACKGROUND("\033[42m"), // GREEN + /** + * Background colors + */ YELLOW_BACKGROUND("\033[43m"), // YELLOW + /** + * Background colors + */ BLUE_BACKGROUND("\033[44m"), // BLUE + /** + * Background colors + */ MAGENTA_BACKGROUND("\033[45m"), // MAGENTA + /** + * Background colors + */ CYAN_BACKGROUND("\033[46m"), // CYAN + /** + * Background colors + */ WHITE_BACKGROUND("\033[47m"), // WHITE - // High Intensity + /** + * High Intensity Colors + */ BLACK_BRIGHT("\033[0;90m"), // BLACK + /** + * High Intensity Colors + */ RED_BRIGHT("\033[0;91m"), // RED + /** + * High Intensity Colors + */ GREEN_BRIGHT("\033[0;92m"), // GREEN + /** + * High Intensity Colors + */ YELLOW_BRIGHT("\033[0;93m"), // YELLOW + /** + * High Intensity Colors + */ BLUE_BRIGHT("\033[0;94m"), // BLUE + /** + * High Intensity Colors + */ MAGENTA_BRIGHT("\033[0;95m"), // MAGENTA + /** + * High Intensity Colors + */ CYAN_BRIGHT("\033[0;96m"), // CYAN + /** + * High Intensity Colors + */ WHITE_BRIGHT("\033[0;97m"), // WHITE - // Bold High Intensity + /** + * Bold and High Intensity + */ BLACK_BOLD_BRIGHT("\033[1;90m"), // BLACK + /** + * Bold and High Intensity + */ RED_BOLD_BRIGHT("\033[1;91m"), // RED + /** + * Bold and High Intensity + */ GREEN_BOLD_BRIGHT("\033[1;92m"), // GREEN + /** + * Bold and High Intensity + */ YELLOW_BOLD_BRIGHT("\033[1;93m"), // YELLOW + /** + * Bold and High Intensity + */ BLUE_BOLD_BRIGHT("\033[1;94m"), // BLUE + /** + * Bold and High Intensity + */ MAGENTA_BOLD_BRIGHT("\033[1;95m"), // MAGENTA + /** + * Bold and High Intensity + */ CYAN_BOLD_BRIGHT("\033[1;96m"), // CYAN + /** + * Bold and High Intensity + */ WHITE_BOLD_BRIGHT("\033[1;97m"), // WHITE - // High Intensity backgrounds + /** + * High Intensity backgrounds + */ BLACK_BACKGROUND_BRIGHT("\033[0;100m"), // BLACK + /** + * High Intensity backgrounds + */ RED_BACKGROUND_BRIGHT("\033[0;101m"), // RED + /** + * High Intensity backgrounds + */ GREEN_BACKGROUND_BRIGHT("\033[0;102m"), // GREEN + /** + * High Intensity backgrounds + */ YELLOW_BACKGROUND_BRIGHT("\033[0;103m"), // YELLOW + /** + * High Intensity backgrounds + */ BLUE_BACKGROUND_BRIGHT("\033[0;104m"), // BLUE + /** + * High Intensity backgrounds + */ MAGENTA_BACKGROUND_BRIGHT("\033[0;105m"), // MAGENTA + /** + * High Intensity backgrounds + */ CYAN_BACKGROUND_BRIGHT("\033[0;106m"), // CYAN + /** + * High Intensity backgrounds + */ WHITE_BACKGROUND_BRIGHT("\033[0;107m"); // WHITE private final String code; + /** + * Creates a new color + * + * @param code The color code + */ Color(String code) { this.code = code; } + /** + * Returns the code of the color + * @return The color code + */ @Override public String toString() { return code; diff --git a/src/main/java/net/cytonic/cytosis/logging/Level.java b/src/main/java/net/cytonic/cytosis/logging/Level.java index dafc0d48..5b313c22 100644 --- a/src/main/java/net/cytonic/cytosis/logging/Level.java +++ b/src/main/java/net/cytonic/cytosis/logging/Level.java @@ -5,11 +5,32 @@ */ package net.cytonic.cytosis.logging; +/** + * Logging levels + */ public enum Level { + /** + * Not used? + */ SETUP, + /** + * Also not used + */ TRACE, + /** + * Used for debugging things + */ DEBUG, + /** + * Used for general information + */ INFO, + /** + * Used for warnings + */ WARN, + /** + * Used for errors + */ ERROR } \ No newline at end of file diff --git a/src/main/java/net/cytonic/cytosis/logging/Logger.java b/src/main/java/net/cytonic/cytosis/logging/Logger.java index b7508765..5494241c 100644 --- a/src/main/java/net/cytonic/cytosis/logging/Logger.java +++ b/src/main/java/net/cytonic/cytosis/logging/Logger.java @@ -5,91 +5,170 @@ */ package net.cytonic.cytosis.logging; +/** + * The blueprint for all loggers. + */ public interface Logger { + /** + * Gets the default logger + * + * @return the default logger + */ static Logger logger() { return LoggerImpl.DEFAULT; } /** * Debug log entries contain common debug information. + * @return the debug logger */ private static Logger debug() { return logger().level(Level.DEBUG); } + /** + * Logs a debug message + * @param message The message to log + * @param args The arguments to format the message + * @return The logger used + */ static Logger debug(String message, Object... args) { if (args.length == 0) return debug().println(message); return debug().printf(message, args).println(); } + /** + * Logs a throwable + * @param throwable the throwable to log + * @param args any additional arguments + * @return the logger used + */ static Logger debug(Throwable throwable, Object... args) { return debug().throwable(throwable, args); } /** * Setup log entries contain information about the setup of the application. + * @return the setup logger */ static Logger setup() { return logger().level(Level.SETUP); } + /** + * Logs a setup message + * @param message The message to log + * @param args The arguments to format the message + * @return The logger used + */ static Logger setup(String message, Object... args) { if (args.length == 0) return setup().println(message); return setup().printf(message, args); } + /** + * Logs a throwable in the setup level + * @param throwable The throwable to log + * @param args any additional arguments + * @return The logger used + */ static Logger setup(Throwable throwable, Object... args) { return setup().throwable(throwable, args); } /** * Info log entries contain important relevant information. + * @return the info logger */ private static Logger info() { return logger().level(Level.INFO); } + /** + * Logs a message in the INFO level + * @param message The message to log + * @param args The args to format the message + * @return The logger used + */ static Logger info(String message, Object... args) { if (args.length == 0) return info().println(message); return info().printf(message, args).println(); } + /** + * Logs a throwable in the INFO level (Why would you do this??) + * @param throwable The throwable to log + * @param args any additional arguments + * @return The logger used + */ static Logger info(Throwable throwable, Object... args) { return info().throwable(throwable, args); } /** * Warn log entries contain technical warnings. Typically, warnings do not prevent the application from continuing. + * @return the warn logger */ private static Logger warn() { return logger().level(Level.WARN); } + /** + * Logs a warning + * @param message The message to log + * @param args The arguments to format the message + * @return The logger used + */ static Logger warn(String message, Object... args) { if (args.length == 0) return warn().println(message); return warn().printf(message, args); } + /** + * Logs a throwable in the WARN level + * @param throwable The throwable to log + * @param args any additional arguments + * @return The logger used + */ static Logger warn(Throwable throwable, Object... args) { return warn().throwable(throwable, args); } /** * Error log entries contain technical errors. Errors WILL stop the application from continuing. + * @return the error logger */ private static Logger error() { return logger().level(Level.ERROR); } + /** + * Logs an error message in the ERROR level + * @param message the message to log + * @param args the arguments used to format the message + * @return the logger used + */ static Logger error(String message, Object... args) { if (args.length == 0) return error().println(message); return error().printf(message, args); } + /** + * Logs an error with a throwable + * @param message the message to log + * @param ex the throwable to log + * @return the logger used + */ static Logger error(String message, Throwable ex) { return error().throwable(message, ex); } + /** + * Logs an error with a throwable + * @param throwable the throwable to log + * @param args the arguments used to format the message + * @return the logger used + */ static Logger error(Throwable throwable, Object... args) { return error().throwable(throwable, args); } @@ -104,23 +183,56 @@ static Logger error(Throwable throwable, Object... args) { /** * Gets the current level of the logger + * @return the level of the logger */ Level level(); + /** + * Print a message + * @param message the message + * @return the logger + */ Logger print(String message); + /** + * Print a message with a new line at the end + * @param message the message + * @return the logger + */ default Logger println(String message) { return print(message).println(); } + /** + * Print a new line + * @return the logger + */ default Logger println() { return print(System.lineSeparator()); } + /** + * Prints a formatted message + * @param message the message + * @param args the formatting + * @return the logger used + */ Logger printf(String message, Object... args); + /** + * Log a throwable + * @param throwable the throwable to log + * @param args any formatting + * @return the logger used + */ Logger throwable(Throwable throwable, Object... args); + /** + * Logs a message with a throwable + * @param message the message + * @param throwable the throwable + * @return the logger used + */ Logger throwable(String message, Throwable throwable); /** diff --git a/src/main/java/net/cytonic/cytosis/logging/SLF4JServiceProvider.java b/src/main/java/net/cytonic/cytosis/logging/SLF4JServiceProvider.java index 5e7f3348..1926b018 100644 --- a/src/main/java/net/cytonic/cytosis/logging/SLF4JServiceProvider.java +++ b/src/main/java/net/cytonic/cytosis/logging/SLF4JServiceProvider.java @@ -11,8 +11,17 @@ import org.slf4j.helpers.NOPMDCAdapter; import org.slf4j.spi.MDCAdapter; +/** + * An SLF4J compatible logger + * + * @see org.slf4j.spi.SLF4JServiceProvider + */ public class SLF4JServiceProvider implements org.slf4j.spi.SLF4JServiceProvider { + /** + * default constructor + */ public SLF4JServiceProvider() { + // do nothing } @Override diff --git a/src/main/java/net/cytonic/cytosis/logging/loading/Loading.java b/src/main/java/net/cytonic/cytosis/logging/loading/Loading.java index 862be138..c4b76bcc 100644 --- a/src/main/java/net/cytonic/cytosis/logging/loading/Loading.java +++ b/src/main/java/net/cytonic/cytosis/logging/loading/Loading.java @@ -7,20 +7,39 @@ import net.cytonic.cytosis.logging.Level; +/** + * A loading bar. Currently unused. + */ public interface Loading { + /** + * Start the loading animation + * + * @param name The name + */ static void start(String name) { LoadingImpl.CURRENT.waitTask(name); } + /** + * Get the current status updater + * @return the status updater + */ static StatusUpdater updater() { return LoadingImpl.CURRENT.getUpdater(); } + /** + * Finish loading + */ static void finish() { LoadingImpl.CURRENT.finishTask(); } + /** + * Set the current level + * @param level the new level + */ static void level(Level level) { LoadingImpl.CURRENT.level = level; } diff --git a/src/main/java/net/cytonic/cytosis/logging/loading/StatusUpdater.java b/src/main/java/net/cytonic/cytosis/logging/loading/StatusUpdater.java index 5556a38f..475a0e27 100644 --- a/src/main/java/net/cytonic/cytosis/logging/loading/StatusUpdater.java +++ b/src/main/java/net/cytonic/cytosis/logging/loading/StatusUpdater.java @@ -5,6 +5,9 @@ */ package net.cytonic.cytosis.logging.loading; +/** + * A statusbar updater + */ public interface StatusUpdater { /** * Updates the progress bar without changing the text message. diff --git a/src/main/java/net/cytonic/cytosis/managers/ChatManager.java b/src/main/java/net/cytonic/cytosis/managers/ChatManager.java index 86a60e1d..ed2747c0 100644 --- a/src/main/java/net/cytonic/cytosis/managers/ChatManager.java +++ b/src/main/java/net/cytonic/cytosis/managers/ChatManager.java @@ -1,29 +1,60 @@ package net.cytonic.cytosis.managers; -import java.util.HashMap; -import java.util.Map; -import java.util.UUID; import net.cytonic.cytosis.Cytosis; import net.cytonic.cytosis.data.enums.ChatChannel; import net.kyori.adventure.text.Component; +import java.util.HashMap; +import java.util.Map; +import java.util.UUID; + +/** + * This class handles chat messages and channels + */ +@SuppressWarnings("unused") public class ChatManager { + /** + * A default constructor for the ChatManager + */ + public ChatManager() { + } + private final Map channels = new HashMap<>(); + /** + * Removes the players from the channel list + * + * @param uuid The player to remove + */ public void removeChannel(UUID uuid) { channels.remove(uuid); } + /** + * Sets a specified players chat channel + * @param uuid The player to set + * @param channel The channel to set + */ public void setChannel(UUID uuid, ChatChannel channel) { channels.put(uuid, channel); Cytosis.getDatabaseManager().getMysqlDatabase().setChatChannel(uuid, channel); } + /** + * Gets the player's chat channel + * @param uuid The player to + * @return the player's curretly selected chat channel + */ public ChatChannel getChannel(UUID uuid) { return channels.getOrDefault(uuid, ChatChannel.ALL); } + /** + * Sends a message to the specified chat channel + * @param component The message + * @param chatChannel The channel to send the message to + */ public void sendMessageToChannel(Component component, ChatChannel chatChannel) { switch (chatChannel) { case ADMIN, MOD, STAFF -> // send a message to all servers diff --git a/src/main/java/net/cytonic/cytosis/managers/NPCManager.java b/src/main/java/net/cytonic/cytosis/managers/NPCManager.java index 9550f281..04e4c9c5 100644 --- a/src/main/java/net/cytonic/cytosis/managers/NPCManager.java +++ b/src/main/java/net/cytonic/cytosis/managers/NPCManager.java @@ -8,17 +8,42 @@ import java.util.Optional; import java.util.UUID; +/** + * A class that manages NPCs + */ public class NPCManager { + + /** + * The defualt Constructor + */ + public NPCManager() { + // Do nothing + } + private final List npcs = new ArrayList<>(); + /** + * Adds an NPC to the manager + * + * @param npc the NPC to add + */ public void addNPC(NPC npc) { npcs.add(npc); } + /** + * Removes an NPC from the manager + * @param npc the NPC to remove + */ public void removeNPC(NPC npc) { npcs.remove(npc); } + /** + * Finds an NPC by UUID + * @param id the uuid to find the NPC by + * @return An optional of the NPC + */ @NotNull public Optional findNPC(UUID id) { for (NPC npc : npcs) { diff --git a/src/main/java/net/cytonic/cytosis/managers/PlayerListManager.java b/src/main/java/net/cytonic/cytosis/managers/PlayerListManager.java index 7f52ca09..27788c32 100644 --- a/src/main/java/net/cytonic/cytosis/managers/PlayerListManager.java +++ b/src/main/java/net/cytonic/cytosis/managers/PlayerListManager.java @@ -11,9 +11,20 @@ import java.util.*; +/** + * A class that manages the player list + */ @Setter @Getter public class PlayerListManager { + + /** + * The default player list manager constructor + */ + public PlayerListManager() { + // do nothing + } + //todo make it per player? private List globalCategories = new ArrayList<>(); @@ -35,6 +46,11 @@ public void setupPlayer(Player player) { } } + /** + * Creates the player list packets + * + * @return the list of packets + */ private List createPackets() { globalCategories.sort(Comparator.comparingInt(PlayerListCategory::getPriority)); List packets = new ArrayList<>(); diff --git a/src/main/java/net/cytonic/cytosis/managers/SideboardManager.java b/src/main/java/net/cytonic/cytosis/managers/SideboardManager.java index 6fbe0f31..f7fb151a 100644 --- a/src/main/java/net/cytonic/cytosis/managers/SideboardManager.java +++ b/src/main/java/net/cytonic/cytosis/managers/SideboardManager.java @@ -16,6 +16,9 @@ import java.util.concurrent.ScheduledExecutorService; import java.util.concurrent.TimeUnit; +/** + * A manager class for sideboards + */ public class SideboardManager { private final Map sideboards = new ConcurrentHashMap<>(); private final ScheduledExecutorService updateExecutor = Executors.newSingleThreadScheduledExecutor(Thread.ofVirtual().name("Cytosis-Sideboard-Updater").factory()); @@ -23,14 +26,34 @@ public class SideboardManager { @Setter private SideboardCreator sideboardCreator = new DefaultCreator(); + /** + * Creates a new SideboardManager + */ + public SideboardManager() { + // Do nothing + } + + /** + * Adds a player to the sideboard manager + * + * @param player the player + */ public void addPlayer(Player player) { sideboards.put(player.getUuid(), sideboardCreator.sideboard(player)); } + /** + * Removes a player from the sideboard manager + * @param player the player + */ public void removePlayer(Player player) { sideboards.remove(player.getUuid()); } + /** + * Removes a player from the sideboard manager + * @param player the player + */ public void removePlayer(UUID player) { sideboards.remove(player); } @@ -43,16 +66,21 @@ private void updatePlayer() { removePlayer(uuid); return; } -// player.get().sendMessage("Hi updating ur scoreboard"); sideboard.updateLines(sideboardCreator.lines(player.get())); sideboard.updateTitle(sideboardCreator.title(player.get())); }); } + /** + * schedule the sideboard updater + */ public void updateBoards() { updateExecutor.scheduleAtFixedRate(this::updatePlayer, 1, 1, TimeUnit.SECONDS); } + /** + * Shuts down the worker + */ public void shutdown() { updateExecutor.shutdown(); } diff --git a/src/main/java/net/cytonic/cytosis/messaging/MessagingManager.java b/src/main/java/net/cytonic/cytosis/messaging/MessagingManager.java index 97200fd1..bb154566 100644 --- a/src/main/java/net/cytonic/cytosis/messaging/MessagingManager.java +++ b/src/main/java/net/cytonic/cytosis/messaging/MessagingManager.java @@ -6,21 +6,30 @@ import java.util.concurrent.CompletableFuture; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; -import lombok.Getter; -import net.cytonic.cytosis.config.CytosisSettings; +/** + * A class to handle messaging + */ public class MessagingManager { @Getter private final RabbitMQ rabbitMQ; private final ExecutorService worker; + /** + * Creates a new MessagingManager with a RabbitMQ instance and a worker thread + */ public MessagingManager() { worker = Executors.newSingleThreadExecutor(Thread.ofVirtual().name("CytosisMessageWorker").factory()); if (CytosisSettings.RABBITMQ_ENABLED) this.rabbitMQ = new RabbitMQ(); else this.rabbitMQ = null; } + /** + * Initializes the messaging systems + * + * @return a future that completes when the initialization is complete + */ public CompletableFuture initialize() { CompletableFuture future = new CompletableFuture<>(); worker.submit(() -> { @@ -35,6 +44,9 @@ public CompletableFuture initialize() { return future; } + /** + * Shuts down the manager by disconnecting from the RabbitMQ instance and shutting down the worker thread + */ public void shutdown() { if (rabbitMQ != null) { rabbitMQ.sendServerShutdownMessage(); diff --git a/src/main/java/net/cytonic/cytosis/messaging/RabbitMQ.java b/src/main/java/net/cytonic/cytosis/messaging/RabbitMQ.java index 9ee8a91f..567205c8 100644 --- a/src/main/java/net/cytonic/cytosis/messaging/RabbitMQ.java +++ b/src/main/java/net/cytonic/cytosis/messaging/RabbitMQ.java @@ -8,7 +8,7 @@ import net.cytonic.cytosis.logging.Logger; import net.cytonic.cytosis.utils.OfflinePlayer; import net.cytonic.cytosis.utils.Utils; -import net.kyori.adventure.sound.*; +import net.kyori.adventure.sound.Sound; import net.kyori.adventure.text.Component; import net.kyori.adventure.text.serializer.json.JSONComponentSerializer; import net.minestom.server.entity.Player; @@ -27,6 +27,13 @@ @SuppressWarnings("unused") public class RabbitMQ { + /** + * Creates a new RabbitMQ instance + */ + public RabbitMQ() { + // do nothing + } + private static final String SERVER_DECLARE_QUEUE = "server-declaration"; private static final String SHUTDOWN_QUEUE = "server-shutdown"; private static final String CHAT_CHANNEL_QUEUE = STR."chat-channel-\{Cytosis.SERVER_ID}"; diff --git a/src/main/java/net/cytonic/cytosis/npcs/Humanoid.java b/src/main/java/net/cytonic/cytosis/npcs/Humanoid.java index 743c5260..d23d9f48 100644 --- a/src/main/java/net/cytonic/cytosis/npcs/Humanoid.java +++ b/src/main/java/net/cytonic/cytosis/npcs/Humanoid.java @@ -15,11 +15,15 @@ import net.minestom.server.network.packet.server.play.PlayerInfoUpdatePacket; import net.minestom.server.network.packet.server.play.TeamsPacket; import org.jetbrains.annotations.NotNull; + import java.util.ArrayList; import java.util.List; import java.util.Map; import java.util.UUID; +/** + * A class representing a Player NPC + */ @SuppressWarnings("UnstableApiUsage") public class Humanoid extends EntityCreature implements NPC { @@ -31,12 +35,23 @@ public class Humanoid extends EntityCreature implements NPC { private boolean glowing = false; private NamedTextColor glowingColor = NamedTextColor.WHITE; + /** + * Creates a new Humanoid from uuid, username, and skin + * + * @param uuid The NPC's UUID + * @param username The NPC's username (pretty irrelevent) + * @param skin The NPC's skin data + */ public Humanoid(UUID uuid, String username, PlayerSkin skin) { super(EntityType.PLAYER, uuid); this.username = username; this.skin = skin; } + /** + * Creates a new NPC from a UUID + * @param uuid The UUID to use + */ public Humanoid(UUID uuid) { super(EntityType.PLAYER, uuid); this.username = STR."npc-\{uuid.toString().substring(0, 12)}"; diff --git a/src/main/java/net/cytonic/cytosis/npcs/HumanoidBuilder.java b/src/main/java/net/cytonic/cytosis/npcs/HumanoidBuilder.java index 623d6c3b..15ddb087 100644 --- a/src/main/java/net/cytonic/cytosis/npcs/HumanoidBuilder.java +++ b/src/main/java/net/cytonic/cytosis/npcs/HumanoidBuilder.java @@ -9,48 +9,91 @@ import java.util.UUID; +/** + * A builder for creating Humanoid NPCs + */ public class HumanoidBuilder { private final Pos pos; private final Instance instanceContainer; private final Humanoid NPC; + /** + * A contructor for creating a builder + * + * @param pos The pos to spawn the NPC at + * @param instanceContainer The instance to spawn the NPC in + */ protected HumanoidBuilder(Pos pos, Instance instanceContainer) { this.pos = pos; this.instanceContainer = instanceContainer; this.NPC = new Humanoid(UUID.randomUUID()); } + /** + * The constructor for creating a builder from an existing NPC + * @param NPC THe NPC to import data from + */ protected HumanoidBuilder(Humanoid NPC) { this.NPC = NPC; this.pos = NPC.getPosition(); this.instanceContainer = NPC.getInstance(); } + /** + * Sets the skin + * @param skin The skin data + * @return The builder with updated data + */ public HumanoidBuilder skin(PlayerSkin skin) { NPC.setSkin(skin); return this; } + /** + * Sets the skin + * @param signature The signature of the skin + * @param value The value of the skin + * @return The builder with updated data + */ public HumanoidBuilder skin(String value, String signature) { this.skin(new PlayerSkin(value, signature)); return this; } + /** + * Sets the NPC's multi-line hologram contents + * @param lines The lines of the hologram + * @return The builder with updated data + */ public HumanoidBuilder lines(Component... lines) { NPC.setLines(lines); return this; } + /** + * Adds an interaction trigger to run an action on interact + * @param action The action to run + * @return The builder with updated data + */ public HumanoidBuilder interactTrigger(NPCAction action) { NPC.addAction(action); return this; } + /** + * Makes the NPC glow + * @param color The color to glow + * @return The builder with updated data + */ public HumanoidBuilder glowing(NamedTextColor color) { NPC.setGlowing(color); return this; } + /** + * Builds the NPC and creates the holograms + * @return The Humanoid NPC + */ public Humanoid build() { NPC.setInstance(instanceContainer, pos); NPC.createHolograms(); diff --git a/src/main/java/net/cytonic/cytosis/npcs/NPC.java b/src/main/java/net/cytonic/cytosis/npcs/NPC.java index 8201312e..a0b98d69 100644 --- a/src/main/java/net/cytonic/cytosis/npcs/NPC.java +++ b/src/main/java/net/cytonic/cytosis/npcs/NPC.java @@ -8,32 +8,84 @@ import java.util.List; import java.util.UUID; +/** + * The blueprint for an NPC + */ public interface NPC { + /** + * Creates a Humanoid NPC builder + * + * @param pos The pos to spawn the NPC at + * @param instanceContainer The instance to spawn the NPC in + * @return The builder + */ // builders static HumanoidBuilder ofHumanoid(Pos pos, Instance instanceContainer) { return new HumanoidBuilder(pos, instanceContainer); } + /** + * Creates a new builder out of an existing NPC + * @param NPC The npc to import data from + * @return the created builder + */ static HumanoidBuilder ofHumanoid(Humanoid NPC) { return new HumanoidBuilder(NPC); } + /** + * Sets the mutli line hologram contents + * @param lines The lines of the hologram + */ void setLines(Component... lines); + /** + * Adds an interaction to the NPC + * @param action the exection action + */ void addAction(NPCAction action); + /** + * Sets the NPC to be glowing + * @param color the color to glow + */ void setGlowing(NamedTextColor color); + /** + * Lists the NPCs actions + * @return the NPC's actions + */ List getActions(); + /** + * Gets the hologram lines + * @return The NPC's hologram lines + */ List getLines(); + /** + * If the NPC is glowing + * @return The NPC's glowing state + */ boolean isGlowing(); + /** + * The color the NPC glows. + *

+ * Returns {@link NamedTextColor#WHITE} if the NPC is not glowing + * @return the NPC's glowing color + */ NamedTextColor getGlowingColor(); + /** + * Gets the NPC's UUID + * @return the uuid + */ UUID getUUID(); + /** + * Creates the holograms + */ void createHolograms(); } diff --git a/src/main/java/net/cytonic/cytosis/npcs/NPCAction.java b/src/main/java/net/cytonic/cytosis/npcs/NPCAction.java index d79c679c..5e23ad3a 100644 --- a/src/main/java/net/cytonic/cytosis/npcs/NPCAction.java +++ b/src/main/java/net/cytonic/cytosis/npcs/NPCAction.java @@ -3,7 +3,17 @@ import net.cytonic.cytosis.data.enums.NPCInteractType; import net.minestom.server.entity.Player; +/** + * A functional interface for NPC actions + */ @FunctionalInterface public interface NPCAction { + /** + * A method to execute an NPC action + * + * @param NPC The NPC in question + * @param type the type of interaction + * @param player the player who interacted + */ void execute(NPC NPC, NPCInteractType type, Player player); } diff --git a/src/main/java/net/cytonic/cytosis/playerlist/PlayerListCategory.java b/src/main/java/net/cytonic/cytosis/playerlist/PlayerListCategory.java index a940c46a..7afee988 100644 --- a/src/main/java/net/cytonic/cytosis/playerlist/PlayerListCategory.java +++ b/src/main/java/net/cytonic/cytosis/playerlist/PlayerListCategory.java @@ -19,10 +19,21 @@ public class PlayerListCategory { private boolean enabled; private List entries; // + /** + * Sort the entries in the category by priority + */ public void sortEntries() { entries.sort(Comparator.comparingInt(PlayerListEntry::getPriority)); } + /** + * Creates a new player list category + * + * @param name The name of the category + * @param favicon The {@link PlayerListFavicon} of the category + * @param priority The ordering of the category + * @param entries The {@link PlayerListEntry}s in the category + */ public PlayerListCategory(Component name, PlayerListFavicon favicon, int priority, List entries) { this.name = name; this.favicon = favicon; diff --git a/src/main/java/net/cytonic/cytosis/playerlist/PlayerListEntry.java b/src/main/java/net/cytonic/cytosis/playerlist/PlayerListEntry.java index a9f75f39..a8f50be7 100644 --- a/src/main/java/net/cytonic/cytosis/playerlist/PlayerListEntry.java +++ b/src/main/java/net/cytonic/cytosis/playerlist/PlayerListEntry.java @@ -14,24 +14,47 @@ public class PlayerListEntry { private PlayerListFavicon favicon; private int priority; + /** + * Creates a new player list entry + * + * @param name The name of the entry + * @param favicon The {@link PlayerListFavicon} of the entry + * @param priority The ordering of the entry + */ public PlayerListEntry(Component name, PlayerListFavicon favicon, int priority) { this.name = name; this.favicon = favicon; this.priority = priority; } + /** + * Creates a new player list entry with the favicon set to {@link PlayerListFavicon#GREY} + * @param name The name of the entry + * @param priority The ordering of the entry + */ public PlayerListEntry(Component name, int priority) { this.name = name; this.favicon = PlayerListFavicon.GREY; this.priority = priority; } + /** + * Creates a new player list entry with the favicon set to {@link PlayerListFavicon#GREY} + * @param name The name of the entry + * @param priority The ordering of the entry + */ public PlayerListEntry(String name, int priority) { this.name = Component.text(name); this.favicon = PlayerListFavicon.GREY; this.priority = priority; } + /** + * Creates a new player list entry + * @param name The name of the entry + * @param favicon The {@link PlayerListFavicon} of the entry + * @param priority The ordering of the entry + */ public PlayerListEntry(String name, PlayerListFavicon favicon, int priority) { this.name = Component.text(name); this.favicon = favicon; diff --git a/src/main/java/net/cytonic/cytosis/playerlist/PlayerListFavicon.java b/src/main/java/net/cytonic/cytosis/playerlist/PlayerListFavicon.java index 8f501775..5dc95083 100644 --- a/src/main/java/net/cytonic/cytosis/playerlist/PlayerListFavicon.java +++ b/src/main/java/net/cytonic/cytosis/playerlist/PlayerListFavicon.java @@ -5,24 +5,63 @@ import java.util.List; +/** + * An enum holding data about player list favicons + */ @Getter public enum PlayerListFavicon { + /** + * A red square + */ RED(new PlayerInfoUpdatePacket.Property("textures", "ewogICJ0aW1lc3RhbXAiIDogMTcxNTk2ODA3OTkwMSwKICAicHJvZmlsZUlkIiA6ICIxYjQwYzcxMGZjMTY0NmQ2OTIxOTVmYzY3YzZlMTE0ZCIsCiAgInByb2ZpbGVOYW1lIiA6ICJ3c3pvbHNvbiIsCiAgInNpZ25hdHVyZVJlcXVpcmVkIiA6IHRydWUsCiAgInRleHR1cmVzIiA6IHsKICAgICJTS0lOIiA6IHsKICAgICAgInVybCIgOiAiaHR0cDovL3RleHR1cmVzLm1pbmVjcmFmdC5uZXQvdGV4dHVyZS9hYzE0NjAwYWNlNTA2OTVjN2M5YmNmMDllNDJhZmQ5ZjUzYzllMjBkYWExNTI0Yzk1ZGI0MTk3ZGQzMTE2NDEyIgogICAgfQogIH0KfQ==", "SPBbaWAoujgmDMZ7dWYiRV++B+/l/MD5u9kgs30TsDeQq0a9PdmE1oTyZJ2Jx4Cn1yZw7zKpmqpmH9j2YlMUVwNq7YU3zm44WnSGcXmS1GwttDrDjyUpXjcmbBOxFjkneL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Q==", "BTeecnOj/9PP93jHqB8pwiuEbG2N24MH7sXVQco7jT/yAdOsBR/KikIDT84NQRCpZV7WwJpgtcfM7D5Hy8Dq7LJCfCECHA42C75HT1FJZEjHaNQGaPsux1xtP6zMfQaC4CAzyh4GZS5Qtt2l8LtqH4mzuSi8s3wId1WKFrC32Sau0GpI6iWkA2+MLtiq596UvuS1g6WkhHmsSXte3W6WwxKm3TPH4l4AxA5fJfB43dGRUBErb0IYosg3ZmWDIzovUYfkXERn8ZrVQ+B2s78lx6VEMujyEesZXC+W6ndtI3TOyukfad1XEobCAVSd14nNAKsu7ouNhOVuHGxIOPtqbjX3qGBpbmjjDSbkXdvn9KhLh1O1dAliEdxX4RdG46K6LtGKrzYlufik7hmuIO+IHtd1MgCeitJbastRorJJl58tLeKUTD/NZwjmXDODUVtLagNihbMaNvIwFNIdHu9rBBEMgPAdbRp5zj/VrmcJ59VqQlKHutYvhfsk+YqAYI/8lxVujUDxxJDr2iUrvIx9qcajdE/p26H3KYvwvQ+RPQehBIFC6XcMNPwQ6S3JBSjsNNG43jLdM0//2F55QO8YdrveAsznnE2VC45jmei26SR34V4Q4/Xrkh4iFymWaOtuOyiKqrWN7VX38BuxK04K56u8d4J0wLxzHmJ+XrQKZCA=")), + /** + * A green square + */ GREEN(new PlayerInfoUpdatePacket.Property("textures", "ewogICJ0aW1lc3RhbXAiIDogMTcxNzUwNzgwNjE4NywKICAicHJvZmlsZUlkIiA6ICI3ZGEyYWIzYTkzY2E0OGVlODMwNDhhZmMzYjgwZTY4ZSIsCiAgInByb2ZpbGVOYW1lIiA6ICJHb2xkYXBmZWwiLAogICJzaWduYXR1cmVSZXF1aXJlZCIgOiB0cnVlLAogICJ0ZXh0dXJlcyIgOiB7CiAgICAiU0tJTiIgOiB7CiAgICAgICJ1cmwiIDogImh0dHA6Ly90ZXh0dXJlcy5taW5lY3JhZnQubmV0L3RleHR1cmUvODdkZmJhNjdmNWU1ZmY0MGUxMGJkYzNmNTEyNjliNmFmN2E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Aj6TVsU/k4CjIZDsi4lU9Nm3g850H6VdWQJTiE4B+D9qXKNnkbNmrOKkBj/5DiNNIxKUtkiIsnVZYOTtqj9oc6LpVBn51y8m7uXUDxbY=")); private final PlayerInfoUpdatePacket.Property property; + /** + * Creates a new player list favicon + * + * @param property the texture data + */ PlayerListFavicon(PlayerInfoUpdatePacket.Property property) { this.property = property; } + /** + * Gets the property in list form + * @return the property in list form + */ public List property() { return List.of(property); } diff --git a/src/main/java/net/cytonic/cytosis/plugins/CytosisPlugin.java b/src/main/java/net/cytonic/cytosis/plugins/CytosisPlugin.java index 0124df16..3f7ed347 100644 --- a/src/main/java/net/cytonic/cytosis/plugins/CytosisPlugin.java +++ b/src/main/java/net/cytonic/cytosis/plugins/CytosisPlugin.java @@ -1,7 +1,16 @@ package net.cytonic.cytosis.plugins; +/** + * The interface for Cytosis plugins + */ public interface CytosisPlugin { + /** + * Called when the plugin is loaded + */ void initialize(); + /** + * Calledwhen the plugin is unloaded + */ void shutdown(); } diff --git a/src/main/java/net/cytonic/cytosis/plugins/Plugin.java b/src/main/java/net/cytonic/cytosis/plugins/Plugin.java index dc91be5b..4a9ea896 100644 --- a/src/main/java/net/cytonic/cytosis/plugins/Plugin.java +++ b/src/main/java/net/cytonic/cytosis/plugins/Plugin.java @@ -3,17 +3,40 @@ import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy; +/** + * An annotation to help with plugin loading + */ @Retention(RetentionPolicy.RUNTIME) public @interface Plugin { + /** + * The name of the plugin + * + * @return the name + */ String name(); + /** + * The dependencies of the plugin + * @return the dependencies + */ String[] dependencies() default {}; + /** + * The description of the plugin + * @return the description + */ String description() default ""; + /** + * The version of the plugin + * @return plugin version + */ String version(); + /** + * The author(s) of the plugin + * @return the author + */ String author() default ""; - } diff --git a/src/main/java/net/cytonic/cytosis/plugins/PluginManager.java b/src/main/java/net/cytonic/cytosis/plugins/PluginManager.java index a2831fd4..4a0afe7d 100644 --- a/src/main/java/net/cytonic/cytosis/plugins/PluginManager.java +++ b/src/main/java/net/cytonic/cytosis/plugins/PluginManager.java @@ -6,16 +6,36 @@ import java.util.ArrayList; import java.util.List; +/** + * A class that manages plugins + */ public class PluginManager { + + /** + * Default constructor + */ + public PluginManager() { + // Do nothing + } + private final List plugins = new ArrayList<>(); private final PluginLoader pluginLoader = new PluginLoader(); + /** + * Registers a plugin + * + * @param plugin The plugin + * @param annotation the plugin annotation + */ public void registerPlugin(CytosisPlugin plugin, Plugin annotation) { Logger.info(STR."Enabling plugin: \{annotation.name()}"); plugins.add(plugin); plugin.initialize(); } + /** + * Loads the plugins in the plugins folder + */ public void loadPlugins() { try { pluginLoader.loadPlugins(); diff --git a/src/main/java/net/cytonic/cytosis/plugins/loader/PluginClassLoader.java b/src/main/java/net/cytonic/cytosis/plugins/loader/PluginClassLoader.java index 461ecb10..5a7dee15 100644 --- a/src/main/java/net/cytonic/cytosis/plugins/loader/PluginClassLoader.java +++ b/src/main/java/net/cytonic/cytosis/plugins/loader/PluginClassLoader.java @@ -3,11 +3,27 @@ import java.net.URL; import java.net.URLClassLoader; +/** + * A classloader for loading plugins + */ public class PluginClassLoader extends URLClassLoader { + + /** + * Creates a new plugin classloader + * + * @param urls The urls to load + * @param parent The parent classloader + */ public PluginClassLoader(URL[] urls, ClassLoader parent) { super(urls, parent); } + /** + * Loads a class + * @param name The name of the class + * @return The loaded class + * @throws ClassNotFoundException If the class could not be loaded + */ @Override public Class loadClass(String name) throws ClassNotFoundException { return super.loadClass(name); diff --git a/src/main/java/net/cytonic/cytosis/plugins/loader/PluginLoader.java b/src/main/java/net/cytonic/cytosis/plugins/loader/PluginLoader.java index 03289959..2c62c822 100644 --- a/src/main/java/net/cytonic/cytosis/plugins/loader/PluginLoader.java +++ b/src/main/java/net/cytonic/cytosis/plugins/loader/PluginLoader.java @@ -4,17 +4,32 @@ import net.cytonic.cytosis.logging.Logger; import net.cytonic.cytosis.plugins.CytosisPlugin; import net.cytonic.cytosis.plugins.Plugin; + import java.io.File; import java.net.URL; import java.util.*; import java.util.jar.JarEntry; import java.util.jar.JarFile; +/** + * A class that loads plugin classes + */ public class PluginLoader { + + /** + * Default constructor + */ + public PluginLoader() { + // Do nothing + } + private final List pluginClassLoaders = new ArrayList<>(); private final Map> pluginClasses = new HashMap<>(); private final Map> pluginDependencies = new HashMap<>(); + /** + * Loads the plugins from the + */ public void loadPlugins() { File pluginDir = new File("plugins"); if (pluginDir.exists() && pluginDir.isDirectory()) { @@ -47,6 +62,12 @@ public void loadPlugins() { } else pluginDir.mkdir(); } + /** + * Discover all plugins + * + * @param jarFile The file to search + * @param classLoader The loader to use + */ private void discoverPlugins(File jarFile, PluginClassLoader classLoader) { try (JarFile jar = new JarFile(jarFile)) { Enumeration entries = jar.entries(); @@ -71,6 +92,12 @@ private void discoverPlugins(File jarFile, PluginClassLoader classLoader) { } } + /** + * Load dependencies first + * @param pluginName the plugin name + * @param loadedPlugins the loaded plugins + * @param classLoader the class loader + */ private void loadDependencies(String pluginName, Set loadedPlugins, PluginClassLoader classLoader) { if (loadedPlugins.contains(pluginName)) { return; diff --git a/src/main/java/net/cytonic/cytosis/ranks/PlayerRank.java b/src/main/java/net/cytonic/cytosis/ranks/PlayerRank.java index f63d0a38..8d7d6834 100644 --- a/src/main/java/net/cytonic/cytosis/ranks/PlayerRank.java +++ b/src/main/java/net/cytonic/cytosis/ranks/PlayerRank.java @@ -3,6 +3,7 @@ import lombok.Getter; import net.kyori.adventure.text.Component; import net.kyori.adventure.text.format.NamedTextColor; + import static net.cytonic.cytosis.utils.MiniMessageTemplate.MM; /** @@ -11,17 +12,47 @@ @Getter public enum PlayerRank { // Staff ranks + /** + * The [OWNER] rank + */ OWNER(MM."[OWNER]", NamedTextColor.RED, NamedTextColor.WHITE, new String[]{"*"}), + /** + * The [ADMIN] rank + */ ADMIN(MM."[ADMIN]", NamedTextColor.RED, NamedTextColor.WHITE, new String[]{"*"}), + /** + * The [MOD] rank + */ MODERATOR(MM."[MOD]", NamedTextColor.GREEN, NamedTextColor.WHITE, new String[]{}), + /** + * The [HELPER] rank + */ HELPER(MM."[HELPER]", NamedTextColor.AQUA, NamedTextColor.WHITE, new String[]{}), // player ranks + /** + * The [ELYSIAN] rank + */ ELYSIAN(MM."[ELYSIAN]", NamedTextColor.GOLD, NamedTextColor.WHITE, new String[]{}), + /** + * The [CELESTIAL] rank + */ CELESTIAL(MM."[CELESTIAL]", NamedTextColor.DARK_AQUA, NamedTextColor.WHITE, new String[]{}), + /** + * The [MASTER] rank + */ MASTER(MM."[MASTER]", NamedTextColor.DARK_RED, NamedTextColor.WHITE, new String[]{}), + /** + * The [VALIENT] rank + */ VALIENT(MM."[VALIENT]", NamedTextColor.DARK_GREEN, NamedTextColor.WHITE, new String[]{}), + /** + * The [NOBLE] rank + */ NOBLE(MM."[NOBLE]", NamedTextColor.DARK_PURPLE, NamedTextColor.WHITE, new String[]{}), + /** + * The [DEFAULT] rank + */ DEFAULT(MM."[DEFAULT]", NamedTextColor.GRAY, NamedTextColor.GRAY, new String[]{"cytosis.commands.gamemode"}); private final Component prefix; @@ -44,14 +75,36 @@ public enum PlayerRank { this.permissions = permissions; } + /** + * A utility method to check if a demotion is valid + * + * @param currentRole The player's current role + * @param newRole The player's new role + * @return Whether the demotion is valid + */ public static boolean isDemotion(PlayerRank currentRole, PlayerRank newRole) { return newRole.ordinal() > currentRole.ordinal(); } + /** + * a method to check if a promotion is valid + * + * @param currentRole The player's current role + * @param newRole The player's new role + * @return Whether the promotion is valid + */ public static boolean isPromotion(PlayerRank currentRole, PlayerRank newRole) { return newRole.ordinal() < currentRole.ordinal(); } + /** + * A method to check if a rank can be changed + * + * @param currentUserRole The changer's current role + * @param targetOriginalRole The player's original role + * @param targetNewRole The player's new role + * @return if the rank can be changed + */ public static boolean canChangeRank(PlayerRank currentUserRole, PlayerRank targetOriginalRole, PlayerRank targetNewRole) { if (currentUserRole == OWNER) return true; if (isDemotion(targetOriginalRole, targetNewRole)) { @@ -63,5 +116,4 @@ public static boolean canChangeRank(PlayerRank currentUserRole, PlayerRank targe // If it's neither promotion nor demotion, it's an invalid operation return false; } - -} \ No newline at end of file +} diff --git a/src/main/java/net/cytonic/cytosis/ranks/RankManager.java b/src/main/java/net/cytonic/cytosis/ranks/RankManager.java index 97c137e0..e2ca12ee 100644 --- a/src/main/java/net/cytonic/cytosis/ranks/RankManager.java +++ b/src/main/java/net/cytonic/cytosis/ranks/RankManager.java @@ -12,14 +12,29 @@ import net.minestom.server.scoreboard.Team; import net.minestom.server.scoreboard.TeamBuilder; import org.jetbrains.annotations.NotNull; + import java.util.Optional; import java.util.UUID; import java.util.concurrent.ConcurrentHashMap; +/** + * A class that manages player ranks + */ public class RankManager { - ConcurrentHashMap rankMap = new ConcurrentHashMap<>(); - ConcurrentHashMap teamMap = new ConcurrentHashMap<>(); + /** + * Default constructor + */ + public RankManager() { + // Do nothing + } + + private final ConcurrentHashMap rankMap = new ConcurrentHashMap<>(); + private final ConcurrentHashMap teamMap = new ConcurrentHashMap<>(); + + /** + * Creates the teams for cosmetic ranks + */ public void init() { for (PlayerRank value : PlayerRank.values()) { Team team = new TeamBuilder(value.ordinal() + value.name(), MinecraftServer.getTeamManager()) @@ -31,6 +46,11 @@ public void init() { } } + /** + * Adds a player to the rank manager + * + * @param player the player + */ public void addPlayer(Player player) { // cache the rank Cytosis.getDatabaseManager().getMysqlDatabase().getPlayerRank(player.getUuid()).whenComplete((playerRank, throwable) -> { @@ -46,6 +66,11 @@ public void addPlayer(Player player) { }); } + /** + * Changes a players rank + * @param player the player + * @param rank the rank + */ public void changeRank(Player player, PlayerRank rank) { if (!rankMap.containsKey(player.getUuid())) throw new IllegalStateException(STR."The player \{player.getUsername()} is not yet initialized! Call addPlayer(Player) first!"); @@ -58,6 +83,11 @@ public void changeRank(Player player, PlayerRank rank) { setupCosmetics(player, rank); } + /** + * Sets up the cosmetics. (Team, tab list, etc) + * @param player The player + * @param rank The rank + */ private void setupCosmetics(Player player, PlayerRank rank) { addPermissions(player, rank.getPermissions()); teamMap.get(rank).addMember(player.getUsername()); @@ -65,19 +95,38 @@ private void setupCosmetics(Player player, PlayerRank rank) { Cytosis.getCommandHandler().recalculateCommands(player); } + /** + * Removes a player from the manager. It also strips permissions + * @param player The player + */ public void removePlayer(Player player) { removePermissions(player, rankMap.getOrDefault(player.getUuid(), PlayerRank.DEFAULT).getPermissions()); rankMap.remove(player.getUuid()); } + /** + * Adds permissions to a player + * @param player the player + * @param nodes the permission nodes + */ public final void addPermissions(@NotNull final Player player, @NotNull final String... nodes) { for (String node : nodes) player.addPermission(new Permission(node)); } + /** + * Strips permissions from a player + * @param player the player + * @param nodes the nodes to remove + */ public final void removePermissions(@NotNull final Player player, @NotNull final String... nodes) { for (String node : nodes) player.removePermission(node); } + /** + * Gets a player's rank + * @param uuid The uuid of the player + * @return the player's Rank, if it exists + */ public Optional getPlayerRank(UUID uuid) { return Optional.ofNullable(rankMap.get(uuid)); } diff --git a/src/main/java/net/cytonic/cytosis/sideboard/DefaultCreator.java b/src/main/java/net/cytonic/cytosis/sideboard/DefaultCreator.java index 0f7d9962..d54f5827 100644 --- a/src/main/java/net/cytonic/cytosis/sideboard/DefaultCreator.java +++ b/src/main/java/net/cytonic/cytosis/sideboard/DefaultCreator.java @@ -4,15 +4,22 @@ import net.cytonic.cytosis.logging.Logger; import net.kyori.adventure.text.Component; import net.minestom.server.entity.Player; + import java.net.InetAddress; import java.util.List; + import static net.cytonic.cytosis.utils.MiniMessageTemplate.MM; /** * The default implementation of {@link SideboardCreator}, creating a baseline sideboard for Cytosis. */ public class DefaultCreator implements SideboardCreator { - private static final int thingy = 0; + + /** + * The default constructor + */ + public DefaultCreator() { + } @Override public Sideboard sideboard(Player player) { @@ -38,7 +45,6 @@ public List lines(Player player) { } catch (Exception e) { Logger.error("error", e); return List.of(MM."Failed to get server information!"); - } } diff --git a/src/main/java/net/cytonic/cytosis/sideboard/Sideboard.java b/src/main/java/net/cytonic/cytosis/sideboard/Sideboard.java index adcb6bda..50f3eb2f 100644 --- a/src/main/java/net/cytonic/cytosis/sideboard/Sideboard.java +++ b/src/main/java/net/cytonic/cytosis/sideboard/Sideboard.java @@ -341,11 +341,20 @@ public void delete() { this.deleted = true; } + /** + * Send a line change packet + * + * @param score the score to change + */ public void sendLineChange(int score) { Component line = getLineByScore(score); sendTeamPacket(score, TeamMode.UPDATE, line, Component.empty()); } + /** + * Get an empty line + * @return an empty line + */ public Component emptyLine() { return Component.empty(); } @@ -364,18 +373,38 @@ private void checkLineNumber(int line, boolean checkInRange, boolean checkMax) { } } + /** + * Gets a score from a line bynver + * @param line the line + * @return the score + */ public int getScoreByLine(int line) { return this.lines.size() - line - 1; } + /** + * Gets a line by the score number + * @param score The score + * @return The line by the score + */ public Component getLineByScore(int score) { return getLineByScore(this.lines, score); } + /** + * gets a sline by score + * @param lines The existing lines + * @param score The score + * @return The Line + */ public Component getLineByScore(List lines, int score) { return score < lines.size() ? lines.get(lines.size() - score - 1) : null; } + /** + * Sends the objective packet + * @param mode with the mode + */ public void sendObjectivePacket(ObjectiveMode mode) { ScoreboardObjectivePacket packet; @@ -392,14 +421,27 @@ public void sendObjectivePacket(ObjectiveMode mode) { sendPacket(packet); } + /** + * Sends a packet to display the objective + */ public void sendDisplayObjectivePacket() { sendPacket(new DisplayScoreboardPacket((byte) 1, this.id)); } + /** + * Sends a score packet + * @param score The score + * @param action the action + */ public void sendScorePacket(int score, ScoreboardAction action) { sendModernScorePacket(score, action); } + /** + * Sends a score packet + * @param score The score + * @param action the action + */ private void sendModernScorePacket(int score, ScoreboardAction action) { String objName = objective[score]; @@ -413,10 +455,22 @@ private void sendModernScorePacket(int score, ScoreboardAction action) { sendPacket(packet); } + /** + * Sends a team packet + * @param score The score + * @param mode the mode + */ public void sendTeamPacket(int score, TeamMode mode) { sendTeamPacket(score, mode, Component.empty(), Component.empty()); } + /** + * Sends a team packet + * @param score the score + * @param mode the mode + * @param prefix the prefix + * @param suffix the suffix + */ public void sendTeamPacket(int score, TeamMode mode, Component prefix, Component suffix) { if (mode == TeamMode.ADD_PLAYERS || mode == TeamMode.REMOVE_PLAYERS) throw new UnsupportedOperationException(); TeamsPacket.Action action; @@ -439,15 +493,61 @@ private void sendPacket(ServerPacket packet) { if (this.player.isOnline()) player.sendPacket(packet); } + /** + * Allowed modes for a scoreboard + */ public enum ObjectiveMode { - CREATE, REMOVE, UPDATE + /** + * Create a new objective + */ + CREATE, + /** + * Remove the objective + */ + REMOVE, + /** + * Update the objective + */ + UPDATE } + /** + * actions for team packets + */ public enum TeamMode { - CREATE, REMOVE, UPDATE, ADD_PLAYERS, REMOVE_PLAYERS + /** + * Create a new team + */ + CREATE, + /** + * Remove a team + */ + REMOVE, + /** + * Update a team + */ + UPDATE, + /** + * Add a player to a team + */ + ADD_PLAYERS, + /** + * Remove a player from a team + */ + REMOVE_PLAYERS } + /** + * Actions for scoreboards + */ public enum ScoreboardAction { - CHANGE, REMOVE + /** + * Change the scoreboard + */ + CHANGE, + /** + * Remove the scoreboard + */ + REMOVE } } \ No newline at end of file diff --git a/src/main/java/net/cytonic/cytosis/sideboard/SideboardCreator.java b/src/main/java/net/cytonic/cytosis/sideboard/SideboardCreator.java index be3c83aa..ab5e8c50 100644 --- a/src/main/java/net/cytonic/cytosis/sideboard/SideboardCreator.java +++ b/src/main/java/net/cytonic/cytosis/sideboard/SideboardCreator.java @@ -9,9 +9,25 @@ * An interface for creating sideboards. */ public interface SideboardCreator { + /** + * Creates the sideboard for the player + * + * @param player The player to create the sideboard for + * @return The Sideboard for the player + */ Sideboard sideboard(Player player); + /** + * A method to create the lines for the sideboard + * @param player The player + * @return The list of components + */ List lines(Player player); + /** + * Creates the title for the sideboard + * @param player The player + * @return The title in Component form + */ Component title(Player player); } diff --git a/src/main/java/net/cytonic/cytosis/utils/BanData.java b/src/main/java/net/cytonic/cytosis/utils/BanData.java index 8d738ae4..409ca965 100644 --- a/src/main/java/net/cytonic/cytosis/utils/BanData.java +++ b/src/main/java/net/cytonic/cytosis/utils/BanData.java @@ -4,10 +4,13 @@ import java.time.Instant; +/** + * A Record that contains information about a player's ban + * + * @param reason The reason they were banned + * @param expiry The Instant when they will be unbanned + * @param isBanned If the player is banned + */ public record BanData(@Nullable String reason, @Nullable Instant expiry, boolean isBanned) { - public BanData(@Nullable String reason, @Nullable Instant expiry, boolean isBanned) { - this.reason = reason; - this.expiry = expiry; - this.isBanned = isBanned; - } + } diff --git a/src/main/java/net/cytonic/cytosis/utils/ComponentWrapper.java b/src/main/java/net/cytonic/cytosis/utils/ComponentWrapper.java index 18ae64e1..3c4fd5c8 100644 --- a/src/main/java/net/cytonic/cytosis/utils/ComponentWrapper.java +++ b/src/main/java/net/cytonic/cytosis/utils/ComponentWrapper.java @@ -6,9 +6,23 @@ import net.kyori.adventure.text.format.Style; import net.kyori.adventure.text.format.TextDecoration; import net.minestom.server.utils.StringUtils; + import java.util.*; -public class ComponentWrapper { +/** + * A util class that wraps text components + */ +public final class ComponentWrapper { + private ComponentWrapper() { + } + + /** + * Wraps the text component with a specified line length + * + * @param component The component to wrap + * @param length The line length + * @return The list of wrapped components + */ public static List wrap(Component component, int length) { if (!(component instanceof TextComponent text)) return Collections.singletonList(component); var wrapped = new ArrayList(); diff --git a/src/main/java/net/cytonic/cytosis/utils/DurationParser.java b/src/main/java/net/cytonic/cytosis/utils/DurationParser.java index 7d649022..470076ca 100644 --- a/src/main/java/net/cytonic/cytosis/utils/DurationParser.java +++ b/src/main/java/net/cytonic/cytosis/utils/DurationParser.java @@ -7,9 +7,18 @@ import java.util.regex.Matcher; import java.util.regex.Pattern; -public class DurationParser { +/** + * A class handling parsing of duration strings + */ +public final class DurationParser { private static final Pattern PATTERN = Pattern.compile("(\\d+)([ydhms])"); + /** + * The default constructor + */ + private DurationParser() { + } + /** * Parses a duration from a string akin to "1y5d6h23m12s" * `-1` provides a null, representing a permanant value diff --git a/src/main/java/net/cytonic/cytosis/utils/MessageUtils.java b/src/main/java/net/cytonic/cytosis/utils/MessageUtils.java index e9b1fcc7..4694c2f4 100644 --- a/src/main/java/net/cytonic/cytosis/utils/MessageUtils.java +++ b/src/main/java/net/cytonic/cytosis/utils/MessageUtils.java @@ -2,16 +2,29 @@ import net.kyori.adventure.text.Component; -public class MessageUtils { +/** + * A class that holds utils for formatting messages + */ +public final class MessageUtils { + /** + * Defaut constructor + */ + private MessageUtils() { + } + /** + * Gets a formatted ban message + * + * @param banData the data to format + * @return the formatted message in Component format + */ public static Component formatBanMessage(BanData banData) { if (!banData.isBanned()) return Component.empty(); - Component finalComp = Component.empty() + + return Component.empty() .append(MiniMessageTemplate.MM."You are currently banned from the Cytonic Network!".appendNewline().appendNewline()) .append(MiniMessageTemplate.MM."Reason: \{banData.reason()}".appendNewline()) .append(MiniMessageTemplate.MM."Expires: \{DurationParser.unparse(banData.expiry(), " ")}".appendNewline().appendNewline()) .append(MiniMessageTemplate.MM."Appeal at: https://cytonic.net".appendNewline()); - - return finalComp; } } diff --git a/src/main/java/net/cytonic/cytosis/utils/MiniMessageTemplate.java b/src/main/java/net/cytonic/cytosis/utils/MiniMessageTemplate.java index 20e2d782..febb43c9 100644 --- a/src/main/java/net/cytonic/cytosis/utils/MiniMessageTemplate.java +++ b/src/main/java/net/cytonic/cytosis/utils/MiniMessageTemplate.java @@ -2,18 +2,28 @@ import net.kyori.adventure.text.Component; import net.kyori.adventure.text.minimessage.MiniMessage; + import java.util.List; +/** + * A class that holds utils for formatting messages + */ public final class MiniMessageTemplate { private MiniMessageTemplate() { } + /** + * Parses MiniMessage into a Component + */ @SuppressWarnings("preview") public static final StringTemplate.Processor MM = stringTemplate -> { String interpolated = STR.process(stringTemplate); return MiniMessage.miniMessage().deserialize(interpolated); }; + /** + * Parses and wraps a component with a width of 36 + */ @SuppressWarnings("preview") public static final StringTemplate.Processor, RuntimeException> MM_WRAP = stringTemplate -> { String interpolated = STR.process(stringTemplate); diff --git a/src/main/java/net/cytonic/cytosis/utils/OfflinePlayer.java b/src/main/java/net/cytonic/cytosis/utils/OfflinePlayer.java index ce4c24a5..8213e471 100644 --- a/src/main/java/net/cytonic/cytosis/utils/OfflinePlayer.java +++ b/src/main/java/net/cytonic/cytosis/utils/OfflinePlayer.java @@ -9,6 +9,13 @@ import java.util.Set; import java.util.UUID; +/** + * An offline player + * + * @param name the name of the player + * @param uuid the uuid of the player + * @param rank the rank of the player + */ public record OfflinePlayer(String name, UUID uuid, PlayerRank rank) implements PermissionHandler { @Override diff --git a/src/main/java/net/cytonic/cytosis/utils/PosSerializer.java b/src/main/java/net/cytonic/cytosis/utils/PosSerializer.java index 324279e4..ab80c1a4 100644 --- a/src/main/java/net/cytonic/cytosis/utils/PosSerializer.java +++ b/src/main/java/net/cytonic/cytosis/utils/PosSerializer.java @@ -2,7 +2,15 @@ import net.minestom.server.coordinate.Pos; -public class PosSerializer { +/** + * A class that provides utilities for serializing and deserializing {@link Pos} objects. + */ +public final class PosSerializer { + /** + * Default constructor + */ + private PosSerializer() { + } /** * Serializes a {@link Pos} object into a human-readable string format. diff --git a/src/main/java/net/cytonic/cytosis/utils/Utils.java b/src/main/java/net/cytonic/cytosis/utils/Utils.java index 9d357432..9a5dd8bf 100644 --- a/src/main/java/net/cytonic/cytosis/utils/Utils.java +++ b/src/main/java/net/cytonic/cytosis/utils/Utils.java @@ -10,12 +10,20 @@ /** * A class holding utility methods */ -public class Utils { +public final class Utils { + + /** + * Default constructor + */ + private Utils() { + // do nothing + } /** * Creates a MUTABLE list from a vararg, for immutable lists, use {@link List#of(Object...)} * * @param vararg The elements to be added to the list + * @param The type of the list * @return The elements as a List object */ @SafeVarargs @@ -23,6 +31,11 @@ public static List list(E... vararg) { return new ArrayList<>(List.of(vararg)); } + /** + * Gets the server's IP address + * + * @return the string of the IP address + */ public static String getServerIP() { String serverIP; try { diff --git a/src/main/java/net/cytonic/cytosis/utils/UuidUtils.java b/src/main/java/net/cytonic/cytosis/utils/UuidUtils.java index 32ac68da..9d19be83 100644 --- a/src/main/java/net/cytonic/cytosis/utils/UuidUtils.java +++ b/src/main/java/net/cytonic/cytosis/utils/UuidUtils.java @@ -4,17 +4,34 @@ import com.google.gson.JsonParser; import net.cytonic.cytosis.logging.Logger; import org.jetbrains.annotations.Nullable; + import java.io.IOException; import java.io.InputStreamReader; import java.net.*; import java.util.UUID; -public class UuidUtils { +/** + * A class that provides utilities for dealing with UUIDs + */ +public final class UuidUtils { + + /** + * Default constructor + */ + private UuidUtils() { + // do nothing + } private static final String UUID_URL_TEMPLATE = "https://api.mojang.com/users/profiles/minecraft/%s"; + /** + * Gets the UUID of a player by their username + * + * @param username the username + * @return the UUID + */ @Nullable - public static String getMojandUUID(final String username) { + public static String UNSAFE_getMojandUUID(final String username) { URL url; try { url = new URI(String.format(UUID_URL_TEMPLATE, username)).toURL(); @@ -39,14 +56,25 @@ public static String getMojandUUID(final String username) { } - public static UUID getUUID(final String username) { - String raw = getMojandUUID(username); + /** + * Gets a UUID from a username + * + * @param username username + * @return the UUID + */ + public static UUID UNSAFE_getUUID(final String username) { + String raw = UNSAFE_getMojandUUID(username); if (raw == null) throw new IllegalArgumentException(STR."A player by the name '\{username}' does not exist!"); if (raw.length() != 32) throw new IllegalArgumentException(STR."Raw UUID provided is not 32 characters! '\{raw}' is \{raw.length()}"); return UUID.fromString(raw.replaceAll("(\\w{8})(\\w{4})(\\w{4})(\\w{4})(\\w{12})", "$1-$2-$3-$4-$5")); } + /** + * Converts a UUID to a mojang UUID by removing the dashes + * @param uuid the UUID + * @return the mojang UUID + */ public static String toMojang(UUID uuid) { return uuid.toString().replace("-", ""); }