Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

DB usage improved #36

Merged
merged 1 commit into from
May 26, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
10 changes: 9 additions & 1 deletion src/main/java/lar/minecraft/hg/ServerSchedulers.java
Original file line number Diff line number Diff line change
Expand Up @@ -85,11 +85,17 @@ public void run() {
public void safeAreaPhase() {
SpigotPlugin.setPhase(HGPhase.SAFE_AREA);
safeAreaTime = 0;
currentHGGameId = DatabaseManager.createHGGame(1);

// Register new HungerGames game on Database
currentHGGameId = DatabaseManager.createHGGame(SpigotPlugin.serverId);

// Notify all players that Hunger Games is starting
ServerManager.getLivingPlayers().forEach(p -> {
p.spigot().sendMessage(ChatMessageType.ACTION_BAR, TextComponent.fromLegacyText("It's starting the Hunger Games!"));
p.setGameMode(GameMode.SURVIVAL);
p.teleport(world.getSpawnLocation());

// Write player join on Database
DatabaseManager.addPlayerJoin(config.getInt("server.id", 1), currentHGGameId, p);
});
ServerManager.giveClasses();
Expand Down Expand Up @@ -170,6 +176,8 @@ public void run() {
SpigotPlugin.server.broadcastMessage(winner.getName() + " wins the Hunger Games!");
winner.sendTitle("You win the Hunger Games!", null, 10, 70, 20);
winnerCelebrationsTime = execTime + (20 * config.getInt("winner-celebrations", 20));

// Save the winning player on Database
DatabaseManager.savePlayerWin(config.getInt("server.id", 1), currentHGGameId, winner);
fireworkEffect(winner);
}
Expand Down
15 changes: 15 additions & 0 deletions src/main/java/lar/minecraft/hg/SpigotPlugin.java
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
package lar.minecraft.hg;

import java.sql.SQLException;
import java.util.HashMap;
import java.util.Map;

Expand All @@ -10,6 +11,7 @@

import lar.minecraft.hg.commands.ClassCommand;
import lar.minecraft.hg.commands.TestCommand;
import lar.minecraft.hg.managers.DatabaseManager;
import lar.minecraft.hg.managers.PlayerManager;

public class SpigotPlugin extends JavaPlugin {
Expand All @@ -18,6 +20,8 @@ public class SpigotPlugin extends JavaPlugin {

public static HGPhase phase;

public static int serverId;

public static Map<Player, PlayerExt> playerExtension = new HashMap<>();

@Override
Expand All @@ -29,20 +33,31 @@ public void onLoad() {
@Override
public void onDisable() {
// Don't log disabling, Spigot does that for you automatically!
try {
DatabaseManager.disconnectToDatabase();
} catch (ClassNotFoundException e) {
e.printStackTrace();
} catch (SQLException e) {
e.printStackTrace();
}
}

@Override
public void onEnable() {
// Don't log enabling, Spigot does that for you automatically!

phase = HGPhase.WAITING_FOR_HG;
serverId = getConfig().getInt("server.id");

getServer().getWorld("world").setDifficulty(Difficulty.PEACEFUL); // TODO For test purpose

// Create world border
getServer().getWorld("world").getWorldBorder().setCenter(getServer().getWorld("world").getSpawnLocation());
getServer().getWorld("world").getWorldBorder().setSize(getConfig().getInt("world-border.max-size", 256));

// Instantiate database connection and connect
new DatabaseManager(this, true);

// Commands enabled with following method must have entries in plugin.yml
getCommand("lobby").setExecutor(new TestCommand(this));
getCommand("nolobby").setExecutor(new TestCommand(this));
Expand Down
192 changes: 124 additions & 68 deletions src/main/java/lar/minecraft/hg/managers/DatabaseManager.java
Original file line number Diff line number Diff line change
@@ -1,61 +1,121 @@
package lar.minecraft.hg.managers;

import java.sql.*;

import org.bukkit.configuration.file.FileConfiguration;
import org.bukkit.entity.Player;

// TODO Make optional connection
import lar.minecraft.hg.SpigotPlugin;

public class DatabaseManager {

// TODO Add these properties into config.yml file
private static String connectionString = "jdbc:mysql://localhost:3306/hunger_games";
private static String databaseUser = "multicraft";
private static String databasePassword = "4E3M4dYSlP9g2yC#";
private static FileConfiguration config;
private static boolean databaseEnabled = false;
private static String dbConnectionString;
private static String dbUser;
private static String dbPassword;
private static Connection dbConnection;

public static void connectToDatabase() throws SQLException, ClassNotFoundException {
if (dbConnection != null) {
if (!dbConnection.isClosed()) {
return;
public static boolean isDatabaseEnabled() {
return databaseEnabled;
}

public DatabaseManager(SpigotPlugin plugin, boolean directlyConnect) {
config = plugin.getConfig();
databaseEnabled = config.getBoolean("database.enable", false);

// Directly connect to database when creating Database Manager
if (isDatabaseEnabled()) {
dbConnectionString = config.getString("database.connection-string");
dbUser = config.getString("database.db-user");
dbPassword = config.getString("database.db-password");

if (directlyConnect) {
try {
connectToDatabase();
} catch (ClassNotFoundException | SQLException e) {
e.printStackTrace();
}
}
}
}

/**
* Connect to Database
* @throws SQLException
* @throws ClassNotFoundException
*/
public static void connectToDatabase() throws SQLException, ClassNotFoundException {
if (isDatabaseEnabled()) {
if (dbConnection != null) {
if (!dbConnection.isClosed()) {
return;
}
}

Class.forName("com.mysql.jdbc.Driver");
dbConnection = DriverManager.getConnection(connectionString, databaseUser, databasePassword);
Class.forName("com.mysql.jdbc.Driver");
dbConnection = DriverManager.getConnection(dbConnectionString, dbUser, dbPassword);

// Create necessary tables if not present
createTables();
}
}

/**
* Disconnect from Database
* @throws SQLException
* @throws ClassNotFoundException
*/
public static void disconnectToDatabase() throws SQLException, ClassNotFoundException {
if (dbConnection != null) {
if (!dbConnection.isClosed()) {
dbConnection.close();
if (isDatabaseEnabled()) {
if (dbConnection != null) {
if (!dbConnection.isClosed()) {
dbConnection.close();
}
}
}
}

public static int createTables() {
if (isDatabaseEnabled()) {
try {
Statement statementCreate = dbConnection.createStatement();
statementCreate.executeUpdate(String.format("CREATE TABLE IF NOT EXISTS hg_games (server_id int NOT NULL, id int NOT NULL, winner_uuid varchar(100), win_datetime datetime)"));
statementCreate.executeUpdate(String.format("CREATE TABLE IF NOT EXISTS played_hg_games (server_id int NOT NULL, id int NOT NULL, player_uuid varchar(100))"));
statementCreate.executeUpdate(String.format("CREATE TABLE IF NOT EXISTS players (uuid varchar(100), name varchar(100))"));
} catch (SQLException e) {
e.printStackTrace();
}
}

return 0;
}

/**
* Save the information of the new match
* @param serverId
* @return the new hg game Id
*/
public static int createHGGame(int ServerId) {
try {
connectToDatabase();

int hgGameId = 1;
Statement statementRead = dbConnection.createStatement();
Statement statementInsert = dbConnection.createStatement();
ResultSet resultSet = statementRead.executeQuery(String.format("SELECT MAX(id) AS foundId FROM hg_games WHERE server_id = %d;", ServerId));

while (resultSet.next()) {
int foundRows = resultSet.getInt("foundId");
hgGameId = foundRows + 1;
public static int createHGGame(int ServerId){
if (isDatabaseEnabled()) {
try {
int hgGameId = 1;
Statement statementRead = dbConnection.createStatement();
Statement statementInsert = dbConnection.createStatement();
ResultSet resultSet = statementRead.executeQuery(String.format("SELECT MAX(id) AS foundId FROM hg_games WHERE server_id = %d;", ServerId));

while (resultSet.next()) {
int foundRows = resultSet.getInt("foundId");
hgGameId = foundRows + 1;
}
statementInsert.executeUpdate(String.format("INSERT INTO hg_games (server_id, id) VALUES (%d, %d);", ServerId, hgGameId));

return hgGameId;
} catch (SQLException e) {
e.printStackTrace();
}
statementInsert.executeUpdate(String.format("INSERT INTO hg_games (server_id, id) VALUES (%d, %d);", ServerId, hgGameId));

disconnectToDatabase();
return hgGameId;
} catch (ClassNotFoundException | SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}

return 0;
}

Expand All @@ -66,34 +126,31 @@ public static int createHGGame(int ServerId) {
* @param player
*/
public static void addPlayerJoin(int ServerId, int HGGameId, Player player) {
try {
connectToDatabase();

Statement statementRead = dbConnection.createStatement();
Statement statementInsert = dbConnection.createStatement();

//Add player into players table if not existing
ResultSet resultSet = statementRead.executeQuery(String.format("SELECT COUNT(*) AS playerFound FROM players WHERE uuid = '%s';", player.getUniqueId().toString()));
while (resultSet.next()) {
int foundRows = resultSet.getInt("playerFound");
if (foundRows == 0) {
statementInsert.executeUpdate(String.format("INSERT INTO players (uuid, name) VALUES ('%s', '%s');", player.getUniqueId(), player.getName()));
if (isDatabaseEnabled()) {
try {
Statement statementRead = dbConnection.createStatement();
Statement statementInsert = dbConnection.createStatement();
//Add player into players table if not existing
ResultSet resultSet = statementRead.executeQuery(String.format("SELECT COUNT(*) AS playerFound FROM players WHERE uuid = '%s';", player.getUniqueId().toString()));
while (resultSet.next()) {
int foundRows = resultSet.getInt("playerFound");
if (foundRows == 0) {
statementInsert.executeUpdate(String.format("INSERT INTO players (uuid, name) VALUES ('%s', '%s');", player.getUniqueId(), player.getName()));
}
}
}

//Add player into played hg games if not existing
resultSet = statementRead.executeQuery(String.format("SELECT COUNT(*) AS playerFound FROM played_hg_games WHERE server_id = %d AND id = %d AND player_uuid = '%s';", ServerId, HGGameId, player.getUniqueId().toString()));
while (resultSet.next()) {
int foundRows = resultSet.getInt("playerFound");
if (foundRows == 0) {
statementInsert.executeUpdate(String.format("INSERT INTO played_hg_games (server_id, id, player_uuid) VALUES ('%d', '%d', '%s');", ServerId, HGGameId, player.getUniqueId(), player.getName()));

//Add player into played hg games if not existing
resultSet = statementRead.executeQuery(String.format("SELECT COUNT(*) AS playerFound FROM played_hg_games WHERE server_id = %d AND id = %d AND player_uuid = '%s';", ServerId, HGGameId, player.getUniqueId().toString()));
while (resultSet.next()) {
int foundRows = resultSet.getInt("playerFound");
if (foundRows == 0) {
statementInsert.executeUpdate(String.format("INSERT INTO played_hg_games (server_id, id, player_uuid) VALUES ('%d', '%d', '%s');", ServerId, HGGameId, player.getUniqueId(), player.getName()));
}
}
} catch (SQLException e) {
e.printStackTrace();
}

disconnectToDatabase();
} catch (ClassNotFoundException | SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}

Expand All @@ -104,17 +161,16 @@ public static void addPlayerJoin(int ServerId, int HGGameId, Player player) {
* @param player the winner
*/
public static void savePlayerWin(int ServerId, int HGGameId, Player player) {
try {
connectToDatabase();

Statement statementUpdate = dbConnection.createStatement();
statementUpdate.executeUpdate(String.format("UPDATE hg_games SET winner_uuid = '%s', win_datetime = NOW() WHERE server_id = %d AND id = %d", player.getUniqueId().toString(), ServerId, HGGameId));

disconnectToDatabase();
} catch (ClassNotFoundException | SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
if (isDatabaseEnabled()) {
try {
Statement statementUpdate = dbConnection.createStatement();
statementUpdate.executeUpdate(String.format("UPDATE hg_games SET winner_uuid = '%s', win_datetime = NOW() WHERE server_id = %d AND id = %d", player.getUniqueId().toString(), ServerId, HGGameId));
} catch (SQLException e) {
e.printStackTrace();
}
}
}


}

7 changes: 6 additions & 1 deletion src/main/resources/config.yml
Original file line number Diff line number Diff line change
Expand Up @@ -7,4 +7,9 @@ world-border:
max-size: 128
min-size: 2
server:
id: 1
id: 1
database:
enable: true
connection-string: jdbc:mysql://51.38.125.46:3306/hunger_games
db-user: test
db-password: test
Loading