Database.java 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402
  1. package com.gmail.nossr50.util;
  2. import java.sql.Connection;
  3. import java.sql.DriverManager;
  4. import java.sql.PreparedStatement;
  5. import java.sql.ResultSet;
  6. import java.sql.SQLException;
  7. import java.util.ArrayList;
  8. import java.util.HashMap;
  9. import java.util.Properties;
  10. import com.gmail.nossr50.mcMMO;
  11. import com.gmail.nossr50.config.Config;
  12. import com.gmail.nossr50.datatypes.DatabaseUpdate;
  13. import com.gmail.nossr50.runnables.SQLReconnect;
  14. public class Database {
  15. private static Config configInstance = Config.getInstance();
  16. private static String connectionString;
  17. private static String tablePrefix = configInstance.getMySQLTablePrefix();
  18. private static Connection connection = null;
  19. private static mcMMO plugin = null;
  20. // Scale waiting time by this much per failed attempt
  21. private static final double SCALING_FACTOR = 10;
  22. // Minimum wait in nanoseconds (default 500ms)
  23. private static final long MIN_WAIT = 500L*1000000L;
  24. // Maximum time to wait between reconnects (default 5 minutes)
  25. private static final long MAX_WAIT = 5L * 60L * 1000L * 1000000L;
  26. // How long to wait when checking if connection is valid (default 3 seconds)
  27. private static final int VALID_TIMEOUT = 3;
  28. // When next to try connecting to Database in nanoseconds
  29. private static long nextReconnectTimestamp = 0L;
  30. // How many connection attemtps have failed
  31. private static int reconnectAttempt = 0;
  32. public Database(mcMMO instance) {
  33. plugin = instance;
  34. checkConnected(); //Connect to MySQL
  35. }
  36. /**
  37. * Attempt to connect to the mySQL database.
  38. */
  39. public static void connect() {
  40. connectionString = "jdbc:mysql://" + configInstance.getMySQLServerName() + ":" + configInstance.getMySQLServerPort() + "/" + configInstance.getMySQLDatabaseName();
  41. try {
  42. mcMMO.p.getLogger().info("Attempting connection to MySQL...");
  43. // Force driver to load if not yet loaded
  44. Class.forName("com.mysql.jdbc.Driver");
  45. Properties connectionProperties = new Properties();
  46. connectionProperties.put("user", configInstance.getMySQLUserName());
  47. connectionProperties.put("password", configInstance.getMySQLUserPassword());
  48. connectionProperties.put("autoReconnect", "false");
  49. connectionProperties.put("maxReconnects", "0");
  50. connection = DriverManager.getConnection(connectionString, connectionProperties);
  51. mcMMO.p.getLogger().info("Connection to MySQL was a success!");
  52. } catch (SQLException ex) {
  53. connection = null;
  54. if(reconnectAttempt == 0 || reconnectAttempt >= 11) mcMMO.p.getLogger().info("Connection to MySQL failed!");
  55. } catch (ClassNotFoundException ex) {
  56. connection = null;
  57. if(reconnectAttempt == 0 || reconnectAttempt >= 11) mcMMO.p.getLogger().info("MySQL database driver not found!");
  58. }
  59. }
  60. /**
  61. * Attempt to create the database structure.
  62. */
  63. public void createStructure() {
  64. write("CREATE TABLE IF NOT EXISTS `" + tablePrefix + "huds` (`user_id` int(10) unsigned NOT NULL,"
  65. + "`hudtype` varchar(50) NOT NULL DEFAULT 'STANDARD',"
  66. + "PRIMARY KEY (`user_id`)) ENGINE=MyISAM DEFAULT CHARSET=latin1;");
  67. write("CREATE TABLE IF NOT EXISTS `" + tablePrefix + "users` (`id` int(10) unsigned NOT NULL AUTO_INCREMENT,"
  68. + "`user` varchar(40) NOT NULL,"
  69. + "`lastlogin` int(32) unsigned NOT NULL,"
  70. + "PRIMARY KEY (`id`),"
  71. + "UNIQUE KEY `user` (`user`)) ENGINE=MyISAM DEFAULT CHARSET=latin1 AUTO_INCREMENT=1;");
  72. write("CREATE TABLE IF NOT EXISTS `" + tablePrefix + "cooldowns` (`user_id` int(10) unsigned NOT NULL,"
  73. + "`taming` int(32) unsigned NOT NULL DEFAULT '0',"
  74. + "`mining` int(32) unsigned NOT NULL DEFAULT '0',"
  75. + "`woodcutting` int(32) unsigned NOT NULL DEFAULT '0',"
  76. + "`repair` int(32) unsigned NOT NULL DEFAULT '0',"
  77. + "`unarmed` int(32) unsigned NOT NULL DEFAULT '0',"
  78. + "`herbalism` int(32) unsigned NOT NULL DEFAULT '0',"
  79. + "`excavation` int(32) unsigned NOT NULL DEFAULT '0',"
  80. + "`archery` int(32) unsigned NOT NULL DEFAULT '0',"
  81. + "`swords` int(32) unsigned NOT NULL DEFAULT '0',"
  82. + "`axes` int(32) unsigned NOT NULL DEFAULT '0',"
  83. + "`acrobatics` int(32) unsigned NOT NULL DEFAULT '0',"
  84. + "`blast_mining` int(32) unsigned NOT NULL DEFAULT '0',"
  85. + "PRIMARY KEY (`user_id`)) ENGINE=MyISAM DEFAULT CHARSET=latin1;");
  86. write("CREATE TABLE IF NOT EXISTS `" + tablePrefix + "skills` (`user_id` int(10) unsigned NOT NULL,"
  87. + "`taming` int(10) unsigned NOT NULL DEFAULT '0',"
  88. + "`mining` int(10) unsigned NOT NULL DEFAULT '0',"
  89. + "`woodcutting` int(10) unsigned NOT NULL DEFAULT '0',"
  90. + "`repair` int(10) unsigned NOT NULL DEFAULT '0',"
  91. + "`unarmed` int(10) unsigned NOT NULL DEFAULT '0',"
  92. + "`herbalism` int(10) unsigned NOT NULL DEFAULT '0',"
  93. + "`excavation` int(10) unsigned NOT NULL DEFAULT '0',"
  94. + "`archery` int(10) unsigned NOT NULL DEFAULT '0',"
  95. + "`swords` int(10) unsigned NOT NULL DEFAULT '0',"
  96. + "`axes` int(10) unsigned NOT NULL DEFAULT '0',"
  97. + "`acrobatics` int(10) unsigned NOT NULL DEFAULT '0',"
  98. + "PRIMARY KEY (`user_id`)) ENGINE=MyISAM DEFAULT CHARSET=latin1;");
  99. write("CREATE TABLE IF NOT EXISTS `" + tablePrefix + "experience` (`user_id` int(10) unsigned NOT NULL,"
  100. + "`taming` int(10) unsigned NOT NULL DEFAULT '0',"
  101. + "`mining` int(10) unsigned NOT NULL DEFAULT '0',"
  102. + "`woodcutting` int(10) unsigned NOT NULL DEFAULT '0',"
  103. + "`repair` int(10) unsigned NOT NULL DEFAULT '0',"
  104. + "`unarmed` int(10) unsigned NOT NULL DEFAULT '0',"
  105. + "`herbalism` int(10) unsigned NOT NULL DEFAULT '0',"
  106. + "`excavation` int(10) unsigned NOT NULL DEFAULT '0',"
  107. + "`archery` int(10) unsigned NOT NULL DEFAULT '0',"
  108. + "`swords` int(10) unsigned NOT NULL DEFAULT '0',"
  109. + "`axes` int(10) unsigned NOT NULL DEFAULT '0',"
  110. + "`acrobatics` int(10) unsigned NOT NULL DEFAULT '0',"
  111. + "PRIMARY KEY (`user_id`)) ENGINE=MyISAM DEFAULT CHARSET=latin1;");
  112. checkDatabaseStructure(DatabaseUpdate.FISHING);
  113. checkDatabaseStructure(DatabaseUpdate.BLAST_MINING);
  114. }
  115. /**
  116. * Check database structure for missing values.
  117. *
  118. * @param update Type of data to check updates for
  119. */
  120. public void checkDatabaseStructure(DatabaseUpdate update) {
  121. String sql = null;
  122. ResultSet resultSet = null;
  123. HashMap<Integer, ArrayList<String>> rows = new HashMap<Integer, ArrayList<String>>();
  124. switch (update) {
  125. case BLAST_MINING:
  126. sql = "SELECT * FROM `" + tablePrefix + "cooldowns` ORDER BY `" + tablePrefix + "cooldowns`.`blast_mining` ASC LIMIT 0 , 30";
  127. break;
  128. case FISHING:
  129. sql = "SELECT * FROM `" + tablePrefix + "experience` ORDER BY `" + tablePrefix + "experience`.`fishing` ASC LIMIT 0 , 30";
  130. break;
  131. default:
  132. break;
  133. }
  134. PreparedStatement statement = null;
  135. try {
  136. if(!checkConnected()) return;
  137. statement = connection.prepareStatement(sql);
  138. resultSet = statement.executeQuery();
  139. while (resultSet.next()) {
  140. ArrayList<String> column = new ArrayList<String>();
  141. for (int i = 1; i <= resultSet.getMetaData().getColumnCount(); i++) {
  142. column.add(resultSet.getString(i));
  143. }
  144. rows.put(resultSet.getRow(), column);
  145. }
  146. }
  147. catch (SQLException ex) {
  148. switch (update) {
  149. case BLAST_MINING:
  150. mcMMO.p.getLogger().info("Updating mcMMO MySQL tables for Blast Mining...");
  151. write("ALTER TABLE `"+tablePrefix + "cooldowns` ADD `blast_mining` int(32) NOT NULL DEFAULT '0' ;");
  152. break;
  153. case FISHING:
  154. mcMMO.p.getLogger().info("Updating mcMMO MySQL tables for Fishing...");
  155. write("ALTER TABLE `"+tablePrefix + "skills` ADD `fishing` int(10) NOT NULL DEFAULT '0' ;");
  156. write("ALTER TABLE `"+tablePrefix + "experience` ADD `fishing` int(10) NOT NULL DEFAULT '0' ;");
  157. break;
  158. default:
  159. break;
  160. }
  161. } finally {
  162. if (resultSet != null) {
  163. try {
  164. resultSet.close();
  165. } catch (SQLException e) {
  166. // Ignore the error, we're leaving
  167. }
  168. }
  169. if (statement != null) {
  170. try {
  171. statement.close();
  172. } catch (SQLException e) {
  173. // Ignore the error, we're leaving
  174. }
  175. }
  176. }
  177. }
  178. /**
  179. * Attempt to write the SQL query.
  180. *
  181. * @param sql Query to write.
  182. * @return true if the query was successfully written, false otherwise.
  183. */
  184. public boolean write(String sql) {
  185. if (checkConnected()) {
  186. PreparedStatement statement = null;
  187. try {
  188. statement = connection.prepareStatement(sql);
  189. statement.executeUpdate();
  190. return true;
  191. }
  192. catch (SQLException ex) {
  193. printErrors(ex);
  194. return false;
  195. } finally {
  196. if (statement != null) {
  197. try {
  198. statement.close();
  199. } catch (SQLException e) {
  200. printErrors(e);
  201. return false;
  202. }
  203. }
  204. }
  205. }
  206. return false;
  207. }
  208. /**
  209. * Get the Integer. Only return first row / first field.
  210. *
  211. * @param sql SQL query to execute
  212. * @return the value in the first row / first field
  213. */
  214. public int getInt(String sql) {
  215. ResultSet resultSet;
  216. int result = 0;
  217. if (checkConnected()) {
  218. try {
  219. PreparedStatement statement = connection.prepareStatement(sql);
  220. resultSet = statement.executeQuery();
  221. if (resultSet.next()) {
  222. result = resultSet.getInt(1);
  223. }
  224. else {
  225. result = 0;
  226. }
  227. statement.close();
  228. }
  229. catch (SQLException ex) {
  230. printErrors(ex);
  231. }
  232. }
  233. return result;
  234. }
  235. /**
  236. * Check connection status and re-establish if dead or stale.
  237. *
  238. * If the very first immediate attempt fails, further attempts
  239. * will be made in progressively larger intervals up to MAX_WAIT
  240. * intervals.
  241. *
  242. * This allows for MySQL to time out idle connections as needed by
  243. * server operator, without affecting McMMO, while still providing
  244. * protection against a database outage taking down Bukkit's tick
  245. * processing loop due to attemping a database connection each
  246. * time McMMO needs the database.
  247. *
  248. * @return the boolean value for whether or not we are connected
  249. */
  250. public static boolean checkConnected() {
  251. boolean isClosed = true;
  252. boolean isValid = false;
  253. boolean exists = (connection != null);
  254. // Initialized as needed later
  255. long timestamp=0;
  256. // If we're waiting for server to recover then leave early
  257. if (nextReconnectTimestamp > 0 && nextReconnectTimestamp > System.nanoTime()) {
  258. return false;
  259. }
  260. if (exists) {
  261. try {
  262. isClosed = connection.isClosed();
  263. } catch (SQLException e) {
  264. isClosed = true;
  265. e.printStackTrace();
  266. printErrors(e);
  267. }
  268. if (!isClosed) {
  269. try {
  270. isValid = connection.isValid(VALID_TIMEOUT);
  271. } catch (SQLException e) {
  272. // Don't print stack trace because it's valid to lose idle connections
  273. // to the server and have to restart them.
  274. isValid = false;
  275. }
  276. }
  277. }
  278. // Leave if all ok
  279. if (exists && !isClosed && isValid) {
  280. // Housekeeping
  281. nextReconnectTimestamp = 0;
  282. reconnectAttempt = 0;
  283. return true;
  284. }
  285. // Cleanup after ourselves for GC and MySQL's sake
  286. if (exists && !isClosed) {
  287. try {
  288. connection.close();
  289. } catch (SQLException ex) {
  290. // This is a housekeeping exercise, ignore errors
  291. }
  292. }
  293. // Try to connect again
  294. connect();
  295. // Leave if connection is good
  296. try {
  297. if (connection != null && !connection.isClosed()) {
  298. // Schedule a database save if we really had an outage
  299. if (reconnectAttempt > 1) {
  300. plugin.getServer().getScheduler().scheduleSyncDelayedTask(plugin, new SQLReconnect(plugin), 5);
  301. }
  302. nextReconnectTimestamp = 0;
  303. reconnectAttempt = 0;
  304. return true;
  305. }
  306. } catch (SQLException e) {
  307. // Failed to check isClosed, so presume connection is bad and attempt later
  308. e.printStackTrace();
  309. printErrors(e);
  310. }
  311. reconnectAttempt++;
  312. nextReconnectTimestamp = (long)(System.nanoTime() + Math.min(MAX_WAIT, (reconnectAttempt*SCALING_FACTOR*MIN_WAIT)));
  313. return false;
  314. }
  315. /**
  316. * Read SQL query.
  317. *
  318. * @param sql SQL query to read
  319. * @return the rows in this SQL query
  320. */
  321. public HashMap<Integer, ArrayList<String>> read(String sql) {
  322. ResultSet resultSet;
  323. HashMap<Integer, ArrayList<String>> rows = new HashMap<Integer, ArrayList<String>>();
  324. if (checkConnected()) {
  325. try {
  326. PreparedStatement statement = connection.prepareStatement(sql);
  327. resultSet = statement.executeQuery();
  328. while (resultSet.next()) {
  329. ArrayList<String> column = new ArrayList<String>();
  330. for (int i = 1; i <= resultSet.getMetaData().getColumnCount(); i++) {
  331. column.add(resultSet.getString(i));
  332. }
  333. rows.put(resultSet.getRow(), column);
  334. }
  335. statement.close();
  336. }
  337. catch (SQLException ex) {
  338. printErrors(ex);
  339. }
  340. }
  341. return rows;
  342. }
  343. private static void printErrors(SQLException ex) {
  344. System.out.println("SQLException: " + ex.getMessage());
  345. System.out.println("SQLState: " + ex.getSQLState());
  346. System.out.println("VendorError: " + ex.getErrorCode());
  347. }
  348. }