Merge pull request #2 from odinfather/master

Change Database Connections
This commit is contained in:
Malcom Green 2017-09-26 16:28:41 -04:00 committed by GitHub
commit 7bdb704523
22 changed files with 968 additions and 665 deletions

5
.gitignore vendored
View File

@ -116,3 +116,8 @@ gradle-app.setting
# gradle/wrapper/gradle-wrapper.properties
# End of https://www.gitignore.io/api/gradle,intellij,intellij+iml
.idea/compiler.xml
.idea/inspectionProfiles/Project_Default.xml
.idea/vcs.xml
build.gradle
build.gradle

View File

@ -31,6 +31,11 @@ dependencies {
compile 'org.twitter4j:twitter4j-stream:4.0.6'
compile 'org.projectlombok:lombok:1.16.18'
compile 'ca.pjer:chatter-bot-api:1.4.7'
compile group: 'com.zaxxer', name: 'HikariCP-java6', version: '2.0.1'
}
compileJava.options.encoding = 'UTF-8'
compileJava.options.fork = true
// Change this if you are getting errors building
compileJava.options.forkOptions.executable = 'C:\\Program Files\\Java\\jdk1.8.0_131\\bin\\javac.exe'

View File

@ -0,0 +1,324 @@
package me.majrly.database;
import com.zaxxer.hikari.HikariConfig;
import com.zaxxer.hikari.HikariDataSource;
import me.majrly.database.params.Parameter;
import me.majrly.database.statements.Query;
import me.majrly.database.statements.Statement;
import java.sql.*;
import java.util.Map;
import java.util.Optional;
/**
* Database API
*
* @author Majrly
* @since 1.0.0
*/
public class Database {
// Variables
private String name;
private String hostname;
private String username;
private String password;
private String database;
private int port = 3306;
private int timeout = 60 * 1000;
private HikariDataSource source;
private HikariConfig config = new HikariConfig();
/**
* Database API
*
* @param name The name of this database instance
* @param hostname The ip to use when connecting
* @param username The username to authenticate as
* @param password The password to authenticate yourself
* @param database The name of the database to switch to
* @param port The port to use when connecting
* @since 1.0.0
*/
public Database(String name, String hostname, String username, String password, String database, int port, HikariConfig config) {
this.config = config;
this.config.setJdbcUrl("jdbc:" + (this.name = name) + "://" + (this.hostname = hostname) + ":" + (this.port = port) + "/" + (this.database = database));
this.config.setDriverClassName("com.mysql.jdbc.Driver");
this.config.setUsername(this.username = username);
this.config.setPassword(this.password = password);
this.source = new HikariDataSource(config);
}
/**
* Get the database options class
*
* @return A reference to {@link DatabaseOptions}
* @since 1.0.0
*/
public static DatabaseOptions options() {
return new DatabaseOptions();
}
/**
* Connects to the database
*
* @return Whether it connected or not
* @since 1.0.0
*/
public void init() {
}
/**
* Sends a query to the database
*
* @param statement The statement to send the database
* @return Either the int of an update, or the ResultSet of a query
* @since 1.0.0
*/
public Optional<?> send(Statement statement) {
Optional<PreparedStatement> optional = prepare(statement);
if (!optional.isPresent()) return Optional.empty();
PreparedStatement preparedStatement = optional.get();
try {
if (statement instanceof Query) {
return Optional.of(preparedStatement.executeQuery());
} else {
return Optional.of(preparedStatement.executeUpdate());
}
} catch (SQLException exception) {
exception.printStackTrace();
return Optional.empty();
}
}
/**
* Close a prepared statement
*
* @param preparedStatement The prepared statement you wish to close
* @since 1.0.0
*/
public void closeStatement(PreparedStatement preparedStatement) {
try {
if (preparedStatement != null && !preparedStatement.isClosed()) {
preparedStatement.close();
}
} catch (SQLException e) {
// Can't handle closing statement
e.printStackTrace();
}
}
/**
* Prepare a statement
*
* @param statement The statement with parameters you wish to prepare
* @return The optional value of {@link PreparedStatement}
* @since 1.0.0
*/
public Optional<PreparedStatement> prepare(Statement statement) {
try {
PreparedStatement preparedStatement = source.getConnection().prepareStatement(statement.getSQL());
for (Map.Entry<Integer, Parameter> parameter : statement.getParameters().entrySet()) {
switch (parameter.getValue().getType()) {
case STRING:
preparedStatement.setString(parameter.getKey(), (String) parameter.getValue().getData());
break;
case INTEGER:
preparedStatement.setInt(parameter.getKey(), (Integer) parameter.getValue().getData());
break;
case DOUBLE:
preparedStatement.setDouble(parameter.getKey(), (Double) parameter.getValue().getData());
break;
case LONG:
preparedStatement.setLong(parameter.getKey(), (Long) parameter.getValue().getData());
break;
case BLOB:
preparedStatement.setBlob(parameter.getKey(), (Blob) parameter.getValue().getData());
break;
case FLOAT:
preparedStatement.setFloat(parameter.getKey(), (Float) parameter.getValue().getData());
break;
case BOOLEAN:
preparedStatement.setBoolean(parameter.getKey(), (Boolean) parameter.getValue().getData());
break;
case DATE:
preparedStatement.setDate(parameter.getKey(), (Date) parameter.getValue().getData());
break;
case OBJECT:
preparedStatement.setObject(parameter.getKey(), parameter.getValue().getData());
break;
default:
preparedStatement.setObject(parameter.getKey(), parameter.getValue().getData());
break;
}
}
return Optional.of(preparedStatement);
} catch (SQLException exception) {
exception.printStackTrace();
return Optional.empty();
}
}
/**
* Prepare a statement
*
* @param sql The statement you want to prepare
* @return The optional value of {@link PreparedStatement}
* @since 1.0.0
*/
public Optional<PreparedStatement> prepare(String sql) {
try {
return Optional.of(source.getConnection().prepareStatement(sql));
} catch (SQLException exception) {
exception.printStackTrace();
return Optional.empty();
}
}
/**
* Get the connection of MySQL
*
* @return The optional value of {@link Connection}
* @since 1.0.0
*/
public Optional<Connection> getConnection() {
try {
return Optional.of(source.getConnection());
} catch (SQLException e) {
return Optional.empty();
}
}
/**
* Closes the database
*
* @since 1.0.0
*/
public void close() {
source.close();
}
public String getName() {
return name;
}
public HikariConfig getConfig() {
return config;
}
public HikariDataSource getSource() {
return source;
}
/**
* Database options used for {@link Database}
*
* @author Majrly
* @since 1.0.0
*/
public static class DatabaseOptions {
// Variables
private HikariConfig config = new HikariConfig();
private String name;
private String hostname = "127.0.0.1";
private String username = "root";
private String password;
private String database;
private int port = 3306;
private int timeout = 60 * 1000;
/**
* Set a key/value in the HikariConfig
*
* @param key The key you want to set a value to
* @param value The value you want to set
* @since 1.0.0
*/
public DatabaseOptions set(String key, String value) {
config.addDataSourceProperty(key, value);
return this;
}
/**
* Set the hostname / port to connect
*
* @param hostname The hostname of the database
* @param port The port of the database
* @return This object
* @since 1.0.0
*/
public DatabaseOptions hostname(String hostname, int port) {
this.database = database;
this.port = port;
return this;
}
/**
* Set the authentication username and password
*
* @param username The user you want to authenticate as
* @param password The password you want to authenticate with
* @return This object
* @since 1.0.0
*/
public DatabaseOptions auth(String username, String password) {
this.username = username;
this.password = password;
return this;
}
/**
* Set the database to switch to
*
* @param database The database you want to switch to
* @return This object
* @since 1.0.0
*/
public DatabaseOptions database(String database) {
this.database = database;
return this;
}
/**
* Set the name of the database connection
*
* @param name The name of the database connection
* @return This object
* @since 1.0.0
*/
public DatabaseOptions type(String name) {
this.name = name;
return this;
}
/**
* Set the timeout of the connection
*
* @param timeout The max amount of time to connect
* @return This object
* @since 1.0.0
*/
public DatabaseOptions timeout(int timeout) {
this.timeout = timeout;
return this;
}
/**
* Build this class
*
* @return The database object
* @since 1.0.0
*/
public Database build() {
if (username.isEmpty()) {
username = "root";
}
return new Database(name, hostname, username, password, database, port, config);
}
}
}

View File

@ -0,0 +1,40 @@
package me.majrly.database;
import java.util.HashMap;
/**
* Apart of the database api to manage all your databases
*
* @author Majrly
* @since 1.0.0
*/
public class DatabaseManager {
private static HashMap<String, Database> databases = new HashMap<>();
/**
* Add a database to {@link #databases}
*
* @param database The database you want to add
* @since 1.0.0
*/
public static void addDatabase(Database database) {
databases.put(database.getName(), database);
}
/**
* Get a database with specified name from {@link #databases}
*
* @param name The name of the database you want to obtain
* @return The database wrapper
* @since 1.0.0
*/
public static Database getDatabase(String name) {
return databases.get(name);
}
// Getters
public static HashMap<String, Database> getDatabases() {
return databases;
}
}

View File

@ -0,0 +1,54 @@
package me.majrly.database.params;
/**
* Apart of the Database API to set parameters (AKA those little question marks in sql statements)
*
* @author Majrly
* @since 1.0.0
*/
public class Parameter {
// Variables
private Object data;
private Type type = Type.OBJECT;
/**
* Used to set parameters
*
* @param type The type of data you want sent
* @param data The data
* @since 1.0.0
*/
public Parameter(Type type, Object data) {
this.type = type;
this.data = data;
}
/**
* Used to set parameters
*
* @param data The object data
* @since 1.0.0
*/
public Parameter(Object data) {
this.data = data;
}
/**
* The type of data you want sent
*
* @author Majrly
* @since 1.0.0
*/
public enum Type {
STRING, BLOB, INTEGER, DOUBLE, FLOAT, DATE, LONG, BOOLEAN, OBJECT;
}
public Object getData() {
return data;
}
public Type getType() {
return type;
}
}

View File

@ -0,0 +1,14 @@
package me.majrly.database.statements;
/**
* Apart of the Database API to differentiate between various Statements
*
* @author Majrly
* @since 1.0.0
*/
public class Query extends Statement {
public Query(String sql) {
super(sql);
}
}

View File

@ -0,0 +1,120 @@
package me.majrly.database.statements;
import me.majrly.database.params.Parameter;
import java.sql.Blob;
import java.sql.Date;
import java.util.HashMap;
/**
* Apart of the Database API to create MySQL statements
*
* @author Majrly
* @since 1.0.0
*/
public class Statement {
// Variables
private String sql;
private int amount = 1;
private HashMap<Integer, Parameter> parameters = new HashMap<Integer, Parameter>();
/**
* Used to create SQL statements
*
* @param sql The SQL string
* @since 1.0.0
*/
public Statement(String sql) {
this.sql = sql;
}
/**
* Escape a string
*
* @param data The string you want to escape
* @since 1.0.0
*/
public void setString(String data) {
this.parameters.put(amount++, new Parameter(Parameter.Type.STRING, data));
}
/**
* Escape a string
*
* @param data The Blob you want to escape
* @since 1.0.0
*/
public void setBlob(Blob data) {
this.parameters.put(amount++, new Parameter(Parameter.Type.BLOB, data));
}
/**
* Escape a double
*
* @param data The double you want to escape
* @since 1.0.0
*/
public void setDouble(double data) {
this.parameters.put(amount++, new Parameter(Parameter.Type.DOUBLE, data));
}
/**
* Escape an integer
*
* @param data The integer you want to escape
* @since 1.0.0
*/
public void setInteger(int data) {
this.parameters.put(amount++, new Parameter(Parameter.Type.INTEGER, data));
}
/**
* Escape a float
*
* @param data The float you want to escape
* @since 1.0.0
*/
public void setFloat(float data) {
this.parameters.put(amount++, new Parameter(Parameter.Type.FLOAT, data));
}
/**
* Escape a date
*
* @param data The date you want to escape
* @since 1.0.0
*/
public void setDate(Date data) {
this.parameters.put(amount++, new Parameter(Parameter.Type.DATE, data));
}
/**
* Escape a boolean
*
* @param data The boolean you want to escape
* @since 1.0.0
*/
public void setBoolean(boolean data) {
this.parameters.put(amount++, new Parameter(Parameter.Type.BOOLEAN, data));
}
/**
* Escape an object
*
* @param data The object you want to escape
* @since 1.0.0
*/
public void setObject(Object data) {
this.parameters.put(amount++, new Parameter(Parameter.Type.OBJECT, data));
}
// Getters
public String getSQL() {
return sql;
}
public HashMap<Integer, Parameter> getParameters() {
return parameters;
}
}

View File

@ -0,0 +1,14 @@
package me.majrly.database.statements;
/**
* Apart of the Database API to differentiate between various Statements
*
* @author Majrly
* @since 1.0.0
*/
public class Update extends Statement {
public Update(String sql) {
super(sql);
}
}

View File

@ -6,7 +6,12 @@ import com.google.code.chatterbotapi.ChatterBotSession;
import com.google.code.chatterbotapi.ChatterBotType;
import lombok.Getter;
import lombok.Setter;
import me.savvy.rixa.commands.admin.*;
import me.majrly.database.Database;
import me.majrly.database.statements.Update;
import me.savvy.rixa.commands.admin.AddRoleCommand;
import me.savvy.rixa.commands.admin.BatchMoveCommand;
import me.savvy.rixa.commands.admin.ConfigCommand;
import me.savvy.rixa.commands.admin.RemoveRoleCommand;
import me.savvy.rixa.commands.general.*;
import me.savvy.rixa.commands.handlers.CommandExec;
import me.savvy.rixa.commands.handlers.CommandHandler;
@ -14,9 +19,6 @@ import me.savvy.rixa.commands.mod.DeleteMessagesCommand;
import me.savvy.rixa.commands.mod.MuteCommand;
import me.savvy.rixa.commands.mod.PurgeMessagesCommand;
import me.savvy.rixa.commands.mod.RaidModeCommand;
import me.savvy.rixa.data.database.Data;
import me.savvy.rixa.data.database.DataType;
import me.savvy.rixa.data.database.sql.DatabaseManager;
import me.savvy.rixa.data.filemanager.ConfigManager;
import me.savvy.rixa.data.filemanager.LanguageManager;
import me.savvy.rixa.events.BotEvent;
@ -33,13 +35,11 @@ import net.dv8tion.jda.core.JDA;
import net.dv8tion.jda.core.JDABuilder;
import net.dv8tion.jda.core.OnlineStatus;
import net.dv8tion.jda.core.entities.Game;
import net.dv8tion.jda.core.entities.Invite;
import net.dv8tion.jda.core.exceptions.RateLimitedException;
import net.dv8tion.jda.core.hooks.AnnotatedEventManager;
import javax.security.auth.login.LoginException;
import java.io.File;
import java.io.IOException;
import java.util.LinkedList;
import java.util.List;
import java.util.concurrent.Executors;
@ -48,11 +48,10 @@ import java.util.logging.Logger;
/**
* Created by Timber on 5/7/2017.
* Edited by Majr on 9/22/2017
*/
public class Rixa {
@Getter
private static Data data;
@Getter
private static long timeUp;
@Getter
@ -61,15 +60,19 @@ public class Rixa {
private static List<JDA> shardsList;
@Getter
private static ConfigManager config;
@Getter @Setter
private static DatabaseManager dbManager;
@Getter
@Setter
private static Database database;
private static ChatterBotFactory factory;
private static ChatterBotSession chatBotSession;
private static ChatterBot chatBot;
@Getter @Setter
@Getter
@Setter
private LanguageManager languageManager;
@Getter @Setter
@Getter
@Setter
private ScheduledExecutorService executorService;
// String search = event.getMessage().getContent().substring(event.getMessage().getContent().indexOf(" ") + 1);
public static void main(String[] args) {
instance = new Rixa();
@ -81,13 +84,16 @@ public class Rixa {
private static void load() {
getInstance().setExecutorService(Executors.newSingleThreadScheduledExecutor());
dbManager = new DatabaseManager(
String.valueOf(config.getJsonObject().getJSONObject("sql").getString("hostName")),
String.valueOf(config.getJsonObject().getJSONObject("sql").getString("portNumber")),
String.valueOf(config.getJsonObject().getJSONObject("sql").getString("databaseName")),
String.valueOf(config.getJsonObject().getJSONObject("sql").getString("userName")),
String.valueOf(config.getJsonObject().getJSONObject("sql").getString("password")));
dbManager.createTable();
database = Database.options()
.type("mysql")
.hostname(String.valueOf(config.getJsonObject().getJSONObject("sql").getString("hostName")), Integer.valueOf(config.getJsonObject().getJSONObject("sql").getInt("portNumber")))
.database(String.valueOf(config.getJsonObject().getJSONObject("sql").getString("databaseName")))
.auth(String.valueOf(config.getJsonObject().getJSONObject("sql").getString("userName")), String.valueOf(config.getJsonObject().getJSONObject("sql").getString("password")))
.build();
Update update = new Update("CREATE TABLE IF NOT EXISTS `core` (`guild_id` varchar(255) NOT NULL, `guild_name` varchar(255) NOT NULL, PRIMARY KEY (`guild_id`));");
database.send(update);
Update modules = new Update("CREATE TABLE IF NOT EXISTS `modules` (`guild_id` varchar(255) NOT NULL, `levels` varchar(255) NOT NULL, `enabled` INT(11) NOT NULL, PRIMARY KEY (`guild_id`));");
database.send(modules);
getInstance().setLanguageManager(new LanguageManager(new File("Rixa/languages/language.json")));
try {
int shards = 5;
@ -120,7 +126,6 @@ public class Rixa {
new AddRoleCommand(), new RemoveRoleCommand(), new LevelsCommand(),
new LeaderboardCommand(), new RaidModeCommand()});
register(new React[]{new HelpReaction(), new ConfigReaction(), new LeaderboardReaction()});
data = new Data(DataType.SQL);
try {
factory = new ChatterBotFactory();
chatBot = factory.create(ChatterBotType.PANDORABOTS, "b0dafd24ee35a477");

View File

@ -1,75 +0,0 @@
package me.savvy.rixa.data.database;
import me.savvy.rixa.Rixa;
import me.savvy.rixa.data.database.sql.DatabaseManager;
import me.savvy.rixa.enums.Result;
import java.sql.PreparedStatement;
import java.sql.SQLException;
/**
* Created by Timber on 5/31/2017.
*
* This class will be used to grab and put data into databases (SQL, FlatFile)
*/
public class Data {
private DataType dataType;
private DatabaseManager db;
public Data(DataType dataType) {
this.dataType = dataType;
this.db = Rixa.getDbManager();
}
public Object get(String key, String value, String objToGet, String table) throws SQLException {
switch (dataType) {
case SQL:
// SELECT objToGet FROM table WHERE key = value.
PreparedStatement ps =
db.getConnection().prepareStatement("SELECT `" + objToGet + "` FROM `" + table + "` WHERE `" + key + "` = ?");
ps.setString(1, value);
return db.getObject(ps).getObject(objToGet);
default:
return null;
}
}
public void put(String key, String value) {
switch (dataType) {
}
}
public Result update(String table, String setting, String key, Object placeholder, Object placeholder2) {
switch (dataType) {
case SQL:
try {
PreparedStatement ps = db.getConnection().prepareStatement("UPDATE `" + table +"` SET `" + setting + "` = ? WHERE `" + key + "` = ?;");
ps.setObject(1, placeholder);
ps.setObject(2, placeholder2);
return db.executeUpdate(ps);
} catch (SQLException ex) {
ex.printStackTrace();
return Result.ERROR;
}
}
return Result.FALSE;
}
public void delete(String key, String value) {
switch (dataType) {
}
}
public Result exists(String check) {
switch(dataType) {
case SQL:
try {
return db.checkExists(check);
} catch (SQLException e) {
e.printStackTrace();
}
}
return Result.FALSE;
}
}

View File

@ -1,10 +0,0 @@
package me.savvy.rixa.data.database;
/**
* Created by Timber on 6/4/2017.
*/
public enum DataType {
SQL,
FLAT_FILE
}

View File

@ -1,138 +0,0 @@
package me.savvy.rixa.data.database.sql;
import me.savvy.rixa.Rixa;
import me.savvy.rixa.data.database.sql.mysql.mysql.MySQL;
import me.savvy.rixa.enums.Result;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
public class DatabaseManager {
private Connection connection;
private MySQL MYSQL = null;
public DatabaseManager(String hostName, String port, String databaseName, String userName, String password) {
MYSQL = new MySQL(hostName, port, databaseName, userName, password);
}
public Connection getConnection() {
return connection;
}
public void createTable() {
checkConnection();
try {
PreparedStatement ps = connection.prepareStatement(
"CREATE TABLE IF NOT EXISTS `core` (`guild_id` varchar(255) NOT NULL, `guild_name` varchar(255) NOT NULL, PRIMARY KEY (`guild_id`));");
ps.executeUpdate();
ps.close();
} catch (SQLException e) {
Rixa.getInstance().getLogger().severe("Could not check if table exists, stopping server.");
e.printStackTrace();
// Redirect to 500
}
}
private void checkConnection() {
try {
if (!MYSQL.checkConnection()) {
connection = MYSQL.openConnection();
Rixa.getInstance().getLogger().info("Mysql database connected");
}
} catch (ClassNotFoundException | SQLException e) {
e.printStackTrace();
}
}
public Result executeUpdate(PreparedStatement ps) throws SQLException {
checkConnection();
try {
ps.executeUpdate();
return Result.SUCCESS;
} catch (SQLException e) {
e.printStackTrace();
return Result.ERROR;
}
}
public Object getObject(String string, String objToGet) throws SQLException {
checkConnection();
PreparedStatement ps = connection.prepareStatement(string);
ResultSet rs = ps.executeQuery();
if (rs.next()) {
return rs.getString(objToGet);
} else {
return null;
}
}
public ResultSet getObject(PreparedStatement ps) throws SQLException {
checkConnection();
ResultSet rs = ps.executeQuery();
if (rs.next()) {
return rs;
}
return null;
}
public ResultSet executeQuery(String query) {
checkConnection();
try {
PreparedStatement ps = connection.prepareStatement(query);
return ps.executeQuery();
} catch (SQLException ex) {
ex.printStackTrace();
}
return null;
}
public int getCount(String table) {
checkConnection();
try {
PreparedStatement preparedStatement = connection.prepareStatement("SELECT count(*) FROM '" + table + "';");
ResultSet resultSet = preparedStatement.executeQuery();
if (resultSet.next()) {
return resultSet.getInt(1);
}
preparedStatement.close();
resultSet.close();
} catch (SQLException ex) {
ex.printStackTrace();
}
return 0;
}
public Result checkExists(String string) throws SQLException {
checkConnection();
try {
PreparedStatement ps = connection.prepareStatement(string);
ResultSet rs = ps.executeQuery();
if (rs.next()) {
rs.close();
return Result.TRUE;
} else {
rs.close();
return Result.FALSE;
}
} catch (SQLException e) {
return Result.ERROR;
}
}
public Result insert(String string) {
checkConnection();
try {
PreparedStatement preparedStatement = connection.prepareStatement(string);
preparedStatement.executeUpdate();
preparedStatement.close();
return Result.SUCCESS;
} catch (SQLException e) {
e.printStackTrace();
return Result.ERROR;
}
}
}

View File

@ -1,117 +0,0 @@
package me.savvy.rixa.data.database.sql.mysql;
import lombok.Getter;
import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
/**
* Abstract Database class, serves as a base for any connection method (MySQL,
* SQLite, etc.)
*
* @author -_Husky_-
* @author tips48
*/
public abstract class Database {
@Getter
protected Connection connection;
/**
* Creates a new Database
*
*/
protected Database() {
this.connection = null;
}
/**
* Opens a connection with the database
*
* @return Opened connection
* @throws SQLException
* if the connection can not be opened
* @throws ClassNotFoundException
* if the driver cannot be found
*/
protected abstract Connection openConnection() throws SQLException,
ClassNotFoundException;
/**
* Checks if a connection is open with the database
*
* @return true if the connection is open
* @throws SQLException
* if the connection cannot be checked
*/
public boolean checkConnection() throws SQLException {
return connection != null && !connection.isClosed();
}
/**
* Closes the connection with the database
*
* @return true if successful
* @throws SQLException
* if the connection cannot be closed
*/
public boolean closeConnection() throws SQLException {
if (connection == null) {
return false;
}
connection.close();
return true;
}
/**
* Executes a SQL Query<br>
*
* If the connection is closed, it will be opened
*
* @param query
* Query to be run
* @return the results of the query
* @throws SQLException
* If the query cannot be executed
* @throws ClassNotFoundException
* If the driver cannot be found; see {@link #openConnection()}
*/
public ResultSet querySQL(String query) throws SQLException,
ClassNotFoundException {
if (!checkConnection()) {
openConnection();
}
Statement statement = connection.createStatement();
return statement.executeQuery(query);
}
/**
* Executes an Update SQL Query<br>
* See {@link Statement#executeUpdate(String)}<br>
* If the connection is closed, it will be opened
*
* @param query
* Query to be run
* @return Result Code, see {@link Statement#executeUpdate(String)}
* @throws SQLException
* If the query cannot be executed
* @throws ClassNotFoundException
* If the driver cannot be found; see {@link #openConnection()}
*/
public int updateSQL(String query) throws SQLException,
ClassNotFoundException {
if (!checkConnection()) {
openConnection();
}
Statement statement = connection.createStatement();
return statement.executeUpdate(query);
}
}

View File

@ -1,80 +0,0 @@
package me.savvy.rixa.data.database.sql.mysql.mysql;
import me.savvy.rixa.data.database.sql.mysql.Database;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
/**
* Connects to and uses a MySQL database
*
* @author -_Husky_-
* @author tips48
*/
public class MySQL extends Database {
private final String user;
private final String database;
private final String password;
private final String port;
private final String hostname;
/**
* Creates a new MySQL instance
*
* @param hostname
* Name of the host
* @param port
* Port number
* @param username
* Username
* @param password
* Password
*/
public MySQL(String hostname, String port, String username,
String password) {
this(hostname, port, null, username, password);
}
/**
* Creates a new MySQL instance for a specific database
*
* @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) {
this.hostname = hostname;
this.port = port;
this.database = database;
this.user = username;
this.password = password;
}
@Override
public Connection openConnection() throws SQLException,
ClassNotFoundException {
if (checkConnection()) {
return connection;
}
String connectionURL = "jdbc:mysql://"
+ this.hostname + ":" + this.port;
if (database != null) {
connectionURL = connectionURL + "/" + this.database;
}
Class.forName("com.mysql.jdbc.Driver");
connection = DriverManager.getConnection(connectionURL,
this.user, this.password);
return connection;
}
}

View File

@ -2,9 +2,11 @@ package me.savvy.rixa.guild;
import lombok.Getter;
import lombok.Setter;
import me.majrly.database.Database;
import me.majrly.database.statements.Query;
import me.majrly.database.statements.Update;
import me.savvy.rixa.Rixa;
import me.savvy.rixa.commands.handlers.RixaPermission;
import me.savvy.rixa.data.database.sql.DatabaseManager;
import me.savvy.rixa.enums.Result;
import me.savvy.rixa.guild.management.GuildSettings;
import me.savvy.rixa.modules.levels.LevelsModule;
@ -15,30 +17,36 @@ import net.dv8tion.jda.core.entities.Member;
import net.dv8tion.jda.core.entities.Role;
import net.dv8tion.jda.core.entities.User;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.*;
/**
* Created by Timber on 5/23/2017.
* Edited by Majr on 9/22/2017
*/
public class RixaGuild {
@Getter private Guild guild;
private DatabaseManager db;
@Setter private GuildSettings guildSettings;
@Getter @Setter private MusicModule musicModule;
@Getter @Setter private TwitterModule twitterModule;
@Getter private List<String> mutedMembers = new ArrayList<>();
@Getter @Setter private LevelsModule levelsModule;
@Getter
private Guild guild;
private Database db;
@Setter
private GuildSettings guildSettings;
@Getter
@Setter
private MusicModule musicModule;
@Getter
@Setter
private TwitterModule twitterModule;
@Getter
private List<String> mutedMembers = new ArrayList<>();
@Getter
@Setter
private LevelsModule levelsModule;
public RixaGuild(Guild guild) {
this.guild = guild;
this.db = Rixa.getDbManager();
this.db = Rixa.getDatabase();
setMusicModule(new MusicModule(guild));
setLevelsModule(new LevelsModule(this));
load();
@ -46,10 +54,10 @@ public class RixaGuild {
private void load() {
if (!(checkExists())) {
Rixa.getDbManager()
.insert("INSERT INTO `core` (`guild_id`, `guild_name`, `description`, `keywords`) VALUES ('%id%', '%name%', 'Description not set.', 'No Keywords Found.')"
.replace("%id%", guild.getId())
.replace("%name%", guild.getName().replace("'", "\\'")));
Update update = new Update("INSERT INTO `core` (`guild_id`, `guild_name`, `description`, `keywords`) VALUES (?, ?, 'Description not set.', 'No Keywords Found.')");
update.setString(guild.getId());
update.setString(guild.getName());
db.send(update);
}
setGuildSettings(new GuildSettings(this.guild));
addGuild(this);
@ -61,11 +69,25 @@ public class RixaGuild {
private boolean checkExists() {
Result r = Result.ERROR;
try {
r = Rixa.getDbManager().checkExists("SELECT `guild_name` FROM `core` WHERE `guild_id` = '" + guild.getId() + "';");
Query query = new Query("SELECT `guild_name` FROM `core` WHERE `guild_id` = '" + guild.getId() + "';");
Optional<?> optional = db.send(query);
if (!optional.isPresent()) r = Result.ERROR;
if (!(optional.get() instanceof ResultSet)) r = Result.ERROR;
if (r != Result.ERROR) {
ResultSet set = (ResultSet) optional.get();
if (set.next()) {
r = Result.TRUE;
} else {
r = Result.FALSE;
}
set.close();
}
} catch (SQLException e) {
e.printStackTrace();
}
return r == Result.TRUE;
}
@ -89,15 +111,14 @@ public class RixaGuild {
boolean b = false;
try {
PreparedStatement ps =
db.getConnection().prepareStatement
("SELECT `" + permission.toString().toUpperCase() + "` FROM `permissions` WHERE `role_id` = ?");
ps.setString(1, role.getId());
ResultSet rs = db.getObject(ps);
b = rs.getBoolean(permission.toString().toUpperCase());
ps.close();
rs.close();
Query query = new Query("SELECT `" + permission.toString().toUpperCase() + "` FROM `permissions` WHERE `role_id` = ?");
query.setString(role.getId());
Optional<?> optional = db.send(query);
if (!optional.isPresent()) return b;
if (!(optional.get() instanceof ResultSet)) return b;
ResultSet set = (ResultSet) optional.get();
b = set.getBoolean(permission.toString().toUpperCase());
set.close();
} catch (SQLException e) {
e.printStackTrace();
}
@ -106,32 +127,40 @@ public class RixaGuild {
public void setPermission(Role role, RixaPermission permission, boolean value) {
if (!permissionExists(role)) {
db
.insert("INSERT INTO `permissions` " +
Update update = new Update("INSERT INTO `permissions` " +
"(`role_id`, `guild_id`, `MUTE`, `ADD_ROLE`, `REMOVE_ROLE`, `CLEAR_CHAT`, " +
"`ACCESS_CONFIG`, `PM_MESSAGE`, `KICK_MEMBER`, `BAN_MEMBER`)" +
" VALUES ('" + role.getId() + "', '" + guild.getId() + "', '0', '0', '0', '0', '0', '0', '0', '0');");
}
try {
PreparedStatement ps = db.getConnection().prepareStatement
("UPDATE `permissions` SET `" + permission.toString().toUpperCase() + "` = ? WHERE `guild_id` = ? AND `role_id` = ?;");
ps.setBoolean(1, value);
ps.setString(2, guild.getId());
ps.setString(3, role.getId());
ps.executeUpdate();
} catch (SQLException e) {
e.printStackTrace();
" VALUES (?, ?, '0', '0', '0', '0', '0', '0', '0', '0');");
update.setString(role.getId());
update.setString(guild.getId());
db.send(update);
}
Update update = new Update("UPDATE `permissions` SET `" + permission.toString().toUpperCase() + "` = ? WHERE `guild_id` = ? AND `role_id` = ?;");
update.setBoolean(value);
update.setString(guild.getId());
update.setString(role.getId());
db.send(update);
}
private boolean permissionExists(Role role) {
ResultSet rs = db.executeQuery
("SELECT `" + RixaPermission.values()[0] + "` FROM `permissions` WHERE `guild_id` = '" + guild.getId() + "' AND `role_id` = '" + role.getId() + "'");
Query query = new Query("SELECT `" + RixaPermission.values()[0] + "` FROM `permissions` WHERE `guild_id` = ? AND `role_id` = ?");
query.setString(guild.getId());
query.setString(role.getId());
Optional<?> optional = db.send(query);
if (!optional.isPresent()) return false;
if (!(optional.get() instanceof ResultSet)) return false;
ResultSet set = (ResultSet) optional.get();
try {
return rs.next();
return set.next();
} catch (SQLException e) {
e.printStackTrace();
return false;
} finally {
try {
set.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
}

View File

@ -2,14 +2,16 @@ package me.savvy.rixa.guild.management;
import lombok.Getter;
import lombok.Setter;
import me.majrly.database.statements.Query;
import me.majrly.database.statements.Update;
import me.savvy.rixa.Rixa;
import me.savvy.rixa.enums.Result;
import net.dv8tion.jda.core.entities.Guild;
import net.dv8tion.jda.core.entities.TextChannel;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.Optional;
import java.util.TimerTask;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;
@ -26,8 +28,12 @@ public class GuildSettings {
private String prefix = "/", defaultRole, muteRole, joinMessage, quitMessage, joinPrivateMessage, description;
@Getter
private TextChannel joinMessageChannel, quitMessageChannel;
@Getter @Setter Guild.VerificationLevel defaultVerificationLevel;
@Getter @Setter long lastJoin;
@Getter
@Setter
Guild.VerificationLevel defaultVerificationLevel;
@Getter
@Setter
long lastJoin;
private boolean raidMode;
public GuildSettings(Guild guild) {
@ -41,16 +47,19 @@ public class GuildSettings {
private void load() throws SQLException {
if (!checkExists()) {
Rixa.getDbManager().insert("INSERT INTO `settings` (`guild_id`, `log_enabled`, `log_channel`, `joinMessage`, `quitMessage`, `greetings`, `farewell`," +
Update update = new Update("INSERT INTO `settings` (`guild_id`, `log_enabled`, `log_channel`, `joinMessage`, `quitMessage`, `greetings`, `farewell`," +
" `prefix`, `joinPm`, `joinVerification`, `defaultRole`, `muteRole`)" +
" VALUES ('" + guild.getId() + "', '0', 'default_value', 'default_value', 'default_value', 'default_value', 'default_value', '/'," +
" 'default', '0', 'default_value', 'default_value');");
Rixa.getDatabase().send(update);
return;
}
PreparedStatement ps = Rixa.getDbManager()
.getConnection().prepareStatement("SELECT * FROM `settings` WHERE `guild_id` = ?");
ps.setString(1, guild.getId());
ResultSet set = Rixa.getDbManager().getObject(ps);
Query query = new Query("SELECT * FROM `settings` WHERE `guild_id` = ?");
query.setString(guild.getId());
Optional<?> optional = Rixa.getDatabase().send(query);
if (!optional.isPresent()) return;
if (!(optional.get() instanceof ResultSet)) return;
ResultSet set = (ResultSet) optional.get();
this.prefix = (set.getString("prefix"));
this.defaultRole = (set.getString("defaultRole"));
this.joinMessage = (set.getString("joinMessage"));
@ -64,23 +73,39 @@ public class GuildSettings {
if (!set.getString("farewell").equalsIgnoreCase("default_value")) {
quitMessageChannel = guild.getTextChannelById(set.getString("farewell"));
}
ps = Rixa.getDbManager()
.getConnection().prepareStatement("SELECT * FROM `core` WHERE `guild_id` = ?");
ps.setString(1, guild.getId());
set = Rixa.getDbManager().getObject(ps);
query = new Query("SELECT * FROM `core` WHERE `guild_id` = ?");
query.setString(guild.getId());
optional = Rixa.getDatabase().send(query);
if (!optional.isPresent()) return;
if (!(optional.get() instanceof ResultSet)) return;
set = (ResultSet) optional.get();
this.description = (set.getString("description"));
this.enlisted = (set.getBoolean("enlisted"));
this.raidMode = false;
}
private boolean checkExists() {
Result r = Result.FALSE;
try {
return Rixa.getDbManager().checkExists("SELECT `guild_id` FROM `settings` WHERE `guild_id` = '" + guild.getId() + "'") == Result.TRUE;
Query query = new Query("SELECT `guild_id` FROM `settings` WHERE `guild_id` = '" + guild.getId() + "'");
Optional<?> optional = Rixa.getDatabase().send(query);
if (!optional.isPresent()) r = Result.ERROR;
if (!(optional.get() instanceof ResultSet)) r = Result.ERROR;
ResultSet set = (ResultSet) optional.get();
if (r != Result.ERROR) {
if (set.next()) {
r = Result.TRUE;
} else {
r = Result.FALSE;
}
}
set.close();
return r == Result.TRUE;
} catch (SQLException e) {
e.printStackTrace();
}
return false;
}
}
public void unload() {
@ -88,67 +113,74 @@ public class GuildSettings {
public void setJoinMessage(String joinMessage) {
this.joinMessage = joinMessage;
Rixa.getData().update("settings", "joinMessage", "guild_id", joinMessage, guild.getId());
update("settings", "joinMessage", "guild_id", joinMessage, guild.getId());
}
public void setQuitMessage(String quitMessage) {
this.quitMessage = quitMessage;
Rixa.getData().update("settings", "quitMessage", "guild_id", quitMessage, guild.getId());
update("settings", "quitMessage", "guild_id", quitMessage, guild.getId());
}
public void setJoinPrivateMessage(String joinPrivateMessage) {
this.joinPrivateMessage = joinPrivateMessage;
Rixa.getData().update("settings", "joinPM", "guild_id", joinPrivateMessage, guild.getId());
update("settings", "joinPM", "guild_id", joinPrivateMessage, guild.getId());
}
public void setJoinMessageChannel(TextChannel joinMessageChannel) {
this.joinMessageChannel = joinMessageChannel;
Rixa.getData().update("settings", "greetings", "guild_id", joinMessageChannel.getId(), guild.getId());
update("settings", "greetings", "guild_id", joinMessageChannel.getId(), guild.getId());
}
public void setJoinMessageChannel(String joinMessageChannel) {
if (joinMessageChannel.equalsIgnoreCase("default_value")) this.joinMessageChannel = null;
Rixa.getData().update("settings", "greetings", "guild_id", joinMessageChannel, guild.getId());
update("settings", "greetings", "guild_id", joinMessageChannel, guild.getId());
}
private void update(String table, String setting, String key, Object placeholder, Object placeholder2) {
Update update = new Update("UPDATE `" + table + "` SET `" + setting + "` = ? WHERE `" + key + "` = ?;");
update.setObject(placeholder);
update.setObject(placeholder2);
Rixa.getDatabase().send(update);
}
public void setQuitMessageChannel(TextChannel quitMessageChannel) {
this.quitMessageChannel = quitMessageChannel;
Rixa.getData().update("settings", "farewell", "guild_id", quitMessageChannel.getId(), guild.getId());
update("settings", "farewell", "guild_id", quitMessageChannel.getId(), guild.getId());
}
public void setQuitMessageChannel(String quitMessageChannel) {
if (quitMessageChannel.equalsIgnoreCase("default_value")) this.quitMessageChannel = null;
Rixa.getData().update("settings", "greetings", "guild_id", quitMessageChannel, guild.getId());
update("settings", "greetings", "guild_id", quitMessageChannel, guild.getId());
}
public void setDefaultRole(String defaultRole) {
this.defaultRole = defaultRole;
Rixa.getData().update("settings", "defaultRole", "guild_id", defaultRole, guild.getId());
update("settings", "defaultRole", "guild_id", defaultRole, guild.getId());
}
public void setPrefix(String prefix) {
this.prefix = prefix;
Rixa.getData().update("settings", "prefix", "guild_id", prefix, guild.getId());
update("settings", "prefix", "guild_id", prefix, guild.getId());
}
public void setDescription(String description) {
this.description = description;
Rixa.getData().update("core", "description", "guild_id", description, guild.getId());
update("core", "description", "guild_id", description, guild.getId());
}
public void setEnlisted(boolean enlisted) {
this.enlisted = enlisted;
Rixa.getData().update("core", "enlisted", "guild_id", enlisted, guild.getId());
update("core", "enlisted", "guild_id", enlisted, guild.getId());
}
public void setMuteRole(String muteRole) {
this.muteRole = muteRole;
Rixa.getData().update("settings", "muteRole", "guild_id", muteRole, guild.getId());
update("settings", "muteRole", "guild_id", muteRole, guild.getId());
}
public void setJoinVerification(boolean joinVerification) {
this.joinVerification = joinVerification;
Rixa.getData().update("settings", "joinVerification", "guild_id", joinVerification, guild.getId());
update("settings", "joinVerification", "guild_id", joinVerification, guild.getId());
}
public void startRaidMode() {

View File

@ -1,25 +1,31 @@
package me.savvy.rixa.guild.user;
import lombok.Getter;
import lombok.Setter;
import me.majrly.database.statements.Query;
import me.majrly.database.statements.Update;
import me.savvy.rixa.Rixa;
import me.savvy.rixa.enums.Result;
import me.savvy.rixa.guild.RixaGuild;
import net.dv8tion.jda.core.entities.Guild;
import net.dv8tion.jda.core.entities.User;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.*;
import java.util.Optional;
import java.util.Random;
import java.util.Timer;
import java.util.TimerTask;
/**
* Created by savit on 7/14/2017.
*/
public class UserData {
@Getter private final Guild guild;
@Getter private User user;
@Getter private int experience;
@Getter
private final Guild guild;
@Getter
private User user;
@Getter
private int experience;
private boolean awardedLast;
private Random random;
@ -42,16 +48,16 @@ public class UserData {
setExperience(0);
return;
}
String query = "SELECT * FROM `%s` WHERE `%s` = '%s' AND `%s` = '%s';";
PreparedStatement ps;
ResultSet rs;
try {
ps = Rixa.getDbManager().getConnection().prepareStatement(String.format
(query, "levels", "guild_id",
guild.getId(), "user_id",
user.getId()));
rs = Rixa.getDbManager().getObject(ps);
setExperience(rs.getInt("experience"));
Query query = new Query("SELECT * FROM `levels` WHERE `guild_id` = ? AND `user_id` = ?;");
query.setString("levels");
query.setString(guild.getId());
query.setString(user.getId());
Optional<?> optional = Rixa.getDatabase().send(query);
if (!optional.isPresent()) return;
if (!(optional.get() instanceof ResultSet)) return;
ResultSet set = (ResultSet) optional.get();
setExperience(set.getInt("experience"));
} catch (SQLException e) {
e.printStackTrace();
}
@ -103,39 +109,46 @@ public class UserData {
}
private boolean checkExists() {
String query = "SELECT `%s` FROM `%s` WHERE `%s` = '%s' AND `%s` = '%s';";
Result r;
Result r = Result.FALSE;
try {
r = Rixa.getDbManager().checkExists(String.format
(query, "user_id", "levels", "guild_id",
guild.getId(), "user_id",
user.getId()));
Query query = new Query("SELECT `user_id` FROM `levels` WHERE `guild_id` = ? AND `user_id` = ?;");
query.setString(guild.getId());
query.setString(user.getId());
Optional<?> optional = Rixa.getDatabase().send(query);
if (!optional.isPresent()) r = Result.ERROR;
if (!(optional.get() instanceof ResultSet)) r = Result.ERROR;
ResultSet set = (ResultSet) optional.get();
if (r != Result.ERROR) {
if (set.next()) {
r = Result.TRUE;
} else {
r = Result.FALSE;
}
}
set.close();
return r == Result.TRUE;
} catch (SQLException e) {
e.printStackTrace();
}
return false;
}
}
private void insert() {
String query = "INSERT INTO `%s` (`%s`,`%s`,`%s`) VALUES ('%s', '%s', '%s');";
Rixa.getDbManager()
.insert(String.format(query, "levels", "guild_id", "user_id", "experience",
guild.getId(), user.getId(), "0"));
Update update = new Update("INSERT INTO `levels` (guild_id, user_id, experience) VALUES (?, ?, ?);");
update.setString(guild.getId());
update.setString(user.getId());
update.setInteger(0);
Rixa.getDatabase().send(update);
}
private void setExperience(int experience) {
this.experience = experience;
String query = "UPDATE `%s` SET `%s` = '%s' WHERE `%s` = '%s' AND `%s` = '%s';";
try {
PreparedStatement ps = Rixa.getDbManager().getConnection().prepareStatement(String.format
(query, "levels", "experience", experience, "guild_id",
guild.getId(), "user_id",
user.getId()));
Rixa.getDbManager().executeUpdate(ps);
} catch (SQLException e) {
e.printStackTrace();
}
String query = "UPDATE `levels` SET `experience` = ? WHERE `guild_id` = ? AND `user_id` = ?;";
Update update = new Update(query);
update.setInteger(experience);
update.setString(guild.getId());
update.setString(user.getId());
Rixa.getDatabase().send(update);
}
private int getRandom() {

View File

@ -1,12 +1,15 @@
package me.savvy.rixa.modules.levels;
import lombok.Getter;
import me.majrly.database.Database;
import me.majrly.database.statements.Query;
import me.majrly.database.statements.Update;
import me.savvy.rixa.Rixa;
import me.savvy.rixa.data.database.sql.DatabaseManager;
import me.savvy.rixa.enums.Result;
import me.savvy.rixa.guild.RixaGuild;
import me.savvy.rixa.guild.user.UserData;
import me.savvy.rixa.modules.RixaModule;
import me.savvy.rixa.utils.DatabaseUtils;
import me.savvy.rixa.utils.MessageBuilder;
import net.dv8tion.jda.core.entities.Member;
@ -20,9 +23,12 @@ import java.util.*;
*/
public class LevelsModule implements RixaModule {
@Getter private final RixaGuild rixaGuild;
@Getter private Map<String, UserData> userData = new HashMap<>();
@Getter private boolean enabled;
@Getter
private final RixaGuild rixaGuild;
@Getter
private Map<String, UserData> userData = new HashMap<>();
@Getter
private boolean enabled;
public LevelsModule(RixaGuild rixaGuild) {
this.rixaGuild = rixaGuild;
@ -30,14 +36,19 @@ public class LevelsModule implements RixaModule {
load();
}
private List<UserData> leaderboard(Member member) {
DatabaseManager db = Rixa.getDbManager();
ResultSet rs = db.executeQuery(String.format
("SELECT * FROM `levels` WHERE `guild_id` = '%s' ORDER BY `experience` DESC;", member.getGuild().getId()));
Database db = Rixa.getDatabase();
ResultSet rs = null;
try {
rs = db.getConnection().get().prepareStatement(String.format("SELECT * FROM `levels` WHERE `guild_id` = '%s' ORDER BY `experience` DESC;", member.getGuild().getId())).executeQuery();
} catch (SQLException e) {
e.printStackTrace();
}
List<UserData> userDataList = new LinkedList<>();
try {
while (rs.next()) {
while (rs != null && rs.next()) {
if (member.getGuild().getMemberById(rs.getString("user_id")) == null) continue;
UserData userData = rixaGuild.getLevelsModule().getUserData(rs.getString("user_id"));
userDataList.add(userData);
@ -124,10 +135,12 @@ public class LevelsModule implements RixaModule {
PreparedStatement ps = null;
ResultSet rs = null;
try {
ps = Rixa.getDbManager().getConnection().prepareStatement(query);
ps = Rixa.getDatabase().getConnection().get().prepareStatement(query);
ps.setString(1, getRixaGuild().getGuild().getId());
rs = Rixa.getDbManager().getObject(ps);
rs = ps.executeQuery();
if (rs.next()) {
this.enabled = rs.getBoolean("levels");
}
ps.close();
rs.close();
} catch (SQLException e) {
@ -136,25 +149,38 @@ public class LevelsModule implements RixaModule {
}
private boolean checkExists() {
String query = "SELECT `%s` FROM `%s` WHERE `%s` = '%s';";
Result r = Result.ERROR;
Result r = Result.FALSE;
try {
r = Rixa.getDbManager().checkExists(String.format
(query, "guild_id", "modules", "guild_id", rixaGuild.getGuild().getId()));
Query query = new Query("SELECT `guild_id` FROM `modules` WHERE `guild_id` = ?;");
query.setString(rixaGuild.getGuild().getId());
Optional<?> optional = Rixa.getDatabase().send(query);
if (!optional.isPresent()) r = Result.ERROR;
if (!(optional.get() instanceof ResultSet)) r = Result.ERROR;
ResultSet set = (ResultSet) optional.get();
if (r != Result.ERROR) {
if (set.next()) {
r = Result.TRUE;
} else {
r = Result.FALSE;
}
}
set.close();
return r == Result.TRUE;
} catch (SQLException e) {
e.printStackTrace();
return false;
}
return r == Result.TRUE;
}
private void insert() {
String query = "INSERT INTO `%s` (`%s`) VALUES ('%s');";
Rixa.getDbManager()
.insert(String.format(query, "modules", "guild_id", rixaGuild.getGuild().getId()));
String query = "INSERT INTO `modules` (`guild_id`) VALUES (?);";
Update update = new Update(query);
update.setString(rixaGuild.getGuild().getId());
Rixa.getDatabase().send(update);
}
public void setEnabled(boolean enabled) {
this.enabled = enabled;
Rixa.getData().update("modules", "levels", "guild_id", enabled, rixaGuild.getGuild().getId());
DatabaseUtils.update("modules", "levels", "guild_id", enabled, rixaGuild.getGuild().getId());
}
}

View File

@ -22,6 +22,7 @@ public class MusicManager {
/**
* Creates a player and a track scheduler.
*
* @param manager Audio player manager to use for creating the player.
*/
public MusicManager(AudioPlayerManager manager) {

View File

@ -1,21 +1,25 @@
package me.savvy.rixa.modules.music;
import lombok.Getter;
import me.majrly.database.Database;
import me.majrly.database.statements.Query;
import me.majrly.database.statements.Update;
import me.savvy.rixa.Rixa;
import me.savvy.rixa.data.database.sql.DatabaseManager;
import me.savvy.rixa.enums.Result;
import me.savvy.rixa.modules.RixaModule;
import me.savvy.rixa.utils.DatabaseUtils;
import net.dv8tion.jda.core.entities.Guild;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.Optional;
/**
* Created by Timber on 5/23/2017.
*/
public class MusicModule implements RixaModule {
private DatabaseManager db;
private Database db;
@Getter
private boolean enabled;
@Getter
@ -27,22 +31,30 @@ public class MusicModule implements RixaModule {
this.guild = guild;
this.enabled = false;
this.musicRole = "default_value";
db = Rixa.getDbManager();
db = Rixa.getDatabase();
load();
}
public void load() {
Update music = new Update("CREATE TABLE IF NOT EXISTS `music` (`guild_id` varchar(255) NOT NULL, `music_role` varchar(255) NOT NULL, `enabled` INT(11) NOT NULL, PRIMARY KEY (`guild_id`));");
db.send(music);
if (!checkExists()) {
db.insert("INSERT INTO `music` (`guild_id`, `music_role`, `enabled`)" +
Update update = new Update("INSERT INTO `music` (`guild_id`, `music_role`, `enabled`)" +
" VALUES ('" + guild.getId() + "', 'default_value', '0');");
db.send(update);
}
try {
PreparedStatement ps = db.getConnection().prepareStatement
("SELECT * FROM `music` WHERE `guild_id` = ?;");
ps.setString(1, guild.getId());
ResultSet rs = db.getObject(ps);
this.musicRole = rs.getString("music_role");
this.enabled = rs.getBoolean("enabled");
Query query = new Query("SELECT * FROM `modules` WHERE `guild_id` = ?");
query.setString(guild.getId());
Optional<?> optional = Rixa.getDatabase().send(query);
if (!optional.isPresent()) return;
if (!(optional.get() instanceof ResultSet)) return;
ResultSet set = (ResultSet) optional.get();
if (set.next()) {
this.musicRole = set.getString("music_role");
this.enabled = set.getBoolean("enabled");
}
set.close();
} catch (SQLException e) {
e.printStackTrace();
}
@ -61,7 +73,7 @@ public class MusicModule implements RixaModule {
public Result setEnabled(boolean val) {
this.enabled = val;
return Rixa.getData().update("music", "enabled", "guild_id", val, guild.getId());
return DatabaseUtils.update("music", "enabled", "guild_id", val, guild.getId());
}
public boolean isRoleRequired() {
@ -71,17 +83,30 @@ public class MusicModule implements RixaModule {
public Result setRole(String newRole) {
this.musicRole = newRole;
return Rixa.getData().update("music", "music_role", "guild_id", newRole, guild.getId());
return DatabaseUtils.update("music", "music_role", "guild_id", newRole, guild.getId());
}
public boolean checkExists() {
Result r = Result.ERROR;
Result r = Result.FALSE;
try {
r = Rixa.getDbManager().checkExists("SELECT `guild_id` FROM `music` WHERE `guild_id` = '" +
Query query = new Query("SELECT `guild_id` FROM `music` WHERE `guild_id` = '" +
guild.getId() + "';");
Optional<?> optional = Rixa.getDatabase().send(query);
if (!optional.isPresent()) r = Result.ERROR;
if (!(optional.get() instanceof ResultSet)) r = Result.ERROR;
ResultSet set = (ResultSet) optional.get();
if (r != Result.ERROR) {
if (set.next()) {
r = Result.TRUE;
} else {
r = Result.FALSE;
}
}
set.close();
return r == Result.TRUE;
} catch (SQLException e) {
e.printStackTrace();
}
return r == Result.TRUE;
return false;
}
}
}

View File

@ -0,0 +1,16 @@
package me.savvy.rixa.utils;
import me.majrly.database.statements.Update;
import me.savvy.rixa.Rixa;
import me.savvy.rixa.enums.Result;
public class DatabaseUtils {
public static Result update(String table, String setting, String key, Object placeholder, Object placeholder2) {
Update update = new Update("UPDATE `" + table + "` SET `" + setting + "` = ? WHERE `" + key + "` = ?;");
update.setObject(placeholder);
update.setObject(placeholder2);
Rixa.getDatabase().send(update);
return Result.TRUE;
}
}