DataBank.java 2.5 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889
  1. package me.km.databank;
  2. import java.sql.Connection;
  3. import java.sql.DriverManager;
  4. import java.sql.SQLException;
  5. import java.sql.Statement;
  6. import me.km.api.Module;
  7. import me.km.scheduler.SnuviScheduler;
  8. import net.minecraft.util.text.TextFormatting;
  9. public class DataBank extends Module
  10. {
  11. private final static DummyStatement DUMMY_STATEMENT = new DummyStatement();
  12. private Connection c;
  13. private final String user;
  14. private final String password;
  15. public DataBank(String mname, String prefix, TextFormatting color, String user, String password)
  16. {
  17. super(mname, prefix, color);
  18. this.user = user;
  19. this.password = password;
  20. }
  21. public boolean openDataBankConnection()
  22. {
  23. c = null;
  24. try
  25. {
  26. // The newInstance() call is a work around for some broken Java implementations
  27. Class.forName("com.mysql.jdbc.Driver").newInstance();
  28. c = DriverManager.getConnection("jdbc:mysql://localhost/minecraft?autoReconnect=true", user, password);
  29. this.sendToConsole("Die Verbindung wurde erfolgreich aufgebaut.");
  30. return true;
  31. }
  32. catch(ClassNotFoundException | IllegalAccessException | InstantiationException | SQLException ex)
  33. {
  34. this.sendWarningToConsole(ex.toString());
  35. return false;
  36. }
  37. }
  38. public void closeDataBankConnection()
  39. {
  40. try
  41. {
  42. c.close();
  43. this.sendToConsole("Die Verbindung wurde erfolgreich unterbrochen.");
  44. }
  45. catch (SQLException ex)
  46. {
  47. this.sendWarningToConsole(ex.getMessage());
  48. }
  49. catch (NullPointerException ex)
  50. {
  51. }
  52. }
  53. public boolean isDummyDatabank()
  54. {
  55. return c == null;
  56. }
  57. public Statement createStatement() throws SQLException
  58. {
  59. if(c == null)
  60. {
  61. return DUMMY_STATEMENT;
  62. }
  63. return c.createStatement();
  64. }
  65. public void startReconnecting(SnuviScheduler scheduler)
  66. {
  67. scheduler.scheduleRepeatingTask(() ->
  68. {
  69. try(Statement stmt = createStatement())
  70. {
  71. // pointless query just for reconnecting
  72. stmt.executeUpdate("SHOW TABLES IN minecraft");
  73. }
  74. catch(SQLException ex)
  75. {
  76. sendToConsole("reconnect was done");
  77. }
  78. }, 100, 12000); // doing this every 10 minutes
  79. }
  80. }