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

SQLite Storage Option #14

Open
wants to merge 2 commits into
base: master
Choose a base branch
from
Open
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
3 changes: 2 additions & 1 deletion pom.xml
Original file line number Diff line number Diff line change
Expand Up @@ -74,7 +74,7 @@
<dependency>
<groupId>me.clip</groupId>
<artifactId>placeholderapi</artifactId>
<version>2.10.9</version>
<version>2.11.6</version>
<scope>provided</scope>
</dependency>
<dependency>
Expand All @@ -83,5 +83,6 @@
<version>4.1.0</version>
<scope>compile</scope>
</dependency>

</dependencies>
</project>
6 changes: 6 additions & 0 deletions src/main/java/net/naturva/morphie/mr/Commands.java
Original file line number Diff line number Diff line change
Expand Up @@ -31,6 +31,12 @@ public Commands(MorphRedeem plugin) {
public boolean onCommand(CommandSender sender, Command cmd, String label, String[] args) {
if (cmd.getName().equalsIgnoreCase("morphredeem") || cmd.getName().equalsIgnoreCase("redeem") || cmd.getName().equalsIgnoreCase("mr")) {
if (args.length == 0) {

if(!(sender instanceof Player)){
sender.sendMessage(ChatColor.RED + "This command can only be used by the player. Did you mean " + ChatColor.AQUA + "/mr help?");
return true;
}

Player player = (Player)sender;
if (!player.isSleeping()) {
if (sender.hasPermission("morphredeem.redeem")) {
Expand Down
27 changes: 17 additions & 10 deletions src/main/java/net/naturva/morphie/mr/MorphRedeem.java
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,7 @@

import net.naturva.morphie.mr.events.JoinEvent;
import net.naturva.morphie.mr.util.Database.RedisConnection;
import net.naturva.morphie.mr.util.Database.SQLiteConnection;
import net.naturva.morphie.mr.util.StringUtils;
import net.naturva.morphie.mr.util.UpdateChecker;
import org.bukkit.Bukkit;
Expand Down Expand Up @@ -62,13 +63,17 @@ public void onEnable() {
getServer().getConsoleSender().sendMessage(new StringUtils().addColor("&bVersion&8: &a" + this.Version));
createConfig();
loadConfigManager();
if (this.getConfig().getString("StorageMethod").equals("MySQL")) {
if (this.getConfig().getString("StorageMethod").equalsIgnoreCase("MySQL")) {
new MySQLConnection(this).mysqlSetup();
new MySQLConnection(this).checkStructure();
getServer().getConsoleSender().sendMessage(new StringUtils().addColor("&bStorage Type&8: &aMySQL"));
} else if(this.getConfig().getString("StorageMethod").equals("Redis")) {
} else if(this.getConfig().getString("StorageMethod").equalsIgnoreCase("Redis")) {
new RedisConnection(this).auth();
getServer().getConsoleSender().sendMessage(new StringUtils().addColor("&bStorage Type&8: &aRedis"));
} else if (this.getConfig().getString("StorageMethod").equalsIgnoreCase("SQLite")) {
new SQLiteConnection(this).sqliteSetup();
new SQLiteConnection(this).checkStructure();
getServer().getConsoleSender().sendMessage(new StringUtils().addColor("&bStorage Type&8: &aSQLite"));
} else {
getServer().getConsoleSender().sendMessage(new StringUtils().addColor("&bStorage Type&8: &aYML"));
}
Expand All @@ -81,15 +86,17 @@ public void onEnable() {
getServer().getConsoleSender().sendMessage(new StringUtils().addColor("&bPlugin Status&8: &aEnabled"));
getServer().getConsoleSender().sendMessage(new StringUtils().addColor("&8[----------[&3MorphRedeem&8]----------]"));

UpdateChecker updater = new UpdateChecker(this);
try {
if (updater.checkForUpdates()) {
if (this.getConfig().getBoolean("Settings.UpdateChecker")) {
Bukkit.getConsoleSender().sendMessage(new StringUtils().addColor(this.getMessage("Prefix") + this.getMessage("UpdateMessage").replace("%VERSION%", new UpdateChecker(this).getLatestVersion()).replace("%LINK%", new UpdateChecker(this).getResourceURL())));
if (this.getConfig().getBoolean("Settings.UpdateChecker")) {
Bukkit.getScheduler().runTaskAsynchronously(this, ()->{
UpdateChecker updater = new UpdateChecker(this);
try {
if (updater.checkForUpdates()) {
Bukkit.getConsoleSender().sendMessage(new StringUtils().addColor(this.getMessage("Prefix") + this.getMessage("UpdateMessage").replace("%VERSION%", new UpdateChecker(this).getLatestVersion()).replace("%LINK%", new UpdateChecker(this).getResourceURL())));
}
} catch (Exception e) {
e.printStackTrace();
}
}
} catch (Exception e) {
e.printStackTrace();
});
}
}

Expand Down
21 changes: 12 additions & 9 deletions src/main/java/net/naturva/morphie/mr/events/JoinEvent.java
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@
import net.naturva.morphie.mr.MorphRedeem;
import net.naturva.morphie.mr.util.StringUtils;
import net.naturva.morphie.mr.util.UpdateChecker;
import org.bukkit.Bukkit;
import org.bukkit.entity.Player;
import org.bukkit.event.EventHandler;
import org.bukkit.event.Listener;
Expand All @@ -18,17 +19,19 @@ public JoinEvent(MorphRedeem plugin) {
@EventHandler
public void onJoin(PlayerJoinEvent e) {
Player player = e.getPlayer();
UpdateChecker updater = new UpdateChecker(plugin);
try {
if (updater.checkForUpdates()) {
if (this.plugin.getConfig().getBoolean("Settings.UpdateChecker")) {
if (player.hasPermission("morphredeem.admin") || player.hasPermission("morphredeem.updateChecker")) {
player.sendMessage(new StringUtils().addColor(plugin.getMessage("Prefix") + plugin.getMessage("UpdateMessage").replace("%VERSION%", new UpdateChecker(plugin).getLatestVersion()).replace("%LINK%", new UpdateChecker(plugin).getResourceURL())));
if (this.plugin.getConfig().getBoolean("Settings.UpdateChecker")) {
Bukkit.getScheduler().runTaskAsynchronously(plugin, ()->{
UpdateChecker updater = new UpdateChecker(plugin);
try {
if (updater.checkForUpdates()) {
if (player.hasPermission("morphredeem.admin") || player.hasPermission("morphredeem.updateChecker")) {
player.sendMessage(new StringUtils().addColor(plugin.getMessage("Prefix") + plugin.getMessage("UpdateMessage").replace("%VERSION%", new UpdateChecker(plugin).getLatestVersion()).replace("%LINK%", new UpdateChecker(plugin).getResourceURL())));
}
}
} catch (Exception e1) {
e1.printStackTrace();
}
}
} catch (Exception e1) {
e1.printStackTrace();
});
}
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@
import java.util.UUID;
import java.util.logging.Level;

import net.naturva.morphie.mr.util.Database.SQLiteConnection;
import org.bukkit.Bukkit;
import org.bukkit.configuration.file.FileConfiguration;
import org.bukkit.configuration.file.YamlConfiguration;
Expand All @@ -30,9 +31,11 @@ public void onJoin(PlayerJoinEvent e) {
Player player = e.getPlayer();
UUID uuid = player.getUniqueId();

if (this.plugin.getConfig().getString("StorageMethod").equals("MySQL")) {
if (this.plugin.getConfig().getString("StorageMethod").equalsIgnoreCase("MySQL")) {
new MySQLConnection(this.plugin).createPlayer(uuid, player);
} else if(!this.plugin.getConfig().getString("StorageMethod").equals("Redis")) {
} else if (this.plugin.getConfig().getString("StorageMethod").equalsIgnoreCase("SQLite")) {
new SQLiteConnection(this.plugin).createPlayer(uuid, player);
} else if(!this.plugin.getConfig().getString("StorageMethod").equalsIgnoreCase("Redis")) {
new BukkitRunnable() {
public void run() {
File file = getData(uuid);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@
import java.util.UUID;

import net.naturva.morphie.mr.util.StringUtils;
import org.bukkit.Bukkit;
import org.bukkit.entity.Player;
import org.bukkit.event.EventHandler;
import org.bukkit.event.EventPriority;
Expand Down Expand Up @@ -75,18 +76,18 @@ public void onChat(AsyncPlayerChatEvent e) {
}
player.sendMessage(new StringUtils().addColor(this.plugin.getMessage("ErrorPrefix") + message));
} else {
new DataManager(plugin).updateData(uuid, +amountToAdd, "Credits_Spent", "add");
new DataManager(plugin).updateData(uuid, -amountToAdd, "Credits", "remove");
ExperienceAPI.addLevel(player, skill, amountToAdd);
String message = this.plugin.getMessage("CreditAssignmentSuccess");
if (message.contains("%SKILL%")) {
message = message.replaceAll("%SKILL%", skill);
}
if (message.contains("%CREDITS%")) {
message = message.replaceAll("%CREDITS%", "" + amountToAdd);
}
player.sendMessage(new StringUtils().addColor(this.plugin.getMessage("Prefix") + message));
new DataManager(plugin).updateData(uuid, +amountToAdd, "Credits_Spent", "add");
new DataManager(plugin).updateData(uuid, -amountToAdd, "Credits", "remove");

ExperienceAPI.addLevel(player, skill, amountToAdd);
String message = this.plugin.getMessage("CreditAssignmentSuccess");
if (message.contains("%SKILL%")) {
message = message.replaceAll("%SKILL%", skill);
}
if (message.contains("%CREDITS%")) {
message = message.replaceAll("%CREDITS%", "" + amountToAdd);
}
player.sendMessage(new StringUtils().addColor(this.plugin.getMessage("Prefix") + message));
}
}
}
Expand Down
16 changes: 11 additions & 5 deletions src/main/java/net/naturva/morphie/mr/util/DataManager.java
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@
import net.naturva.morphie.mr.files.PlayerFileMethods;
import net.naturva.morphie.mr.util.Database.MySQLConnection;
import net.naturva.morphie.mr.util.Database.RedisConnection;
import net.naturva.morphie.mr.util.Database.SQLiteConnection;

public class DataManager {

Expand All @@ -16,20 +17,25 @@ public DataManager(MorphRedeem plugin) {
}

public String getData(UUID uuid, String name) {
if (this.plugin.getConfig().getString("StorageMethod").equals("MySQL")) {
if (this.plugin.getConfig().getString("StorageMethod").equalsIgnoreCase("MySQL")) {
return new MySQLConnection(this.plugin).getData(uuid, name);
} else if(this.plugin.getConfig().getString("StorageMethod").equals("Redis")){
} else if(this.plugin.getConfig().getString("StorageMethod").equalsIgnoreCase("Redis")){
return new RedisConnection(this.plugin).getData(uuid, name);
} else {
} else if(this.plugin.getConfig().getString("StorageMethod").equalsIgnoreCase("SQLite")){
return new SQLiteConnection(this.plugin).getData(uuid, name);
}
else {
return new PlayerFileMethods(plugin).getStat(uuid, name);
}
}

public void updateData(UUID uuid, int data, String name, String type) {
if (this.plugin.getConfig().getString("StorageMethod").equals("MySQL")) {
if (this.plugin.getConfig().getString("StorageMethod").equalsIgnoreCase("MySQL")) {
new MySQLConnection(this.plugin).updateData(uuid, data, name, type);
} else if(this.plugin.getConfig().getString("StorageMethod").equals("Redis")){
} else if(this.plugin.getConfig().getString("StorageMethod").equalsIgnoreCase("Redis")){
new RedisConnection(this.plugin).updateData(uuid, data, name, type);
} else if (this.plugin.getConfig().getString("StorageMethod").equalsIgnoreCase("SQLite")) {
new SQLiteConnection(this.plugin).updateData(uuid, data, name, type);
} else if (type == "add" || type == "remove"){
new PlayerFileMethods(plugin).updateCredits(uuid, name, data);
} else if (type == "set") {
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,155 @@
package net.naturva.morphie.mr.util.Database;

import java.io.File;
import java.io.FileFilter;
import java.io.IOException;
import java.sql.*;
import java.util.UUID;

import org.bukkit.entity.Player;

import net.naturva.morphie.mr.MorphRedeem;

public class SQLiteConnection {
private static MorphRedeem plugin;
private static String tablePrefix;
private static String databasePath;

public SQLiteConnection(MorphRedeem plugin) {
SQLiteConnection.plugin = plugin;
tablePrefix = SQLiteConnection.plugin.getConfig().getString("SQLite.TablePrefix", "mr_");
}

public void sqliteSetup() {
try {
synchronized (this) {
File dbFile = new File(plugin.getDataFolder(), "database.db");

// Create parent directories if they don't exist
if (!dbFile.getParentFile().exists()) {
dbFile.getParentFile().mkdirs();
}

// Create the database file if it doesn't exist
if (!dbFile.exists()) {
try {
dbFile.createNewFile();
} catch (IOException e) {
throw new SQLException("Could not create database file", e);
}
}

databasePath = dbFile.getPath();
}

} catch (SQLException e) {
e.printStackTrace();
}
}

public void checkStructure() {
try (Connection connection = DriverManager.getConnection("jdbc:sqlite:" + databasePath)) {
if (connection == null) {
return;
}

String sql = "CREATE TABLE IF NOT EXISTS " + this.tablePrefix + "creditdata ("
+ "uuid TEXT NULL DEFAULT NULL, "
+ "credits INTEGER NOT NULL DEFAULT 0, "
+ "credits_spent INTEGER NOT NULL DEFAULT 0, "
+ "UNIQUE(uuid)"
+ ");";

PreparedStatement statement = connection.prepareStatement(sql);

statement.executeUpdate();
statement.close();
} catch (SQLException e) {
e.printStackTrace();
}
}

public boolean playerExists(UUID uuid) {
String query = "SELECT 1 FROM `" + tablePrefix + "creditdata` WHERE uuid=?";

try (Connection connection = DriverManager.getConnection("jdbc:sqlite:" + databasePath);
PreparedStatement statement = connection.prepareStatement(query)) {

statement.setString(1, uuid.toString());

try (ResultSet results = statement.executeQuery()) {
return results.next();
}

} catch (SQLException e) {
e.printStackTrace();
}

return false;
}

public void createPlayer(final UUID uuid, Player player) {
String insertQuery = "INSERT INTO `" + tablePrefix + "creditdata` (uuid, credits, credits_spent) VALUES (?, ?, ?)";

// Use a try-with-resources block to manage connection and statement
try (Connection connection = DriverManager.getConnection("jdbc:sqlite:" + databasePath);
PreparedStatement insert = connection.prepareStatement(insertQuery)) {

if (!playerExists(uuid)) {
insert.setString(1, uuid.toString());
insert.setInt(2, 0); // Starting credits
insert.setInt(3, 0); // Starting credits spent
insert.executeUpdate();

}

} catch (SQLException e) {
e.printStackTrace();
}
}

public void updateData(UUID uuid, int num, String column, String type) {
String sql = "UPDATE `" + tablePrefix + "creditdata` SET " + column.toLowerCase() + "=? WHERE uuid=?";

try (Connection connection = DriverManager.getConnection("jdbc:sqlite:" + databasePath);
PreparedStatement statement = connection.prepareStatement(sql)) {

int data = Integer.parseInt(getData(uuid, column));

if (type.equalsIgnoreCase("set")) {
statement.setInt(1, num);
} else if (type.equalsIgnoreCase("add") || type.equalsIgnoreCase("remove")) {
statement.setInt(1, data + num);
}
statement.setString(2, uuid.toString());
statement.executeUpdate();

} catch (SQLException e) {
e.printStackTrace();
}
}

public String getData(UUID uuid, String data) {
String sql = "SELECT credits, credits_spent FROM `" + tablePrefix + "creditdata` WHERE uuid=?";

try (Connection connection = DriverManager.getConnection("jdbc:sqlite:" + databasePath);
PreparedStatement statement = connection.prepareStatement(sql)) {

statement.setString(1, uuid.toString());

try (ResultSet results = statement.executeQuery()){
if (results.next()) {
if (data.equals("Credits")) {
return String.valueOf(results.getInt("credits"));
} else if (data.equals("Credits_Spent")) {
return String.valueOf(results.getInt("credits_spent"));
}
}
}

} catch (SQLException e) {
e.printStackTrace();
}
return "0";
}
}
2 changes: 1 addition & 1 deletion src/main/resources/config.yml
Original file line number Diff line number Diff line change
Expand Up @@ -76,7 +76,7 @@ Settings:

#============================================================================================================================|

# Storage method, can be MySQL, Redis, or YML
# Storage method, can be MySQL, Redis, SQLite, or YML
StorageMethod: "YML"

# Requires 'StorageMethod' to be MySQL
Expand Down
2 changes: 1 addition & 1 deletion target/classes/config.yml
Original file line number Diff line number Diff line change
Expand Up @@ -76,7 +76,7 @@ Settings:

#============================================================================================================================|

# Storage method, can be MySQL, Redis, or YML
# Storage method, can be MySQL, Redis, SQLite, or YML
StorageMethod: "YML"

# Requires 'StorageMethod' to be MySQL
Expand Down