Database.java 25 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586
  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.Map;
  10. import java.util.Properties;
  11. import org.bukkit.Bukkit;
  12. import org.bukkit.entity.Player;
  13. import com.gmail.nossr50.mcMMO;
  14. import com.gmail.nossr50.config.Config;
  15. import com.gmail.nossr50.datatypes.DatabaseUpdate;
  16. import com.gmail.nossr50.datatypes.McMMOPlayer;
  17. import com.gmail.nossr50.datatypes.SkillType;
  18. import com.gmail.nossr50.datatypes.SpoutHud;
  19. import com.gmail.nossr50.runnables.SQLReconnect;
  20. import com.gmail.nossr50.spout.SpoutStuff;
  21. public class Database {
  22. private static Config configInstance = Config.getInstance();
  23. private static String connectionString;
  24. private static String tablePrefix = configInstance.getMySQLTablePrefix();
  25. private static Connection connection = null;
  26. private static mcMMO plugin = null;
  27. // Scale waiting time by this much per failed attempt
  28. private static final double SCALING_FACTOR = 40;
  29. // Minimum wait in nanoseconds (default 500ms)
  30. private static final long MIN_WAIT = 500L*1000000L;
  31. // Maximum time to wait between reconnects (default 5 minutes)
  32. private static final long MAX_WAIT = 5L * 60L * 1000L * 1000000L;
  33. // How long to wait when checking if connection is valid (default 3 seconds)
  34. private static final int VALID_TIMEOUT = 3;
  35. // When next to try connecting to Database in nanoseconds
  36. private static long nextReconnectTimestamp = 0L;
  37. // How many connection attemtps have failed
  38. private static int reconnectAttempt = 0;
  39. public Database(mcMMO instance) {
  40. plugin = instance;
  41. checkConnected(); //Connect to MySQL
  42. }
  43. /**
  44. * Attempt to connect to the mySQL database.
  45. */
  46. public static void connect() {
  47. connectionString = "jdbc:mysql://" + configInstance.getMySQLServerName() + ":" + configInstance.getMySQLServerPort() + "/" + configInstance.getMySQLDatabaseName();
  48. try {
  49. mcMMO.p.getLogger().info("Attempting connection to MySQL...");
  50. // Force driver to load if not yet loaded
  51. Class.forName("com.mysql.jdbc.Driver");
  52. Properties connectionProperties = new Properties();
  53. connectionProperties.put("user", configInstance.getMySQLUserName());
  54. connectionProperties.put("password", configInstance.getMySQLUserPassword());
  55. connectionProperties.put("autoReconnect", "false");
  56. connectionProperties.put("maxReconnects", "0");
  57. connection = DriverManager.getConnection(connectionString, connectionProperties);
  58. mcMMO.p.getLogger().info("Connection to MySQL was a success!");
  59. } catch (SQLException ex) {
  60. connection = null;
  61. if (reconnectAttempt == 0 || reconnectAttempt >= 11) mcMMO.p.getLogger().info("Connection to MySQL failed!");
  62. } catch (ClassNotFoundException ex) {
  63. connection = null;
  64. if (reconnectAttempt == 0 || reconnectAttempt >= 11) mcMMO.p.getLogger().info("MySQL database driver not found!");
  65. }
  66. }
  67. /**
  68. * Attempt to create the database structure.
  69. */
  70. public void createStructure() {
  71. write("CREATE TABLE IF NOT EXISTS `" + tablePrefix + "users` ("
  72. + "`id` int(10) unsigned NOT NULL AUTO_INCREMENT,"
  73. + "`user` varchar(40) NOT NULL,"
  74. + "`lastlogin` int(32) unsigned NOT NULL,"
  75. + "PRIMARY KEY (`id`),"
  76. + "UNIQUE KEY `user` (`user`)) ENGINE=MyISAM DEFAULT CHARSET=latin1 AUTO_INCREMENT=1;");
  77. write("CREATE TABLE IF NOT EXISTS `" + tablePrefix + "huds` ("
  78. + "`user_id` int(10) unsigned NOT NULL,"
  79. + "`hudtype` varchar(50) NOT NULL DEFAULT 'STANDARD',"
  80. + "PRIMARY KEY (`user_id`),"
  81. + "FOREIGN KEY (`user_id`) REFERENCES `" + tablePrefix + "users` (`id`) "
  82. + "ON DELETE CASCADE) ENGINE=MyISAM DEFAULT CHARSET=latin1;");
  83. write("CREATE TABLE IF NOT EXISTS `" + tablePrefix + "cooldowns` ("
  84. + "`user_id` int(10) unsigned NOT NULL,"
  85. + "`taming` int(32) unsigned NOT NULL DEFAULT '0',"
  86. + "`mining` int(32) unsigned NOT NULL DEFAULT '0',"
  87. + "`woodcutting` int(32) unsigned NOT NULL DEFAULT '0',"
  88. + "`repair` int(32) unsigned NOT NULL DEFAULT '0',"
  89. + "`unarmed` int(32) unsigned NOT NULL DEFAULT '0',"
  90. + "`herbalism` int(32) unsigned NOT NULL DEFAULT '0',"
  91. + "`excavation` int(32) unsigned NOT NULL DEFAULT '0',"
  92. + "`archery` int(32) unsigned NOT NULL DEFAULT '0',"
  93. + "`swords` int(32) unsigned NOT NULL DEFAULT '0',"
  94. + "`axes` int(32) unsigned NOT NULL DEFAULT '0',"
  95. + "`acrobatics` int(32) unsigned NOT NULL DEFAULT '0',"
  96. + "`blast_mining` int(32) unsigned NOT NULL DEFAULT '0',"
  97. + "PRIMARY KEY (`user_id`),"
  98. + "FOREIGN KEY (`user_id`) REFERENCES `" + tablePrefix + "users` (`id`) "
  99. + "ON DELETE CASCADE) ENGINE=MyISAM DEFAULT CHARSET=latin1;");
  100. write("CREATE TABLE IF NOT EXISTS `" + tablePrefix + "skills` ("
  101. + "`user_id` int(10) unsigned NOT NULL,"
  102. + "`taming` int(10) unsigned NOT NULL DEFAULT '0',"
  103. + "`mining` int(10) unsigned NOT NULL DEFAULT '0',"
  104. + "`woodcutting` int(10) unsigned NOT NULL DEFAULT '0',"
  105. + "`repair` int(10) unsigned NOT NULL DEFAULT '0',"
  106. + "`unarmed` int(10) unsigned NOT NULL DEFAULT '0',"
  107. + "`herbalism` int(10) unsigned NOT NULL DEFAULT '0',"
  108. + "`excavation` int(10) unsigned NOT NULL DEFAULT '0',"
  109. + "`archery` int(10) unsigned NOT NULL DEFAULT '0',"
  110. + "`swords` int(10) unsigned NOT NULL DEFAULT '0',"
  111. + "`axes` int(10) unsigned NOT NULL DEFAULT '0',"
  112. + "`acrobatics` int(10) unsigned NOT NULL DEFAULT '0',"
  113. + "PRIMARY KEY (`user_id`),"
  114. + "FOREIGN KEY (`user_id`) REFERENCES `" + tablePrefix + "users` (`id`) "
  115. + "ON DELETE CASCADE) ENGINE=MyISAM DEFAULT CHARSET=latin1;");
  116. write("CREATE TABLE IF NOT EXISTS `" + tablePrefix + "experience` ("
  117. + "`user_id` int(10) unsigned NOT NULL,"
  118. + "`taming` int(10) unsigned NOT NULL DEFAULT '0',"
  119. + "`mining` int(10) unsigned NOT NULL DEFAULT '0',"
  120. + "`woodcutting` int(10) unsigned NOT NULL DEFAULT '0',"
  121. + "`repair` int(10) unsigned NOT NULL DEFAULT '0',"
  122. + "`unarmed` int(10) unsigned NOT NULL DEFAULT '0',"
  123. + "`herbalism` int(10) unsigned NOT NULL DEFAULT '0',"
  124. + "`excavation` int(10) unsigned NOT NULL DEFAULT '0',"
  125. + "`archery` int(10) unsigned NOT NULL DEFAULT '0',"
  126. + "`swords` int(10) unsigned NOT NULL DEFAULT '0',"
  127. + "`axes` int(10) unsigned NOT NULL DEFAULT '0',"
  128. + "`acrobatics` int(10) unsigned NOT NULL DEFAULT '0',"
  129. + "PRIMARY KEY (`user_id`),"
  130. + "FOREIGN KEY (`user_id`) REFERENCES `" + tablePrefix + "users` (`id`) "
  131. + "ON DELETE CASCADE) ENGINE=MyISAM DEFAULT CHARSET=latin1;");
  132. checkDatabaseStructure(DatabaseUpdate.FISHING);
  133. checkDatabaseStructure(DatabaseUpdate.BLAST_MINING);
  134. checkDatabaseStructure(DatabaseUpdate.CASCADE_DELETE);
  135. checkDatabaseStructure(DatabaseUpdate.INDEX);
  136. }
  137. /**
  138. * Check database structure for missing values.
  139. *
  140. * @param update Type of data to check updates for
  141. */
  142. public void checkDatabaseStructure(DatabaseUpdate update) {
  143. String sql = null;
  144. ResultSet resultSet = null;
  145. HashMap<Integer, ArrayList<String>> rows = new HashMap<Integer, ArrayList<String>>();
  146. switch (update) {
  147. case BLAST_MINING:
  148. sql = "SELECT * FROM `" + tablePrefix + "cooldowns` ORDER BY `" + tablePrefix + "cooldowns`.`blast_mining` ASC LIMIT 0 , 30";
  149. break;
  150. case CASCADE_DELETE:
  151. write("ALTER TABLE `" + tablePrefix + "huds` ADD FOREIGN KEY (`user_id`) REFERENCES `users`(`id`) ON DELETE CASCADE;");
  152. write("ALTER TABLE `" + tablePrefix + "experience` ADD FOREIGN KEY (`user_id`) REFERENCES `users`(`id`) ON DELETE CASCADE;");
  153. write("ALTER TABLE `" + tablePrefix + "cooldowns` ADD FOREIGN KEY (`user_id`) REFERENCES `users`(`id`) ON DELETE CASCADE;");
  154. write("ALTER TABLE `" + tablePrefix + "skills` ADD FOREIGN KEY (`user_id`) REFERENCES `users`(`id`) ON DELETE CASCADE;");
  155. case FISHING:
  156. sql = "SELECT * FROM `" + tablePrefix + "experience` ORDER BY `" + tablePrefix + "experience`.`fishing` ASC LIMIT 0 , 30";
  157. break;
  158. case INDEX:
  159. if(read("SHOW INDEX FROM " + tablePrefix + "skills").size() != 13) {
  160. plugin.getLogger().info("Indexing tables, this may take a while on larger databases");
  161. write("ALTER TABLE `" + tablePrefix + "skills` ADD INDEX `idx_taming` (`taming`) USING BTREE, "
  162. + "ADD INDEX `idx_mining` (`mining`) USING BTREE, "
  163. + "ADD INDEX `idx_woodcutting` (`woodcutting`) USING BTREE, "
  164. + "ADD INDEX `idx_repair` (`repair`) USING BTREE, "
  165. + "ADD INDEX `idx_unarmed` (`unarmed`) USING BTREE, "
  166. + "ADD INDEX `idx_herbalism` (`herbalism`) USING BTREE, "
  167. + "ADD INDEX `idx_excavation` (`excavation`) USING BTREE, "
  168. + "ADD INDEX `idx_archery` (`archery`) USING BTREE, "
  169. + "ADD INDEX `idx_swords` (`swords`) USING BTREE, "
  170. + "ADD INDEX `idx_axes` (`axes`) USING BTREE, "
  171. + "ADD INDEX `idx_acrobatics` (`acrobatics`) USING BTREE, "
  172. + "ADD INDEX `idx_fishing` (`fishing`) USING BTREE;");
  173. }
  174. break;
  175. default:
  176. break;
  177. }
  178. PreparedStatement statement = null;
  179. try {
  180. if (!checkConnected()) return;
  181. statement = connection.prepareStatement(sql);
  182. resultSet = statement.executeQuery();
  183. while (resultSet.next()) {
  184. ArrayList<String> column = new ArrayList<String>();
  185. for (int i = 1; i <= resultSet.getMetaData().getColumnCount(); i++) {
  186. column.add(resultSet.getString(i));
  187. }
  188. rows.put(resultSet.getRow(), column);
  189. }
  190. }
  191. catch (SQLException ex) {
  192. switch (update) {
  193. case BLAST_MINING:
  194. mcMMO.p.getLogger().info("Updating mcMMO MySQL tables for Blast Mining...");
  195. write("ALTER TABLE `"+tablePrefix + "cooldowns` ADD `blast_mining` int(32) NOT NULL DEFAULT '0' ;");
  196. break;
  197. case FISHING:
  198. mcMMO.p.getLogger().info("Updating mcMMO MySQL tables for Fishing...");
  199. write("ALTER TABLE `"+tablePrefix + "skills` ADD `fishing` int(10) NOT NULL DEFAULT '0' ;");
  200. write("ALTER TABLE `"+tablePrefix + "experience` ADD `fishing` int(10) NOT NULL DEFAULT '0' ;");
  201. break;
  202. default:
  203. break;
  204. }
  205. } finally {
  206. if (resultSet != null) {
  207. try {
  208. resultSet.close();
  209. } catch (SQLException e) {
  210. // Ignore the error, we're leaving
  211. }
  212. }
  213. if (statement != null) {
  214. try {
  215. statement.close();
  216. } catch (SQLException e) {
  217. // Ignore the error, we're leaving
  218. }
  219. }
  220. }
  221. }
  222. /**
  223. * Attempt to write the SQL query.
  224. *
  225. * @param sql Query to write.
  226. * @return true if the query was successfully written, false otherwise.
  227. */
  228. public boolean write(String sql) {
  229. if (checkConnected()) {
  230. PreparedStatement statement = null;
  231. try {
  232. statement = connection.prepareStatement(sql);
  233. statement.executeUpdate();
  234. statement.close();
  235. return true;
  236. }
  237. catch (SQLException ex) {
  238. printErrors(ex);
  239. return false;
  240. } finally {
  241. if (statement != null) {
  242. try {
  243. statement.close();
  244. } catch (SQLException e) {
  245. printErrors(e);
  246. return false;
  247. }
  248. }
  249. }
  250. }
  251. return false;
  252. }
  253. /**
  254. * Returns the number of rows affected by either a DELETE or UPDATE query
  255. *
  256. * @param sql SQL query to execute
  257. * @return the number of rows affected
  258. */
  259. public int update(String sql) {
  260. int ret = 0;
  261. if (checkConnected()) {
  262. PreparedStatement statement = null;
  263. try {
  264. statement = connection.prepareStatement(sql);
  265. ret = statement.executeUpdate();
  266. statement.close();
  267. return ret;
  268. } catch (SQLException ex) {
  269. printErrors(ex);
  270. return 0;
  271. } finally {
  272. if (statement != null) {
  273. try {
  274. statement.close();
  275. } catch (SQLException e) {
  276. printErrors(e);
  277. return 0;
  278. }
  279. }
  280. }
  281. }
  282. return ret;
  283. }
  284. /**
  285. * Get the Integer. Only return first row / first field.
  286. *
  287. * @param sql SQL query to execute
  288. * @return the value in the first row / first field
  289. */
  290. public int getInt(String sql) {
  291. ResultSet resultSet;
  292. int result = 0;
  293. if (checkConnected()) {
  294. try {
  295. PreparedStatement statement = connection.prepareStatement(sql);
  296. resultSet = statement.executeQuery();
  297. if (resultSet.next()) {
  298. result = resultSet.getInt(1);
  299. }
  300. else {
  301. result = 0;
  302. }
  303. statement.close();
  304. }
  305. catch (SQLException ex) {
  306. printErrors(ex);
  307. }
  308. }
  309. return result;
  310. }
  311. /**
  312. * Check connection status and re-establish if dead or stale.
  313. *
  314. * If the very first immediate attempt fails, further attempts
  315. * will be made in progressively larger intervals up to MAX_WAIT
  316. * intervals.
  317. *
  318. * This allows for MySQL to time out idle connections as needed by
  319. * server operator, without affecting McMMO, while still providing
  320. * protection against a database outage taking down Bukkit's tick
  321. * processing loop due to attemping a database connection each
  322. * time McMMO needs the database.
  323. *
  324. * @return the boolean value for whether or not we are connected
  325. */
  326. public static boolean checkConnected() {
  327. boolean isClosed = true;
  328. boolean isValid = false;
  329. boolean exists = (connection != null);
  330. // If we're waiting for server to recover then leave early
  331. if (nextReconnectTimestamp > 0 && nextReconnectTimestamp > System.nanoTime()) {
  332. return false;
  333. }
  334. if (exists) {
  335. try {
  336. isClosed = connection.isClosed();
  337. } catch (SQLException e) {
  338. isClosed = true;
  339. e.printStackTrace();
  340. printErrors(e);
  341. }
  342. if (!isClosed) {
  343. try {
  344. isValid = connection.isValid(VALID_TIMEOUT);
  345. } catch (SQLException e) {
  346. // Don't print stack trace because it's valid to lose idle connections
  347. // to the server and have to restart them.
  348. isValid = false;
  349. }
  350. }
  351. }
  352. // Leave if all ok
  353. if (exists && !isClosed && isValid) {
  354. // Housekeeping
  355. nextReconnectTimestamp = 0;
  356. reconnectAttempt = 0;
  357. return true;
  358. }
  359. // Cleanup after ourselves for GC and MySQL's sake
  360. if (exists && !isClosed) {
  361. try {
  362. connection.close();
  363. } catch (SQLException ex) {
  364. // This is a housekeeping exercise, ignore errors
  365. }
  366. }
  367. // Try to connect again
  368. connect();
  369. // Leave if connection is good
  370. try {
  371. if (connection != null && !connection.isClosed()) {
  372. // Schedule a database save if we really had an outage
  373. if (reconnectAttempt > 1) {
  374. plugin.getServer().getScheduler().scheduleSyncDelayedTask(plugin, new SQLReconnect(plugin), 5);
  375. }
  376. nextReconnectTimestamp = 0;
  377. reconnectAttempt = 0;
  378. return true;
  379. }
  380. } catch (SQLException e) {
  381. // Failed to check isClosed, so presume connection is bad and attempt later
  382. e.printStackTrace();
  383. printErrors(e);
  384. }
  385. reconnectAttempt++;
  386. nextReconnectTimestamp = (long)(System.nanoTime() + Math.min(MAX_WAIT, (reconnectAttempt*SCALING_FACTOR*MIN_WAIT)));
  387. return false;
  388. }
  389. /**
  390. * Read SQL query.
  391. *
  392. * @param sql SQL query to read
  393. * @return the rows in this SQL query
  394. */
  395. public HashMap<Integer, ArrayList<String>> read(String sql) {
  396. ResultSet resultSet;
  397. HashMap<Integer, ArrayList<String>> rows = new HashMap<Integer, ArrayList<String>>();
  398. if (checkConnected()) {
  399. try {
  400. PreparedStatement statement = connection.prepareStatement(sql);
  401. resultSet = statement.executeQuery();
  402. while (resultSet.next()) {
  403. ArrayList<String> column = new ArrayList<String>();
  404. for (int i = 1; i <= resultSet.getMetaData().getColumnCount(); i++) {
  405. column.add(resultSet.getString(i));
  406. }
  407. rows.put(resultSet.getRow(), column);
  408. }
  409. statement.close();
  410. }
  411. catch (SQLException ex) {
  412. printErrors(ex);
  413. }
  414. }
  415. return rows;
  416. }
  417. public Map<String, Integer> readSQLRank(String playerName) {
  418. ResultSet resultSet;
  419. Map<String, Integer> skills = new HashMap<String, Integer>();
  420. if (checkConnected()) {
  421. try {
  422. for (SkillType skillType: SkillType.values()) {
  423. String sql;
  424. if(skillType != SkillType.ALL) {
  425. sql = "SELECT COUNT(*) AS rank FROM " + tablePrefix + "users JOIN " + tablePrefix + "skills ON user_id = id WHERE " + skillType.name().toLowerCase() + " > 0 AND " + skillType.name().toLowerCase() + " > (SELECT " + skillType.name().toLowerCase() + " FROM " + tablePrefix + "users JOIN " + tablePrefix + "skills ON user_id = id WHERE user = '" + playerName + "')";
  426. } else {
  427. sql = "SELECT COUNT(*) AS rank FROM " + tablePrefix + "users JOIN " + tablePrefix + "skills ON user_id = id WHERE taming+mining+woodcutting+repair+unarmed+herbalism+excavation+archery+swords+axes+acrobatics+fishing > 0 AND taming+mining+woodcutting+repair+unarmed+herbalism+excavation+archery+swords+axes+acrobatics+fishing > (SELECT taming+mining+woodcutting+repair+unarmed+herbalism+excavation+archery+swords+axes+acrobatics+fishing FROM " + tablePrefix + "users JOIN " + tablePrefix + "skills ON user_id = id WHERE user = '" + playerName + "')";
  428. }
  429. PreparedStatement statement = connection.prepareStatement(sql);
  430. resultSet = statement.executeQuery();
  431. resultSet.next();
  432. int rank = resultSet.getInt("rank");
  433. if(skillType != SkillType.ALL) {
  434. sql = "SELECT user, " + skillType.name().toLowerCase() + " FROM " + tablePrefix + "users JOIN " + tablePrefix + "skills ON user_id = id WHERE " + skillType.name().toLowerCase() + " > 0 AND " + skillType.name().toLowerCase() + " = (SELECT " + skillType.name().toLowerCase() + " FROM " + tablePrefix + "users JOIN " + tablePrefix + "skills ON user_id = id WHERE user = '" + playerName + "') ORDER BY " + skillType.name().toLowerCase() + " desc";
  435. } else {
  436. sql = "SELECT user, taming+mining+woodcutting+repair+unarmed+herbalism+excavation+archery+swords+axes+acrobatics+fishing FROM " + tablePrefix + "users JOIN " + tablePrefix + "skills ON user_id = id WHERE taming+mining+woodcutting+repair+unarmed+herbalism+excavation+archery+swords+axes+acrobatics+fishing > 0 AND taming+mining+woodcutting+repair+unarmed+herbalism+excavation+archery+swords+axes+acrobatics+fishing = (SELECT taming+mining+woodcutting+repair+unarmed+herbalism+excavation+archery+swords+axes+acrobatics+fishing FROM " + tablePrefix + "users JOIN " + tablePrefix + "skills ON user_id = id WHERE user = '" + playerName + "') ORDER BY taming+mining+woodcutting+repair+unarmed+herbalism+excavation+archery+swords+axes+acrobatics+fishing desc";
  437. }
  438. statement = connection.prepareStatement(sql);
  439. resultSet = statement.executeQuery();
  440. while (resultSet.next()) {
  441. if(resultSet.getString("user").equalsIgnoreCase(playerName)) {
  442. skills.put(skillType.name(), rank + resultSet.getRow());
  443. break;
  444. }
  445. }
  446. statement.close();
  447. }
  448. }
  449. catch (SQLException ex) {
  450. printErrors(ex);
  451. }
  452. }
  453. return skills;
  454. }
  455. public void purgePowerlessSQL() {
  456. plugin.getLogger().info("Purging powerless users...");
  457. HashMap<Integer, ArrayList<String>> usernames = read("SELECT u.user FROM " + tablePrefix + "skills AS s, " + tablePrefix + "users AS u WHERE s.user_id = u.id AND (s.taming+s.mining+s.woodcutting+s.repair+s.unarmed+s.herbalism+s.excavation+s.archery+s.swords+s.axes+s.acrobatics+s.fishing) = 0");
  458. write("DELETE FROM " + tablePrefix + "users WHERE " + tablePrefix + "users.id IN (SELECT * FROM (SELECT u.id FROM " + tablePrefix + "skills AS s, " + tablePrefix + "users AS u WHERE s.user_id = u.id AND (s.taming+s.mining+s.woodcutting+s.repair+s.unarmed+s.herbalism+s.excavation+s.archery+s.swords+s.axes+s.acrobatics+s.fishing) = 0) AS p)");
  459. int purgedUsers = 0;
  460. for (int i = 1; i <= usernames.size(); i++) {
  461. String playerName = usernames.get(i).get(0);
  462. if (playerName == null || Bukkit.getOfflinePlayer(playerName).isOnline()) {
  463. continue;
  464. }
  465. profileCleanup(playerName);
  466. purgedUsers++;
  467. }
  468. plugin.getLogger().info("Purged " + purgedUsers + " users from the database.");
  469. }
  470. public void purgeOldSQL() {
  471. plugin.getLogger().info("Purging old users...");
  472. long currentTime = System.currentTimeMillis();
  473. long purgeTime = 2630000000L * Config.getInstance().getOldUsersCutoff();
  474. HashMap<Integer, ArrayList<String>> usernames = read("SELECT user FROM " + tablePrefix + "users WHERE ((" + currentTime + " - lastlogin*1000) > " + purgeTime + ")");
  475. write("DELETE FROM " + tablePrefix + "users WHERE " + tablePrefix + "users.id IN (SELECT * FROM (SELECT id FROM " + tablePrefix + "users WHERE ((" + currentTime + " - lastlogin*1000) > " + purgeTime + ")) AS p)");
  476. int purgedUsers = 0;
  477. for (int i = 1; i <= usernames.size(); i++) {
  478. String playerName = usernames.get(i).get(0);
  479. if (playerName == null) {
  480. continue;
  481. }
  482. profileCleanup(playerName);
  483. purgedUsers++;
  484. }
  485. plugin.getLogger().info("Purged " + purgedUsers + " users from the database.");
  486. }
  487. private static void printErrors(SQLException ex) {
  488. System.out.println("SQLException: " + ex.getMessage());
  489. System.out.println("SQLState: " + ex.getSQLState());
  490. System.out.println("VendorError: " + ex.getErrorCode());
  491. }
  492. public static void profileCleanup(String playerName) {
  493. McMMOPlayer mcmmoPlayer = Users.getPlayer(playerName);
  494. if (mcmmoPlayer != null) {
  495. Player player = mcmmoPlayer.getPlayer();
  496. SpoutHud spoutHud = mcmmoPlayer.getProfile().getSpoutHud();
  497. if (spoutHud != null) {
  498. spoutHud.removeWidgets();
  499. }
  500. Users.remove(playerName);
  501. if (player.isOnline()) {
  502. Users.addUser(player);
  503. if (mcMMO.spoutEnabled) {
  504. SpoutStuff.reloadSpoutPlayer(player);
  505. }
  506. }
  507. }
  508. }
  509. }