mcMMO/src/main/java/com/gmail/nossr50/util/Database.java

379 lines
14 KiB
Java
Raw Normal View History

2012-04-27 11:47:11 +02:00
package com.gmail.nossr50.util;
import java.sql.Connection;
import java.sql.DriverManager;
2012-06-05 16:13:10 +02:00
import java.sql.PreparedStatement;
2012-04-27 11:47:11 +02:00
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
2012-06-05 16:13:10 +02:00
import java.util.HashMap;
2012-04-27 11:47:11 +02:00
import java.util.Properties;
2012-06-05 16:13:10 +02:00
import com.gmail.nossr50.mcMMO;
2012-04-27 11:47:11 +02:00
import com.gmail.nossr50.config.Config;
import com.gmail.nossr50.datatypes.DatabaseUpdate;
import com.gmail.nossr50.runnables.SQLReconnect;
public class Database {
private static Config configInstance = Config.getInstance();
private static String connectionString = "jdbc:mysql://" + configInstance.getMySQLServerName() + ":" + configInstance.getMySQLServerPort() + "/" + configInstance.getMySQLDatabaseName() + "?user=" + configInstance.getMySQLUserName() + "&password=" + configInstance.getMySQLUserPassword();
private static String tablePrefix = configInstance.getMySQLTablePrefix();
private static Connection connection = null;
private static mcMMO plugin = null;
// Scale waiting time by this much per failed attempt
private static final double SCALING_FACTOR = 5;
// Minimum wait in nanoseconds (default 500ms)
private static final long MIN_WAIT = 500*100000L;
// Maximum time to wait between reconnects (default 5 minutes)
private static final long MAX_WAIT = 5*60000000000L;
// How long to wait when checking if connection is valid (default 3 seconds)
private static final int VALID_TIMEOUT = 3;
// When next to try connecting to Database in nanoseconds
private static long nextReconnectTimestamp = 0L;
// How many connection attemtps have failed
private static int reconnectAttempt = 0;
2012-04-27 11:47:11 +02:00
public Database(mcMMO instance) {
2012-04-27 11:47:11 +02:00
plugin = instance;
checkConnected(); //Connect to MySQL
2012-04-27 11:47:11 +02:00
}
/**
* Attempt to connect to the mySQL database.
*/
public static void connect() {
try {
System.out.println("[mcMMO] Attempting connection to MySQL...");
// Force driver to load if not yet loaded
Class.forName("com.mysql.jdbc.Driver");
Properties connectionProperties = new Properties();
connectionProperties.put("autoReconnect", "false");
connectionProperties.put("maxReconnects", "0");
connection = DriverManager.getConnection(connectionString, connectionProperties);
2012-04-27 11:47:11 +02:00
System.out.println("[mcMMO] Connection to MySQL was a success!");
}
catch (SQLException ex) {
connection = null;
2012-04-27 11:47:11 +02:00
System.out.println("[mcMMO] Connection to MySQL failed!");
ex.printStackTrace();
printErrors(ex);
} catch (ClassNotFoundException ex) {
connection = null;
System.out.println("[mcMMO] MySQL database driver not found!");
ex.printStackTrace();
}
2012-04-27 11:47:11 +02:00
}
/**
* Attempt to create the database structure.
*/
public void createStructure() {
write("CREATE TABLE IF NOT EXISTS `" + tablePrefix + "huds` (`user_id` int(10) unsigned NOT NULL,"
+ "`hudtype` varchar(50) NOT NULL DEFAULT 'STANDARD',"
2012-04-27 11:47:11 +02:00
+ "PRIMARY KEY (`user_id`)) ENGINE=MyISAM DEFAULT CHARSET=latin1;");
write("CREATE TABLE IF NOT EXISTS `" + tablePrefix + "users` (`id` int(10) unsigned NOT NULL AUTO_INCREMENT,"
+ "`user` varchar(40) NOT NULL,"
+ "`lastlogin` int(32) unsigned NOT NULL,"
+ "PRIMARY KEY (`id`),"
+ "UNIQUE KEY `user` (`user`)) ENGINE=MyISAM DEFAULT CHARSET=latin1 AUTO_INCREMENT=1;");
write("CREATE TABLE IF NOT EXISTS `" + tablePrefix + "cooldowns` (`user_id` int(10) unsigned NOT NULL,"
+ "`taming` int(32) unsigned NOT NULL DEFAULT '0',"
+ "`mining` int(32) unsigned NOT NULL DEFAULT '0',"
+ "`woodcutting` int(32) unsigned NOT NULL DEFAULT '0',"
+ "`repair` int(32) unsigned NOT NULL DEFAULT '0',"
+ "`unarmed` int(32) unsigned NOT NULL DEFAULT '0',"
+ "`herbalism` int(32) unsigned NOT NULL DEFAULT '0',"
+ "`excavation` int(32) unsigned NOT NULL DEFAULT '0',"
+ "`archery` int(32) unsigned NOT NULL DEFAULT '0',"
+ "`swords` int(32) unsigned NOT NULL DEFAULT '0',"
+ "`axes` int(32) unsigned NOT NULL DEFAULT '0',"
+ "`acrobatics` int(32) unsigned NOT NULL DEFAULT '0',"
+ "`blast_mining` int(32) unsigned NOT NULL DEFAULT '0',"
+ "PRIMARY KEY (`user_id`)) ENGINE=MyISAM DEFAULT CHARSET=latin1;");
write("CREATE TABLE IF NOT EXISTS `" + tablePrefix + "skills` (`user_id` int(10) unsigned NOT NULL,"
+ "`taming` int(10) unsigned NOT NULL DEFAULT '0',"
+ "`mining` int(10) unsigned NOT NULL DEFAULT '0',"
+ "`woodcutting` int(10) unsigned NOT NULL DEFAULT '0',"
+ "`repair` int(10) unsigned NOT NULL DEFAULT '0',"
+ "`unarmed` int(10) unsigned NOT NULL DEFAULT '0',"
+ "`herbalism` int(10) unsigned NOT NULL DEFAULT '0',"
+ "`excavation` int(10) unsigned NOT NULL DEFAULT '0',"
+ "`archery` int(10) unsigned NOT NULL DEFAULT '0',"
+ "`swords` int(10) unsigned NOT NULL DEFAULT '0',"
+ "`axes` int(10) unsigned NOT NULL DEFAULT '0',"
+ "`acrobatics` int(10) unsigned NOT NULL DEFAULT '0',"
+ "PRIMARY KEY (`user_id`)) ENGINE=MyISAM DEFAULT CHARSET=latin1;");
write("CREATE TABLE IF NOT EXISTS `" + tablePrefix + "experience` (`user_id` int(10) unsigned NOT NULL,"
+ "`taming` int(10) unsigned NOT NULL DEFAULT '0',"
+ "`mining` int(10) unsigned NOT NULL DEFAULT '0',"
+ "`woodcutting` int(10) unsigned NOT NULL DEFAULT '0',"
+ "`repair` int(10) unsigned NOT NULL DEFAULT '0',"
+ "`unarmed` int(10) unsigned NOT NULL DEFAULT '0',"
+ "`herbalism` int(10) unsigned NOT NULL DEFAULT '0',"
+ "`excavation` int(10) unsigned NOT NULL DEFAULT '0',"
+ "`archery` int(10) unsigned NOT NULL DEFAULT '0',"
+ "`swords` int(10) unsigned NOT NULL DEFAULT '0',"
+ "`axes` int(10) unsigned NOT NULL DEFAULT '0',"
+ "`acrobatics` int(10) unsigned NOT NULL DEFAULT '0',"
+ "PRIMARY KEY (`user_id`)) ENGINE=MyISAM DEFAULT CHARSET=latin1;");
checkDatabaseStructure(DatabaseUpdate.FISHING);
checkDatabaseStructure(DatabaseUpdate.BLAST_MINING);
}
/**
* Check database structure for missing values.
*
* @param update Type of data to check updates for
*/
public void checkDatabaseStructure(DatabaseUpdate update) {
String sql = null;
ResultSet resultSet;
HashMap<Integer, ArrayList<String>> rows = new HashMap<Integer, ArrayList<String>>();
2012-04-27 11:47:11 +02:00
switch (update) {
case BLAST_MINING:
sql = "SELECT * FROM `" + tablePrefix + "cooldowns` ORDER BY `" + tablePrefix + "cooldowns`.`blast_mining` ASC LIMIT 0 , 30";
2012-04-27 11:47:11 +02:00
break;
2012-04-27 11:47:11 +02:00
case FISHING:
sql = "SELECT * FROM `" + tablePrefix + "experience` ORDER BY `" + tablePrefix + "experience`.`fishing` ASC LIMIT 0 , 30";
2012-04-27 11:47:11 +02:00
break;
2012-04-27 11:47:11 +02:00
default:
break;
}
try {
PreparedStatement statement = connection.prepareStatement(sql);
resultSet = statement.executeQuery();
while (resultSet.next()) {
ArrayList<String> column = new ArrayList<String>();
for (int i = 1; i <= resultSet.getMetaData().getColumnCount(); i++) {
column.add(resultSet.getString(i));
2012-04-27 11:47:11 +02:00
}
rows.put(resultSet.getRow(), column);
2012-04-27 11:47:11 +02:00
}
statement.close();
2012-04-27 11:47:11 +02:00
}
catch (SQLException ex) {
switch (update) {
case BLAST_MINING:
2012-04-27 11:47:11 +02:00
System.out.println("Updating mcMMO MySQL tables for Blast Mining...");
write("ALTER TABLE `"+tablePrefix + "cooldowns` ADD `blast_mining` int(32) NOT NULL DEFAULT '0' ;");
break;
case FISHING:
2012-04-27 11:47:11 +02:00
System.out.println("Updating mcMMO MySQL tables for Fishing...");
write("ALTER TABLE `"+tablePrefix + "skills` ADD `fishing` int(10) NOT NULL DEFAULT '0' ;");
write("ALTER TABLE `"+tablePrefix + "experience` ADD `fishing` int(10) NOT NULL DEFAULT '0' ;");
break;
default:
break;
2012-04-27 11:47:11 +02:00
}
}
}
/**
* Attempt to write the SQL query.
*
* @param sql Query to write.
* @return true if the query was successfully written, false otherwise.
*/
public boolean write(String sql) {
if (checkConnected()) {
2012-04-27 11:47:11 +02:00
try {
PreparedStatement statement = connection.prepareStatement(sql);
statement.executeUpdate();
statement.close();
2012-04-27 11:47:11 +02:00
return true;
}
catch (SQLException ex) {
printErrors(ex);
return false;
}
}
2012-04-27 11:47:11 +02:00
return false;
}
/**
* Get the Integer. Only return first row / first field.
*
* @param sql SQL query to execute
* @return the value in the first row / first field
*/
public int getInt(String sql) {
ResultSet resultSet;
int result = 0;
2012-04-27 11:47:11 +02:00
if (checkConnected()) {
2012-04-27 11:47:11 +02:00
try {
PreparedStatement statement = connection.prepareStatement(sql);
resultSet = statement.executeQuery();
if (resultSet.next()) {
result = resultSet.getInt(1);
2012-06-28 05:35:56 +02:00
}
else {
result = 0;
2012-04-27 11:47:11 +02:00
}
statement.close();
2012-04-27 11:47:11 +02:00
}
catch (SQLException ex) {
printErrors(ex);
}
}
2012-04-27 11:47:11 +02:00
return result;
}
2012-06-05 15:57:10 +02:00
2012-04-27 11:47:11 +02:00
/**
* Check connection status and re-establish if dead or stale.
*
* If the very first immediate attempt fails, further attempts
* will be made in progressively larger intervals up to MAX_WAIT
* intervals.
*
* This allows for MySQL to time out idle connections as needed by
* server operator, without affecting McMMO, while still providing
* protection against a database outage taking down Bukkit's tick
* processing loop due to attemping a database connection each
* time McMMO needs the database.
2012-06-05 15:57:10 +02:00
*
2012-04-27 11:47:11 +02:00
* @return the boolean value for whether or not we are connected
*/
public static boolean checkConnected() {
boolean isClosed = true;
boolean isValid = false;
boolean exists = (connection != null);
// Initialized as needed later
long timestamp=0;
// If we're waiting for server to recover then leave early
if (nextReconnectTimestamp > 0 && nextReconnectTimestamp > System.nanoTime()) {
return false;
}
if (exists) {
try {
isClosed = connection.isClosed();
} catch (SQLException e) {
isClosed = true;
e.printStackTrace();
printErrors(e);
}
if (!isClosed) {
try {
isValid = connection.isValid(VALID_TIMEOUT);
} catch (SQLException e) {
// Don't print stack trace because it's valid to lose idle connections
// to the server and have to restart them.
isValid = false;
}
}
}
// Leave if all ok
if (exists && !isClosed && isValid) {
// Housekeeping
nextReconnectTimestamp = 0;
reconnectAttempt = 0;
return true;
}
// Cleanup after ourselves for GC and MySQL's sake
if (exists && !isClosed) {
try {
connection.close();
} catch (SQLException ex) {
// This is a housekeeping exercise, ignore errors
}
}
// Try to connect again
connect();
// Leave if connection is good
try {
if (connection != null && !connection.isClosed()) {
// Schedule a database save if we really had an outage
if (reconnectAttempt > 1) {
plugin.getServer().getScheduler().scheduleSyncDelayedTask(plugin, new SQLReconnect(plugin), 5);
}
nextReconnectTimestamp = 0;
reconnectAttempt = 0;
return true;
}
} catch (SQLException e) {
// Failed to check isClosed, so presume connection is bad and attempt later
e.printStackTrace();
printErrors(e);
}
reconnectAttempt++;
nextReconnectTimestamp = (long)(System.nanoTime() + Math.min(MAX_WAIT, (reconnectAttempt*SCALING_FACTOR*MIN_WAIT)));
return false;
2012-04-27 11:47:11 +02:00
}
/**
* Read SQL query.
*
* @param sql SQL query to read
* @return the rows in this SQL query
*/
public HashMap<Integer, ArrayList<String>> read(String sql) {
ResultSet resultSet;
HashMap<Integer, ArrayList<String>> rows = new HashMap<Integer, ArrayList<String>>();
2012-04-27 11:47:11 +02:00
if (checkConnected()) {
2012-04-27 11:47:11 +02:00
try {
PreparedStatement statement = connection.prepareStatement(sql);
resultSet = statement.executeQuery();
while (resultSet.next()) {
ArrayList<String> column = new ArrayList<String>();
for (int i = 1; i <= resultSet.getMetaData().getColumnCount(); i++) {
column.add(resultSet.getString(i));
2012-04-27 11:47:11 +02:00
}
rows.put(resultSet.getRow(), column);
2012-04-27 11:47:11 +02:00
}
statement.close();
2012-04-27 11:47:11 +02:00
}
catch (SQLException ex) {
printErrors(ex);
}
}
return rows;
2012-04-27 11:47:11 +02:00
}
private static void printErrors(SQLException ex) {
System.out.println("SQLException: " + ex.getMessage());
System.out.println("SQLState: " + ex.getSQLState());
System.out.println("VendorError: " + ex.getErrorCode());
}
}