Advertisement
Guest User

Mysql

a guest
Apr 6th, 2016
101
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 8.41 KB | None | 0 0
  1. import com.google.common.collect.Lists;
  2. import com.mysql.jdbc.Connection;
  3. import org.apollodevs.smashheroes.SmashHeroes;
  4. import org.bukkit.configuration.ConfigurationSection;
  5.  
  6. import java.sql.*;
  7. import java.util.ArrayList;
  8. import java.util.HashMap;
  9. import java.util.Map;
  10. import java.util.UUID;
  11. import java.util.concurrent.ExecutorService;
  12. import java.util.concurrent.Executors;
  13.  
  14. /**
  15. * MySQL Database management utility
  16. */
  17. public class MySQLDatabase {
  18. private static ExecutorService executeThread = Executors.newSingleThreadExecutor(), prepareThread = Executors.newSingleThreadExecutor(), runnableThread = Executors.newSingleThreadExecutor();
  19. public String table;
  20. private String host;
  21. private String username;
  22. private String password;
  23. private String database;
  24. private int timeout = 10000;
  25. private Connection con;
  26.  
  27. /**
  28. * Initialize and load MySQL settings from the config
  29. */
  30. public MySQLDatabase() {
  31. ConfigurationSection c = SmashHeroes.kf.getConfigurationSection("mysql");
  32. host = c.getString("host");
  33. username = c.getString("username");
  34. password = c.getString("password");
  35. database = c.getString("database");
  36. table = c.getString("table");
  37. timeout = c.getInt("timeout");
  38. prepareThread.submit(new MySQLPrepare(Lists.newArrayList("CREATE TABLE IF NOT EXISTS `" + table + "` (`uuid` TINYTEXT, `key` TEXT, `value` TEXT)"), null));
  39. }
  40.  
  41. public static String escape(String in) {
  42. StringBuilder out = new StringBuilder();
  43. for (char c : in.toCharArray()) {
  44. switch (c) {
  45. case '\u0000':
  46. out.append("\\0");
  47. break;
  48. case '\u001a':
  49. out.append("\\Z");
  50. break;
  51. case '\n':
  52. out.append("\\n");
  53. break;
  54. case '\r':
  55. out.append("\\r");
  56. break;
  57. case '\'':
  58. out.append("\\'");
  59. break;
  60. case '"':
  61. out.append("\\\"");
  62. break;
  63. case '\\':
  64. out.append("\\\\");
  65. break;
  66. default:
  67. out.append(c);
  68. }
  69. }
  70. return out.toString();
  71. }
  72.  
  73. /**
  74. * Execute a MySQL command from the current thread
  75. *
  76. * @param cmd - The MySQL command
  77. * @return The success of the command execution
  78. */
  79. public boolean command(String cmd) {
  80. PreparedStatement st;
  81. try {
  82. st = getConnection().prepareStatement(cmd);
  83. return st.execute();
  84. } catch (Throwable ex) {
  85. ex.printStackTrace();
  86. }
  87. return false;
  88. }
  89.  
  90. /**
  91. * Get the data of a player from the database.
  92. * This process will took long time, so use an
  93. * async thread for calling this method
  94. *
  95. * @param uid - The UUID of the player
  96. * @return The map with the player data loaded from the database
  97. */
  98. public HashMap<String, String> get(UUID uid) {
  99. HashMap<String, String> out = new HashMap<>();
  100. try {
  101. ResultSet rs = querry("SELECT `key`,`value` FROM `" + table + "` WHERE `uuid` = \"" + escape(uid.toString()) + "\" LIMIT 1");
  102. while (rs.next()) {
  103. out.put(rs.getString(1), rs.getString(2));
  104. }
  105. } catch (Throwable e) {
  106. e.printStackTrace();
  107. }
  108. return out;
  109. }
  110.  
  111. private Connection getConnection() {
  112. try {
  113. if (this.con == null || !this.con.isValid(timeout)) {
  114. this.openConnection();
  115. }
  116. } catch (Throwable e) {
  117. e.printStackTrace();
  118. }
  119. return this.con;
  120. }
  121.  
  122. /**
  123. * Opens connection to the MySQL
  124. *
  125. * @return The success of the connection opening
  126. */
  127. public boolean openConnection() {
  128. try {
  129. System.out.println("[Smash Heroes] Connecting to server database!");
  130. this.con = (Connection) DriverManager.getConnection("jdbc:mysql://" + this.host + "/" + this.database + "?autoReconnect=true", this.username, this.password);
  131. this.con.setAutoReconnect(true);
  132. this.con.setConnectTimeout(timeout);
  133. System.out.println("[Smash Heroes] Connected to mySQL!");
  134. } catch (Throwable e) {
  135. e.printStackTrace();
  136. return false;
  137. }
  138. return true;
  139. }
  140.  
  141. /**
  142. * Executes a querry request from the current thread
  143. *
  144. * @param cmd - The querry command
  145. * @return The result of the querry
  146. */
  147. public ResultSet querry(String cmd) {
  148. ResultSet rs;
  149. PreparedStatement st;
  150. try {
  151. st = getConnection().prepareStatement(cmd);
  152. rs = st.executeQuery();
  153. return rs;
  154. } catch (Throwable ex) {
  155. ex.printStackTrace();
  156. return null;
  157. }
  158. }
  159.  
  160. /**
  161. * Remove a player from the database, feel free to use this method
  162. * from any kind of thread, because it executes fast
  163. *
  164. * @param uid - The UUID of the removable player
  165. * @param afterDone - An optional runnable which will be executed after the
  166. * remove process is done
  167. */
  168. public void remove(UUID uid, Runnable afterDone) {
  169. prepareThread.submit(new MySQLPrepare(Lists.newArrayList("\"DELETE FROM `\"+ table+\" WHERE `uuid` = \"" + escape(uid.toString()) + "\""), afterDone));
  170. }
  171.  
  172. /**
  173. * Set the data of the given player in the MySQL, feel free to use this method
  174. * from any kind of thread, because it executes fast
  175. *
  176. * @param uid - The UUID of the setable player
  177. * @param data - The saveable data
  178. * @param afterDone - An optional runnable which will be executed after the
  179. * remove process is done
  180. */
  181. public void set(UUID uid, HashMap<String, String> data, Runnable afterDone) {
  182. ArrayList<String> cmds = new ArrayList<>();
  183. String uis = escape(uid.toString());
  184. cmds.add("DELETE FROM `" + table + "` WHERE `uuid`=\"" + uis + "\"");
  185. for (Map.Entry<String, String> e : data.entrySet()) {
  186. cmds.add("INSERT INTO `" + table + "` VALUES (\"" + uis + "\", \"" + escape(e.getKey()) + "\", \"" + escape(e.getValue()) + "\")");
  187. }
  188. prepareThread.submit(new MySQLPrepare(cmds, afterDone));
  189. }
  190.  
  191. /**
  192. * Executes an update request from the current thread
  193. *
  194. * @param cmd - The update command
  195. * @return The number of updated lines
  196. */
  197. public int update(String cmd) {
  198. PreparedStatement st;
  199. try {
  200. st = getConnection().prepareStatement(cmd);
  201. int out = st.executeUpdate();
  202. return out;
  203. } catch (Throwable ex) {
  204. ex.printStackTrace();
  205. return -1;
  206. }
  207. }
  208.  
  209. /**
  210. * The runnable for thread used for executing MySQL statements
  211. */
  212. public class MySQLExecute implements Runnable {
  213. private final Statement st;
  214. private final Runnable r;
  215.  
  216. public MySQLExecute(Statement st, Runnable r) {
  217. this.st = st;
  218. this.r = r;
  219. }
  220.  
  221. public void run() {
  222. try {
  223. st.executeBatch();
  224. if (r != null)
  225. runnableThread.submit(r);
  226. } catch (SQLException e) {
  227. e.printStackTrace();
  228. }
  229. }
  230. }
  231.  
  232. /**
  233. * The runnable for thread used to prepare MySQL statements from String commands
  234. */
  235. public class MySQLPrepare implements Runnable {
  236. private final Iterable<String> ps;
  237. private final Runnable r;
  238.  
  239. public MySQLPrepare(Iterable<String> cmds, Runnable r) {
  240. this.ps = cmds;
  241. this.r = r;
  242. }
  243.  
  244. public void run() {
  245. try {
  246. Statement st = getConnection().createStatement();
  247. for (String s : ps) {
  248. st.addBatch(s);
  249. }
  250. executeThread.submit(new MySQLExecute(st, r));
  251. } catch (Throwable e) {
  252. e.printStackTrace();
  253. }
  254. }
  255. }
  256. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement