Move Plex to API-driven plugin and fix NoClassDefFoundError on startup

This commit is contained in:
Focusvity
2022-04-24 14:16:14 +10:00
parent edeecb51f4
commit f9a577035b
346 changed files with 736 additions and 118 deletions

View File

@ -0,0 +1,53 @@
package dev.plex.storage;
import com.mongodb.client.MongoClient;
import com.mongodb.client.MongoClients;
import dev.morphia.Datastore;
import dev.morphia.Morphia;
import dev.morphia.mapping.MapperOptions;
import dev.plex.PlexBase;
import dev.plex.player.PlexPlayer;
import dev.plex.util.PlexLog;
public class MongoConnection implements PlexBase
{
// USE MORPHIA API FOR MONGO <3
public Datastore getDatastore()
{
if (!plugin.config.getString("data.central.storage").equalsIgnoreCase("mongodb"))
{
return null;
}
String host = plugin.config.getString("data.central.hostname");
int port = plugin.config.getInt("data.central.port");
String username = plugin.config.getString("data.central.user");
String password = plugin.config.getString("data.central.password");
String database = plugin.config.getString("data.central.db");
String connectionString;
if (username != null && password != null && !username.isEmpty() && !password.isEmpty())
{
if (database != null && !database.isEmpty())
{
connectionString = "mongodb://" + username + ":" + password + "@" + host + ":" + port + "/?authSource=" + database;
}
else
{
connectionString = "mongodb://" + username + ":" + password + "@" + host + ":" + port + "/";
}
}
else
{
connectionString = "mongodb://" + host + ":" + port + "/";
}
connectionString += "?uuidRepresentation=STANDARD";
PlexLog.debug("Using mongo connection string: " + connectionString);
MongoClient client = MongoClients.create(connectionString);
Datastore datastore = Morphia.createDatastore(client, database == null ? "admin" : database, MapperOptions.DEFAULT);
datastore.getMapper().map(PlexPlayer.class);
datastore.ensureIndexes();
plugin.setStorageType(StorageType.MONGODB);
return datastore;
}
}

View File

@ -0,0 +1,47 @@
package dev.plex.storage;
import dev.plex.PlexBase;
import dev.plex.util.PlexLog;
import java.util.function.Consumer;
import redis.clients.jedis.Jedis;
public class RedisConnection implements PlexBase
{
private Jedis jedis;
public Jedis getJedis()
{
try
{
jedis = new Jedis(plugin.config.getString("data.side.hostname"),
plugin.config.getInt("data.side.port"));
if (plugin.config.getBoolean("data.side.auth"))
{
jedis.auth(plugin.config.getString("data.side.password"));
}
return jedis;
}
catch (Exception ex)
{
PlexLog.error("An error occurred with Redis.");
ex.printStackTrace();
}
return jedis;
}
public void runAsync(Consumer<Jedis> jedisConsumer)
{
new Thread(() ->
{
try (Jedis jedis = getJedis())
{
jedisConsumer.accept(jedis);
}
}).start();
}
public final boolean isEnabled()
{
return plugin.config.getBoolean("data.side.enabled");
}
}

View File

@ -0,0 +1,122 @@
package dev.plex.storage;
import com.zaxxer.hikari.HikariConfig;
import com.zaxxer.hikari.HikariDataSource;
import dev.plex.Plex;
import dev.plex.PlexBase;
import java.io.File;
import java.sql.Connection;
import java.sql.SQLException;
import lombok.Getter;
@Getter
public class SQLConnection implements PlexBase
{
private HikariDataSource dataSource;
public SQLConnection()
{
if (!plugin.config.getString("data.central.storage").equalsIgnoreCase("sqlite") && !plugin.config.getString("data.central.storage").equalsIgnoreCase("mariadb"))
{
return;
}
String host = plugin.config.getString("data.central.hostname");
int port = plugin.config.getInt("data.central.port");
String username = plugin.config.getString("data.central.user");
String password = plugin.config.getString("data.central.password");
String database = plugin.config.getString("data.central.db");
HikariConfig config = new HikariConfig();
config.addDataSourceProperty("cachePrepStmts", "true");
config.addDataSourceProperty("prepStmtCacheSize", "250");
config.addDataSourceProperty("prepStmtCacheSqlLimit", "2048");
this.dataSource = new HikariDataSource();
dataSource.setMaxLifetime(15000);
dataSource.setIdleTimeout(15000 * 2);
dataSource.setConnectionTimeout(15000 * 4);
dataSource.setMinimumIdle(2);
dataSource.setMaximumPoolSize(10);
try
{
if (plugin.config.getString("data.central.storage").equalsIgnoreCase("sqlite"))
{
dataSource.setJdbcUrl("jdbc:sqlite:" + new File(plugin.getDataFolder(), "database.db").getAbsolutePath());
plugin.setStorageType(StorageType.SQLITE);
}
else if (plugin.config.getString("data.central.storage").equalsIgnoreCase("mariadb"))
{
Class.forName("org.mariadb.jdbc.Driver");
dataSource.setJdbcUrl("jdbc:mariadb://" + host + ":" + port + "/" + database);
dataSource.setUsername(username);
dataSource.setPassword(password);
Plex.get().setStorageType(StorageType.MARIADB);
}
}
catch (ClassNotFoundException throwables)
{
throwables.printStackTrace();
}
try (Connection con = getCon())
{
con.prepareStatement("CREATE TABLE IF NOT EXISTS `players` (" +
"`uuid` VARCHAR(46) NOT NULL, " +
"`name` VARCHAR(18), " +
"`login_msg` VARCHAR(2000), " +
"`prefix` VARCHAR(2000), " +
"`rank` VARCHAR(20), " +
"`adminActive` BOOLEAN," +
"`ips` VARCHAR(2000), " +
"`coins` BIGINT, " +
"`vanished` BOOLEAN, " +
"`commandspy` BOOLEAN, " +
"PRIMARY KEY (`uuid`));").execute();
con.prepareStatement("CREATE TABLE IF NOT EXISTS `punishments` (" +
"`punished` VARCHAR(46) NOT NULL, " +
"`punisher` VARCHAR(46), " +
"`punishedUsername` VARCHAR(16), " +
"`ip` VARCHAR(2000), " +
"`type` VARCHAR(30), " +
"`reason` VARCHAR(2000), " +
"`customTime` BOOLEAN, " +
"`active` BOOLEAN, " +
"`endDate` BIGINT" +
");").execute();
con.prepareStatement("CREATE TABLE IF NOT EXISTS `notes` (" +
"`id` INT NOT NULL, " +
"`uuid` VARCHAR(46) NOT NULL, " +
"`written_by` VARCHAR(46), " +
"`note` VARCHAR(2000), " +
"`timestamp` BIGINT" +
");").execute();
con.prepareStatement("CREATE TABLE IF NOT EXISTS `permissions` (" +
"`uuid` VARCHAR(46) NOT NULL," +
"`permission` VARCHAR(1000) NOT NULL," +
"`allowed` BOOLEAN" +
");").execute();
}
catch (SQLException throwables)
{
throwables.printStackTrace();
}
}
public Connection getCon()
{
if (this.dataSource == null)
{
return null;
}
try
{
return dataSource.getConnection();
}
catch (SQLException e)
{
e.printStackTrace();
}
return null;
}
}

View File

@ -0,0 +1,6 @@
package dev.plex.storage;
public enum StorageType
{
MONGODB, MARIADB, SQLITE
}

View File

@ -0,0 +1,95 @@
package dev.plex.storage.permission;
import com.google.common.collect.Lists;
import dev.plex.Plex;
import dev.plex.permission.Permission;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.List;
import java.util.Locale;
import java.util.UUID;
public class SQLPermissions
{
private static final String SELECT = "SELECT * FROM `permissions` WHERE uuid=?";
private static final String INSERT = "INSERT INTO `permissions` (`uuid`, `permission`, `allowed`) VALUES(?, ?, ?)";
private static final String REMOVE_PERMISSION = "DELETE FROM `permissions` WHERE uuid=? AND permission=?";
private static final String UPDATE_PERMISSION = "UPDATE `permissions` SET allowed=? WHERE uuid=? AND permission=?";
public List<Permission> getPermissions(UUID uuid)
{
List<Permission> permissions = Lists.newArrayList();
try (Connection con = Plex.get().getSqlConnection().getCon())
{
PreparedStatement statement = con.prepareStatement(SELECT);
statement.setString(1, uuid.toString());
ResultSet set = statement.executeQuery();
while (set.next())
{
Permission permission = new Permission(UUID.fromString(set.getString("uuid")), set.getString("permission"));
permission.setAllowed(set.getBoolean("allowed"));
permissions.add(permission);
}
}
catch (SQLException e)
{
e.printStackTrace();
}
return permissions;
}
public void addPermission(Permission permission)
{
try (Connection con = Plex.get().getSqlConnection().getCon())
{
PreparedStatement statement = con.prepareStatement(INSERT);
statement.setString(1, permission.getUuid().toString());
statement.setString(2, permission.getPermission().toLowerCase(Locale.ROOT));
statement.setBoolean(3, permission.isAllowed());
statement.execute();
}
catch (SQLException e)
{
e.printStackTrace();
}
}
public void updatePermission(Permission permission, boolean newValue)
{
try (Connection con = Plex.get().getSqlConnection().getCon())
{
PreparedStatement statement = con.prepareStatement(UPDATE_PERMISSION);
statement.setBoolean(1, newValue);
statement.setString(2, permission.getUuid().toString());
statement.setString(3, permission.getPermission().toLowerCase(Locale.ROOT));
statement.executeUpdate();
}
catch (SQLException e)
{
e.printStackTrace();
}
}
public void removePermission(Permission permission)
{
this.removePermission(permission.getUuid(), permission.getPermission());
}
public void removePermission(UUID uuid, String permission)
{
try (Connection con = Plex.get().getSqlConnection().getCon())
{
PreparedStatement statement = con.prepareStatement(REMOVE_PERMISSION);
statement.setString(1, uuid.toString());
statement.setString(2, permission.toLowerCase(Locale.ROOT));
statement.execute();
}
catch (SQLException e)
{
e.printStackTrace();
}
}
}

View File

@ -0,0 +1,148 @@
package dev.plex.storage.player;
import dev.morphia.Datastore;
import dev.morphia.query.Query;
import dev.morphia.query.Update;
import dev.morphia.query.experimental.filters.Filters;
import dev.morphia.query.experimental.updates.UpdateOperators;
import dev.plex.Plex;
import dev.plex.cache.PlayerCache;
import dev.plex.player.PlexPlayer;
import java.util.Collections;
import java.util.List;
import java.util.UUID;
/**
* Mongo fetching utilities for players
*/
public class MongoPlayerData
{
/**
* The datastore object / database
*/
private final Datastore datastore;
/**
* Creates an instance of the player data
*/
public MongoPlayerData()
{
this.datastore = Plex.get().getMongoConnection().getDatastore();
}
/**
* Checks whether the player exists in mongo's database
*
* @param uuid The unique ID of the player
* @return true if the player was found
*/
public boolean exists(UUID uuid)
{
Query<PlexPlayer> query = datastore.find(PlexPlayer.class)
.filter(Filters.eq("uuid", uuid));
return query.first() != null;
}
public boolean exists(String username)
{
Query<PlexPlayer> query = datastore.find(PlexPlayer.class)
.filter(Filters.regex("name").caseInsensitive().pattern(username));
return query.first() != null;
}
/**
* Gets the player from cache or from mongo's database
*
* @param uuid The unique ID of the player
* @return a PlexPlayer object
* @see PlexPlayer
*/
public PlexPlayer getByUUID(UUID uuid)
{
if (PlayerCache.getPlexPlayerMap().containsKey(uuid))
{
return PlayerCache.getPlexPlayerMap().get(uuid);
}
Query<PlexPlayer> query2 = datastore.find(PlexPlayer.class).filter(Filters.eq("uuid", uuid));
return query2.first();
}
public PlexPlayer getByName(String username)
{
PlexPlayer player = PlayerCache.getPlexPlayerMap().values().stream().filter(plexPlayer -> plexPlayer.getName().equalsIgnoreCase(username)).findFirst().orElse(null);
if (player != null)
{
return player;
}
Query<PlexPlayer> query2 = datastore.find(PlexPlayer.class).filter(Filters.regex("name").caseInsensitive().pattern(username));
return query2.first();
}
/**
* Gets the player from cache or from mongo's database
*
* @param ip The IP address of the player.
* @return a PlexPlayer object
* @see PlexPlayer
*/
public PlexPlayer getByIP(String ip)
{
PlexPlayer player = PlayerCache.getPlexPlayerMap().values().stream().filter(plexPlayer -> plexPlayer.getIps().contains(ip)).findFirst().orElse(null);
if (player != null)
{
return player;
}
Query<PlexPlayer> query2 = datastore.find(PlexPlayer.class).filter(Filters.in("ips", Collections.singleton(ip)));
return query2.first();
}
/**
* Updates a player's information in the mongo database
*
* @param player The PlexPlayer object
* @see PlexPlayer
*/
public void update(PlexPlayer player)
{
Query<PlexPlayer> filter = datastore.find(PlexPlayer.class)
.filter(Filters.eq("uuid", player.getUuid()));
Update<PlexPlayer> updateOps = filter
.update(
UpdateOperators.set("name", player.getName()),
UpdateOperators.set("loginMessage", player.getLoginMessage()),
UpdateOperators.set("prefix", player.getPrefix()),
UpdateOperators.set("vanished", player.isVanished()),
UpdateOperators.set("commandSpy", player.isCommandSpy()),
UpdateOperators.set("adminActive", player.isAdminActive()),
UpdateOperators.set("rank", player.getRank().toLowerCase()),
UpdateOperators.set("ips", player.getIps()),
UpdateOperators.set("coins", player.getCoins()),
UpdateOperators.set("punishments", player.getPunishments()),
UpdateOperators.set("notes", player.getNotes()));
updateOps.execute();
}
public List<PlexPlayer> getPlayers()
{
return datastore.find(PlexPlayer.class).stream().toList();
}
/**
* Saves the player's information in the database
*
* @param plexPlayer The PlexPlayer object
* @see PlexPlayer
*/
public void save(PlexPlayer plexPlayer)
{
datastore.save(plexPlayer);
}
}

View File

@ -0,0 +1,316 @@
package dev.plex.storage.player;
import com.google.common.reflect.TypeToken;
import com.google.gson.Gson;
import dev.plex.Plex;
import dev.plex.cache.PlayerCache;
import dev.plex.player.PlexPlayer;
import dev.plex.storage.StorageType;
import dev.plex.util.PlexLog;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.List;
import java.util.UUID;
/**
* SQL fetching utilities for players
*/
public class SQLPlayerData
{
private final String SELECT = "SELECT * FROM `players` WHERE uuid=?";
private final String UPDATE = "UPDATE `players` SET name=?, login_msg=?, prefix=?, rank=?, adminActive=?, ips=?, coins=?, vanished=?, commandspy=? WHERE uuid=?";
private final String INSERT = "INSERT INTO `players` (`uuid`, `name`, `login_msg`, `prefix`, `rank`, `adminActive`, `ips`, `coins`, `vanished`, `commandspy`) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?);";
/**
* Checks if a player exists in the SQL database
*
* @param uuid The unique ID of the player
* @return true if the player was found in the database
*/
public boolean exists(UUID uuid)
{
try (Connection con = Plex.get().getSqlConnection().getCon())
{
PreparedStatement statement = con.prepareStatement(SELECT);
statement.setString(1, uuid.toString());
ResultSet set = statement.executeQuery();
return set.next();
} catch (SQLException throwables)
{
throwables.printStackTrace();
}
return false;
}
public boolean exists(String username)
{
try (Connection con = Plex.get().getSqlConnection().getCon())
{
PreparedStatement statement = con.prepareStatement("SELECT * FROM `players` WHERE name=?");
statement.setString(1, username);
ResultSet set = statement.executeQuery();
return set.next();
} catch (SQLException throwables)
{
throwables.printStackTrace();
}
return false;
}
/**
* Gets the player from cache or from the SQL database
*
* @param uuid The unique ID of the player
* @return a PlexPlayer object
* @see PlexPlayer
*/
public PlexPlayer getByUUID(UUID uuid)
{
if (PlayerCache.getPlexPlayerMap().containsKey(uuid))
{
return PlayerCache.getPlexPlayerMap().get(uuid);
}
try (Connection con = Plex.get().getSqlConnection().getCon())
{
PreparedStatement statement = con.prepareStatement(SELECT);
statement.setString(1, uuid.toString());
ResultSet set = statement.executeQuery();
PlexPlayer plexPlayer = new PlexPlayer(uuid);
while (set.next())
{
String name = set.getString("name");
String loginMSG = set.getString("login_msg");
String prefix = set.getString("prefix");
String rankName = set.getString("rank").toUpperCase();
boolean adminActive = set.getBoolean("adminActive");
long coins = set.getLong("coins");
boolean vanished = set.getBoolean("vanished");
boolean commandspy = set.getBoolean("commandspy");
List<String> ips = new Gson().fromJson(set.getString("ips"), new TypeToken<List<String>>()
{
}.getType());
plexPlayer.setName(name);
plexPlayer.setLoginMessage(loginMSG);
plexPlayer.setPrefix(prefix);
plexPlayer.setRank(rankName);
plexPlayer.setAdminActive(adminActive);
plexPlayer.setIps(ips);
plexPlayer.setCoins(coins);
plexPlayer.setVanished(vanished);
plexPlayer.setCommandSpy(commandspy);
}
return plexPlayer;
} catch (SQLException throwables)
{
throwables.printStackTrace();
}
return null;
}
public PlexPlayer getByName(String username)
{
PlexPlayer player = PlayerCache.getPlexPlayerMap().values().stream().filter(plexPlayer -> plexPlayer.getName().equalsIgnoreCase(username)).findFirst().orElse(null);
if (player != null)
{
return player;
}
try (Connection con = Plex.get().getSqlConnection().getCon())
{
PreparedStatement statement = con.prepareStatement("SELECT * FROM `players` WHERE name=? LIMIT 1");
statement.setString(1, username);
ResultSet set = statement.executeQuery();
while (set.next())
{
PlexPlayer plexPlayer = new PlexPlayer(UUID.fromString(set.getString("uuid")));
String loginMSG = set.getString("login_msg");
String prefix = set.getString("prefix");
String rankName = set.getString("rank").toUpperCase();
boolean adminActive = set.getBoolean("adminActive");
long coins = set.getLong("coins");
boolean vanished = set.getBoolean("vanished");
boolean commandspy = set.getBoolean("commandspy");
List<String> ips = new Gson().fromJson(set.getString("ips"), new TypeToken<List<String>>()
{
}.getType());
plexPlayer.setName(username);
plexPlayer.setLoginMessage(loginMSG);
plexPlayer.setPrefix(prefix);
plexPlayer.setRank(rankName);
plexPlayer.setAdminActive(adminActive);
plexPlayer.setIps(ips);
plexPlayer.setCoins(coins);
plexPlayer.setVanished(vanished);
plexPlayer.setCommandSpy(commandspy);
return plexPlayer;
}
return null;
} catch (SQLException throwables)
{
throwables.printStackTrace();
}
return null;
}
/**
* Gets the player from cache or from the SQL database
*
* @param ip The IP address of the player.
* @return a PlexPlayer object
* @see PlexPlayer
*/
public PlexPlayer getByIP(String ip)
{
PlexPlayer player = PlayerCache.getPlexPlayerMap().values().stream().filter(plexPlayer -> plexPlayer.getIps().contains(ip)).findFirst().orElse(null);
if (player != null)
{
return player;
}
if (Plex.get().getStorageType() == StorageType.MARIADB)
{
try (Connection con = Plex.get().getSqlConnection().getCon())
{
PreparedStatement statement = con.prepareStatement("select * from `players` where json_search(ips, ?, ?) IS NOT NULL LIMIT 1");
statement.setString(1, "one");
statement.setString(2, ip);
ResultSet set = statement.executeQuery();
PlexPlayer plexPlayer = null;
while (set.next())
{
String uuid = set.getString("uuid");
String name = set.getString("name");
String loginMSG = set.getString("login_msg");
String prefix = set.getString("prefix");
String rankName = set.getString("rank").toUpperCase();
boolean adminActive = set.getBoolean("adminActive");
long coins = set.getLong("coins");
boolean vanished = set.getBoolean("vanished");
boolean commandspy = set.getBoolean("commandspy");
List<String> ips = new Gson().fromJson(set.getString("ips"), new TypeToken<List<String>>()
{
}.getType());
plexPlayer = new PlexPlayer(UUID.fromString(uuid));
plexPlayer.setName(name);
plexPlayer.setLoginMessage(loginMSG);
plexPlayer.setPrefix(prefix);
plexPlayer.setRank(rankName);
plexPlayer.setAdminActive(adminActive);
plexPlayer.setIps(ips);
plexPlayer.setCoins(coins);
plexPlayer.setVanished(vanished);
plexPlayer.setCommandSpy(commandspy);
}
return plexPlayer;
} catch (SQLException throwables)
{
throwables.printStackTrace();
}
} else if (Plex.get().getStorageType() == StorageType.SQLITE)
{
PlexLog.warn("Querying a user by IP running SQLite can cause performance issues! Please try to switch to a remote DB ASAP!");
try (Connection con = Plex.get().getSqlConnection().getCon())
{
PreparedStatement statement = con.prepareStatement("select * from `players`");
ResultSet set = statement.executeQuery();
PlexPlayer plexPlayer = null;
while (set.next())
{
List<String> ips = new Gson().fromJson(set.getString("ips"), new TypeToken<List<String>>()
{
}.getType());
if (!ips.contains(ip))
{
continue;
}
String uuid = set.getString("uuid");
String name = set.getString("name");
String loginMSG = set.getString("login_msg");
String prefix = set.getString("prefix");
String rankName = set.getString("rank").toUpperCase();
boolean adminActive = set.getBoolean("adminActive");
long coins = set.getLong("coins");
boolean vanished = set.getBoolean("vanished");
boolean commandspy = set.getBoolean("commandspy");
plexPlayer = new PlexPlayer(UUID.fromString(uuid));
plexPlayer.setName(name);
plexPlayer.setLoginMessage(loginMSG);
plexPlayer.setPrefix(prefix);
plexPlayer.setRank(rankName);
plexPlayer.setAdminActive(adminActive);
plexPlayer.setIps(ips);
plexPlayer.setCoins(coins);
plexPlayer.setVanished(vanished);
plexPlayer.setCommandSpy(commandspy);
}
return plexPlayer;
} catch (SQLException throwables)
{
throwables.printStackTrace();
}
}
return null;
}
/**
* Updates a player's information in the SQL database
*
* @param player The PlexPlayer object
* @see PlexPlayer
*/
public void update(PlexPlayer player)
{
try (Connection con = Plex.get().getSqlConnection().getCon())
{
PreparedStatement statement = con.prepareStatement(UPDATE);
statement.setString(1, player.getName());
statement.setString(2, player.getLoginMessage());
statement.setString(3, player.getPrefix());
statement.setString(4, player.getRank().toLowerCase());
statement.setBoolean(5, player.isAdminActive());
statement.setString(6, new Gson().toJson(player.getIps()));
statement.setLong(7, player.getCoins());
statement.setBoolean(8, player.isVanished());
statement.setBoolean(9, player.isCommandSpy());
statement.setString(10, player.getUuid().toString());
statement.executeUpdate();
} catch (SQLException throwables)
{
throwables.printStackTrace();
}
}
/**
* Inserts the player's information in the database
*
* @param player The PlexPlayer object
* @see PlexPlayer
*/
public void insert(PlexPlayer player)
{
try (Connection con = Plex.get().getSqlConnection().getCon())
{
PreparedStatement statement = con.prepareStatement(INSERT);
statement.setString(1, player.getUuid().toString());
statement.setString(2, player.getName());
statement.setString(3, player.getLoginMessage());
statement.setString(4, player.getPrefix());
statement.setString(5, player.getRank().toLowerCase());
statement.setBoolean(6, player.isAdminActive());
statement.setString(7, new Gson().toJson(player.getIps()));
statement.setLong(8, player.getCoins());
statement.setBoolean(9, player.isVanished());
statement.setBoolean(10, player.isCommandSpy());
statement.execute();
} catch (SQLException throwables)
{
throwables.printStackTrace();
}
}
}

View File

@ -0,0 +1,96 @@
package dev.plex.storage.punishment;
import com.google.common.collect.Lists;
import dev.plex.Plex;
import dev.plex.punishment.extra.Note;
import dev.plex.util.TimeUtils;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.time.*;
import java.util.List;
import java.util.UUID;
import java.util.concurrent.CompletableFuture;
public class SQLNotes
{
private static final String SELECT = "SELECT * FROM `notes` WHERE uuid=?";
private static final String INSERT = "INSERT INTO `notes` (`id`, `uuid`, `written_by`, `note`, `timestamp`) VALUES(?, ?, ?, ?, ?)";
private static final String DELETE = "DELETE FROM `notes` WHERE uuid=? AND id=?";
public CompletableFuture<List<Note>> getNotes(UUID uuid)
{
return CompletableFuture.supplyAsync(() ->
{
List<Note> notes = Lists.newArrayList();
try (Connection con = Plex.get().getSqlConnection().getCon())
{
PreparedStatement statement = con.prepareStatement(SELECT);
statement.setString(1, uuid.toString());
ResultSet set = statement.executeQuery();
while (set.next())
{
Note note = new Note(
uuid,
set.getString("note"),
UUID.fromString(set.getString("written_by")),
ZonedDateTime.ofInstant(Instant.ofEpochMilli(set.getLong("timestamp")), ZoneId.of(TimeUtils.TIMEZONE))
);
note.setId(set.getInt("id"));
notes.add(note);
}
}
catch (SQLException e)
{
e.printStackTrace();
return notes;
}
return notes;
});
}
public CompletableFuture<Void> deleteNote(int id, UUID uuid)
{
return CompletableFuture.runAsync(() ->
{
try (Connection con = Plex.get().getSqlConnection().getCon())
{
PreparedStatement statement = con.prepareStatement(DELETE);
statement.setString(1, uuid.toString());
statement.setInt(2, id);
statement.execute();
}
catch (SQLException e)
{
e.printStackTrace();
}
});
}
public CompletableFuture<Void> addNote(Note note)
{
return CompletableFuture.runAsync(() ->
{
getNotes(note.getUuid()).whenComplete((notes, throwable) ->
{
try (Connection con = Plex.get().getSqlConnection().getCon())
{
PreparedStatement statement = con.prepareStatement(INSERT);
statement.setInt(1, notes.size() + 1);
statement.setString(2, note.getUuid().toString());
statement.setString(3, note.getWrittenBy().toString());
statement.setString(4, note.getNote());
statement.setLong(5, note.getTimestamp().toInstant().toEpochMilli());
statement.execute();
note.setId(notes.size());
}
catch (SQLException e)
{
e.printStackTrace();
}
});
});
}
}

View File

@ -0,0 +1,160 @@
package dev.plex.storage.punishment;
import com.google.common.collect.Lists;
import dev.plex.Plex;
import dev.plex.punishment.Punishment;
import dev.plex.punishment.PunishmentType;
import dev.plex.util.PlexLog;
import dev.plex.util.TimeUtils;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.time.Instant;
import java.time.ZoneId;
import java.time.ZonedDateTime;
import java.util.List;
import java.util.UUID;
import java.util.concurrent.CompletableFuture;
public class SQLPunishment
{
private static final String SELECT = "SELECT * FROM `punishments` WHERE punished=?";
private static final String SELECT_BY = "SELECT * FROM `punishments` WHERE punisher=?";
private static final String INSERT = "INSERT INTO `punishments` (`punished`, `punisher`, `punishedUsername`, `ip`, `type`, `reason`, `customTime`, `active`, `endDate`) VALUES(?, ?, ?, ?, ?, ?, ?, ?, ?)";
private static final String UPDATE_BAN = "UPDATE `punishments` SET active=? WHERE active=? AND punished=? AND type=?";
public CompletableFuture<List<Punishment>> getPunishments()
{
return CompletableFuture.supplyAsync(() ->
{
List<Punishment> punishments = Lists.newArrayList();
try (Connection con = Plex.get().getSqlConnection().getCon())
{
PreparedStatement statement = con.prepareStatement("SELECT * FROM `punishments`");
ResultSet set = statement.executeQuery();
while (set.next())
{
Punishment punishment = new Punishment(UUID.fromString(set.getString("punished")), set.getString("punisher") != null && set.getString("punisher").isEmpty() ? UUID.fromString(set.getString("punisher")) : null);
punishment.setActive(set.getBoolean("active"));
punishment.setType(PunishmentType.valueOf(set.getString("type")));
punishment.setCustomTime(set.getBoolean("customTime"));
punishment.setPunishedUsername(set.getString("punishedUsername"));
punishment.setEndDate(ZonedDateTime.ofInstant(Instant.ofEpochMilli(set.getLong("endDate")), ZoneId.of(TimeUtils.TIMEZONE)));
punishment.setReason(set.getString("reason"));
punishment.setIp(set.getString("ip"));
punishments.add(punishment);
}
} catch (SQLException e)
{
e.printStackTrace();
return punishments;
}
return punishments;
});
}
public List<Punishment> getPunishments(UUID uuid)
{
List<Punishment> punishments = Lists.newArrayList();
try (Connection con = Plex.get().getSqlConnection().getCon())
{
PreparedStatement statement = con.prepareStatement(SELECT);
statement.setString(1, uuid.toString());
ResultSet set = statement.executeQuery();
while (set.next())
{
Punishment punishment = new Punishment(UUID.fromString(set.getString("punished")), set.getString("punisher") == null ? null : UUID.fromString(set.getString("punisher")));
punishment.setActive(set.getBoolean("active"));
punishment.setType(PunishmentType.valueOf(set.getString("type")));
punishment.setCustomTime(set.getBoolean("customTime"));
punishment.setPunishedUsername(set.getString("punishedUsername"));
punishment.setEndDate(ZonedDateTime.ofInstant(Instant.ofEpochMilli(set.getLong("endDate")), ZoneId.of(TimeUtils.TIMEZONE)));
punishment.setReason(set.getString("reason"));
punishment.setIp(set.getString("ip"));
punishments.add(punishment);
}
} catch (SQLException e)
{
e.printStackTrace();
}
return punishments;
}
public CompletableFuture<Void> insertPunishment(Punishment punishment)
{
return CompletableFuture.runAsync(() ->
{
try (Connection con = Plex.get().getSqlConnection().getCon())
{
PlexLog.debug("Running execute punishment on " + punishment.getPunished().toString());
PreparedStatement statement = con.prepareStatement(INSERT);
statement.setString(1, punishment.getPunished().toString());
statement.setString(2, punishment.getPunisher() == null ? null : punishment.getPunisher().toString());
statement.setString(3, punishment.getPunishedUsername());
statement.setString(4, punishment.getIp());
statement.setString(5, punishment.getType().name());
statement.setString(6, punishment.getReason());
statement.setBoolean(7, punishment.isCustomTime());
statement.setBoolean(8, punishment.isActive());
statement.setLong(9, punishment.getEndDate().toInstant().toEpochMilli());
PlexLog.debug("Executing punishment");
statement.execute();
} catch (SQLException e)
{
e.printStackTrace();
}
});
}
public void syncRemoveBan(UUID uuid)
{
try (Connection con = Plex.get().getSqlConnection().getCon())
{
PreparedStatement statement = con.prepareStatement(UPDATE_BAN);
statement.setBoolean(1, false);
statement.setBoolean(2, true);
statement.setString(3, uuid.toString());
statement.setString(4, PunishmentType.BAN.name());
PreparedStatement statement1 = con.prepareStatement(UPDATE_BAN);
statement1.setBoolean(1, false);
statement1.setBoolean(2, true);
statement1.setString(3, uuid.toString());
statement1.setString(4, PunishmentType.TEMPBAN.name());
statement1.executeUpdate();
} catch (SQLException e)
{
e.printStackTrace();
}
}
public CompletableFuture<Void> removeBan(UUID uuid)
{
return CompletableFuture.runAsync(() ->
{
try (Connection con = Plex.get().getSqlConnection().getCon())
{
PreparedStatement statement = con.prepareStatement(UPDATE_BAN);
statement.setBoolean(1, false);
statement.setBoolean(2, true);
statement.setString(3, uuid.toString());
statement.setString(4, PunishmentType.BAN.name());
statement.executeUpdate();
PreparedStatement statement1 = con.prepareStatement(UPDATE_BAN);
statement1.setBoolean(1, false);
statement1.setBoolean(2, true);
statement1.setString(3, uuid.toString());
statement1.setString(4, PunishmentType.TEMPBAN.name());
statement1.executeUpdate();
} catch (SQLException e)
{
e.printStackTrace();
}
});
}
}