Started SQLite work

This commit is contained in:
[email protected] authored and William278 committed 2020-12-07 22:56:33 +00:00
1 parent d3a787be67
commit 559e38fc4b
21 files changed
+788 -65

No files matched your search

@@ -0,0 +1,146 @@
package me.william278.huskhomes2.Data.SQLite;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.logging.Level;
import me.william278.huskhomes2.Main;
import me.william278.huskhomes2.Data.SQLite.Errors.Error;
import me.william278.huskhomes2.Data.SQLite.Errors.Errors;
import org.bukkit.entity.Player;
public abstract class Database {
Main plugin;
Connection connection;
// The name of the table we created back in SQLite class.
public String table = "table_name";
public int tokens = 0;
public Database(Main instance){
plugin = instance;
}
public abstract Connection getSQLConnection();
public abstract void load();
public void initialize(){
connection = getSQLConnection();
try{
PreparedStatement ps = connection.prepareStatement("SELECT * FROM " + table + " WHERE player = ?");
ResultSet rs = ps.executeQuery();
close(ps,rs);
} catch (SQLException ex) {
plugin.getLogger().log(Level.SEVERE, "Unable to retreive connection", ex);
}
}
// These are the methods you can use to get things out of your database. You of course can make new ones to return different things in the database.
// This returns the number of people the player killed.
public Integer getTokens(String string) {
Connection conn = null;
PreparedStatement ps = null;
ResultSet rs = null;
try {
conn = getSQLConnection();
ps = conn.prepareStatement("SELECT * FROM " + table + " WHERE player = '"+string+"';");
rs = ps.executeQuery();
while(rs.next()){
if(rs.getString("player").equalsIgnoreCase(string.toLowerCase())){ // Tell database to search for the player you sent into the method. e.g getTokens(sam) It will look for sam.
return rs.getInt("kills"); // Return the players ammount of kills. If you wanted to get total (just a random number for an example for you guys) You would change this to total!
}
}
} catch (SQLException ex) {
plugin.getLogger().log(Level.SEVERE, Errors.sqlConnectionExecute(), ex);
} finally {
try {
if (ps != null)
ps.close();
if (conn != null)
conn.close();
} catch (SQLException ex) {
plugin.getLogger().log(Level.SEVERE, Errors.sqlConnectionClose(), ex);
}
}
return 0;
}
// Exact same method here, Except as mentioned above i am looking for total!
public Integer getTotal(String string) {
Connection conn = null;
PreparedStatement ps = null;
ResultSet rs = null;
try {
conn = getSQLConnection();
ps = conn.prepareStatement("SELECT * FROM " + table + " WHERE player = '"+string+"';");
rs = ps.executeQuery();
while(rs.next()){
if(rs.getString("player").equalsIgnoreCase(string.toLowerCase())){
return rs.getInt("total");
}
}
} catch (SQLException ex) {
plugin.getLogger().log(Level.SEVERE, Errors.sqlConnectionExecute(), ex);
} finally {
try {
if (ps != null)
ps.close();
if (conn != null)
conn.close();
} catch (SQLException ex) {
plugin.getLogger().log(Level.SEVERE, Errors.sqlConnectionClose(), ex);
}
}
return 0;
}
// Now we need methods to save things to the database
public void setTokens(Player player, Integer tokens, Integer total) {
Connection conn = null;
PreparedStatement ps = null;
try {
conn = getSQLConnection();
ps = conn.prepareStatement("REPLACE INTO " + table + " (player,kills,total) VALUES(?,?,?)"); // IMPORTANT. In SQLite class, We made 3 colums. player, Kills, Total.
ps.setString(1, player.getName().toLowerCase()); // YOU MUST put these into this line!! And depending on how many
// colums you put (say you made 5) All 5 need to be in the brackets
// Seperated with comma's (,) AND there needs to be the same amount of
// question marks in the VALUES brackets. Right now i only have 3 colums
// So VALUES (?,?,?) If you had 5 colums VALUES(?,?,?,?,?)
ps.setInt(2, tokens); // This sets the value in the database. The colums go in order. Player is ID 1, kills is ID 2, Total would be 3 and so on. you can use
// setInt, setString and so on. tokens and total are just variables sent in, You can manually send values in as well. p.setInt(2, 10) <-
// This would set the players kills instantly to 10. Sorry about the variable names, It sets their kills to 10 i just have the variable called
// Tokens from another plugin :/
ps.setInt(3, total);
ps.executeUpdate();
return;
} catch (SQLException ex) {
plugin.getLogger().log(Level.SEVERE, Errors.sqlConnectionExecute(), ex);
} finally {
try {
if (ps != null)
ps.close();
if (conn != null)
conn.close();
} catch (SQLException ex) {
plugin.getLogger().log(Level.SEVERE, Errors.sqlConnectionClose(), ex);
}
}
return;
}
public void close(PreparedStatement ps,ResultSet rs){
try {
if (ps != null)
ps.close();
if (rs != null)
rs.close();
} catch (SQLException ex) {
Error.close(plugin, ex);
}
}
}
@@ -0,0 +1,15 @@
package me.william278.huskhomes2.Data.SQLite.Errors;
import me.william278.huskhomes2.Main;
import java.util.logging.Level;
public class Error {
public static void execute(Main plugin, Exception ex){
plugin.getLogger().log(Level.SEVERE, "Couldn't execute MySQL statement: ", ex);
}
public static void close(Main plugin, Exception ex){
plugin.getLogger().log(Level.SEVERE, "Failed to close MySQL connection: ", ex);
}
}
@@ -0,0 +1,16 @@
package me.william278.huskhomes2.Data.SQLite.Errors;
public class Errors {
public static String sqlConnectionExecute(){
return "Couldn't execute MySQL statement: ";
}
public static String sqlConnectionClose(){
return "Failed to close MySQL connection: ";
}
public static String noSQLConnection(){
return "Unable to retreive MYSQL connection: ";
}
public static String noTableFound(){
return "Database Error: No Table Found";
}
}
@@ -0,0 +1,102 @@
package me.william278.huskhomes2.Data.SQLite;
import me.william278.huskhomes2.Main;
import java.io.File;
import java.io.IOException;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.logging.Level;
public class SQLite extends Database {
final String databaseName = "HuskHomesData";
public SQLite(Main instance) {
super(instance);
}
public String createPlayerTable = "CREATE TABLE IF NOT EXISTS " + Main.settings.getPlayerTable() + " (" +
"`player_id` integer PRIMARY KEY," +
"`uuid` text NOT NULL UNIQUE," +
"`username` text NOT NULL," +
"`home_count` integer NOT NULL," +
"`home_slots` integer NOT NULL," +
"`rtp_cooldown` integer NOT NULL," +
"`home_count` integer NOT NULL" +
");";
public String createLocationsTable = "CREATE TABLE IF NOT EXISTS " + Main.settings.getLocationsTable() + " (" +
"`location_id` integer PRIMARY KEY," +
"`world` text NOT NULL," +
"`server` text NOT NULL," +
"`x` double NOT NULL," +
"`y` double NOT NULL," +
"`z` double NOT NULL," +
"`yaw` float NOT NULL," +
"`pitch` float NOT NULL" +
");";
public String createHomesTable = "CREATE TABLE IF NOT EXISTS " + Main.settings.getHomesTable() + " (" +
"`player_id` integer NOT NULL," +
"`location_id` integer NOT NULL," +
"`name` text NOT NULL," +
"`description` double NOT NULL," +
"`public` boolean NOT NULL," +
"PRIMARY KEY (`player_id`, `location_id`)," +
"FOREIGN KEY (`player_id`) REFERENCES " + Main.settings.getPlayerTable() + " (`player_id`) ON DELETE CASCADE ON UPDATE NO ACTION," +
"FOREIGN KEY (`location_id`) REFERENCES " + Main.settings.getLocationsTable() + " (`location_id`) ON DELETE CASCADE ON UPDATE NO ACTION," +
");";
public String createWarpsTable = "CREATE TABLE IF NOT EXISTS " + Main.settings.getWarpsTable() + " (" +
"`location_id` integer NOT NULL," +
"`name` text NOT NULL," +
"`description` double NOT NULL," +
"PRIMARY KEY (`location_id`)," +
"FOREIGN KEY (`location_id`) REFERENCES " + Main.settings.getLocationsTable() + " (`location_id`) ON DELETE CASCADE ON UPDATE NO ACTION," +
");";
// SQL creation stuff, You can leave the blow stuff untouched.
public Connection getSQLConnection() {
File dataFolder = new File(plugin.getDataFolder(), databaseName + ".db");
if (!dataFolder.exists()) {
try {
dataFolder.createNewFile();
} catch (IOException e) {
plugin.getLogger().log(Level.SEVERE, "File write error: " + databaseName + ".db");
}
}
try {
if (connection != null && !connection.isClosed()) {
return connection;
}
Class.forName("org.sqlite.JDBC");
connection = DriverManager.getConnection("jdbc:sqlite:" + dataFolder);
return connection;
} catch (SQLException ex) {
plugin.getLogger().log(Level.SEVERE, "An exception occurred initialising the SQLite database", ex);
} catch (ClassNotFoundException ex) {
plugin.getLogger().log(Level.SEVERE, "You need the SQLite JBDC library; please download and place this in the /lib folder.");
}
return null;
}
public void load() {
connection = getSQLConnection();
try {
Statement s = connection.createStatement();
s.executeUpdate(createPlayerTable);
s.executeUpdate(createLocationsTable);
s.executeUpdate(createHomesTable);
s.executeUpdate(createWarpsTable);
s.close();
} catch (SQLException e) {
e.printStackTrace();
}
initialize();
}
}
@@ -1,19 +1,37 @@
package me.william278.huskhomes2;
import me.william278.huskhomes2.Objects.Settings;
import org.bukkit.plugin.java.JavaPlugin;
public final class Main extends JavaPlugin {
public static final String server = "server";
private static Main instance;
public static Main getInstance() {
return instance;
}
private void setInstance(Main instance) {
Main.instance = instance;
}
public static Settings settings;
@Override
public void onEnable() {
// Plugin startup logic
getLogger().info("Enabling HuskHomes version " + this.getDescription().getVersion());
// Set instance for easy cross-class referencing
setInstance(this);
// Load the config
configManager.loadConfig();
// Set up data storage
dataManager.setupStorage(settings.getStorageType());
}
@Override
public void onDisable() {
// Plugin shutdown logic
getLogger().info("Disabled HuskHomes version " + this.getDescription().getVersion());
}
}
@@ -58,6 +58,10 @@ public class Home extends TeleportationPoint {
return name;
}
public String getDescription() {
return description;
}
public void setName(String name) {
this.name = name;
}
@@ -0,0 +1,72 @@
package me.william278.huskhomes2.Objects;
import org.bukkit.configuration.file.FileConfiguration;
public class Settings {
String language;
String server;
String storageType;
String playerTable;
String locationsTable;
String homesTable;
String warpsTable;
boolean doBungee;
private void setSettings(FileConfiguration configFile) {
this.language = configFile.getString("language");
this.doBungee = configFile.getBoolean("bungee_options.enable_bungee_mode");
this.server = configFile.getString("bungee_options.server_id");
this.storageType = configFile.getString("data_storage_option.storage_type");
this.playerTable = configFile.getString("data_storage_options.table_names.player_data");
this.locationsTable = configFile.getString("data_storage_options.table_names.location_data");
this.homesTable = configFile.getString("data_storage_options.table_names.home_data");
this.warpsTable = configFile.getString("data_storage_options.table_names.warp_data");
}
public Settings(FileConfiguration configFile) {
setSettings(configFile);
}
public void reloadSettings(FileConfiguration configFile) {
setSettings(configFile);
}
public String getStorageType() {
return storageType;
}
public String getLanguage() {
return language;
}
public String getServerID() {
return server;
}
public boolean doBungee() {
return doBungee;
}
public String getPlayerTable() {
return playerTable;
}
public String getLocationsTable() {
return locationsTable;
}
public String getHomesTable() {
return homesTable;
}
public String getWarpsTable() {
return warpsTable;
}
}
@@ -58,4 +58,27 @@ public class TeleportationPoint {
}
}
public String getWorldName() {
return worldName;
}
public double getX() {
return x;
}
public double getY() {
return y;
}
public double getZ() {
return z;
}
public float getYaw() {
return yaw;
}
public float getPitch() {
return pitch;
}
}
@@ -0,0 +1,32 @@
package me.william278.huskhomes2.Objects;
import org.bukkit.Location;
public class Warp extends TeleportationPoint {
String name;
String description;
public Warp(Location location, String server, String name) {
super(location, server);
this.name = name;
this.description = "A publicly accessible warp";
}
public String getDescription() {
return description;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public void setDescription(String description) {
this.name = description;
}
}
@@ -0,0 +1,25 @@
package me.william278.huskhomes2;
import me.william278.huskhomes2.Objects.Settings;
public class configManager {
private static final Main plugin = Main.getInstance();
// (Re-)Load the config file
public static void loadConfig() {
plugin.getConfig().options().header(
" ------------------------------ \n" +
"| HuskHomes Config |\n" +
"| Developed by William278 |\n" +
" ------------------------------ \n" +
"Configuration guide: https://github.com/WiIIiam278/HuskHomesDocs/wiki/Config-File/ \n" +
"To quickly setup the plugin:\n" +
"1. Fill in the details of your mySQL Database below\n" +
"2. (Optional) Change the appropriate details in the configuration\n" +
"3. Restart the server");
plugin.getConfig().options().copyHeader(true).copyDefaults(true);
plugin.saveConfig();
Main.settings = new Settings(plugin.getConfig());
}
}
@@ -0,0 +1,32 @@
package me.william278.huskhomes2;
import me.william278.huskhomes2.Data.SQLite.Database;
import me.william278.huskhomes2.Data.SQLite.SQLite;
import org.bukkit.Bukkit;
// This class handles the saving of data; whether that be through SQLite or SQL
public class dataManager {
private static Database sqliteDatabase;
private static void initializeSQLite() {
sqliteDatabase = new SQLite(Main.getInstance());
sqliteDatabase.load();
}
private static void initializeMySQL() {
}
public static void setupStorage(String storageType) {
if (storageType.toLowerCase().equals("sqlite")) {
initializeSQLite();
} else if (storageType.toLowerCase().equals("mysql")) {
initializeMySQL();
} else {
Bukkit.getLogger().warning("Invalid storage method set in config.yml; defaulting to SQLite");
initializeSQLite();
}
}
}
@@ -1,59 +0,0 @@
package me.william278.huskhomes2;
import net.md_5.bungee.api.chat.TextComponent;
import org.bukkit.entity.Player;
import java.awt.*;
import java.util.HashMap;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import static net.md_5.bungee.api.ChatColor.COLOR_CHAR;
public class messageHandler {
private static HashMap<String, String> messages = new HashMap<>();
private static String translateHexColorCodes(String message)
{
final Pattern hexPattern = Pattern.compile("&#([A-Fa-f0-9]{6})");
Matcher matcher = hexPattern.matcher(message);
StringBuffer buffer = new StringBuffer(message.length() + 4 * 8);
while (matcher.find())
{
String group = matcher.group(1);
matcher.appendReplacement(buffer, COLOR_CHAR + "x"
+ COLOR_CHAR + group.charAt(0) + COLOR_CHAR + group.charAt(1)
+ COLOR_CHAR + group.charAt(2) + COLOR_CHAR + group.charAt(3)
+ COLOR_CHAR + group.charAt(4) + COLOR_CHAR + group.charAt(5)
);
}
return matcher.appendTail(buffer).toString();
}
// Send a blank message
public static void sendMessage(Player p, String messageID, String... placeholderReplacements) {
String message = messages.get(messageID);
int replacementIndexer = 1;
// Replace placeholders
for (String replacement : placeholderReplacements) {
String replacementString = "%" + replacementIndexer + "%";
message = message.replace(replacementString, replacement);
replacementIndexer = replacementIndexer + 1;
}
// Convert to text component and send
p.spigot().sendMessage(TextComponent.fromLegacyText(translateHexColorCodes(message)));
}
// Send a message with no placeholder parameters
public static void sendMessage(Player p, String messageID) {
String message = messages.get(messageID);
// Convert to text component and send
p.spigot().sendMessage(TextComponent.fromLegacyText(translateHexColorCodes(message)));
}
}
@@ -0,0 +1,138 @@
package me.william278.huskhomes2;
import net.md_5.bungee.api.chat.TextComponent;
import org.apache.commons.lang.StringEscapeUtils;
import org.bukkit.Bukkit;
import org.bukkit.configuration.file.FileConfiguration;
import org.bukkit.configuration.file.YamlConfiguration;
import org.bukkit.entity.Player;
import java.awt.*;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.nio.charset.Charset;
import java.nio.charset.StandardCharsets;
import java.util.HashMap;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import static net.md_5.bungee.api.ChatColor.COLOR_CHAR;
import static org.bukkit.configuration.file.YamlConfiguration.loadConfiguration;
public class messageManager {
private static final int languageFileVersion = 1;
private static HashMap<String, String> messages = new HashMap<>();
private static final Main plugin = Main.getInstance();
// Delete the file at the pointer specified
private static void deleteFile(File f) {
try {
if (!f.delete()) {
Bukkit.getLogger().severe("Failed to delete messages.yml file!");
}
} catch (Exception e) {
Bukkit.getLogger().severe("An error occurred while deleting the messages.yml file!");
e.printStackTrace();
}
}
// Create a new file, at the pointer specified
private static void createFile(File f) {
try {
if (!f.createNewFile()) {
Bukkit.getLogger().severe("Failed to create messages.yml file!");
}
} catch (IOException e) {
Bukkit.getLogger().severe("An error occurred while creating the messages.yml file!");
e.printStackTrace();
}
}
// Save the config file specified to the file at the pointer specified
private static void saveFile(FileConfiguration config, File f) {
try {
config.save(f);
} catch (IOException e) {
Bukkit.getLogger().severe("An error occurred while saving the messages.yml file!");
}
}
// (Re-)Load the messages file with the correct language
public static void loadMessages(String language) {
File f = new File(plugin.getDataFolder() + File.separator + "messages_" + language + ".yml");
if (!f.exists()) {
createFile(f);
}
FileConfiguration config = loadConfiguration(f);
config.options().header(
" ------------------------------ \n" +
"| HuskHomes Messages |\n" +
"| Developed by William278 |\n" +
" ------------------------------ \n" +
"If you'd like to use a different language, you can change it in the config.yml \n" +
"Change the appearance/text of messages in the plugin using this config: \n" +
"1. Use the selection symbol (§) followed by a Minecraft color code to add color to the messages.\n" +
"2. Use an ampersand symbol and hashtag (&#) followed by a 6 digit hex code to add custom colors.\n" +
"3. Example 1: \"§cHello!\" will display \"Hello!\" in light red.\n" +
"4. Example 2: \"&#32CD32Hello\" will display \"Hello!\" in a bright green color (hex: #32CD32)");
InputStream defaultMessageFile = plugin.getResource("Languages/" + language);
if (defaultMessageFile != null) {
YamlConfiguration yamlConfiguration = YamlConfiguration.loadConfiguration(new InputStreamReader(defaultMessageFile, StandardCharsets.UTF_8));
config.setDefaults(yamlConfiguration);
config.options().copyHeader(true).copyDefaults(true);
}
saveFile(config, f);
messages.clear();
for (String message : config.getConfigurationSection("").getKeys(false)) {
messages.put(message, StringEscapeUtils.unescapeJava(config.getString(message)));
}
}
// Translate hexadecimal custom color codes
private static String translateHexColorCodes(String message) {
final Pattern hexPattern = Pattern.compile("&#([A-Fa-f0-9]{6})");
Matcher matcher = hexPattern.matcher(message);
StringBuffer buffer = new StringBuffer(message.length() + 4 * 8);
while (matcher.find()) {
String group = matcher.group(1);
matcher.appendReplacement(buffer, COLOR_CHAR + "x"
+ COLOR_CHAR + group.charAt(0) + COLOR_CHAR + group.charAt(1)
+ COLOR_CHAR + group.charAt(2) + COLOR_CHAR + group.charAt(3)
+ COLOR_CHAR + group.charAt(4) + COLOR_CHAR + group.charAt(5)
);
}
return matcher.appendTail(buffer).toString();
}
// Send a message with multiple placeholders
public static void sendMessage(Player p, String messageID, String... placeholderReplacements) {
String message = messages.get(messageID);
int replacementIndexer = 1;
// Replace placeholders
for (String replacement : placeholderReplacements) {
String replacementString = "%" + replacementIndexer + "%";
message = message.replace(replacementString, replacement);
replacementIndexer = replacementIndexer + 1;
}
// Convert to text component and send
p.spigot().sendMessage(TextComponent.fromLegacyText(translateHexColorCodes(message)));
}
// Send a message with no placeholder parameters
public static void sendMessage(Player p, String messageID) {
String message = messages.get(messageID);
// Convert to text component and send
p.spigot().sendMessage(TextComponent.fromLegacyText(translateHexColorCodes(message)));
}
}
@@ -0,0 +1,5 @@
package me.william278.huskhomes2;
public class pluginMessageHandler {
}
@@ -0,0 +1,13 @@
package me.william278.huskhomes2;
import org.bukkit.Location;
// This class handles setting homes, warps and the spawn location.
public class settingHandler {
// Set a home at the specified position
public static void setHome(Location location) {
}
}
@@ -6,9 +6,9 @@ import org.bukkit.entity.Player;
public class teleportManager {
private static void teleportPlayer(Player p, TeleportationPoint teleportationPoint) {
if (teleportationPoint.getServer().equals(Main.server)) {
if (teleportationPoint.getServer().equals(Main.settings.getServerID())) {
p.teleport(teleportationPoint.getLocation());
messageHandler.sendMessage(p, "teleport_success");
messageManager.sendMessage(p, "teleport_success");
}
}