Skip to content

Commit

Permalink
MySQL support
Browse files Browse the repository at this point in the history
  • Loading branch information
ChromMob authored Feb 12, 2022
1 parent f25f414 commit 8d83714
Show file tree
Hide file tree
Showing 10 changed files with 379 additions and 7 deletions.
27 changes: 26 additions & 1 deletion src/main/java/me/chrommob/minestore/MineStore.java
Original file line number Diff line number Diff line change
Expand Up @@ -6,11 +6,15 @@
import io.netty.channel.EventLoopGroup;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.nio.NioServerSocketChannel;
import lombok.Getter;
import me.chrommob.minestore.commands.Buy;
import me.chrommob.minestore.commands.Reload;
import me.chrommob.minestore.commands.Store;
import me.chrommob.minestore.data.Config;
import me.chrommob.minestore.gui.Event;
import me.chrommob.minestore.mysql.MySQLData;
import me.chrommob.minestore.mysql.connection.ConnectionPool;
import me.chrommob.minestore.mysql.data.UserManager;
import me.chrommob.minestore.placeholders.PlaceholderHook;
import me.chrommob.minestore.commands.PunishmentManager;
import me.chrommob.minestore.commandexecution.JoinQuitListener;
Expand All @@ -22,7 +26,10 @@
import org.bukkit.plugin.PluginManager;
import org.bukkit.plugin.java.JavaPlugin;


public final class MineStore extends JavaPlugin {
@Getter
UserManager userManager;
public static MineStore instance;
Mode mode = Mode.WEBSOCKET;

Expand All @@ -33,10 +40,10 @@ public void onLoad() {

@Override
public void onEnable() {
instance = this;
Metrics metrics = new Metrics(this, 14043);
dependencyCheck();
PluginManager plManager = Bukkit.getPluginManager();
instance = this;
PaperCommandManager manager = new PaperCommandManager(this);
manager.registerCommand(new Reload());
plManager.registerEvents(new JoinQuitListener(), this);
Expand All @@ -49,6 +56,7 @@ public void onEnable() {
} else {
mode = Mode.WEBLISTENER;
}
MySQLData.setEnabled(getConfig().getBoolean("mysql.enabled"));
Config.setStoreEnabled(getConfig().getBoolean("store-enabled"));
Config.setPort(getConfig().getInt("port"));
Config.setGuiEnabled(getConfig().getBoolean("gui-enabled"));
Expand All @@ -70,6 +78,11 @@ public void onEnable() {
if (Config.isStoreEnabled()) {
manager.registerCommand(new Store());
}
if (MySQLData.isEnabled() && Config.isVaultPresent()) {
new ConnectionPool(this);
ConnectionPool.createTable();
userManager = new UserManager();
}
}

@Override
Expand All @@ -85,6 +98,13 @@ private void dependencyCheck() {
Config.setPlaceholderPresent(true);
new PlaceholderHook(this).register();
}
if (Bukkit.getPluginManager().getPlugin("Vault") == null) {
Bukkit.getLogger().info("[MineStore] Vault found!");
Config.setVaultPresent(false);
}
else {
Config.setVaultPresent(true);
}
}

private void NettyServer(int port) throws Exception
Expand All @@ -105,6 +125,11 @@ private void NettyServer(int port) throws Exception

public void loadConfig() {
reloadConfig();
MySQLData.setIp(getConfig().getString("mysql.ip"));
MySQLData.setPort(getConfig().getInt("mysql.port"));
MySQLData.setUser(getConfig().getString("mysql.username"));
MySQLData.setPassword(getConfig().getString("mysql.password"));
MySQLData.setDatabase(getConfig().getString("mysql.database"));
Config.setPassword(getConfig().getString("password"));
Config.setApiUrl(getConfig().getString("store-api"));
Config.setStoreMessage(getConfig().getString("store-message"));
Expand Down
Original file line number Diff line number Diff line change
@@ -1,19 +1,25 @@
package me.chrommob.minestore.commandexecution;

import me.chrommob.minestore.MineStore;
import me.chrommob.minestore.commands.PunishmentManager;
import me.chrommob.minestore.data.Config;
import me.chrommob.minestore.mysql.MySQLData;
import me.chrommob.minestore.mysql.data.UserManager;
import org.bukkit.Bukkit;
import org.bukkit.event.EventHandler;
import org.bukkit.event.Listener;
import org.bukkit.event.player.PlayerJoinEvent;

import java.util.UUID;

import static me.chrommob.minestore.commandexecution.Command.runLater;


public class JoinQuitListener implements Listener {
@EventHandler
public void onPlayerJoin(final PlayerJoinEvent event) {
String name = event.getPlayer().getName();
try {
String name = event.getPlayer().getName();
if (runLater.get(name).isEmpty()) {
runLater.remove(name);
} else {
Expand All @@ -26,6 +32,18 @@ public void onPlayerJoin(final PlayerJoinEvent event) {
}
} catch (Exception ignored) {
}
if (Config.isVaultPresent() && MySQLData.isEnabled()) {
String name = event.getPlayer().getName();
UUID uuid = event.getPlayer().getUniqueId();
MineStore.instance.getUserManager().createProfile(uuid, name);
}
}
@EventHandler
public void onPlayerQuit(final PlayerJoinEvent event) {
if (Config.isVaultPresent() && MySQLData.isEnabled()) {
String name = event.getPlayer().getName();
UUID uuid = event.getPlayer().getUniqueId();
MineStore.instance.getUserManager().removeProfile(uuid);
}
}

}
2 changes: 1 addition & 1 deletion src/main/java/me/chrommob/minestore/commands/Reload.java
Original file line number Diff line number Diff line change
Expand Up @@ -14,7 +14,7 @@ public class Reload extends BaseCommand {
private void onReload(CommandSender sender) {
try {
MineStore.instance.loadConfig();
sender.sendMessage("§aConfig reloaded! Be aware reloading doesn't reload the mode, websocket port, gui toggle and store toggle.");
sender.sendMessage("§aConfig reloaded! Be aware reloading doesn't reload the mode, websocket port, gui toggle, mysql toggle and store toggle.");
} catch (Exception e) {
sender.sendMessage("§cAn error occurred while reloading the config.");
e.printStackTrace();
Expand Down
5 changes: 5 additions & 0 deletions src/main/java/me/chrommob/minestore/data/Config.java
Original file line number Diff line number Diff line change
Expand Up @@ -64,4 +64,9 @@ public class Config {
@Setter
@Getter
private static boolean placeholderPresent;

@Setter
@Getter
private static boolean vaultPresent;

}
30 changes: 30 additions & 0 deletions src/main/java/me/chrommob/minestore/mysql/MySQLData.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,30 @@
package me.chrommob.minestore.mysql;

import lombok.Getter;
import lombok.Setter;

public class MySQLData {
@Getter
@Setter
private static boolean enabled;

@Getter
@Setter
private static String ip;

@Getter
@Setter
private static int port;

@Getter
@Setter
private static String database;

@Getter
@Setter
private static String user;

@Getter
@Setter
private static String password;
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,174 @@
package me.chrommob.minestore.mysql.connection;

import com.zaxxer.hikari.HikariConfig;
import com.zaxxer.hikari.HikariDataSource;
import me.chrommob.minestore.MineStore;
import me.chrommob.minestore.mysql.MySQLData;
import me.chrommob.minestore.mysql.data.User;
import org.bukkit.Bukkit;
import org.bukkit.configuration.file.FileConfiguration;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.Map;
import java.util.UUID;

public class ConnectionPool {
private static MineStore plugin;

private static HikariDataSource hikari;

private String hostname;
private String port;
public static String database;
private String username;
private String password;

private int minimumConnections;
private int maximumConnections;
private long connectionTimeout;

public ConnectionPool(MineStore plugin) {
this.plugin = plugin;
init();
setupPool();
}

private void init() {
FileConfiguration fileConfig = plugin.getConfig();

this.username = MySQLData.getUser();
this.password = MySQLData.getPassword();
this.database = MySQLData.getDatabase();
this.hostname = MySQLData.getIp();
this.port = String.valueOf(MySQLData.getPort());

this.minimumConnections = 5;
this.maximumConnections = 100;
this.connectionTimeout = 2000;
}

private void setupPool() {
HikariConfig config = new HikariConfig();
config.setJdbcUrl(
"jdbc:mysql://" +
hostname +
":" +
port +
"/" +
database +
"?useUnicode=true&useJDBCCompliantTimezoneShift=true&useLegacyDatetimeCode=false&serverTimezone=UTC"
);
config.setDriverClassName("com.mysql.jdbc.Driver");
config.setUsername(username);
config.setPassword(password);
config.setMinimumIdle(minimumConnections);
config.setMaximumPoolSize(maximumConnections);
config.setConnectionTimeout(connectionTimeout);
config.setLeakDetectionThreshold(60000);
config.setIdleTimeout(600000);
config.setMaxLifetime(1800000);

//config.setConnectionTestQuery(testQuery);
hikari = new HikariDataSource(config);
}


public static void close(Connection conn, PreparedStatement ps, ResultSet res) {
if (conn != null) try { conn.close(); } catch (SQLException ignored) {}
if (ps != null) try { ps.close(); } catch (SQLException ignored) {}
if (res != null) try { res.close(); } catch (SQLException ignored) {}
}


public static void closePool() {
if (hikari != null && !hikari.isClosed()) {
hikari.close();
}
}

public static void createTable(){
Connection conn = null;
PreparedStatement ps = null;
try {
conn = hikari.getConnection();
ps = conn.prepareStatement("CREATE TABLE IF NOT EXISTS playerdata"
+ " (uuid VARCHAR(255) UNIQUE,"
+ " username VARCHAR(255) NOT NULL default '',"
+ " prefix VARCHAR(255) NOT NULL default '',"
+ " suffix VARCHAR(255) NOT NULL default '',"
+ " balance DOUBLE NOT NULL default 0.00,"
+ " player_group VARCHAR(255) NOT NULL default 0,"
+ " PRIMARY KEY (uuid));");
ps.executeUpdate();
} catch (SQLException e) {
e.printStackTrace();
}
finally {
close(conn, ps, null);
}
}

public static void updateTable() {
try {
Map<UUID, User> userMap = MineStore.instance.getUserManager().getAll();
userMap.forEach((uuid, user) -> {
update(user);
}
);
} catch (Exception e) {
e.printStackTrace();
}

}

private static void update(User user) {
Connection conn = null;
PreparedStatement ps = null;
try {
Bukkit.getLogger().info("[MineStore] Updated user: " + user.getName());
conn = hikari.getConnection();
String sql_qury = "INSERT INTO playerdata (uuid,username,prefix,suffix,balance,player_group) VALUES (?,?,?,?,?,?) ON DUPLICATE KEY UPDATE username=?,prefix=?,suffix=?,balance=?,player_group=?";
ps = conn.prepareStatement(sql_qury);
String uuid = user.getUuid().toString();
String username = user.getName();
String prefix;
String suffix;
String group;
if (user.getPrefix() == null) {
prefix = "";
} else {
prefix = user.getPrefix();
}
if (user.getSuffix() == null) {
suffix = "";
} else {
suffix = user.getSuffix();
}
if (user.getGroup_name() == null) {
group = "";
} else {
group = user.getGroup_name();
}
ps.setString(1, uuid);
ps.setString(2, username);
ps.setString(3, prefix);
ps.setString(4, suffix);
ps.setDouble(5, user.getBalance());
ps.setString(6, group);
ps.setString(7, username);
ps.setString(8, prefix);
ps.setString(9, suffix);
ps.setDouble(10, user.getBalance());
ps.setString(11, group);
ps.executeUpdate();
} catch (SQLException e) {
e.printStackTrace();
}
finally {
close(conn, ps, null);
}
}
}
Loading

0 comments on commit 8d83714

Please sign in to comment.