Guest User

Untitled

a guest
Jan 15th, 2018
79
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 8.70 KB | None | 0 0
  1. import java.sql.Connection;
  2. import java.sql.DriverManager;
  3. import java.sql.PreparedStatement;
  4. import java.sql.ResultSet;
  5. import java.sql.SQLException;
  6. import java.sql.Statement;
  7. import java.util.List;
  8. import java.util.Map;
  9. import java.util.stream.Collectors;
  10. import java.util.stream.IntStream;
  11.  
  12. import org.bukkit.configuration.ConfigurationSection;
  13.  
  14. import com.google.common.base.Joiner;
  15. import com.google.common.collect.Lists;
  16. import com.google.common.collect.Maps;
  17. import us.opalprison.core.OPalCore;
  18. import us.opalprison.core.utils.Lambda;
  19.  
  20. public class MySQL {
  21.  
  22. private static MySQL instance;
  23. private Connection connection;
  24. private OPalCore plugin;
  25.  
  26. public MySQL(OPalCore plugin) {
  27. this.plugin = plugin;
  28. instance = this;
  29. }
  30.  
  31. /**
  32. * Gets a map of values of length num. If orderedBy is specified results
  33. * will be ordered descending. Advanced selection allows for the database to
  34. * do division or multiplication but should not be used to try to obtain
  35. * extra columns.
  36. *
  37. * Keys and values in the returned map should never be null.
  38. *
  39. * @param table table to access
  40. * @param advancedSelection column or calculated value to get
  41. * @param orderedBy column or equation to order by
  42. * @param num number of rows to get
  43. * @return
  44. */
  45. public <K> Map<K, Object> getRows(Table table, Column<K> keyColumn,
  46. String advancedSelection, String orderedBy, int num) {
  47. String query =
  48. "SELECT " + keyColumn + "," + advancedSelection + " FROM " + table;
  49. if (orderedBy != null) {
  50. query += " ORDER BY " + orderedBy + " DESC";
  51. }
  52. query += " LIMIT " + num;
  53.  
  54. checkConnectionOpen();
  55.  
  56. try (Statement s = connection.createStatement()) {
  57. ResultSet rs = s.executeQuery(query);
  58. Map<K, Object> result = Maps.newLinkedHashMap();
  59. while (rs.next()) {
  60. K key = keyColumn.dataType().deserialize(rs.getObject(1));
  61. Object value = rs.getObject(2);
  62. if (value == null) {
  63. continue;
  64. }
  65.  
  66. result.put(key, value);
  67. }
  68. return result;
  69. } catch (SQLException e) {
  70. plugin.getLogger().severe("Error with MySQL: " + e.getMessage());
  71. }
  72.  
  73. return null;
  74. }
  75.  
  76. /**
  77. * Retrieves a value from the database which is related to a certain key
  78. *
  79. * @param targetColumn column containing the desired value
  80. * @param table table to access
  81. * @param keyColumn column containing the key
  82. * @param key key
  83. * @return value if it exists otherwise null
  84. */
  85. public <K, V> V select(Column<V> targetColumn, Table table,
  86. Column<K> keyColumn, K key) {
  87. String query =
  88. "SELECT " + targetColumn + " FROM " + table + " WHERE " + keyColumn
  89. + " = '" + keyColumn.dataType().serialize(key) + "' LIMIT 1";
  90.  
  91. checkConnectionOpen();
  92.  
  93. try (Statement s = connection.createStatement()) {
  94. ResultSet rs = s.executeQuery(query);
  95. while (rs.next()) {
  96. Object o = rs.getObject(1);
  97. return o == null ? null
  98. : targetColumn.dataType().deserialize(o);
  99. }
  100. } catch (SQLException e) {
  101. plugin.getLogger().severe("Error with MySQL: " + e.getMessage());
  102. }
  103.  
  104. return null;
  105. }
  106.  
  107. public List<List<Object>> selectAll(Table table) {
  108. String query = "SELECT * FROM " + table;
  109. checkConnectionOpen();
  110. List<List<Object>> rows = Lists.newArrayList();
  111. try (Statement s = connection.createStatement()) {
  112. ResultSet rs = s.executeQuery(query);
  113. while (rs.next()) {
  114. rows.add(IntStream.range(0, rs.getMetaData().getColumnCount())
  115. .mapToObj(
  116. Lambda.ofInt(rs::getObject, this::handleException))
  117. .collect(Collectors.toList()));
  118. }
  119. } catch (SQLException e) {
  120. handleException(e);
  121. }
  122.  
  123. return rows;
  124. }
  125.  
  126. public void handleException(Exception e) {
  127. plugin.getLogger().severe("Error with MySQL: " + e.getMessage());
  128. }
  129.  
  130. public <K, V> void update(Table table, Column<V> valueColumn, V value,
  131. Column<K> keyColumn, K key) {
  132. String update = "UPDATE " + table + " SET " + valueColumn
  133. + " = ? WHERE " + keyColumn + " = ?";
  134.  
  135. checkConnectionOpen();
  136.  
  137. try (PreparedStatement s = connection.prepareStatement(update)) {
  138. s.setObject(1, valueColumn.dataType().serialize(value));
  139. s.setObject(2, keyColumn.dataType().serialize(key));
  140. s.executeUpdate();
  141. } catch (SQLException e) {
  142. plugin.getLogger().severe("Error with MySQL: " + e.getMessage());
  143. }
  144. }
  145.  
  146. public <K> void deleteRow(Table table, Column<K> keyColumn, K key) {
  147. String update = "DELETE FROM " + table + " WHERE " + keyColumn + " = "
  148. + keyColumn.dataType().serialize(key);
  149. checkConnectionOpen();
  150. try (PreparedStatement s = connection.prepareStatement(update)) {
  151. s.executeUpdate();
  152. } catch (SQLException e) {
  153. handleException(e);
  154. }
  155. }
  156.  
  157. public <K> void makeNewRow(Table table, Column<K> keyColumn, K key) {
  158. checkConnectionOpen();
  159. try (Statement s = connection.createStatement()) {
  160. String query =
  161. "SELECT " + keyColumn + " FROM " + table + " WHERE " + keyColumn
  162. + " = '" + keyColumn.dataType().serialize(key) + "'";
  163.  
  164. ResultSet rs = s.executeQuery(query);
  165. if (!rs.next()) {
  166. String columnNames = Joiner.on(", ").join(table.getColumns());
  167. String values = table.getColumns().stream().map(c -> {
  168. if (c.equals(keyColumn)) {
  169. return keyColumn.dataType().serialize(key);
  170. }
  171.  
  172. return c.dataType().serializedDef();
  173. }).map(o -> "'" + o.toString() + "'")
  174. .reduce((o1, o2) -> o1 + ", " + o2).orElse("");
  175. query = "INSERT INTO " + table + " (" + columnNames
  176. + ") VALUES (" + values + ")";
  177.  
  178. s.executeUpdate(query);
  179. }
  180. } catch (SQLException e) {
  181. plugin.getLogger().severe("Error with MySQL: " + e.getMessage());
  182. }
  183. }
  184.  
  185. public void createTable(Table table) {
  186. checkConnectionOpen();
  187. List<String> namesWithTypes = table.getNamesWithTypes();
  188. executeUpdate("CREATE TABLE IF NOT EXISTS " + table + " ("
  189. + Joiner.on(", ").join(namesWithTypes) + ")");
  190. namesWithTypes.stream().forEach(s -> {
  191. String value = table.getColumns().stream()
  192. .filter(c -> c.name().equalsIgnoreCase(s.split(" ")[0]))
  193. .map(c -> c.dataType().serializedDef().toString()).findAny()
  194. .orElse("''");
  195. executeUpdate("ALTER TABLE " + table + " ADD COLUMN " + s
  196. + " DEFAULT " + value);
  197. });
  198. }
  199.  
  200. private void executeUpdate(String update) {
  201. try (Statement s = connection.createStatement()) {
  202. s.executeUpdate(update);
  203. } catch (SQLException e) {
  204. plugin.getLogger().severe("Error with MySQL: " + e.getMessage());
  205. }
  206. }
  207.  
  208. private void checkConnectionOpen() {
  209. try {
  210. if (connection == null || connection.isClosed()) {
  211. openConnection();
  212. }
  213. } catch (SQLException e1) {
  214.  
  215. }
  216. }
  217.  
  218. private void openConnection() {
  219. closeConnection();
  220.  
  221. ConfigurationSection c =
  222. plugin.getConfig().getConfigurationSection("database");
  223.  
  224. String host = c.getString("host");
  225. String port = c.getString("port");
  226. String name = c.getString("name");
  227. String user = c.getString("user");
  228. String pass = c.getString("pass");
  229.  
  230. try {
  231. connection = DriverManager.getConnection(
  232. "jdbc:mysql://" + host + ":" + port + "/" + name, user, pass);
  233. } catch (SQLException e) {
  234. plugin.getLogger().severe("Error with MySQL: " + e.getMessage());
  235. }
  236. }
  237.  
  238. public void closeConnection() {
  239. if (connection == null) {
  240. return;
  241. }
  242.  
  243. try {
  244. connection.close();
  245. } catch (SQLException e) {
  246. plugin.getLogger().severe("Error with MySQL: " + e.getMessage());
  247. }
  248.  
  249. connection = null;
  250. }
  251.  
  252. public static MySQL getInstance() {
  253. return instance;
  254. }
  255.  
  256. }
Add Comment
Please, Sign In to add comment