SQLDatabaseManager.java 49 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251
  1. package com.gmail.nossr50.database;
  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.sql.Statement;
  8. import java.util.ArrayList;
  9. import java.util.Collection;
  10. import java.util.HashMap;
  11. import java.util.List;
  12. import java.util.Map;
  13. import java.util.Properties;
  14. import com.gmail.nossr50.mcMMO;
  15. import com.gmail.nossr50.config.Config;
  16. import com.gmail.nossr50.datatypes.MobHealthbarType;
  17. import com.gmail.nossr50.datatypes.database.DatabaseType;
  18. import com.gmail.nossr50.datatypes.database.DatabaseUpdateType;
  19. import com.gmail.nossr50.datatypes.database.PlayerStat;
  20. import com.gmail.nossr50.datatypes.player.PlayerProfile;
  21. import com.gmail.nossr50.datatypes.skills.AbilityType;
  22. import com.gmail.nossr50.datatypes.skills.SkillType;
  23. import com.gmail.nossr50.runnables.database.SQLDatabaseKeepaliveTask;
  24. import com.gmail.nossr50.runnables.database.SQLReconnectTask;
  25. import com.gmail.nossr50.util.Misc;
  26. public final class SQLDatabaseManager implements DatabaseManager {
  27. private String connectionString;
  28. private String tablePrefix = Config.getInstance().getMySQLTablePrefix();
  29. private Connection connection = null;
  30. // Scale waiting time by this much per failed attempt
  31. private final double SCALING_FACTOR = 40.0;
  32. // Minimum wait in nanoseconds (default 500ms)
  33. private final long MIN_WAIT = 500L * 1000000L;
  34. // Maximum time to wait between reconnects (default 5 minutes)
  35. private final long MAX_WAIT = 5L * 60L * 1000L * 1000000L;
  36. // How long to wait when checking if connection is valid (default 3 seconds)
  37. private final int VALID_TIMEOUT = 3;
  38. // When next to try connecting to Database in nanoseconds
  39. private long nextReconnectTimestamp = 0L;
  40. // How many connection attempts have failed
  41. private int reconnectAttempt = 0;
  42. protected SQLDatabaseManager() {
  43. checkStructure();
  44. new SQLDatabaseKeepaliveTask(this).runTaskTimerAsynchronously(mcMMO.p, 10, 60L * 60 * Misc.TICK_CONVERSION_FACTOR);
  45. }
  46. public void purgePowerlessUsers() {
  47. if (!checkConnected()) {
  48. return;
  49. }
  50. mcMMO.p.getLogger().info("Purging powerless users...");
  51. Collection<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").values();
  52. write("DELETE FROM u, e, h, s, c USING " + tablePrefix + "users u " +
  53. "JOIN " + tablePrefix + "experience e ON (u.id = e.user_id) " +
  54. "JOIN " + tablePrefix + "huds h ON (u.id = h.user_id) " +
  55. "JOIN " + tablePrefix + "skills s ON (u.id = s.user_id) " +
  56. "JOIN " + tablePrefix + "cooldowns c ON (u.id = c.user_id) " +
  57. "WHERE (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");
  58. processPurge(usernames);
  59. mcMMO.p.getLogger().info("Purged " + usernames.size() + " users from the database.");
  60. }
  61. public void purgeOldUsers() {
  62. if (!checkConnected()) {
  63. return;
  64. }
  65. long currentTime = System.currentTimeMillis();
  66. mcMMO.p.getLogger().info("Purging old users...");
  67. Collection<ArrayList<String>> usernames = read("SELECT user FROM " + tablePrefix + "users WHERE ((" + currentTime + " - lastlogin * " + Misc.TIME_CONVERSION_FACTOR + ") > " + PURGE_TIME + ")").values();
  68. write("DELETE FROM u, e, h, s, c USING " + tablePrefix + "users u " +
  69. "JOIN " + tablePrefix + "experience e ON (u.id = e.user_id) " +
  70. "JOIN " + tablePrefix + "huds h ON (u.id = h.user_id) " +
  71. "JOIN " + tablePrefix + "skills s ON (u.id = s.user_id) " +
  72. "JOIN " + tablePrefix + "cooldowns c ON (u.id = c.user_id) " +
  73. "WHERE ((" + currentTime + " - lastlogin * " + Misc.TIME_CONVERSION_FACTOR + ") > " + PURGE_TIME + ")");
  74. processPurge(usernames);
  75. mcMMO.p.getLogger().info("Purged " + usernames.size() + " users from the database.");
  76. }
  77. public boolean removeUser(String playerName) {
  78. if (!checkConnected()) {
  79. return false;
  80. }
  81. boolean success = update("DELETE FROM u, e, h, s, c " +
  82. "USING " + tablePrefix + "users u " +
  83. "JOIN " + tablePrefix + "experience e ON (u.id = e.user_id) " +
  84. "JOIN " + tablePrefix + "huds h ON (u.id = h.user_id) " +
  85. "JOIN " + tablePrefix + "skills s ON (u.id = s.user_id) " +
  86. "JOIN " + tablePrefix + "cooldowns c ON (u.id = c.user_id) " +
  87. "WHERE u.user = '" + playerName + "'") != 0;
  88. Misc.profileCleanup(playerName);
  89. return success;
  90. }
  91. public boolean saveUser(PlayerProfile profile) {
  92. if (!checkConnected()) {
  93. return false;
  94. }
  95. int userId = readId(profile.getPlayerName());
  96. if (userId == -1) {
  97. newUser(profile.getPlayerName());
  98. userId = readId(profile.getPlayerName());
  99. if (userId == -1) {
  100. return false;
  101. }
  102. }
  103. boolean success = true;
  104. MobHealthbarType mobHealthbarType = profile.getMobHealthbarType();
  105. success &= saveLogin(userId, ((int) (System.currentTimeMillis() / Misc.TIME_CONVERSION_FACTOR)));
  106. success &= saveHuds(userId, (mobHealthbarType == null ? Config.getInstance().getMobHealthbarDefault().toString() : mobHealthbarType.toString()));
  107. success &= saveLongs(
  108. "UPDATE " + tablePrefix + "cooldowns SET "
  109. + " mining = ?, woodcutting = ?, unarmed = ?"
  110. + ", herbalism = ?, excavation = ?, swords = ?"
  111. + ", axes = ?, blast_mining = ? WHERE user_id = ?",
  112. userId,
  113. profile.getSkillDATS(AbilityType.SUPER_BREAKER),
  114. profile.getSkillDATS(AbilityType.TREE_FELLER),
  115. profile.getSkillDATS(AbilityType.BERSERK),
  116. profile.getSkillDATS(AbilityType.GREEN_TERRA),
  117. profile.getSkillDATS(AbilityType.GIGA_DRILL_BREAKER),
  118. profile.getSkillDATS(AbilityType.SERRATED_STRIKES),
  119. profile.getSkillDATS(AbilityType.SKULL_SPLITTER),
  120. profile.getSkillDATS(AbilityType.BLAST_MINING));
  121. success &= saveIntegers(
  122. "UPDATE " + tablePrefix + "skills SET "
  123. + " taming = ?, mining = ?, repair = ?, woodcutting = ?"
  124. + ", unarmed = ?, herbalism = ?, excavation = ?"
  125. + ", archery = ?, swords = ?, axes = ?, acrobatics = ?"
  126. + ", fishing = ? WHERE user_id = ?",
  127. profile.getSkillLevel(SkillType.TAMING),
  128. profile.getSkillLevel(SkillType.MINING),
  129. profile.getSkillLevel(SkillType.REPAIR),
  130. profile.getSkillLevel(SkillType.WOODCUTTING),
  131. profile.getSkillLevel(SkillType.UNARMED),
  132. profile.getSkillLevel(SkillType.HERBALISM),
  133. profile.getSkillLevel(SkillType.EXCAVATION),
  134. profile.getSkillLevel(SkillType.ARCHERY),
  135. profile.getSkillLevel(SkillType.SWORDS),
  136. profile.getSkillLevel(SkillType.AXES),
  137. profile.getSkillLevel(SkillType.ACROBATICS),
  138. profile.getSkillLevel(SkillType.FISHING),
  139. userId);
  140. success &= saveIntegers(
  141. "UPDATE " + tablePrefix + "experience SET "
  142. + " taming = ?, mining = ?, repair = ?, woodcutting = ?"
  143. + ", unarmed = ?, herbalism = ?, excavation = ?"
  144. + ", archery = ?, swords = ?, axes = ?, acrobatics = ?"
  145. + ", fishing = ? WHERE user_id = ?",
  146. profile.getSkillXpLevel(SkillType.TAMING),
  147. profile.getSkillXpLevel(SkillType.MINING),
  148. profile.getSkillXpLevel(SkillType.REPAIR),
  149. profile.getSkillXpLevel(SkillType.WOODCUTTING),
  150. profile.getSkillXpLevel(SkillType.UNARMED),
  151. profile.getSkillXpLevel(SkillType.HERBALISM),
  152. profile.getSkillXpLevel(SkillType.EXCAVATION),
  153. profile.getSkillXpLevel(SkillType.ARCHERY),
  154. profile.getSkillXpLevel(SkillType.SWORDS),
  155. profile.getSkillXpLevel(SkillType.AXES),
  156. profile.getSkillXpLevel(SkillType.ACROBATICS),
  157. profile.getSkillXpLevel(SkillType.FISHING),
  158. userId);
  159. return success;
  160. }
  161. public List<PlayerStat> readLeaderboard(String skillName, int pageNumber, int statsPerPage) {
  162. List<PlayerStat> stats = new ArrayList<PlayerStat>();
  163. if (checkConnected()) {
  164. String query = skillName.equalsIgnoreCase("ALL") ? "taming+mining+woodcutting+repair+unarmed+herbalism+excavation+archery+swords+axes+acrobatics+fishing" : skillName;
  165. ResultSet resultSet = null;
  166. PreparedStatement statement = null;
  167. try {
  168. statement = connection.prepareStatement("SELECT " + query + ", user, NOW() FROM " + tablePrefix + "users JOIN " + tablePrefix + "skills ON (user_id = id) WHERE " + query + " > 0 ORDER BY " + query + " DESC, user LIMIT ?, ?");
  169. statement.setInt(1, (pageNumber * statsPerPage) - statsPerPage);
  170. statement.setInt(2, statsPerPage);
  171. resultSet = statement.executeQuery();
  172. while (resultSet.next()) {
  173. ArrayList<String> column = new ArrayList<String>();
  174. for (int i = 1; i <= resultSet.getMetaData().getColumnCount(); i++) {
  175. column.add(resultSet.getString(i));
  176. }
  177. stats.add(new PlayerStat(column.get(1), Integer.valueOf(column.get(0))));
  178. }
  179. }
  180. catch (SQLException ex) {
  181. printErrors(ex);
  182. }
  183. finally {
  184. if (statement != null) {
  185. try {
  186. statement.close();
  187. }
  188. catch (SQLException e) {
  189. // Ignore
  190. }
  191. }
  192. }
  193. }
  194. return stats;
  195. }
  196. public Map<String, Integer> readRank(String playerName) {
  197. Map<String, Integer> skills = new HashMap<String, Integer>();
  198. if (checkConnected()) {
  199. ResultSet resultSet;
  200. try {
  201. for (SkillType skillType : SkillType.NON_CHILD_SKILLS) {
  202. String skillName = skillType.name().toLowerCase();
  203. String sql = "SELECT COUNT(*) AS rank FROM " + tablePrefix + "users JOIN " + tablePrefix + "skills ON user_id = id WHERE " + skillName + " > 0 " +
  204. "AND " + skillName + " > (SELECT " + skillName + " FROM " + tablePrefix + "users JOIN " + tablePrefix + "skills ON user_id = id " +
  205. "WHERE user = ?)";
  206. PreparedStatement statement = connection.prepareStatement(sql);
  207. statement.setString(1, playerName);
  208. resultSet = statement.executeQuery();
  209. resultSet.next();
  210. int rank = resultSet.getInt("rank");
  211. sql = "SELECT user, " + skillName + " FROM " + tablePrefix + "users JOIN " + tablePrefix + "skills ON user_id = id WHERE " + skillName + " > 0 " +
  212. "AND " + skillName + " = (SELECT " + skillName + " FROM " + tablePrefix + "users JOIN " + tablePrefix + "skills ON user_id = id " +
  213. "WHERE user = '" + playerName + "') ORDER BY user";
  214. statement.close();
  215. statement = connection.prepareStatement(sql);
  216. resultSet = statement.executeQuery();
  217. while (resultSet.next()) {
  218. if (resultSet.getString("user").equalsIgnoreCase(playerName)) {
  219. skills.put(skillType.name(), rank + resultSet.getRow());
  220. break;
  221. }
  222. }
  223. statement.close();
  224. }
  225. String sql = "SELECT COUNT(*) AS rank FROM " + tablePrefix + "users JOIN " + tablePrefix + "skills ON user_id = id " +
  226. "WHERE taming+mining+woodcutting+repair+unarmed+herbalism+excavation+archery+swords+axes+acrobatics+fishing > 0 " +
  227. "AND taming+mining+woodcutting+repair+unarmed+herbalism+excavation+archery+swords+axes+acrobatics+fishing > " +
  228. "(SELECT taming+mining+woodcutting+repair+unarmed+herbalism+excavation+archery+swords+axes+acrobatics+fishing " +
  229. "FROM " + tablePrefix + "users JOIN " + tablePrefix + "skills ON user_id = id WHERE user = ?)";
  230. PreparedStatement statement = connection.prepareStatement(sql);
  231. statement.setString(1, playerName);
  232. resultSet = statement.executeQuery();
  233. resultSet.next();
  234. int rank = resultSet.getInt("rank");
  235. statement.close();
  236. sql = "SELECT user, taming+mining+woodcutting+repair+unarmed+herbalism+excavation+archery+swords+axes+acrobatics+fishing " +
  237. "FROM " + tablePrefix + "users JOIN " + tablePrefix + "skills ON user_id = id " +
  238. "WHERE taming+mining+woodcutting+repair+unarmed+herbalism+excavation+archery+swords+axes+acrobatics+fishing > 0 " +
  239. "AND taming+mining+woodcutting+repair+unarmed+herbalism+excavation+archery+swords+axes+acrobatics+fishing = " +
  240. "(SELECT taming+mining+woodcutting+repair+unarmed+herbalism+excavation+archery+swords+axes+acrobatics+fishing " +
  241. "FROM " + tablePrefix + "users JOIN " + tablePrefix + "skills ON user_id = id WHERE user = ?) ORDER BY user";
  242. statement = connection.prepareStatement(sql);
  243. statement.setString(1, playerName);
  244. resultSet = statement.executeQuery();
  245. while (resultSet.next()) {
  246. if (resultSet.getString("user").equalsIgnoreCase(playerName)) {
  247. skills.put("ALL", rank + resultSet.getRow());
  248. break;
  249. }
  250. }
  251. statement.close();
  252. }
  253. catch (SQLException ex) {
  254. printErrors(ex);
  255. }
  256. }
  257. return skills;
  258. }
  259. public void newUser(String playerName) {
  260. if (!checkConnected()) {
  261. return;
  262. }
  263. PreparedStatement statement = null;
  264. try {
  265. statement = connection.prepareStatement("INSERT INTO " + tablePrefix + "users (user, lastlogin) VALUES (?, ?)", Statement.RETURN_GENERATED_KEYS);
  266. statement.setString(1, playerName);
  267. statement.setLong(2, System.currentTimeMillis() / Misc.TIME_CONVERSION_FACTOR);
  268. statement.execute();
  269. int id = readId(playerName);
  270. writeMissingRows(id);
  271. }
  272. catch (SQLException ex) {
  273. printErrors(ex);
  274. }
  275. finally {
  276. if (statement != null) {
  277. try {
  278. statement.close();
  279. }
  280. catch (SQLException e) {
  281. // Ignore
  282. }
  283. }
  284. }
  285. }
  286. public PlayerProfile loadPlayerProfile(String playerName, boolean create) {
  287. return loadPlayerProfile(playerName, create, true);
  288. }
  289. private PlayerProfile loadPlayerProfile(String playerName, boolean create, boolean retry) {
  290. if (!checkConnected()) {
  291. return new PlayerProfile(playerName, false); // return fake profile if not connected
  292. }
  293. PreparedStatement statement = null;
  294. try {
  295. statement = connection.prepareStatement(
  296. "SELECT "
  297. + "s.taming, s.mining, s.repair, s.woodcutting, s.unarmed, s.herbalism, s.excavation, s.archery, s.swords, s.axes, s.acrobatics, s.fishing, "
  298. + "e.taming, e.mining, e.repair, e.woodcutting, e.unarmed, e.herbalism, e.excavation, e.archery, e.swords, e.axes, e.acrobatics, e.fishing, "
  299. + "c.taming, c.mining, c.repair, c.woodcutting, c.unarmed, c.herbalism, c.excavation, c.archery, c.swords, c.axes, c.acrobatics, c.blast_mining, "
  300. + "h.mobhealthbar "
  301. + "FROM " + tablePrefix + "users u "
  302. + "JOIN " + tablePrefix + "skills s ON (u.id = s.user_id) "
  303. + "JOIN " + tablePrefix + "experience e ON (u.id = e.user_id) "
  304. + "JOIN " + tablePrefix + "cooldowns c ON (u.id = c.user_id) "
  305. + "JOIN " + tablePrefix + "huds h ON (u.id = h.user_id) "
  306. + "WHERE u.user = ?");
  307. statement.setString(1, playerName);
  308. ResultSet result = statement.executeQuery();
  309. if (result.next()) {
  310. try {
  311. PlayerProfile ret = loadFromResult(playerName, result);
  312. result.close();
  313. return ret;
  314. }
  315. catch (SQLException e) {
  316. }
  317. }
  318. result.close();
  319. }
  320. catch (SQLException ex) {
  321. printErrors(ex);
  322. }
  323. finally {
  324. if (statement != null) {
  325. try {
  326. statement.close();
  327. }
  328. catch (SQLException e) {
  329. // Ignore
  330. }
  331. }
  332. }
  333. // Problem, nothing was returned
  334. // Quit if this is second time around
  335. if (!retry) {
  336. return new PlayerProfile(playerName, false);
  337. }
  338. // First, read User Id - this is to check for orphans
  339. int id = readId(playerName);
  340. if (id == -1) {
  341. // There is no such user
  342. if (create) {
  343. newUser(playerName);
  344. return loadPlayerProfile(playerName, false, false);
  345. }
  346. // Return unloaded profile if can't create
  347. return new PlayerProfile(playerName, false);
  348. }
  349. // There is such a user
  350. writeMissingRows(id);
  351. // Retry, and abort on re-failure
  352. return loadPlayerProfile(playerName, create, false);
  353. }
  354. public void convertUsers(DatabaseManager destination) {
  355. if (!checkConnected()) {
  356. return;
  357. }
  358. PreparedStatement statement = null;
  359. try {
  360. statement = connection.prepareStatement(
  361. "SELECT "
  362. + "s.taming, s.mining, s.repair, s.woodcutting, s.unarmed, s.herbalism, s.excavation, s.archery, s.swords, s.axes, s.acrobatics, s.fishing, "
  363. + "e.taming, e.mining, e.repair, e.woodcutting, e.unarmed, e.herbalism, e.excavation, e.archery, e.swords, e.axes, e.acrobatics, e.fishing, "
  364. + "c.taming, c.mining, c.repair, c.woodcutting, c.unarmed, c.herbalism, c.excavation, c.archery, c.swords, c.axes, c.acrobatics, c.blast_mining, "
  365. + "h.mobhealthbar "
  366. + "FROM " + tablePrefix + "users u "
  367. + "JOIN " + tablePrefix + "skills s ON (u.id = s.user_id) "
  368. + "JOIN " + tablePrefix + "experience e ON (u.id = e.user_id) "
  369. + "JOIN " + tablePrefix + "cooldowns c ON (u.id = c.user_id) "
  370. + "JOIN " + tablePrefix + "huds h ON (u.id = h.user_id) "
  371. + "WHERE u.user = ?");
  372. List<String> usernames = getStoredUsers();
  373. ResultSet result = null;
  374. int convertedUsers = 0;
  375. long startMillis = System.currentTimeMillis();
  376. for (String playerName : usernames) {
  377. statement.setString(1, playerName);
  378. try {
  379. result = statement.executeQuery();
  380. result.next();
  381. destination.saveUser(loadFromResult(playerName, result));
  382. result.close();
  383. }
  384. catch (SQLException e) {
  385. // Ignore
  386. }
  387. convertedUsers++;
  388. if ((convertedUsers % DatabaseManager.progressInterval) == 0) {
  389. // Can't use Bukkit.broadcastMessage because async
  390. System.out.println(String.format("[mcMMO] Conversion progress: %d users at %.2f users/second", convertedUsers, convertedUsers / ((System.currentTimeMillis() - startMillis) / 1000D)));
  391. }
  392. }
  393. }
  394. catch (SQLException e) {
  395. printErrors(e);
  396. }
  397. finally {
  398. if (statement != null) {
  399. try {
  400. statement.close();
  401. }
  402. catch (SQLException e) {
  403. // Ignore
  404. }
  405. }
  406. }
  407. }
  408. /**
  409. * Check connection status and re-establish if dead or stale.
  410. *
  411. * If the very first immediate attempt fails, further attempts
  412. * will be made in progressively larger intervals up to MAX_WAIT
  413. * intervals.
  414. *
  415. * This allows for MySQL to time out idle connections as needed by
  416. * server operator, without affecting McMMO, while still providing
  417. * protection against a database outage taking down Bukkit's tick
  418. * processing loop due to attempting a database connection each
  419. * time McMMO needs the database.
  420. *
  421. * @return the boolean value for whether or not we are connected
  422. */
  423. public boolean checkConnected() {
  424. boolean isClosed = true;
  425. boolean isValid = false;
  426. boolean exists = (connection != null);
  427. // If we're waiting for server to recover then leave early
  428. if (nextReconnectTimestamp > 0 && nextReconnectTimestamp > System.nanoTime()) {
  429. return false;
  430. }
  431. if (exists) {
  432. try {
  433. isClosed = connection.isClosed();
  434. }
  435. catch (SQLException e) {
  436. isClosed = true;
  437. e.printStackTrace();
  438. printErrors(e);
  439. }
  440. if (!isClosed) {
  441. try {
  442. isValid = connection.isValid(VALID_TIMEOUT);
  443. }
  444. catch (SQLException e) {
  445. // Don't print stack trace because it's valid to lose idle connections to the server and have to restart them.
  446. isValid = false;
  447. }
  448. }
  449. }
  450. // Leave if all ok
  451. if (exists && !isClosed && isValid) {
  452. // Housekeeping
  453. nextReconnectTimestamp = 0;
  454. reconnectAttempt = 0;
  455. return true;
  456. }
  457. // Cleanup after ourselves for GC and MySQL's sake
  458. if (exists && !isClosed) {
  459. try {
  460. connection.close();
  461. }
  462. catch (SQLException ex) {
  463. // This is a housekeeping exercise, ignore errors
  464. }
  465. }
  466. // Try to connect again
  467. connect();
  468. // Leave if connection is good
  469. try {
  470. if (connection != null && !connection.isClosed()) {
  471. // Schedule a database save if we really had an outage
  472. if (reconnectAttempt > 1) {
  473. new SQLReconnectTask().runTaskLater(mcMMO.p, 5);
  474. }
  475. nextReconnectTimestamp = 0;
  476. reconnectAttempt = 0;
  477. return true;
  478. }
  479. }
  480. catch (SQLException e) {
  481. // Failed to check isClosed, so presume connection is bad and attempt later
  482. e.printStackTrace();
  483. printErrors(e);
  484. }
  485. reconnectAttempt++;
  486. nextReconnectTimestamp = (long) (System.nanoTime() + Math.min(MAX_WAIT, (reconnectAttempt * SCALING_FACTOR * MIN_WAIT)));
  487. return false;
  488. }
  489. public List<String> getStoredUsers() {
  490. ArrayList<String> users = new ArrayList<String>();
  491. if (checkConnected()) {
  492. Statement stmt = null;
  493. try {
  494. stmt = connection.createStatement();
  495. ResultSet result = stmt.executeQuery("SELECT user FROM " + tablePrefix + "users");
  496. while (result.next()) {
  497. users.add(result.getString("user"));
  498. }
  499. result.close();
  500. }
  501. catch (SQLException e) {
  502. printErrors(e);
  503. }
  504. finally {
  505. if (stmt != null) {
  506. try {
  507. stmt.close();
  508. }
  509. catch (SQLException e) {
  510. // Ignore
  511. }
  512. }
  513. }
  514. }
  515. return users;
  516. }
  517. /**
  518. * Attempt to connect to the mySQL database.
  519. */
  520. private void connect() {
  521. connectionString = "jdbc:mysql://" + Config.getInstance().getMySQLServerName() + ":" + Config.getInstance().getMySQLServerPort() + "/" + Config.getInstance().getMySQLDatabaseName();
  522. try {
  523. mcMMO.p.getLogger().info("Attempting connection to MySQL...");
  524. // Force driver to load if not yet loaded
  525. Class.forName("com.mysql.jdbc.Driver");
  526. Properties connectionProperties = new Properties();
  527. connectionProperties.put("user", Config.getInstance().getMySQLUserName());
  528. connectionProperties.put("password", Config.getInstance().getMySQLUserPassword());
  529. connectionProperties.put("autoReconnect", "false");
  530. connectionProperties.put("maxReconnects", "0");
  531. connection = DriverManager.getConnection(connectionString, connectionProperties);
  532. mcMMO.p.getLogger().info("Connection to MySQL was a success!");
  533. }
  534. catch (SQLException ex) {
  535. connection = null;
  536. if (reconnectAttempt == 0 || reconnectAttempt >= 11) {
  537. mcMMO.p.getLogger().severe("Connection to MySQL failed!");
  538. printErrors(ex);
  539. }
  540. }
  541. catch (ClassNotFoundException ex) {
  542. connection = null;
  543. if (reconnectAttempt == 0 || reconnectAttempt >= 11) {
  544. mcMMO.p.getLogger().severe("MySQL database driver not found!");
  545. }
  546. }
  547. }
  548. /**
  549. * Checks that the database structure is present and correct
  550. */
  551. private void checkStructure() {
  552. if (!checkConnected()) {
  553. return;
  554. }
  555. write("CREATE TABLE IF NOT EXISTS `" + tablePrefix + "users` ("
  556. + "`id` int(10) unsigned NOT NULL AUTO_INCREMENT,"
  557. + "`user` varchar(40) NOT NULL,"
  558. + "`lastlogin` int(32) unsigned NOT NULL,"
  559. + "PRIMARY KEY (`id`),"
  560. + "UNIQUE KEY `user` (`user`)) DEFAULT CHARSET=latin1 AUTO_INCREMENT=1;");
  561. write("CREATE TABLE IF NOT EXISTS `" + tablePrefix + "huds` ("
  562. + "`user_id` int(10) unsigned NOT NULL,"
  563. + "`mobhealthbar` varchar(50) NOT NULL DEFAULT '" + Config.getInstance().getMobHealthbarDefault() + "',"
  564. + "PRIMARY KEY (`user_id`)) "
  565. + "DEFAULT CHARSET=latin1;");
  566. write("CREATE TABLE IF NOT EXISTS `" + tablePrefix + "cooldowns` ("
  567. + "`user_id` int(10) unsigned NOT NULL,"
  568. + "`taming` int(32) unsigned NOT NULL DEFAULT '0',"
  569. + "`mining` int(32) unsigned NOT NULL DEFAULT '0',"
  570. + "`woodcutting` int(32) unsigned NOT NULL DEFAULT '0',"
  571. + "`repair` int(32) unsigned NOT NULL DEFAULT '0',"
  572. + "`unarmed` int(32) unsigned NOT NULL DEFAULT '0',"
  573. + "`herbalism` int(32) unsigned NOT NULL DEFAULT '0',"
  574. + "`excavation` int(32) unsigned NOT NULL DEFAULT '0',"
  575. + "`archery` int(32) unsigned NOT NULL DEFAULT '0',"
  576. + "`swords` int(32) unsigned NOT NULL DEFAULT '0',"
  577. + "`axes` int(32) unsigned NOT NULL DEFAULT '0',"
  578. + "`acrobatics` int(32) unsigned NOT NULL DEFAULT '0',"
  579. + "`blast_mining` int(32) unsigned NOT NULL DEFAULT '0',"
  580. + "PRIMARY KEY (`user_id`)) "
  581. + "DEFAULT CHARSET=latin1;");
  582. write("CREATE TABLE IF NOT EXISTS `" + tablePrefix + "skills` ("
  583. + "`user_id` int(10) unsigned NOT NULL,"
  584. + "`taming` int(10) unsigned NOT NULL DEFAULT '0',"
  585. + "`mining` int(10) unsigned NOT NULL DEFAULT '0',"
  586. + "`woodcutting` int(10) unsigned NOT NULL DEFAULT '0',"
  587. + "`repair` int(10) unsigned NOT NULL DEFAULT '0',"
  588. + "`unarmed` int(10) unsigned NOT NULL DEFAULT '0',"
  589. + "`herbalism` int(10) unsigned NOT NULL DEFAULT '0',"
  590. + "`excavation` int(10) unsigned NOT NULL DEFAULT '0',"
  591. + "`archery` int(10) unsigned NOT NULL DEFAULT '0',"
  592. + "`swords` int(10) unsigned NOT NULL DEFAULT '0',"
  593. + "`axes` int(10) unsigned NOT NULL DEFAULT '0',"
  594. + "`acrobatics` int(10) unsigned NOT NULL DEFAULT '0',"
  595. + "`fishing` int(10) unsigned NOT NULL DEFAULT '0',"
  596. + "PRIMARY KEY (`user_id`)) "
  597. + "DEFAULT CHARSET=latin1;");
  598. write("CREATE TABLE IF NOT EXISTS `" + tablePrefix + "experience` ("
  599. + "`user_id` int(10) unsigned NOT NULL,"
  600. + "`taming` int(10) unsigned NOT NULL DEFAULT '0',"
  601. + "`mining` int(10) unsigned NOT NULL DEFAULT '0',"
  602. + "`woodcutting` int(10) unsigned NOT NULL DEFAULT '0',"
  603. + "`repair` int(10) unsigned NOT NULL DEFAULT '0',"
  604. + "`unarmed` int(10) unsigned NOT NULL DEFAULT '0',"
  605. + "`herbalism` int(10) unsigned NOT NULL DEFAULT '0',"
  606. + "`excavation` int(10) unsigned NOT NULL DEFAULT '0',"
  607. + "`archery` int(10) unsigned NOT NULL DEFAULT '0',"
  608. + "`swords` int(10) unsigned NOT NULL DEFAULT '0',"
  609. + "`axes` int(10) unsigned NOT NULL DEFAULT '0',"
  610. + "`acrobatics` int(10) unsigned NOT NULL DEFAULT '0',"
  611. + "`fishing` int(10) unsigned NOT NULL DEFAULT '0',"
  612. + "PRIMARY KEY (`user_id`)) "
  613. + "DEFAULT CHARSET=latin1;");
  614. for (DatabaseUpdateType updateType : DatabaseUpdateType.values()) {
  615. checkDatabaseStructure(updateType);
  616. }
  617. }
  618. /**
  619. * Check database structure for missing values.
  620. *
  621. * @param update Type of data to check updates for
  622. */
  623. private void checkDatabaseStructure(DatabaseUpdateType update) {
  624. String sql = "";
  625. switch (update) {
  626. case BLAST_MINING:
  627. sql = "SELECT * FROM `" + tablePrefix + "cooldowns` ORDER BY `" + tablePrefix + "cooldowns`.`blast_mining` ASC LIMIT 0 , 30";
  628. break;
  629. case FISHING:
  630. sql = "SELECT * FROM `" + tablePrefix + "experience` ORDER BY `" + tablePrefix + "experience`.`fishing` ASC LIMIT 0 , 30";
  631. break;
  632. case INDEX:
  633. if (read("SHOW INDEX FROM " + tablePrefix + "skills").size() != 13 && checkConnected()) {
  634. mcMMO.p.getLogger().info("Indexing tables, this may take a while on larger databases");
  635. write("ALTER TABLE `" + tablePrefix + "skills` ADD INDEX `idx_taming` (`taming`) USING BTREE, "
  636. + "ADD INDEX `idx_mining` (`mining`) USING BTREE, "
  637. + "ADD INDEX `idx_woodcutting` (`woodcutting`) USING BTREE, "
  638. + "ADD INDEX `idx_repair` (`repair`) USING BTREE, "
  639. + "ADD INDEX `idx_unarmed` (`unarmed`) USING BTREE, "
  640. + "ADD INDEX `idx_herbalism` (`herbalism`) USING BTREE, "
  641. + "ADD INDEX `idx_excavation` (`excavation`) USING BTREE, "
  642. + "ADD INDEX `idx_archery` (`archery`) USING BTREE, "
  643. + "ADD INDEX `idx_swords` (`swords`) USING BTREE, "
  644. + "ADD INDEX `idx_axes` (`axes`) USING BTREE, "
  645. + "ADD INDEX `idx_acrobatics` (`acrobatics`) USING BTREE, "
  646. + "ADD INDEX `idx_fishing` (`fishing`) USING BTREE;");
  647. }
  648. return;
  649. case MOB_HEALTHBARS:
  650. sql = "SELECT * FROM `" + tablePrefix + "huds` ORDER BY `" + tablePrefix + "huds`.`mobhealthbar` ASC LIMIT 0 , 30";
  651. break;
  652. case PARTY_NAMES:
  653. write("ALTER TABLE `" + tablePrefix + "users` DROP COLUMN `party` ;");
  654. return;
  655. case DROPPED_SPOUT:
  656. write("ALTER TABLE `" + tablePrefix + "huds` DROP COLUMN `hudtype` ;");
  657. return;
  658. case KILL_ORPHANS:
  659. mcMMO.p.getLogger().info("Killing orphans");
  660. write(
  661. "DELETE FROM " + tablePrefix + "experience " +
  662. "WHERE NOT EXISTS (SELECT * FROM " +
  663. tablePrefix + "users u WHERE " +
  664. tablePrefix + "experience.user_id = u.id);"
  665. );
  666. write(
  667. "DELETE FROM " + tablePrefix + "huds " +
  668. "WHERE NOT EXISTS (SELECT * FROM " +
  669. tablePrefix + "users u WHERE " +
  670. tablePrefix + "huds.user_id = u.id);"
  671. );
  672. write(
  673. "DELETE FROM " + tablePrefix + "cooldowns " +
  674. "WHERE NOT EXISTS (SELECT * FROM " +
  675. tablePrefix + "users u WHERE " +
  676. tablePrefix + "cooldowns.user_id = u.id);"
  677. );
  678. write(
  679. "DELETE FROM " + tablePrefix + "skills " +
  680. "WHERE NOT EXISTS (SELECT * FROM " +
  681. tablePrefix + "users u WHERE " +
  682. tablePrefix + "skills.user_id = u.id);"
  683. );
  684. return;
  685. default:
  686. break;
  687. }
  688. ResultSet resultSet = null;
  689. HashMap<Integer, ArrayList<String>> rows = new HashMap<Integer, ArrayList<String>>();
  690. PreparedStatement statement = null;
  691. try {
  692. if (!checkConnected()) {
  693. return;
  694. }
  695. statement = connection.prepareStatement(sql);
  696. resultSet = statement.executeQuery();
  697. while (resultSet.next()) {
  698. ArrayList<String> column = new ArrayList<String>();
  699. for (int i = 1; i <= resultSet.getMetaData().getColumnCount(); i++) {
  700. column.add(resultSet.getString(i));
  701. }
  702. rows.put(resultSet.getRow(), column);
  703. }
  704. }
  705. catch (SQLException ex) {
  706. switch (update) {
  707. case BLAST_MINING:
  708. mcMMO.p.getLogger().info("Updating mcMMO MySQL tables for Blast Mining...");
  709. write("ALTER TABLE `"+tablePrefix + "cooldowns` ADD `blast_mining` int(32) NOT NULL DEFAULT '0' ;");
  710. break;
  711. case FISHING:
  712. mcMMO.p.getLogger().info("Updating mcMMO MySQL tables for Fishing...");
  713. write("ALTER TABLE `"+tablePrefix + "skills` ADD `fishing` int(10) NOT NULL DEFAULT '0' ;");
  714. write("ALTER TABLE `"+tablePrefix + "experience` ADD `fishing` int(10) NOT NULL DEFAULT '0' ;");
  715. break;
  716. case MOB_HEALTHBARS:
  717. mcMMO.p.getLogger().info("Updating mcMMO MySQL tables for mob healthbars...");
  718. write("ALTER TABLE `" + tablePrefix + "huds` ADD `mobhealthbar` varchar(50) NOT NULL DEFAULT '" + Config.getInstance().getMobHealthbarDefault() + "' ;");
  719. break;
  720. default:
  721. break;
  722. }
  723. }
  724. finally {
  725. if (statement != null) {
  726. try {
  727. statement.close();
  728. }
  729. catch (SQLException e) {
  730. // Ignore the error, we're leaving
  731. }
  732. }
  733. }
  734. }
  735. /**
  736. * Attempt to write the SQL query.
  737. *
  738. * @param sql Query to write.
  739. * @return true if the query was successfully written, false otherwise.
  740. */
  741. private boolean write(String sql) {
  742. if (!checkConnected()) {
  743. return false;
  744. }
  745. PreparedStatement statement = null;
  746. try {
  747. statement = connection.prepareStatement(sql);
  748. statement.executeUpdate();
  749. return true;
  750. }
  751. catch (SQLException ex) {
  752. if (!sql.contains("DROP COLUMN")) {
  753. printErrors(ex);
  754. }
  755. return false;
  756. }
  757. finally {
  758. if (statement != null) {
  759. try {
  760. statement.close();
  761. }
  762. catch (SQLException e) {
  763. // Ignore
  764. }
  765. }
  766. }
  767. }
  768. /**
  769. * Returns the number of rows affected by either a DELETE or UPDATE query
  770. *
  771. * @param sql SQL query to execute
  772. * @return the number of rows affected
  773. */
  774. private int update(String sql) {
  775. int rows = 0;
  776. if (checkConnected()) {
  777. PreparedStatement statement = null;
  778. try {
  779. statement = connection.prepareStatement(sql);
  780. rows = statement.executeUpdate();
  781. }
  782. catch (SQLException ex) {
  783. printErrors(ex);
  784. }
  785. finally {
  786. if (statement != null) {
  787. try {
  788. statement.close();
  789. }
  790. catch (SQLException e) {
  791. // Ignore
  792. }
  793. }
  794. }
  795. }
  796. return rows;
  797. }
  798. /**
  799. * Read SQL query.
  800. *
  801. * @param sql SQL query to read
  802. * @return the rows in this SQL query
  803. */
  804. private HashMap<Integer, ArrayList<String>> read(String sql) {
  805. HashMap<Integer, ArrayList<String>> rows = new HashMap<Integer, ArrayList<String>>();
  806. if (checkConnected()) {
  807. PreparedStatement statement = null;
  808. ResultSet resultSet;
  809. try {
  810. statement = connection.prepareStatement(sql);
  811. resultSet = statement.executeQuery();
  812. while (resultSet.next()) {
  813. ArrayList<String> column = new ArrayList<String>();
  814. for (int i = 1; i <= resultSet.getMetaData().getColumnCount(); i++) {
  815. column.add(resultSet.getString(i));
  816. }
  817. rows.put(resultSet.getRow(), column);
  818. }
  819. }
  820. catch (SQLException ex) {
  821. printErrors(ex);
  822. }
  823. finally {
  824. if (statement != null) {
  825. try {
  826. statement.close();
  827. }
  828. catch (SQLException e) {
  829. // Ignore
  830. }
  831. }
  832. }
  833. }
  834. return rows;
  835. }
  836. /**
  837. * Get the Integer. Only return first row / first field.
  838. *
  839. * @param statement SQL query to execute
  840. * @return the value in the first row / first field
  841. */
  842. private int readInt(PreparedStatement statement) {
  843. int result = -1;
  844. if (checkConnected()) {
  845. ResultSet resultSet = null;
  846. try {
  847. resultSet = statement.executeQuery();
  848. if (resultSet.next()) {
  849. result = resultSet.getInt(1);
  850. }
  851. }
  852. catch (SQLException ex) {
  853. printErrors(ex);
  854. }
  855. finally {
  856. if (statement != null) {
  857. try {
  858. statement.close();
  859. }
  860. catch (SQLException e) {
  861. // Ignore
  862. }
  863. }
  864. }
  865. }
  866. return result;
  867. }
  868. private void writeMissingRows(int id) {
  869. PreparedStatement statement = null;
  870. try {
  871. statement = connection.prepareStatement("INSERT IGNORE INTO " + tablePrefix + "experience (user_id) VALUES (?)");
  872. statement.setInt(1, id);
  873. statement.execute();
  874. statement.close();
  875. statement = connection.prepareStatement("INSERT IGNORE INTO " + tablePrefix + "skills (user_id) VALUES (?)");
  876. statement.setInt(1, id);
  877. statement.execute();
  878. statement.close();
  879. statement = connection.prepareStatement("INSERT IGNORE INTO " + tablePrefix + "cooldowns (user_id) VALUES (?)");
  880. statement.setInt(1, id);
  881. statement.execute();
  882. statement.close();
  883. statement = connection.prepareStatement("INSERT IGNORE INTO " + tablePrefix + "huds (user_id, mobhealthbar) VALUES (? ,'" + Config.getInstance().getMobHealthbarDefault().name() + "')");
  884. statement.setInt(1, id);
  885. statement.execute();
  886. statement.close();
  887. }
  888. catch (SQLException ex) {
  889. printErrors(ex);
  890. }
  891. finally {
  892. if (statement != null) {
  893. try {
  894. statement.close();
  895. }
  896. catch (SQLException e) {
  897. // Ignore
  898. }
  899. }
  900. }
  901. }
  902. private void processPurge(Collection<ArrayList<String>> usernames) {
  903. for (ArrayList<String> user : usernames) {
  904. Misc.profileCleanup(user.get(0));
  905. }
  906. }
  907. private boolean saveIntegers(String sql, int... args) {
  908. PreparedStatement statement = null;
  909. try {
  910. statement = connection.prepareStatement(sql);
  911. int i = 1;
  912. for (int arg : args) {
  913. statement.setInt(i++, arg);
  914. }
  915. statement.execute();
  916. return true;
  917. }
  918. catch (SQLException ex) {
  919. printErrors(ex);
  920. return false;
  921. }
  922. finally {
  923. if (statement != null) {
  924. try {
  925. statement.close();
  926. }
  927. catch (SQLException e) {
  928. // Ignore
  929. }
  930. }
  931. }
  932. }
  933. private boolean saveLongs(String sql, int id, long... args) {
  934. PreparedStatement statement = null;
  935. try {
  936. statement = connection.prepareStatement(sql);
  937. int i = 1;
  938. for (long arg : args) {
  939. statement.setLong(i++, arg);
  940. }
  941. statement.setInt(i++, id);
  942. statement.execute();
  943. return true;
  944. }
  945. catch (SQLException ex) {
  946. printErrors(ex);
  947. return false;
  948. }
  949. finally {
  950. if (statement != null) {
  951. try {
  952. statement.close();
  953. }
  954. catch (SQLException e) {
  955. // Ignore
  956. }
  957. }
  958. }
  959. }
  960. /**
  961. * Retrieve the database id for a player
  962. *
  963. * @param playerName The name of the user to retrieve the id for
  964. * @return the requested id or -1 if not found
  965. */
  966. private int readId(String playerName) {
  967. int id = -1;
  968. try {
  969. PreparedStatement statement = connection.prepareStatement("SELECT id FROM " + tablePrefix + "users WHERE user = ?");
  970. statement.setString(1, playerName);
  971. id = readInt(statement);
  972. }
  973. catch (SQLException ex) {
  974. printErrors(ex);
  975. }
  976. return id;
  977. }
  978. private boolean saveLogin(int id, long login) {
  979. PreparedStatement statement = null;
  980. try {
  981. statement = connection.prepareStatement("UPDATE " + tablePrefix + "users SET lastlogin = ? WHERE id = ?");
  982. statement.setLong(1, login);
  983. statement.setInt(2, id);
  984. statement.execute();
  985. return true;
  986. }
  987. catch (SQLException ex) {
  988. printErrors(ex);
  989. return false;
  990. }
  991. finally {
  992. if (statement != null) {
  993. try {
  994. statement.close();
  995. }
  996. catch (SQLException e) {
  997. // Ignore
  998. }
  999. }
  1000. }
  1001. }
  1002. private boolean saveHuds(int userId, String mobHealthBar) {
  1003. PreparedStatement statement = null;
  1004. try {
  1005. statement = connection.prepareStatement("UPDATE " + tablePrefix + "huds SET mobhealthbar = ? WHERE user_id = ?");
  1006. statement.setString(1, mobHealthBar);
  1007. statement.setInt(2, userId);
  1008. statement.execute();
  1009. return true;
  1010. }
  1011. catch (SQLException ex) {
  1012. printErrors(ex);
  1013. return false;
  1014. }
  1015. finally {
  1016. if (statement != null) {
  1017. try {
  1018. statement.close();
  1019. }
  1020. catch (SQLException e) {
  1021. // Ignore
  1022. }
  1023. }
  1024. }
  1025. }
  1026. private PlayerProfile loadFromResult(String playerName, ResultSet result) throws SQLException {
  1027. Map<SkillType, Integer> skills = new HashMap<SkillType, Integer>(); // Skill & Level
  1028. Map<SkillType, Float> skillsXp = new HashMap<SkillType, Float>(); // Skill & XP
  1029. Map<AbilityType, Integer> skillsDATS = new HashMap<AbilityType, Integer>(); // Ability & Cooldown
  1030. MobHealthbarType mobHealthbarType;
  1031. final int OFFSET_SKILLS = 0; // TODO update these numbers when the query changes (a new skill is added)
  1032. final int OFFSET_XP = 12;
  1033. final int OFFSET_DATS = 24;
  1034. final int OFFSET_OTHER = 36;
  1035. skills.put(SkillType.TAMING, result.getInt(OFFSET_SKILLS + 1));
  1036. skills.put(SkillType.MINING, result.getInt(OFFSET_SKILLS + 2));
  1037. skills.put(SkillType.REPAIR, result.getInt(OFFSET_SKILLS + 3));
  1038. skills.put(SkillType.WOODCUTTING, result.getInt(OFFSET_SKILLS + 4));
  1039. skills.put(SkillType.UNARMED, result.getInt(OFFSET_SKILLS + 5));
  1040. skills.put(SkillType.HERBALISM, result.getInt(OFFSET_SKILLS + 6));
  1041. skills.put(SkillType.EXCAVATION, result.getInt(OFFSET_SKILLS + 7));
  1042. skills.put(SkillType.ARCHERY, result.getInt(OFFSET_SKILLS + 8));
  1043. skills.put(SkillType.SWORDS, result.getInt(OFFSET_SKILLS + 9));
  1044. skills.put(SkillType.AXES, result.getInt(OFFSET_SKILLS + 10));
  1045. skills.put(SkillType.ACROBATICS, result.getInt(OFFSET_SKILLS + 11));
  1046. skills.put(SkillType.FISHING, result.getInt(OFFSET_SKILLS + 12));
  1047. skillsXp.put(SkillType.TAMING, result.getFloat(OFFSET_XP + 1));
  1048. skillsXp.put(SkillType.MINING, result.getFloat(OFFSET_XP + 2));
  1049. skillsXp.put(SkillType.REPAIR, result.getFloat(OFFSET_XP + 3));
  1050. skillsXp.put(SkillType.WOODCUTTING, result.getFloat(OFFSET_XP + 4));
  1051. skillsXp.put(SkillType.UNARMED, result.getFloat(OFFSET_XP + 5));
  1052. skillsXp.put(SkillType.HERBALISM, result.getFloat(OFFSET_XP + 6));
  1053. skillsXp.put(SkillType.EXCAVATION, result.getFloat(OFFSET_XP + 7));
  1054. skillsXp.put(SkillType.ARCHERY, result.getFloat(OFFSET_XP + 8));
  1055. skillsXp.put(SkillType.SWORDS, result.getFloat(OFFSET_XP + 9));
  1056. skillsXp.put(SkillType.AXES, result.getFloat(OFFSET_XP + 10));
  1057. skillsXp.put(SkillType.ACROBATICS, result.getFloat(OFFSET_XP + 11));
  1058. skillsXp.put(SkillType.FISHING, result.getFloat(OFFSET_XP + 12));
  1059. // Taming - Unused - result.getInt(OFFSET_DATS + 1)
  1060. skillsDATS.put(AbilityType.SUPER_BREAKER, result.getInt(OFFSET_DATS + 2));
  1061. // Repair - Unused - result.getInt(OFFSET_DATS + 3)
  1062. skillsDATS.put(AbilityType.TREE_FELLER, result.getInt(OFFSET_DATS + 4));
  1063. skillsDATS.put(AbilityType.BERSERK, result.getInt(OFFSET_DATS + 5));
  1064. skillsDATS.put(AbilityType.GREEN_TERRA, result.getInt(OFFSET_DATS + 6));
  1065. skillsDATS.put(AbilityType.GIGA_DRILL_BREAKER, result.getInt(OFFSET_DATS + 7));
  1066. // Archery - Unused - result.getInt(OFFSET_DATS + 8)
  1067. skillsDATS.put(AbilityType.SERRATED_STRIKES, result.getInt(OFFSET_DATS + 9));
  1068. skillsDATS.put(AbilityType.SKULL_SPLITTER, result.getInt(OFFSET_DATS + 10));
  1069. // Acrobatics - Unused - result.getInt(OFFSET_DATS + 11)
  1070. skillsDATS.put(AbilityType.BLAST_MINING, result.getInt(OFFSET_DATS + 12));
  1071. try {
  1072. mobHealthbarType = MobHealthbarType.valueOf(result.getString(OFFSET_OTHER + 2));
  1073. }
  1074. catch (Exception e) {
  1075. mobHealthbarType = Config.getInstance().getMobHealthbarDefault();
  1076. }
  1077. return new PlayerProfile(playerName, skills, skillsXp, skillsDATS, mobHealthbarType);
  1078. }
  1079. private void printErrors(SQLException ex) {
  1080. mcMMO.p.getLogger().severe("SQLException: " + ex.getMessage());
  1081. mcMMO.p.getLogger().severe("SQLState: " + ex.getSQLState());
  1082. mcMMO.p.getLogger().severe("VendorError: " + ex.getErrorCode());
  1083. }
  1084. public DatabaseType getDatabaseType() {
  1085. return DatabaseType.SQL;
  1086. }
  1087. }