PageRenderTime 29ms CodeModel.GetById 17ms RepoModel.GetById 0ms app.codeStats 1ms

/src/mpv5/db/common/DatabaseConnection.java

http://mp-rechnungs-und-kundenverwaltung.googlecode.com/
Java | 324 lines | 225 code | 32 blank | 67 comment | 27 complexity | bf2cced830aee14a82aff648b02f19b2 MD5 | raw file
Possible License(s): LGPL-3.0, Apache-2.0, GPL-3.0, GPL-2.0, AGPL-3.0, JSON, BSD-3-Clause
  1. /*
  2. * To change this template, choose Tools | Templates
  3. * and open the template in the editor.
  4. */
  5. package mpv5.db.common;
  6. import java.sql.Connection;
  7. import java.sql.Driver;
  8. import java.sql.DriverManager;
  9. import java.sql.SQLException;
  10. import java.sql.Statement;
  11. import java.util.logging.Level;
  12. import java.util.logging.Logger;
  13. import javax.swing.JProgressBar;
  14. import mpv5.Main;
  15. import mpv5.db.objects.User;
  16. import mpv5.globals.LocalSettings;
  17. import mpv5.globals.Messages;
  18. import mpv5.logging.Log;
  19. import mpv5.ui.dialogs.Popup;
  20. /**
  21. *
  22. *
  23. */
  24. public class DatabaseConnection {
  25. private static java.sql.Connection conn;
  26. private static DatabaseConnection connector;
  27. /**
  28. * @return the connector
  29. */
  30. public static DatabaseConnection getConnector() {
  31. return connector;
  32. }
  33. /**
  34. * @return the user
  35. */
  36. public static String getUser() {
  37. return user;
  38. }
  39. /**
  40. * @return the password
  41. */
  42. public static String getPassword() {
  43. return password;
  44. }
  45. /**
  46. * @return the prefix
  47. */
  48. public static String getPrefix() {
  49. return prefix;
  50. }
  51. private ConnectionTypeHandler ctype;
  52. private static String user;
  53. private static String password;
  54. private static String prefix = "";
  55. /**
  56. *
  57. * @return Database connector
  58. * @throws Exception
  59. */
  60. public static synchronized DatabaseConnection instanceOf() throws Exception {
  61. if (getConnector() == null) {
  62. connector = new DatabaseConnection();
  63. getConnector().connect(false);
  64. new connectionPing(connector).start();
  65. }
  66. return getConnector();
  67. }
  68. private Statement statement;
  69. private JProgressBar prog;
  70. /**
  71. *
  72. * @return
  73. */
  74. public java.sql.Connection getConnection() {
  75. return conn;
  76. }
  77. /**
  78. * Test-Verbindung zur Datenbank herstellen.
  79. *
  80. * @param predefinedDriver
  81. * @param user
  82. * @param password
  83. * @param location
  84. * @param dbname
  85. * @param create
  86. * @return Connection
  87. * @throws Exception
  88. */
  89. public boolean connect(String predefinedDriver, String user, String password, String location, String dbname, String prefix, boolean create) throws Exception {
  90. try {
  91. ctype = new ConnectionTypeHandler();
  92. getCtype().setDRIVER(predefinedDriver);
  93. getCtype().setURL(location);
  94. getCtype().setDBName(dbname);
  95. getCtype().setPrefix(prefix);
  96. DatabaseConnection.user = user;
  97. DatabaseConnection.password = password;
  98. DatabaseConnection.prefix = prefix;
  99. DriverManager.registerDriver((Driver) Class.forName(getCtype().getDriver()).newInstance());
  100. Log.Debug(this, "Driver: " + getCtype().getDriver());
  101. } catch (Exception ex) {
  102. Log.Debug(this, ex.getMessage());
  103. }
  104. return reconnect(create);
  105. }
  106. public boolean reconnect(boolean create) throws SQLException {
  107. Statement stmt;
  108. String sql;
  109. try {
  110. Log.Debug(this, "RECONNECT::Datenbankverbindung: " + getCtype().getConnectionString(create));
  111. conn = DriverManager.getConnection(getCtype().getConnectionString(create), user, password);
  112. conn.setAutoCommit(true);
  113. if (conn != null //&& conn.isValid(10)//does not work with MySQL Connector/J 5.0
  114. ) {//mysql (and others) need explicit create database, derby does it by itself
  115. if (create && ConnectionTypeHandler.getDriverType() != ConnectionTypeHandler.DERBY) {
  116. stmt = conn.createStatement();
  117. conn.setCatalog(ConnectionTypeHandler.getDBNAME());
  118. if (User.PROPERTIES_OVERRIDE.hasProperty("drop_database_on_create")) {
  119. try {
  120. sql = "DROP DATABASE "
  121. + ConnectionTypeHandler.getDBNAME()
  122. + ";";
  123. stmt.execute(sql);
  124. } catch (SQLException ex) {
  125. Log.Debug(this, "Database Error Cleaing of old DB failed!");
  126. }
  127. }
  128. try {
  129. sql = "CREATE DATABASE "
  130. + ConnectionTypeHandler.getDBNAME()
  131. + " ;";
  132. stmt.execute(sql);
  133. } catch (SQLException ex) {
  134. Popup.OK_dialog(Messages.CREATE_DATABASE_OWN.toString(), "Database Creation");
  135. return false;
  136. }
  137. }
  138. connector = this;
  139. return true;
  140. } else {
  141. throw new RuntimeException("Could not create connection: " + getCtype().getConnectionString(create));
  142. }
  143. } catch (SQLException ex) {
  144. System.out.println("Database Error: " + ex.getMessage());
  145. Popup.notice(ex.getLocalizedMessage());
  146. Log.Debug(this, ex);
  147. Log.Debug(this, ex.getNextException());
  148. DatabaseConnection.shutdown();
  149. throw ex;
  150. }
  151. }
  152. /**
  153. * Verbindung zur Datenbank herstellen.
  154. *
  155. * @return Connection
  156. */
  157. private Connection connect(boolean create) throws Exception {
  158. ctype = new ConnectionTypeHandler();
  159. if (getCtype().getDriver() != null) {
  160. Log.Debug(this, "Datenbanktreiber: " + getCtype().getDriver());
  161. try {
  162. Class.forName(getCtype().getDriver()).newInstance();
  163. } catch (ClassNotFoundException ex) {
  164. // Popup.error(ex);
  165. //possibly not fatal, driver can have a different class [org.apache.derby.jdbc.ClientDriver,org.apache.derby.jdbc.EmbeddedDriver]
  166. Log.Debug(this, ex.getMessage());
  167. }
  168. user = LocalSettings.getProperty("dbuser");
  169. password = LocalSettings.getProperty("dbpassword");
  170. prefix = LocalSettings.getProperty("dbprefix");
  171. reconnect(create);
  172. } else {
  173. throw new UnsupportedOperationException("Datenbanktreiber: undefined");
  174. }
  175. return conn;
  176. }
  177. /**
  178. * Verbindung trennen
  179. */
  180. @SuppressWarnings("CallToThreadDumpStack")
  181. public static void shutdown() {
  182. try {
  183. if (conn != null && !conn.isClosed()) {
  184. if (ConnectionTypeHandler.getDriverType() == ConnectionTypeHandler.DERBY) {
  185. try {
  186. DriverManager.getConnection(
  187. DatabaseConnection.instanceOf().getCtype().getConnectionString(false) + "shutdown=true;", user, password);
  188. } catch (Exception ex) {
  189. Log.Debug(DatabaseConnection.class, ex.getLocalizedMessage());
  190. }
  191. }
  192. conn.close();
  193. conn = null;
  194. }
  195. } catch (SQLException ex) {
  196. ex.printStackTrace();
  197. System.exit(1);
  198. }
  199. }
  200. public boolean runQueries(String[] queries) throws SQLException {
  201. if (prog != null) {
  202. prog.setStringPainted(true);
  203. prog.setMaximum(queries.length);
  204. prog.setMinimum(0);
  205. prog.setValue(0);
  206. }
  207. Statement stm = this.getConnection().createStatement();
  208. // for (int i = 0; i < queries.length; i++) {
  209. // stm.addBatch(queries[i]);
  210. // }
  211. // Log.PrintArray(queries);
  212. try {
  213. // stm.executeBatch();
  214. for (int i = 0; i < queries.length; i++) {
  215. try {
  216. String string = queries[i];
  217. if (prefix != null) {
  218. string = string.replace(" table ", " table " + prefix);
  219. string = string.replace(" TABLE ", " TABLE " + prefix);
  220. string = string.replace(" on ", " on " + prefix);
  221. string = string.replace(" ON ", " ON " + prefix);
  222. string = string.replace(" into ", " into " + prefix);
  223. string = string.replace(" INTO ", " INTO " + prefix);
  224. }
  225. Log.Print(string);
  226. stm.execute(string);
  227. if (prog != null) {
  228. prog.setValue(i);
  229. }
  230. Thread.sleep(100);
  231. } catch (Exception ex) {
  232. throw ex;
  233. }
  234. }
  235. return true;
  236. } catch (Exception sQLException) {
  237. Log.Debug(this, sQLException.getMessage());
  238. return false;
  239. } finally {
  240. if (prog != null) {
  241. prog.setValue(0);
  242. }
  243. }
  244. }
  245. /**
  246. * Set a progressbar
  247. *
  248. * @param progressbar
  249. */
  250. public void setProgressbar(JProgressBar progressbar) {
  251. prog = progressbar;
  252. }
  253. /**
  254. * @return the ctype
  255. */
  256. public ConnectionTypeHandler getCtype() {
  257. return ctype;
  258. }
  259. /**
  260. * @return the statement
  261. */
  262. public Statement getStatement() {
  263. return statement;
  264. }
  265. static class connectionPing extends Thread {
  266. private DatabaseConnection c;
  267. public connectionPing(DatabaseConnection c) {
  268. this.c = c;
  269. setPriority(MIN_PRIORITY);
  270. }
  271. @Override
  272. public void run() {
  273. try {
  274. while (!c.getConnection().isClosed()) {
  275. try {
  276. sleep(180000);
  277. } catch (InterruptedException ex) {
  278. Log.Debug(ex);
  279. }
  280. try {
  281. Log.Debug(this, "ping to " + c.getCtype().getURL());
  282. c.runQueries(new String[]{"select count(ids) from groups"});
  283. } catch (SQLException ex) {
  284. Log.Debug(ex);
  285. }
  286. }
  287. } catch (SQLException ex) {
  288. Log.Debug(ex);
  289. }
  290. }
  291. }
  292. }