From 2da2d91a2330f1155a71285ecdd41dde8add3a92 Mon Sep 17 00:00:00 2001 From: Flibio Date: Sun, 12 Jul 2015 08:57:29 -0600 Subject: [PATCH] v0.0.4 - Alpha --- src/me/Flibio/EconomyLite/BalanceCommand.java | 2 +- .../EconomyLite/ConfigurationManager.java | 4 +- src/me/Flibio/EconomyLite/DataEditor.java | 154 +++++++------ src/me/Flibio/EconomyLite/Main.java | 93 +++++++- src/me/Flibio/EconomyLite/MySQL.java | 217 ++++++++++++++++++ src/me/Flibio/EconomyLite/PlayerJoin.java | 71 +++--- 6 files changed, 433 insertions(+), 108 deletions(-) create mode 100644 src/me/Flibio/EconomyLite/MySQL.java diff --git a/src/me/Flibio/EconomyLite/BalanceCommand.java b/src/me/Flibio/EconomyLite/BalanceCommand.java index 9cdae2d..1ef5cd2 100644 --- a/src/me/Flibio/EconomyLite/BalanceCommand.java +++ b/src/me/Flibio/EconomyLite/BalanceCommand.java @@ -53,7 +53,7 @@ public Text getUsage(CommandSource source) { public Optional process(CommandSource source, String arg_string) throws CommandException { if(!(source instanceof Player)){ - source.sendMessage(Texts.builder("Error: You must a player to use /balance").color(TextColors.RED).build()); + source.sendMessage(Texts.builder("Error: You must be a player to use /balance").color(TextColors.RED).build()); return Optional.of(CommandResult.builder().successCount(0).build()); } diff --git a/src/me/Flibio/EconomyLite/ConfigurationManager.java b/src/me/Flibio/EconomyLite/ConfigurationManager.java index 33044cf..447f500 100644 --- a/src/me/Flibio/EconomyLite/ConfigurationManager.java +++ b/src/me/Flibio/EconomyLite/ConfigurationManager.java @@ -19,7 +19,7 @@ public ConfigurationManager(Logger log){ } protected ConfigurationNode getFile(){ - ConfigurationLoader manager = HoconConfigurationLoader.builder().setFile(new File("EconomyLite/config.conf")).build(); + ConfigurationLoader manager = HoconConfigurationLoader.builder().setFile(new File("config/EconomyLite/config.conf")).build(); ConfigurationNode root; try { root = manager.load(); @@ -32,7 +32,7 @@ protected ConfigurationNode getFile(){ } protected void saveFile(ConfigurationNode root){ - ConfigurationLoader manager = HoconConfigurationLoader.builder().setFile(new File("EconomyLite/config.conf")).build(); + ConfigurationLoader manager = HoconConfigurationLoader.builder().setFile(new File("config/EconomyLite/config.conf")).build(); try { manager.save(root); diff --git a/src/me/Flibio/EconomyLite/DataEditor.java b/src/me/Flibio/EconomyLite/DataEditor.java index 5336a21..98217c2 100644 --- a/src/me/Flibio/EconomyLite/DataEditor.java +++ b/src/me/Flibio/EconomyLite/DataEditor.java @@ -14,96 +14,114 @@ public class DataEditor { private Logger logger; + private boolean mySQL; + private MySQL sql; public DataEditor(Logger log){ this.logger = log; + mySQL = Main.sqlEnabled(); } protected boolean setBalance(String name, int balance) { - ConfigurationLoader manager = HoconConfigurationLoader.builder().setFile(new File("EconomyLite/data.conf")).build(); - ConfigurationNode root; - try { - root = manager.load(); - } catch (IOException e) { - logger.error("Error loading data file!"); - logger.error(e.getMessage()); - return false; + if(mySQL){ + sql = Main.getSQL(); + return sql.setCurrency(name, balance); + } else { + ConfigurationLoader manager = HoconConfigurationLoader.builder().setFile(new File("config/EconomyLite/data.conf")).build(); + ConfigurationNode root; + try { + root = manager.load(); + } catch (IOException e) { + logger.error("Error loading data file!"); + logger.error(e.getMessage()); + return false; + } + + if(playerExists(name)){ + Map playerMap = root.getChildrenMap(); + for(Entry entry : playerMap.entrySet()){ + String uuid = (String) entry.getKey(); + if(root.getNode(uuid).getNode("name").getValue().equals(name)){ + root.getNode(uuid).getNode("balance").setValue(""+balance); + } + } + } else { + return false; + } + + try { + manager.save(root); + } catch (IOException e) { + logger.error("Error saving data file!"); + logger.error(e.getMessage()); + return false; + } + return true; } - - if(playerExists(name)){ + } + + protected boolean playerExists(String name) { + if(mySQL){ + sql = Main.getSQL(); + return sql.playerExists(name); + } else { + ConfigurationLoader manager = HoconConfigurationLoader.builder().setFile(new File("config/EconomyLite/data.conf")).build(); + ConfigurationNode root; + + try { + root = manager.load(); + } catch (IOException e) { + logger.error("Error loading data file!"); + logger.error(e.getMessage()); + return false; + } + + //Iterate and find the name Map playerMap = root.getChildrenMap(); + for(Entry entry : playerMap.entrySet()){ String uuid = (String) entry.getKey(); if(root.getNode(uuid).getNode("name").getValue().equals(name)){ - root.getNode(uuid).getNode("balance").setValue(""+balance); + return true; } } - } else { return false; } - - try { - manager.save(root); - } catch (IOException e) { - logger.error("Error saving data file!"); - logger.error(e.getMessage()); - return false; - } - return true; } - protected boolean playerExists(String name) { - ConfigurationLoader manager = HoconConfigurationLoader.builder().setFile(new File("EconomyLite/data.conf")).build(); - ConfigurationNode root; - - try { - root = manager.load(); - } catch (IOException e) { - logger.error("Error loading data file!"); - logger.error(e.getMessage()); - return false; - } - - //Iterate and find the name - Map playerMap = root.getChildrenMap(); - - for(Entry entry : playerMap.entrySet()){ - String uuid = (String) entry.getKey(); - if(root.getNode(uuid).getNode("name").getValue().equals(name)){ - return true; + protected int getBalance(String name) { + if(mySQL){ + sql = Main.getSQL(); + return sql.getCurrency(name); + } else { + ConfigurationLoader manager = HoconConfigurationLoader.builder().setFile(new File("config/EconomyLite/data.conf")).build(); + ConfigurationNode root; + + try { + root = manager.load(); + } catch (IOException e) { + logger.error("Error loading data file!"); + logger.error(e.getMessage()); + return 0; } - } - return false; - } - protected int getBalance(String name) { - ConfigurationLoader manager = HoconConfigurationLoader.builder().setFile(new File("EconomyLite/data.conf")).build(); - ConfigurationNode root; - - try { - root = manager.load(); - } catch (IOException e) { - logger.error("Error loading data file!"); - logger.error(e.getMessage()); - return 0; - } - - Map playerMap = root.getChildrenMap(); - - for(Entry entry : playerMap.entrySet()){ - String uuid = (String) entry.getKey(); - if(root.getNode(uuid).getNode("name").getValue().equals(name)){ - String amnt = root.getNode(uuid).getNode("balance").getString(); - try{ - return Integer.parseInt(amnt); - } catch(NumberFormatException e){ - logger.error("Invalid number read from data file!"); - logger.error(e.getMessage()); - return 0; + Map playerMap = root.getChildrenMap(); + + for(Entry entry : playerMap.entrySet()){ + String uuid = (String) entry.getKey(); + if(root.getNode(uuid).getNode("name").getValue().equals(name)){ + String amnt = root.getNode(uuid).getNode("balance").getString(); + try{ + return Integer.parseInt(amnt); + } catch(NumberFormatException e){ + logger.error("Invalid number read from data file!"); + logger.error(e.getMessage()); + return 0; + } } } + return 0; } - return 0; } protected boolean addCurrency(String name, int amount){ diff --git a/src/me/Flibio/EconomyLite/Main.java b/src/me/Flibio/EconomyLite/Main.java index 462b2e4..c986575 100644 --- a/src/me/Flibio/EconomyLite/Main.java +++ b/src/me/Flibio/EconomyLite/Main.java @@ -8,11 +8,14 @@ import org.slf4j.Logger; import org.spongepowered.api.event.Subscribe; import org.spongepowered.api.event.state.InitializationEvent; +import org.spongepowered.api.event.state.ServerStartedEvent; import org.spongepowered.api.plugin.Plugin; +import org.spongepowered.api.service.sql.SqlService; +import com.google.common.base.Optional; import com.google.inject.Inject; -@Plugin(id = "EconomyLite", name = "EconomyLite", version = "0.0.3") +@Plugin(id = "EconomyLite", name = "EconomyLite", version = "0.0.4") public class Main { @Inject @@ -20,10 +23,17 @@ public class Main { private static String currencyPlural = ""; private static String currencySingular = ""; + private static boolean sql = false; + private static String hostname = ""; + private static String port = ""; + private static String database = ""; + private static String username = ""; + private static String password = ""; + private static MySQL mySQL; @Subscribe - public void onServerStart(InitializationEvent event) { - logger.info("EconomyLite by Flibio enabling!"); + public void onServerInitialize(InitializationEvent event) { + logger.info("EconomyLite by Flibio initializing!"); createFiles(); configurationDefaults(); @@ -34,11 +44,27 @@ public void onServerStart(InitializationEvent event) { event.getGame().getCommandDispatcher().register(this, new EconCommand(logger), "econ"); event.getGame().getCommandDispatcher().register(this, new BalanceCommand(logger), "balance"); - } + Optional sqlServiceOptional = event.getGame().getServiceManager().provide(SqlService.class); + if(sql&&sqlServiceOptional.isPresent()){ + logger.info("MySQL Storage Enabled..."); + mySQL = new MySQL(hostname,port,database,username,password,logger,sqlServiceOptional.get()); + } + } + + @Subscribe + public void onServerStart(ServerStartedEvent event){ + logger.info("EconomyLite by Flibio enabled: "); + String type = "Local File"; + if(sql){ + type = "MySQL"; + } + logger.info("Storage type: "+type); + } + private void createFiles(){ //Create EconomyLite folder if doesn't exist - File folder = new File("EconomyLite"); + File folder = new File("config/EconomyLite"); try{ if(!folder.exists()){ logger.info("No EconomyLite folder found, attempting to create one"); @@ -50,13 +76,13 @@ private void createFiles(){ } } catch(Exception e){ - logger.warn("Error creating EconomyLite folder! DETAILED ERROR:"); + logger.warn("Error creating EconomyLite folder! Detailed Error:"); logger.warn(e.getMessage()); logger.warn("END EconomyLite Error"); } //EconomyLite File Generation - File data = new File("EconomyLite/data.conf"); + File data = new File("config/EconomyLite/data.conf"); if(!data.exists()){ logger.info("No existing data file was found, attempting to create a new one!"); try { @@ -68,7 +94,7 @@ private void createFiles(){ } } //Configuration file - File conf = new File("EconomyLite/config.conf"); + File conf = new File("config/EconomyLite/config.conf"); if(!conf.exists()){ logger.info("No existing configuration file was found, attempting to create a new one!"); try { @@ -91,12 +117,31 @@ private void configurationDefaults(){ if(root!=null){ if(!root.getChildrenMap().containsKey("Currency-Plural")){ root.getNode("Currency-Plural").setValue("Coins"); - manager.saveFile(root); } if(!root.getChildrenMap().containsKey("Currency-Singular")){ root.getNode("Currency-Singular").setValue("Coin"); - manager.saveFile(root); } + //check if MySQL Node exists + if(!root.getChildrenMap().containsKey("MySQL")){ + root.getNode("MySQL").getNode("enabled").setValue(false); + } + //Check all MySQL child nodes + if(!root.getNode("MySQL").getChildrenMap().containsKey("hostname")){ + root.getNode("MySQL").getNode("hostname").setValue("hostname"); + } + if(!root.getNode("MySQL").getChildrenMap().containsKey("port")){ + root.getNode("MySQL").getNode("port").setValue("3306"); + } + if(!root.getNode("MySQL").getChildrenMap().containsKey("database")){ + root.getNode("MySQL").getNode("database").setValue("database"); + } + if(!root.getNode("MySQL").getChildrenMap().containsKey("username")){ + root.getNode("MySQL").getNode("username").setValue("username"); + } + if(!root.getNode("MySQL").getChildrenMap().containsKey("password")){ + root.getNode("MySQL").getNode("password").setValue("password"); + } + manager.saveFile(root); } } @@ -113,6 +158,26 @@ private void loadOptions(){ if(root.getChildrenMap().containsKey("Currency-Singular")){ currencySingular = root.getNode("Currency-Singular").getString(); } + if(root.getChildrenMap().containsKey("MySQL")){ + if(root.getNode("MySQL").getChildrenMap().containsKey("enabled")){ + sql = root.getNode("MySQL").getNode("enabled").getBoolean(); + } + if(root.getNode("MySQL").getChildrenMap().containsKey("hostname")){ + hostname = root.getNode("MySQL").getNode("hostname").getString(); + } + if(root.getNode("MySQL").getChildrenMap().containsKey("port")){ + port = root.getNode("MySQL").getNode("port").getString(); + } + if(root.getNode("MySQL").getChildrenMap().containsKey("database")){ + database = root.getNode("MySQL").getNode("database").getString(); + } + if(root.getNode("MySQL").getChildrenMap().containsKey("username")){ + username = root.getNode("MySQL").getNode("username").getString(); + } + if(root.getNode("MySQL").getChildrenMap().containsKey("password")){ + password = root.getNode("MySQL").getNode("password").getString(); + } + } } } @@ -123,4 +188,12 @@ public static String getCurrencyPlural(){ public static String getCurrencySingular(){ return currencySingular; } + + public static boolean sqlEnabled(){ + return sql; + } + + public static MySQL getSQL(){ + return mySQL; + } } \ No newline at end of file diff --git a/src/me/Flibio/EconomyLite/MySQL.java b/src/me/Flibio/EconomyLite/MySQL.java new file mode 100644 index 0000000..077eb62 --- /dev/null +++ b/src/me/Flibio/EconomyLite/MySQL.java @@ -0,0 +1,217 @@ +package me.Flibio.EconomyLite; + +import java.sql.Connection; +import java.sql.PreparedStatement; +import java.sql.ResultSet; +import java.sql.SQLException; +import java.sql.Statement; +import java.util.UUID; + +import javax.sql.DataSource; + +import org.slf4j.Logger; +import org.spongepowered.api.service.sql.SqlService; + +public class MySQL { + private final String user; + private final String database; + private final String password; + private final String port; + private final String hostname; + private final Logger logger; + private Connection c; + private Statement s; + private SqlService sql; + + + /** + * Creates a new MySQL instance + * + * @param plugin + * Plugin instance + * @param hostname + * Name of the host + * @param port + * Port number + * @param database + * Database name + * @param username + * Username + * @param password + * Password + */ + public MySQL(String hostname, String port, String database, + String username, String password, Logger logger, SqlService sql) { + this.hostname = hostname; + this.port = port; + this.database = database; + this.user = username; + this.password = password; + this.logger = logger; + this.sql = sql; + + c = openConnection(); + + createStatement(); + if(s!=null){ + try { + PreparedStatement ps = c.prepareStatement("CREATE TABLE IF NOT EXISTS EconomyLite(uuid VARCHAR(100), name VARCHAR(100) ,currency INT(100))"); + ps.executeUpdate(); + } catch (SQLException e) { + logger.error("Error creating EconomyLite database..."); + e.printStackTrace(); + } + } + closeConnection(); + } + + protected Connection openConnection() { + try { + DataSource source = sql.getDataSource("jdbc:mysql://"+hostname+":"+port+"/"+database+"?user="+user+"&password="+password); + return source.getConnection(); + } catch (SQLException e) { + logger.error("Error opening MySQL connection..."); + logger.error("Invalid credentials, hostname, database?"); + return null; + } + } + + protected void closeConnection(){ + try { + c.close(); + } catch (SQLException e) { + logger.error("Error closing MySQL connection..."); + e.printStackTrace(); + } + } + + protected void createStatement() { + if(c == null) return; + try { + s = c.createStatement(); + } catch (SQLException e) { + logger.error("Error creating MySQL statement..."); + e.printStackTrace(); + } + } + + protected void reconnect() { + closeConnection(); + c = openConnection(); + createStatement(); + } + + protected boolean playerExists(String name){ + reconnect(); + ResultSet res; + try { + PreparedStatement ps = c.prepareStatement("SELECT name FROM EconomyLite WHERE name = ?"); + ps.setString(1, name); + res = ps.executeQuery(); + if(!(res.next())) { + closeConnection(); + return false; + } else { + closeConnection(); + return true; + } + } catch (SQLException e) { + logger.error("Error checking if player exists..."); + e.printStackTrace(); + closeConnection(); + return false; + } + } + + protected boolean playerExists(UUID uuid){ + reconnect(); + ResultSet res; + try { + PreparedStatement ps = c.prepareStatement("SELECT uuid FROM EconomyLite WHERE uuid = ?"); + ps.setString(1, uuid.toString()); + res = ps.executeQuery(); + if(!(res.next())) { + closeConnection(); + return false; + } else { + closeConnection(); + return true; + } + } catch (SQLException e) { + logger.error("Error checking if player exists..."); + e.printStackTrace(); + closeConnection(); + return false; + } + } + + protected int getCurrency(String name) { + reconnect(); + int amount; + ResultSet res; + try { + PreparedStatement ps = c.prepareStatement("SELECT currency FROM EconomyLite WHERE name = ?"); + ps.setString(1, name); + res = ps.executeQuery(); + res.next(); + amount = res.getInt("currency"); + } catch (SQLException e) { + logger.error("Error getting currency of player..."); + e.printStackTrace(); + amount = 0; + } + closeConnection(); + return amount; + } + + protected boolean setCurrency(String name, int amount) { + reconnect(); + try { + PreparedStatement ps = c.prepareStatement("UPDATE EconomyLite SET currency = ? WHERE name = ?"); + ps.setString(1, Integer.toString(amount)); + ps.setString(2, name); + ps.executeUpdate(); + } catch (SQLException e) { + logger.error("Error setting currency of player..."); + e.printStackTrace(); + closeConnection(); + return false; + } + closeConnection(); + return true; + } + + protected boolean addPlayer(String uuid, String name) { + reconnect(); + try { + PreparedStatement ps = c.prepareStatement("INSERT INTO EconomyLite (`uuid`, `name`, `currency`) VALUES (?, ?, '0');"); + ps.setString(1, uuid); + ps.setString(2, name); + ps.executeUpdate(); + } catch (SQLException e) { + logger.error("Error setting currency of player..."); + e.printStackTrace(); + closeConnection(); + return false; + } + closeConnection(); + return true; + } + + protected boolean updateName(String uuid, String name){ + reconnect(); + try { + PreparedStatement ps = c.prepareStatement("UPDATE EconomyLite SET name = ? WHERE uuid = ?"); + ps.setString(1, name); + ps.setString(2, uuid); + ps.executeUpdate(); + } catch (SQLException e) { + logger.error("Error updating name of player..."); + e.printStackTrace(); + closeConnection(); + return false; + } + closeConnection(); + return true; + } +} \ No newline at end of file diff --git a/src/me/Flibio/EconomyLite/PlayerJoin.java b/src/me/Flibio/EconomyLite/PlayerJoin.java index cbea62f..2d717a3 100644 --- a/src/me/Flibio/EconomyLite/PlayerJoin.java +++ b/src/me/Flibio/EconomyLite/PlayerJoin.java @@ -2,6 +2,7 @@ import java.io.File; import java.io.IOException; +import java.util.UUID; import ninja.leaping.configurate.ConfigurationNode; import ninja.leaping.configurate.hocon.HoconConfigurationLoader; @@ -14,10 +15,13 @@ public class PlayerJoin { - Logger logger; + private Logger logger; + private boolean mySQL; + private MySQL sql; public PlayerJoin(Logger logger){ this.logger = logger; + mySQL = Main.sqlEnabled(); } @Subscribe @@ -25,34 +29,47 @@ public void onPlayerJoin(PlayerJoinEvent event) { Player player = event.getUser(); String uuid = player.getUniqueId().toString(); + UUID UUID = player.getUniqueId(); - ConfigurationLoader manager = HoconConfigurationLoader.builder().setFile(new File("EconomyLite/data.conf")).build(); - - ConfigurationNode root; - - try { - root = manager.load(); - } catch (IOException e) { - logger.error("Error loading data file!"); - logger.error(e.getMessage()); - return; - } - - //If UUID doesn't exist add it - if(!root.getChildrenMap().containsKey(uuid)){ - root.getNode(uuid).getNode("name").setValue(player.getName()); - root.getNode(uuid).getNode("balance").setValue(0); + if(mySQL){ + sql = Main.getSQL(); + sql.reconnect(); + + if(!sql.playerExists(UUID)){ + sql.addPlayer(uuid, player.getName()); + } else { + sql.updateName(uuid, player.getName()); + } + } else { - //UUID Exists set the name in case of name change - root.getNode(uuid).getNode("name").setValue(player.getName()); - } - - try { - manager.save(root); - } catch (IOException e) { - logger.error("Error loading data file!"); - logger.error(e.getMessage()); - return; + ConfigurationLoader manager = HoconConfigurationLoader.builder().setFile(new File("config/EconomyLite/data.conf")).build(); + + ConfigurationNode root; + + try { + root = manager.load(); + } catch (IOException e) { + logger.error("Error loading data file!"); + logger.error(e.getMessage()); + return; + } + + //If UUID doesn't exist add it + if(!root.getChildrenMap().containsKey(uuid)){ + root.getNode(uuid).getNode("name").setValue(player.getName()); + root.getNode(uuid).getNode("balance").setValue(0); + } else { + //UUID Exists set the name in case of name change + root.getNode(uuid).getNode("name").setValue(player.getName()); + } + + try { + manager.save(root); + } catch (IOException e) { + logger.error("Error loading data file!"); + logger.error(e.getMessage()); + return; + } } } }