SQLDatabaseManager.java 51 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292
  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.ResultSetMetaData;
  7. import java.sql.SQLException;
  8. import java.sql.Statement;
  9. import java.util.ArrayList;
  10. import java.util.Collection;
  11. import java.util.HashMap;
  12. import java.util.List;
  13. import java.util.Map;
  14. import java.util.Properties;
  15. import com.gmail.nossr50.mcMMO;
  16. import com.gmail.nossr50.config.Config;
  17. import com.gmail.nossr50.datatypes.MobHealthbarType;
  18. import com.gmail.nossr50.datatypes.database.DatabaseType;
  19. import com.gmail.nossr50.datatypes.database.PlayerStat;
  20. import com.gmail.nossr50.datatypes.database.UpgradeType;
  21. import com.gmail.nossr50.datatypes.player.PlayerProfile;
  22. import com.gmail.nossr50.datatypes.skills.AbilityType;
  23. import com.gmail.nossr50.datatypes.skills.SkillType;
  24. import com.gmail.nossr50.runnables.database.SQLDatabaseKeepaliveTask;
  25. import com.gmail.nossr50.runnables.database.SQLReconnectTask;
  26. import com.gmail.nossr50.util.Misc;
  27. public final class SQLDatabaseManager implements DatabaseManager {
  28. private String connectionString;
  29. private String tablePrefix = Config.getInstance().getMySQLTablePrefix();
  30. private Connection connection = null;
  31. // Scale waiting time by this much per failed attempt
  32. private final double SCALING_FACTOR = 40.0;
  33. // Minimum wait in nanoseconds (default 500ms)
  34. private final long MIN_WAIT = 500L * 1000000L;
  35. // Maximum time to wait between reconnects (default 5 minutes)
  36. private final long MAX_WAIT = 5L * 60L * 1000L * 1000000L;
  37. // How long to wait when checking if connection is valid (default 3 seconds)
  38. private final int VALID_TIMEOUT = 3;
  39. // When next to try connecting to Database in nanoseconds
  40. private long nextReconnectTimestamp = 0L;
  41. // How many connection attempts have failed
  42. private int reconnectAttempt = 0;
  43. protected SQLDatabaseManager() {
  44. checkStructure();
  45. new SQLDatabaseKeepaliveTask(this).runTaskTimerAsynchronously(mcMMO.p, 10, 60L * 60 * Misc.TICK_CONVERSION_FACTOR);
  46. }
  47. public void purgePowerlessUsers() {
  48. if (!checkConnected()) {
  49. return;
  50. }
  51. mcMMO.p.getLogger().info("Purging powerless users...");
  52. 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();
  53. write("DELETE FROM u, e, h, s, c USING " + tablePrefix + "users u " +
  54. "JOIN " + tablePrefix + "experience e ON (u.id = e.user_id) " +
  55. "JOIN " + tablePrefix + "huds h ON (u.id = h.user_id) " +
  56. "JOIN " + tablePrefix + "skills s ON (u.id = s.user_id) " +
  57. "JOIN " + tablePrefix + "cooldowns c ON (u.id = c.user_id) " +
  58. "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");
  59. processPurge(usernames);
  60. mcMMO.p.getLogger().info("Purged " + usernames.size() + " users from the database.");
  61. }
  62. public void purgeOldUsers() {
  63. if (!checkConnected()) {
  64. return;
  65. }
  66. long currentTime = System.currentTimeMillis();
  67. mcMMO.p.getLogger().info("Purging old users...");
  68. Collection<ArrayList<String>> usernames = read("SELECT user FROM " + tablePrefix + "users WHERE ((" + currentTime + " - lastlogin * " + Misc.TIME_CONVERSION_FACTOR + ") > " + PURGE_TIME + ")").values();
  69. write("DELETE FROM u, e, h, s, c USING " + tablePrefix + "users u " +
  70. "JOIN " + tablePrefix + "experience e ON (u.id = e.user_id) " +
  71. "JOIN " + tablePrefix + "huds h ON (u.id = h.user_id) " +
  72. "JOIN " + tablePrefix + "skills s ON (u.id = s.user_id) " +
  73. "JOIN " + tablePrefix + "cooldowns c ON (u.id = c.user_id) " +
  74. "WHERE ((" + currentTime + " - lastlogin * " + Misc.TIME_CONVERSION_FACTOR + ") > " + PURGE_TIME + ")");
  75. processPurge(usernames);
  76. mcMMO.p.getLogger().info("Purged " + usernames.size() + " users from the database.");
  77. }
  78. public boolean removeUser(String playerName) {
  79. if (!checkConnected()) {
  80. return false;
  81. }
  82. boolean success = update("DELETE FROM u, e, h, s, c " +
  83. "USING " + tablePrefix + "users u " +
  84. "JOIN " + tablePrefix + "experience e ON (u.id = e.user_id) " +
  85. "JOIN " + tablePrefix + "huds h ON (u.id = h.user_id) " +
  86. "JOIN " + tablePrefix + "skills s ON (u.id = s.user_id) " +
  87. "JOIN " + tablePrefix + "cooldowns c ON (u.id = c.user_id) " +
  88. "WHERE u.user = '" + playerName + "'") != 0;
  89. Misc.profileCleanup(playerName);
  90. return success;
  91. }
  92. public boolean saveUser(PlayerProfile profile) {
  93. if (!checkConnected()) {
  94. return false;
  95. }
  96. int userId = readId(profile.getPlayerName());
  97. if (userId == -1) {
  98. newUser(profile.getPlayerName());
  99. userId = readId(profile.getPlayerName());
  100. if (userId == -1) {
  101. return false;
  102. }
  103. }
  104. boolean success = true;
  105. MobHealthbarType mobHealthbarType = profile.getMobHealthbarType();
  106. success &= saveLogin(userId, ((int) (System.currentTimeMillis() / Misc.TIME_CONVERSION_FACTOR)));
  107. success &= saveHuds(userId, (mobHealthbarType == null ? Config.getInstance().getMobHealthbarDefault().toString() : mobHealthbarType.toString()));
  108. success &= saveLongs(
  109. "UPDATE " + tablePrefix + "cooldowns SET "
  110. + " mining = ?, woodcutting = ?, unarmed = ?"
  111. + ", herbalism = ?, excavation = ?, swords = ?"
  112. + ", axes = ?, blast_mining = ? WHERE user_id = ?",
  113. userId,
  114. profile.getAbilityDATS(AbilityType.SUPER_BREAKER),
  115. profile.getAbilityDATS(AbilityType.TREE_FELLER),
  116. profile.getAbilityDATS(AbilityType.BERSERK),
  117. profile.getAbilityDATS(AbilityType.GREEN_TERRA),
  118. profile.getAbilityDATS(AbilityType.GIGA_DRILL_BREAKER),
  119. profile.getAbilityDATS(AbilityType.SERRATED_STRIKES),
  120. profile.getAbilityDATS(AbilityType.SKULL_SPLITTER),
  121. profile.getAbilityDATS(AbilityType.BLAST_MINING));
  122. success &= saveIntegers(
  123. "UPDATE " + tablePrefix + "skills SET "
  124. + " taming = ?, mining = ?, repair = ?, woodcutting = ?"
  125. + ", unarmed = ?, herbalism = ?, excavation = ?"
  126. + ", archery = ?, swords = ?, axes = ?, acrobatics = ?"
  127. + ", fishing = ?, alchemy = ? WHERE user_id = ?",
  128. profile.getSkillLevel(SkillType.TAMING),
  129. profile.getSkillLevel(SkillType.MINING),
  130. profile.getSkillLevel(SkillType.REPAIR),
  131. profile.getSkillLevel(SkillType.WOODCUTTING),
  132. profile.getSkillLevel(SkillType.UNARMED),
  133. profile.getSkillLevel(SkillType.HERBALISM),
  134. profile.getSkillLevel(SkillType.EXCAVATION),
  135. profile.getSkillLevel(SkillType.ARCHERY),
  136. profile.getSkillLevel(SkillType.SWORDS),
  137. profile.getSkillLevel(SkillType.AXES),
  138. profile.getSkillLevel(SkillType.ACROBATICS),
  139. profile.getSkillLevel(SkillType.FISHING),
  140. profile.getSkillLevel(SkillType.ALCHEMY),
  141. userId);
  142. success &= saveIntegers(
  143. "UPDATE " + tablePrefix + "experience SET "
  144. + " taming = ?, mining = ?, repair = ?, woodcutting = ?"
  145. + ", unarmed = ?, herbalism = ?, excavation = ?"
  146. + ", archery = ?, swords = ?, axes = ?, acrobatics = ?"
  147. + ", fishing = ?, alchemy = ? WHERE user_id = ?",
  148. profile.getSkillXpLevel(SkillType.TAMING),
  149. profile.getSkillXpLevel(SkillType.MINING),
  150. profile.getSkillXpLevel(SkillType.REPAIR),
  151. profile.getSkillXpLevel(SkillType.WOODCUTTING),
  152. profile.getSkillXpLevel(SkillType.UNARMED),
  153. profile.getSkillXpLevel(SkillType.HERBALISM),
  154. profile.getSkillXpLevel(SkillType.EXCAVATION),
  155. profile.getSkillXpLevel(SkillType.ARCHERY),
  156. profile.getSkillXpLevel(SkillType.SWORDS),
  157. profile.getSkillXpLevel(SkillType.AXES),
  158. profile.getSkillXpLevel(SkillType.ACROBATICS),
  159. profile.getSkillXpLevel(SkillType.FISHING),
  160. profile.getSkillXpLevel(SkillType.ALCHEMY),
  161. userId);
  162. return success;
  163. }
  164. public List<PlayerStat> readLeaderboard(SkillType skill, int pageNumber, int statsPerPage) {
  165. List<PlayerStat> stats = new ArrayList<PlayerStat>();
  166. if (checkConnected()) {
  167. String query = skill == null ? "taming+mining+woodcutting+repair+unarmed+herbalism+excavation+archery+swords+axes+acrobatics+fishing+alchemy" : skill.name().toLowerCase();
  168. ResultSet resultSet;
  169. PreparedStatement statement = null;
  170. try {
  171. 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 ?, ?");
  172. statement.setInt(1, (pageNumber * statsPerPage) - statsPerPage);
  173. statement.setInt(2, statsPerPage);
  174. resultSet = statement.executeQuery();
  175. while (resultSet.next()) {
  176. ArrayList<String> column = new ArrayList<String>();
  177. for (int i = 1; i <= resultSet.getMetaData().getColumnCount(); i++) {
  178. column.add(resultSet.getString(i));
  179. }
  180. stats.add(new PlayerStat(column.get(1), Integer.valueOf(column.get(0))));
  181. }
  182. }
  183. catch (SQLException ex) {
  184. printErrors(ex);
  185. }
  186. finally {
  187. if (statement != null) {
  188. try {
  189. statement.close();
  190. }
  191. catch (SQLException e) {
  192. // Ignore
  193. }
  194. }
  195. }
  196. }
  197. return stats;
  198. }
  199. public Map<SkillType, Integer> readRank(String playerName) {
  200. Map<SkillType, Integer> skills = new HashMap<SkillType, Integer>();
  201. if (checkConnected()) {
  202. ResultSet resultSet;
  203. try {
  204. for (SkillType skillType : SkillType.NON_CHILD_SKILLS) {
  205. String skillName = skillType.name().toLowerCase();
  206. String sql = "SELECT COUNT(*) AS rank FROM " + tablePrefix + "users JOIN " + tablePrefix + "skills ON user_id = id WHERE " + skillName + " > 0 " +
  207. "AND " + skillName + " > (SELECT " + skillName + " FROM " + tablePrefix + "users JOIN " + tablePrefix + "skills ON user_id = id " +
  208. "WHERE user = ?)";
  209. PreparedStatement statement = connection.prepareStatement(sql);
  210. statement.setString(1, playerName);
  211. resultSet = statement.executeQuery();
  212. resultSet.next();
  213. int rank = resultSet.getInt("rank");
  214. sql = "SELECT user, " + skillName + " FROM " + tablePrefix + "users JOIN " + tablePrefix + "skills ON user_id = id WHERE " + skillName + " > 0 " +
  215. "AND " + skillName + " = (SELECT " + skillName + " FROM " + tablePrefix + "users JOIN " + tablePrefix + "skills ON user_id = id " +
  216. "WHERE user = '" + playerName + "') ORDER BY user";
  217. statement.close();
  218. statement = connection.prepareStatement(sql);
  219. resultSet = statement.executeQuery();
  220. while (resultSet.next()) {
  221. if (resultSet.getString("user").equalsIgnoreCase(playerName)) {
  222. skills.put(skillType, rank + resultSet.getRow());
  223. break;
  224. }
  225. }
  226. statement.close();
  227. }
  228. String sql = "SELECT COUNT(*) AS rank FROM " + tablePrefix + "users JOIN " + tablePrefix + "skills ON user_id = id " +
  229. "WHERE taming+mining+woodcutting+repair+unarmed+herbalism+excavation+archery+swords+axes+acrobatics+fishing+alchemy > 0 " +
  230. "AND taming+mining+woodcutting+repair+unarmed+herbalism+excavation+archery+swords+axes+acrobatics+fishing+alchemy > " +
  231. "(SELECT taming+mining+woodcutting+repair+unarmed+herbalism+excavation+archery+swords+axes+acrobatics+fishing+alchemy " +
  232. "FROM " + tablePrefix + "users JOIN " + tablePrefix + "skills ON user_id = id WHERE user = ?)";
  233. PreparedStatement statement = connection.prepareStatement(sql);
  234. statement.setString(1, playerName);
  235. resultSet = statement.executeQuery();
  236. resultSet.next();
  237. int rank = resultSet.getInt("rank");
  238. statement.close();
  239. sql = "SELECT user, taming+mining+woodcutting+repair+unarmed+herbalism+excavation+archery+swords+axes+acrobatics+fishing+alchemy " +
  240. "FROM " + tablePrefix + "users JOIN " + tablePrefix + "skills ON user_id = id " +
  241. "WHERE taming+mining+woodcutting+repair+unarmed+herbalism+excavation+archery+swords+axes+acrobatics+fishing+alchemy > 0 " +
  242. "AND taming+mining+woodcutting+repair+unarmed+herbalism+excavation+archery+swords+axes+acrobatics+fishing+alchemy = " +
  243. "(SELECT taming+mining+woodcutting+repair+unarmed+herbalism+excavation+archery+swords+axes+acrobatics+fishing+alchemy " +
  244. "FROM " + tablePrefix + "users JOIN " + tablePrefix + "skills ON user_id = id WHERE user = ?) ORDER BY user";
  245. statement = connection.prepareStatement(sql);
  246. statement.setString(1, playerName);
  247. resultSet = statement.executeQuery();
  248. while (resultSet.next()) {
  249. if (resultSet.getString("user").equalsIgnoreCase(playerName)) {
  250. skills.put(null, rank + resultSet.getRow());
  251. break;
  252. }
  253. }
  254. statement.close();
  255. }
  256. catch (SQLException ex) {
  257. printErrors(ex);
  258. }
  259. }
  260. return skills;
  261. }
  262. public void newUser(String playerName) {
  263. if (!checkConnected()) {
  264. return;
  265. }
  266. PreparedStatement statement = null;
  267. try {
  268. statement = connection.prepareStatement("INSERT INTO " + tablePrefix + "users (user, lastlogin) VALUES (?, ?)", Statement.RETURN_GENERATED_KEYS);
  269. statement.setString(1, playerName);
  270. statement.setLong(2, System.currentTimeMillis() / Misc.TIME_CONVERSION_FACTOR);
  271. statement.execute();
  272. int id = readId(playerName);
  273. writeMissingRows(id);
  274. }
  275. catch (SQLException ex) {
  276. printErrors(ex);
  277. }
  278. finally {
  279. if (statement != null) {
  280. try {
  281. statement.close();
  282. }
  283. catch (SQLException e) {
  284. // Ignore
  285. }
  286. }
  287. }
  288. }
  289. public PlayerProfile loadPlayerProfile(String playerName, boolean create) {
  290. return loadPlayerProfile(playerName, create, true);
  291. }
  292. private PlayerProfile loadPlayerProfile(String playerName, boolean create, boolean retry) {
  293. if (!checkConnected()) {
  294. return new PlayerProfile(playerName, false); // return fake profile if not connected
  295. }
  296. PreparedStatement statement = null;
  297. try {
  298. statement = connection.prepareStatement(
  299. "SELECT "
  300. + "s.taming, s.mining, s.repair, s.woodcutting, s.unarmed, s.herbalism, s.excavation, s.archery, s.swords, s.axes, s.acrobatics, s.fishing, s.alchemy, "
  301. + "e.taming, e.mining, e.repair, e.woodcutting, e.unarmed, e.herbalism, e.excavation, e.archery, e.swords, e.axes, e.acrobatics, e.fishing, e.alchemy, "
  302. + "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, "
  303. + "h.mobhealthbar "
  304. + "FROM " + tablePrefix + "users u "
  305. + "JOIN " + tablePrefix + "skills s ON (u.id = s.user_id) "
  306. + "JOIN " + tablePrefix + "experience e ON (u.id = e.user_id) "
  307. + "JOIN " + tablePrefix + "cooldowns c ON (u.id = c.user_id) "
  308. + "JOIN " + tablePrefix + "huds h ON (u.id = h.user_id) "
  309. + "WHERE u.user = ?");
  310. statement.setString(1, playerName);
  311. ResultSet result = statement.executeQuery();
  312. if (result.next()) {
  313. try {
  314. PlayerProfile ret = loadFromResult(playerName, result);
  315. result.close();
  316. return ret;
  317. }
  318. catch (SQLException e) {
  319. }
  320. }
  321. result.close();
  322. }
  323. catch (SQLException ex) {
  324. printErrors(ex);
  325. }
  326. finally {
  327. if (statement != null) {
  328. try {
  329. statement.close();
  330. }
  331. catch (SQLException e) {
  332. // Ignore
  333. }
  334. }
  335. }
  336. // Problem, nothing was returned
  337. // Quit if this is second time around
  338. if (!retry) {
  339. return new PlayerProfile(playerName, false);
  340. }
  341. // First, read User Id - this is to check for orphans
  342. int id = readId(playerName);
  343. if (id == -1) {
  344. // There is no such user
  345. if (create) {
  346. newUser(playerName);
  347. return loadPlayerProfile(playerName, false, false);
  348. }
  349. // Return unloaded profile if can't create
  350. return new PlayerProfile(playerName, false);
  351. }
  352. // There is such a user
  353. writeMissingRows(id);
  354. // Retry, and abort on re-failure
  355. return loadPlayerProfile(playerName, create, false);
  356. }
  357. public void convertUsers(DatabaseManager destination) {
  358. if (!checkConnected()) {
  359. return;
  360. }
  361. PreparedStatement statement = null;
  362. try {
  363. statement = connection.prepareStatement(
  364. "SELECT "
  365. + "s.taming, s.mining, s.repair, s.woodcutting, s.unarmed, s.herbalism, s.excavation, s.archery, s.swords, s.axes, s.acrobatics, s.fishing, s.alchemy, "
  366. + "e.taming, e.mining, e.repair, e.woodcutting, e.unarmed, e.herbalism, e.excavation, e.archery, e.swords, e.axes, e.acrobatics, e.fishing, e.alchemy, "
  367. + "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, "
  368. + "h.mobhealthbar "
  369. + "FROM " + tablePrefix + "users u "
  370. + "JOIN " + tablePrefix + "skills s ON (u.id = s.user_id) "
  371. + "JOIN " + tablePrefix + "experience e ON (u.id = e.user_id) "
  372. + "JOIN " + tablePrefix + "cooldowns c ON (u.id = c.user_id) "
  373. + "JOIN " + tablePrefix + "huds h ON (u.id = h.user_id) "
  374. + "WHERE u.user = ?");
  375. List<String> usernames = getStoredUsers();
  376. ResultSet resultSet;
  377. int convertedUsers = 0;
  378. long startMillis = System.currentTimeMillis();
  379. for (String playerName : usernames) {
  380. statement.setString(1, playerName);
  381. try {
  382. resultSet = statement.executeQuery();
  383. resultSet.next();
  384. destination.saveUser(loadFromResult(playerName, resultSet));
  385. resultSet.close();
  386. }
  387. catch (SQLException e) {
  388. // Ignore
  389. }
  390. convertedUsers++;
  391. Misc.printProgress(convertedUsers, progressInterval, startMillis);
  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. * <p/>
  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. * <p/>
  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. connection = DriverManager.getConnection(connectionString, connectionProperties);
  531. mcMMO.p.getLogger().info("Connection to MySQL was a success!");
  532. }
  533. catch (SQLException ex) {
  534. connection = null;
  535. if (reconnectAttempt == 0 || reconnectAttempt >= 11) {
  536. mcMMO.p.getLogger().severe("Connection to MySQL failed!");
  537. printErrors(ex);
  538. }
  539. }
  540. catch (ClassNotFoundException ex) {
  541. connection = null;
  542. if (reconnectAttempt == 0 || reconnectAttempt >= 11) {
  543. mcMMO.p.getLogger().severe("MySQL database driver not found!");
  544. }
  545. }
  546. }
  547. /**
  548. * Checks that the database structure is present and correct
  549. */
  550. private void checkStructure() {
  551. if (!checkConnected()) {
  552. return;
  553. }
  554. write("CREATE TABLE IF NOT EXISTS `" + tablePrefix + "users` ("
  555. + "`id` int(10) unsigned NOT NULL AUTO_INCREMENT,"
  556. + "`user` varchar(40) NOT NULL,"
  557. + "`lastlogin` int(32) unsigned NOT NULL,"
  558. + "PRIMARY KEY (`id`),"
  559. + "UNIQUE KEY `user` (`user`)) DEFAULT CHARSET=latin1 AUTO_INCREMENT=1;");
  560. write("CREATE TABLE IF NOT EXISTS `" + tablePrefix + "huds` ("
  561. + "`user_id` int(10) unsigned NOT NULL,"
  562. + "`mobhealthbar` varchar(50) NOT NULL DEFAULT '" + Config.getInstance().getMobHealthbarDefault() + "',"
  563. + "PRIMARY KEY (`user_id`)) "
  564. + "DEFAULT CHARSET=latin1;");
  565. write("CREATE TABLE IF NOT EXISTS `" + tablePrefix + "cooldowns` ("
  566. + "`user_id` int(10) unsigned NOT NULL,"
  567. + "`taming` int(32) unsigned NOT NULL DEFAULT '0',"
  568. + "`mining` int(32) unsigned NOT NULL DEFAULT '0',"
  569. + "`woodcutting` int(32) unsigned NOT NULL DEFAULT '0',"
  570. + "`repair` int(32) unsigned NOT NULL DEFAULT '0',"
  571. + "`unarmed` int(32) unsigned NOT NULL DEFAULT '0',"
  572. + "`herbalism` int(32) unsigned NOT NULL DEFAULT '0',"
  573. + "`excavation` int(32) unsigned NOT NULL DEFAULT '0',"
  574. + "`archery` int(32) unsigned NOT NULL DEFAULT '0',"
  575. + "`swords` int(32) unsigned NOT NULL DEFAULT '0',"
  576. + "`axes` int(32) unsigned NOT NULL DEFAULT '0',"
  577. + "`acrobatics` int(32) unsigned NOT NULL DEFAULT '0',"
  578. + "`blast_mining` int(32) unsigned NOT NULL DEFAULT '0',"
  579. + "PRIMARY KEY (`user_id`)) "
  580. + "DEFAULT CHARSET=latin1;");
  581. write("CREATE TABLE IF NOT EXISTS `" + tablePrefix + "skills` ("
  582. + "`user_id` int(10) unsigned NOT NULL,"
  583. + "`taming` int(10) unsigned NOT NULL DEFAULT '0',"
  584. + "`mining` int(10) unsigned NOT NULL DEFAULT '0',"
  585. + "`woodcutting` int(10) unsigned NOT NULL DEFAULT '0',"
  586. + "`repair` int(10) unsigned NOT NULL DEFAULT '0',"
  587. + "`unarmed` int(10) unsigned NOT NULL DEFAULT '0',"
  588. + "`herbalism` int(10) unsigned NOT NULL DEFAULT '0',"
  589. + "`excavation` int(10) unsigned NOT NULL DEFAULT '0',"
  590. + "`archery` int(10) unsigned NOT NULL DEFAULT '0',"
  591. + "`swords` int(10) unsigned NOT NULL DEFAULT '0',"
  592. + "`axes` int(10) unsigned NOT NULL DEFAULT '0',"
  593. + "`acrobatics` int(10) unsigned NOT NULL DEFAULT '0',"
  594. + "`fishing` int(10) unsigned NOT NULL DEFAULT '0',"
  595. + "`alchemy` 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. + "`alchemy` int(10) unsigned NOT NULL DEFAULT '0',"
  613. + "PRIMARY KEY (`user_id`)) "
  614. + "DEFAULT CHARSET=latin1;");
  615. for (UpgradeType updateType : UpgradeType.values()) {
  616. checkDatabaseStructure(updateType);
  617. }
  618. mcMMO.p.getLogger().info("Killing orphans");
  619. write("DELETE FROM `" + tablePrefix + "experience` WHERE NOT EXISTS (SELECT * FROM `" + tablePrefix + "users` `u` WHERE `" + tablePrefix + "experience`.`user_id` = `u`.`id`)");
  620. write("DELETE FROM `" + tablePrefix + "huds` WHERE NOT EXISTS (SELECT * FROM `" + tablePrefix + "users` `u` WHERE `" + tablePrefix + "huds`.`user_id` = `u`.`id`)");
  621. write("DELETE FROM `" + tablePrefix + "cooldowns` WHERE NOT EXISTS (SELECT * FROM `" + tablePrefix + "users` `u` WHERE `" + tablePrefix + "cooldowns`.`user_id` = `u`.`id`)");
  622. write("DELETE FROM `" + tablePrefix + "skills` WHERE NOT EXISTS (SELECT * FROM `" + tablePrefix + "users` `u` WHERE `" + tablePrefix + "skills`.`user_id` = `u`.`id`)");
  623. }
  624. /**
  625. * Check database structure for necessary upgrades.
  626. *
  627. * @param upgrade Upgrade to attempt to apply
  628. */
  629. private void checkDatabaseStructure(UpgradeType upgrade) {
  630. if (!checkConnected()) {
  631. return;
  632. }
  633. if (!mcMMO.getUpgradeManager().shouldUpgrade(upgrade)) {
  634. mcMMO.p.debug("Skipping " + upgrade.name() + " upgrade (unneeded)");
  635. return;
  636. }
  637. Statement statement = null;
  638. ResultSet resultSet = null;
  639. try {
  640. statement = connection.createStatement();
  641. switch (upgrade) {
  642. case ADD_FISHING:
  643. try {
  644. statement.executeQuery("SELECT `fishing` FROM `" + tablePrefix + "skills` LIMIT 1");
  645. }
  646. catch (SQLException ex) {
  647. mcMMO.p.getLogger().info("Updating mcMMO MySQL tables for Fishing...");
  648. statement.executeQuery("ALTER TABLE `" + tablePrefix + "skills` ADD `fishing` int(10) NOT NULL DEFAULT '0'");
  649. statement.executeQuery("ALTER TABLE `" + tablePrefix + "experience` ADD `fishing` int(10) NOT NULL DEFAULT '0'");
  650. }
  651. break;
  652. case ADD_BLAST_MINING_COOLDOWN:
  653. try {
  654. statement.executeQuery("SELECT `blast_mining` FROM `" + tablePrefix + "cooldowns` LIMIT 1");
  655. }
  656. catch (SQLException ex) {
  657. mcMMO.p.getLogger().info("Updating mcMMO MySQL tables for Blast Mining...");
  658. statement.executeQuery("ALTER TABLE `" + tablePrefix + "cooldowns` ADD `blast_mining` int(32) NOT NULL DEFAULT '0'");
  659. }
  660. break;
  661. case ADD_SQL_INDEXES:
  662. resultSet = statement.executeQuery("SHOW INDEX FROM `" + tablePrefix + "skills` WHERE `Key_name` LIKE 'idx\\_%'");
  663. resultSet.last();
  664. if (resultSet.getRow() != SkillType.NON_CHILD_SKILLS.size()) {
  665. mcMMO.p.getLogger().info("Indexing tables, this may take a while on larger databases");
  666. for (SkillType skill : SkillType.NON_CHILD_SKILLS) {
  667. String skill_name = skill.name().toLowerCase();
  668. try {
  669. statement.executeUpdate("ALTER TABLE `" + tablePrefix + "skills` ADD INDEX `idx_" + skill_name + "` (`" + skill_name + "`) USING BTREE");
  670. }
  671. catch (SQLException ex) {
  672. // Ignore
  673. }
  674. }
  675. }
  676. break;
  677. case ADD_MOB_HEALTHBARS:
  678. try {
  679. statement.executeQuery("SELECT `mobhealthbar` FROM `" + tablePrefix + "huds` LIMIT 1");
  680. }
  681. catch (SQLException ex) {
  682. mcMMO.p.getLogger().info("Updating mcMMO MySQL tables for mob healthbars...");
  683. statement.executeQuery("ALTER TABLE `" + tablePrefix + "huds` ADD `mobhealthbar` varchar(50) NOT NULL DEFAULT '" + Config.getInstance().getMobHealthbarDefault() + "'");
  684. }
  685. break;
  686. case DROP_SQL_PARTY_NAMES:
  687. try {
  688. resultSet = statement.executeQuery("SELECT * FROM `" + tablePrefix + "users` LIMIT 1");
  689. ResultSetMetaData rsmeta = resultSet.getMetaData();
  690. boolean column_exists = false;
  691. for (int i = 1; i <= rsmeta.getColumnCount(); i++) {
  692. if (rsmeta.getColumnName(i).equalsIgnoreCase("party")) {
  693. column_exists = true;
  694. break;
  695. }
  696. }
  697. if (column_exists) {
  698. mcMMO.p.getLogger().info("Removing party name from users table...");
  699. statement.executeQuery("ALTER TABLE `" + tablePrefix + "users` DROP COLUMN `party`");
  700. }
  701. }
  702. catch (SQLException ex) {
  703. // Ignore
  704. }
  705. break;
  706. case DROP_SPOUT:
  707. try {
  708. resultSet = statement.executeQuery("SELECT * FROM `" + tablePrefix + "huds` LIMIT 1");
  709. ResultSetMetaData rsmeta = resultSet.getMetaData();
  710. boolean column_exists = false;
  711. for (int i = 1; i <= rsmeta.getColumnCount(); i++) {
  712. if (rsmeta.getColumnName(i).equalsIgnoreCase("hudtype")) {
  713. column_exists = true;
  714. break;
  715. }
  716. }
  717. if (column_exists) {
  718. mcMMO.p.getLogger().info("Removing Spout HUD type from huds table...");
  719. statement.executeQuery("ALTER TABLE `" + tablePrefix + "huds` DROP COLUMN `hudtype`");
  720. }
  721. }
  722. catch (SQLException ex) {
  723. // Ignore
  724. }
  725. break;
  726. case ADD_ALCHEMY:
  727. try {
  728. statement.executeQuery("SELECT `alchemy` FROM `" + tablePrefix + "skills` LIMIT 1");
  729. }
  730. catch (SQLException ex) {
  731. mcMMO.p.getLogger().info("Updating mcMMO MySQL tables for Alchemy...");
  732. statement.executeQuery("ALTER TABLE `" + tablePrefix + "skills` ADD `alchemy` int(10) NOT NULL DEFAULT '0'");
  733. statement.executeQuery("ALTER TABLE `" + tablePrefix + "experience` ADD `alchemy` int(10) NOT NULL DEFAULT '0'");
  734. }
  735. break;
  736. default:
  737. break;
  738. }
  739. mcMMO.getUpgradeManager().setUpgradeCompleted(upgrade);
  740. }
  741. catch (SQLException ex) {
  742. }
  743. finally {
  744. if (resultSet != null) {
  745. try {
  746. resultSet.close();
  747. }
  748. catch (SQLException e) {
  749. // Ignore
  750. }
  751. }
  752. if (statement != null) {
  753. try {
  754. statement.close();
  755. }
  756. catch (SQLException e) {
  757. // Ignore
  758. }
  759. }
  760. }
  761. }
  762. /**
  763. * Attempt to write the SQL query.
  764. *
  765. * @param sql Query to write.
  766. *
  767. * @return true if the query was successfully written, false otherwise.
  768. */
  769. private boolean write(String sql) {
  770. if (!checkConnected()) {
  771. return false;
  772. }
  773. PreparedStatement statement = null;
  774. try {
  775. statement = connection.prepareStatement(sql);
  776. statement.executeUpdate();
  777. return true;
  778. }
  779. catch (SQLException ex) {
  780. if (!sql.contains("DROP COLUMN")) {
  781. printErrors(ex);
  782. }
  783. return false;
  784. }
  785. finally {
  786. if (statement != null) {
  787. try {
  788. statement.close();
  789. }
  790. catch (SQLException e) {
  791. // Ignore
  792. }
  793. }
  794. }
  795. }
  796. /**
  797. * Returns the number of rows affected by either a DELETE or UPDATE query
  798. *
  799. * @param sql SQL query to execute
  800. *
  801. * @return the number of rows affected
  802. */
  803. private int update(String sql) {
  804. int rows = 0;
  805. if (checkConnected()) {
  806. PreparedStatement statement = null;
  807. try {
  808. statement = connection.prepareStatement(sql);
  809. rows = statement.executeUpdate();
  810. }
  811. catch (SQLException ex) {
  812. printErrors(ex);
  813. }
  814. finally {
  815. if (statement != null) {
  816. try {
  817. statement.close();
  818. }
  819. catch (SQLException e) {
  820. // Ignore
  821. }
  822. }
  823. }
  824. }
  825. return rows;
  826. }
  827. /**
  828. * Read SQL query.
  829. *
  830. * @param sql SQL query to read
  831. *
  832. * @return the rows in this SQL query
  833. */
  834. private HashMap<Integer, ArrayList<String>> read(String sql) {
  835. HashMap<Integer, ArrayList<String>> rows = new HashMap<Integer, ArrayList<String>>();
  836. if (checkConnected()) {
  837. PreparedStatement statement = null;
  838. ResultSet resultSet;
  839. try {
  840. statement = connection.prepareStatement(sql);
  841. resultSet = statement.executeQuery();
  842. while (resultSet.next()) {
  843. ArrayList<String> column = new ArrayList<String>();
  844. for (int i = 1; i <= resultSet.getMetaData().getColumnCount(); i++) {
  845. column.add(resultSet.getString(i));
  846. }
  847. rows.put(resultSet.getRow(), column);
  848. }
  849. }
  850. catch (SQLException ex) {
  851. printErrors(ex);
  852. }
  853. finally {
  854. if (statement != null) {
  855. try {
  856. statement.close();
  857. }
  858. catch (SQLException e) {
  859. // Ignore
  860. }
  861. }
  862. }
  863. }
  864. return rows;
  865. }
  866. /**
  867. * Get the Integer. Only return first row / first field.
  868. *
  869. * @param statement SQL query to execute
  870. *
  871. * @return the value in the first row / first field
  872. */
  873. private int readInt(PreparedStatement statement) {
  874. int result = -1;
  875. if (checkConnected()) {
  876. ResultSet resultSet;
  877. try {
  878. resultSet = statement.executeQuery();
  879. if (resultSet.next()) {
  880. result = resultSet.getInt(1);
  881. }
  882. }
  883. catch (SQLException ex) {
  884. printErrors(ex);
  885. }
  886. finally {
  887. if (statement != null) {
  888. try {
  889. statement.close();
  890. }
  891. catch (SQLException e) {
  892. // Ignore
  893. }
  894. }
  895. }
  896. }
  897. return result;
  898. }
  899. private void writeMissingRows(int id) {
  900. PreparedStatement statement = null;
  901. try {
  902. statement = connection.prepareStatement("INSERT IGNORE INTO " + tablePrefix + "experience (user_id) VALUES (?)");
  903. statement.setInt(1, id);
  904. statement.execute();
  905. statement.close();
  906. statement = connection.prepareStatement("INSERT IGNORE INTO " + tablePrefix + "skills (user_id) VALUES (?)");
  907. statement.setInt(1, id);
  908. statement.execute();
  909. statement.close();
  910. statement = connection.prepareStatement("INSERT IGNORE INTO " + tablePrefix + "cooldowns (user_id) VALUES (?)");
  911. statement.setInt(1, id);
  912. statement.execute();
  913. statement.close();
  914. statement = connection.prepareStatement("INSERT IGNORE INTO " + tablePrefix + "huds (user_id, mobhealthbar) VALUES (? ,'" + Config.getInstance().getMobHealthbarDefault().name() + "')");
  915. statement.setInt(1, id);
  916. statement.execute();
  917. statement.close();
  918. }
  919. catch (SQLException ex) {
  920. printErrors(ex);
  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 void processPurge(Collection<ArrayList<String>> usernames) {
  934. for (ArrayList<String> user : usernames) {
  935. Misc.profileCleanup(user.get(0));
  936. }
  937. }
  938. private boolean saveIntegers(String sql, int... args) {
  939. PreparedStatement statement = null;
  940. try {
  941. statement = connection.prepareStatement(sql);
  942. int i = 1;
  943. for (int arg : args) {
  944. statement.setInt(i++, arg);
  945. }
  946. statement.execute();
  947. return true;
  948. }
  949. catch (SQLException ex) {
  950. printErrors(ex);
  951. return false;
  952. }
  953. finally {
  954. if (statement != null) {
  955. try {
  956. statement.close();
  957. }
  958. catch (SQLException e) {
  959. // Ignore
  960. }
  961. }
  962. }
  963. }
  964. private boolean saveLongs(String sql, int id, long... args) {
  965. PreparedStatement statement = null;
  966. try {
  967. statement = connection.prepareStatement(sql);
  968. int i = 1;
  969. for (long arg : args) {
  970. statement.setLong(i++, arg);
  971. }
  972. statement.setInt(i++, id);
  973. statement.execute();
  974. return true;
  975. }
  976. catch (SQLException ex) {
  977. printErrors(ex);
  978. return false;
  979. }
  980. finally {
  981. if (statement != null) {
  982. try {
  983. statement.close();
  984. }
  985. catch (SQLException e) {
  986. // Ignore
  987. }
  988. }
  989. }
  990. }
  991. /**
  992. * Retrieve the database id for a player
  993. *
  994. * @param playerName The name of the user to retrieve the id for
  995. *
  996. * @return the requested id or -1 if not found
  997. */
  998. private int readId(String playerName) {
  999. int id = -1;
  1000. try {
  1001. PreparedStatement statement = connection.prepareStatement("SELECT id FROM " + tablePrefix + "users WHERE user = ?");
  1002. statement.setString(1, playerName);
  1003. id = readInt(statement);
  1004. }
  1005. catch (SQLException ex) {
  1006. printErrors(ex);
  1007. }
  1008. return id;
  1009. }
  1010. private boolean saveLogin(int id, long login) {
  1011. PreparedStatement statement = null;
  1012. try {
  1013. statement = connection.prepareStatement("UPDATE " + tablePrefix + "users SET lastlogin = ? WHERE id = ?");
  1014. statement.setLong(1, login);
  1015. statement.setInt(2, id);
  1016. statement.execute();
  1017. return true;
  1018. }
  1019. catch (SQLException ex) {
  1020. printErrors(ex);
  1021. return false;
  1022. }
  1023. finally {
  1024. if (statement != null) {
  1025. try {
  1026. statement.close();
  1027. }
  1028. catch (SQLException e) {
  1029. // Ignore
  1030. }
  1031. }
  1032. }
  1033. }
  1034. private boolean saveHuds(int userId, String mobHealthBar) {
  1035. PreparedStatement statement = null;
  1036. try {
  1037. statement = connection.prepareStatement("UPDATE " + tablePrefix + "huds SET mobhealthbar = ? WHERE user_id = ?");
  1038. statement.setString(1, mobHealthBar);
  1039. statement.setInt(2, userId);
  1040. statement.execute();
  1041. return true;
  1042. }
  1043. catch (SQLException ex) {
  1044. printErrors(ex);
  1045. return false;
  1046. }
  1047. finally {
  1048. if (statement != null) {
  1049. try {
  1050. statement.close();
  1051. }
  1052. catch (SQLException e) {
  1053. // Ignore
  1054. }
  1055. }
  1056. }
  1057. }
  1058. private PlayerProfile loadFromResult(String playerName, ResultSet result) throws SQLException {
  1059. Map<SkillType, Integer> skills = new HashMap<SkillType, Integer>(); // Skill & Level
  1060. Map<SkillType, Float> skillsXp = new HashMap<SkillType, Float>(); // Skill & XP
  1061. Map<AbilityType, Integer> skillsDATS = new HashMap<AbilityType, Integer>(); // Ability & Cooldown
  1062. MobHealthbarType mobHealthbarType;
  1063. final int OFFSET_SKILLS = 0; // TODO update these numbers when the query changes (a new skill is added)
  1064. final int OFFSET_XP = 13;
  1065. final int OFFSET_DATS = 26;
  1066. final int OFFSET_OTHER = 38;
  1067. skills.put(SkillType.TAMING, result.getInt(OFFSET_SKILLS + 1));
  1068. skills.put(SkillType.MINING, result.getInt(OFFSET_SKILLS + 2));
  1069. skills.put(SkillType.REPAIR, result.getInt(OFFSET_SKILLS + 3));
  1070. skills.put(SkillType.WOODCUTTING, result.getInt(OFFSET_SKILLS + 4));
  1071. skills.put(SkillType.UNARMED, result.getInt(OFFSET_SKILLS + 5));
  1072. skills.put(SkillType.HERBALISM, result.getInt(OFFSET_SKILLS + 6));
  1073. skills.put(SkillType.EXCAVATION, result.getInt(OFFSET_SKILLS + 7));
  1074. skills.put(SkillType.ARCHERY, result.getInt(OFFSET_SKILLS + 8));
  1075. skills.put(SkillType.SWORDS, result.getInt(OFFSET_SKILLS + 9));
  1076. skills.put(SkillType.AXES, result.getInt(OFFSET_SKILLS + 10));
  1077. skills.put(SkillType.ACROBATICS, result.getInt(OFFSET_SKILLS + 11));
  1078. skills.put(SkillType.FISHING, result.getInt(OFFSET_SKILLS + 12));
  1079. skills.put(SkillType.ALCHEMY, result.getInt(OFFSET_SKILLS + 13));
  1080. skillsXp.put(SkillType.TAMING, result.getFloat(OFFSET_XP + 1));
  1081. skillsXp.put(SkillType.MINING, result.getFloat(OFFSET_XP + 2));
  1082. skillsXp.put(SkillType.REPAIR, result.getFloat(OFFSET_XP + 3));
  1083. skillsXp.put(SkillType.WOODCUTTING, result.getFloat(OFFSET_XP + 4));
  1084. skillsXp.put(SkillType.UNARMED, result.getFloat(OFFSET_XP + 5));
  1085. skillsXp.put(SkillType.HERBALISM, result.getFloat(OFFSET_XP + 6));
  1086. skillsXp.put(SkillType.EXCAVATION, result.getFloat(OFFSET_XP + 7));
  1087. skillsXp.put(SkillType.ARCHERY, result.getFloat(OFFSET_XP + 8));
  1088. skillsXp.put(SkillType.SWORDS, result.getFloat(OFFSET_XP + 9));
  1089. skillsXp.put(SkillType.AXES, result.getFloat(OFFSET_XP + 10));
  1090. skillsXp.put(SkillType.ACROBATICS, result.getFloat(OFFSET_XP + 11));
  1091. skillsXp.put(SkillType.FISHING, result.getFloat(OFFSET_XP + 12));
  1092. skillsXp.put(SkillType.ALCHEMY, result.getFloat(OFFSET_XP + 13));
  1093. // Taming - Unused - result.getInt(OFFSET_DATS + 1)
  1094. skillsDATS.put(AbilityType.SUPER_BREAKER, result.getInt(OFFSET_DATS + 2));
  1095. // Repair - Unused - result.getInt(OFFSET_DATS + 3)
  1096. skillsDATS.put(AbilityType.TREE_FELLER, result.getInt(OFFSET_DATS + 4));
  1097. skillsDATS.put(AbilityType.BERSERK, result.getInt(OFFSET_DATS + 5));
  1098. skillsDATS.put(AbilityType.GREEN_TERRA, result.getInt(OFFSET_DATS + 6));
  1099. skillsDATS.put(AbilityType.GIGA_DRILL_BREAKER, result.getInt(OFFSET_DATS + 7));
  1100. // Archery - Unused - result.getInt(OFFSET_DATS + 8)
  1101. skillsDATS.put(AbilityType.SERRATED_STRIKES, result.getInt(OFFSET_DATS + 9));
  1102. skillsDATS.put(AbilityType.SKULL_SPLITTER, result.getInt(OFFSET_DATS + 10));
  1103. // Acrobatics - Unused - result.getInt(OFFSET_DATS + 11)
  1104. skillsDATS.put(AbilityType.BLAST_MINING, result.getInt(OFFSET_DATS + 12));
  1105. try {
  1106. mobHealthbarType = MobHealthbarType.valueOf(result.getString(OFFSET_OTHER + 2));
  1107. }
  1108. catch (Exception e) {
  1109. mobHealthbarType = Config.getInstance().getMobHealthbarDefault();
  1110. }
  1111. return new PlayerProfile(playerName, skills, skillsXp, skillsDATS, mobHealthbarType);
  1112. }
  1113. private void printErrors(SQLException ex) {
  1114. mcMMO.p.getLogger().severe("SQLException: " + ex.getMessage());
  1115. mcMMO.p.getLogger().severe("SQLState: " + ex.getSQLState());
  1116. mcMMO.p.getLogger().severe("VendorError: " + ex.getErrorCode());
  1117. }
  1118. public DatabaseType getDatabaseType() {
  1119. return DatabaseType.SQL;
  1120. }
  1121. }