Database.java 5.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190
  1. package db;
  2. import java.sql.Statement;
  3. import java.util.HashMap;
  4. import java.util.List;
  5. import java.util.Map;
  6. import java.util.Optional;
  7. import java.util.logging.Logger;
  8. import db.mapper.ResultSetMapper;
  9. import java.lang.reflect.InvocationTargetException;
  10. import java.sql.Connection;
  11. import java.sql.DriverManager;
  12. import java.sql.PreparedStatement;
  13. import java.sql.ResultSet;
  14. import java.sql.SQLException;
  15. public class Database {
  16. private static final Logger LOGGER = Logger.getLogger(Database.class.getName());
  17. private static Connection db;
  18. static {
  19. ini();
  20. setup();
  21. }
  22. public static void ini() {
  23. try{
  24. Class.forName("org.apache.derby.jdbc.EmbeddedDriver");
  25. } catch(ClassNotFoundException e){
  26. LOGGER.severe("Unable to find Derby driver");
  27. throw new IllegalStateException("Unable to connect to the database", e);
  28. }
  29. try {
  30. db = DriverManager.getConnection(DatabaseProperties.get("url"));
  31. } catch (SQLException e) {
  32. LOGGER.severe(e.getMessage());
  33. throw new IllegalStateException("Unable to connect to the database", e);
  34. }
  35. }
  36. public static void close() throws DatabaseException {
  37. if(db != null) {
  38. try {
  39. db.close();
  40. db = null;
  41. } catch (SQLException e) {
  42. LOGGER.warning(e.getMessage());
  43. throw new DatabaseException("Unable to close database connection", e);
  44. }
  45. }
  46. }
  47. public static void setup() {
  48. LOGGER.info("Checking the database");
  49. if(isSet()) {
  50. LOGGER.info("Database il already set");
  51. return;
  52. }
  53. LOGGER.info("Creating table");
  54. DatabaseManager md = getDatabaseManager();
  55. md.create().forEach(sql -> execute(sql));
  56. List<String> content = md.content();
  57. if(content != null) {
  58. LOGGER.info("Add content");
  59. content.forEach(sql -> execute(sql));
  60. }
  61. }
  62. public static void unset() {
  63. if(!isSet()) {
  64. return;
  65. }
  66. LOGGER.info("Dropping table");
  67. DatabaseManager md = getDatabaseManager();
  68. md.drop().forEach(sql -> execute(sql));
  69. }
  70. public static boolean query(String sql) {
  71. try(Statement st = db.createStatement()) {
  72. st.executeQuery(sql);
  73. return true;
  74. } catch (SQLException | IllegalStateException e) {
  75. LOGGER.warning(e.getMessage());
  76. return false;
  77. }
  78. }
  79. public static <T> Optional<T> query(String sql, ResultSetMapper<T> mapper) {
  80. try(Statement st = db.createStatement()) {
  81. ResultSet result = st.executeQuery(sql);
  82. T obj = mapper.map(result);
  83. return (obj == null) ? Optional.empty() : Optional.of(obj);
  84. } catch (SQLException | IllegalStateException e) {
  85. LOGGER.warning(e.getMessage());
  86. return Optional.empty();
  87. }
  88. }
  89. public static <T> Optional<T> query(String sql, List<Object> params, ResultSetMapper<T> mapper) {
  90. try(PreparedStatement st = db.prepareStatement(sql)) {
  91. int i = 1;
  92. for(Object param : params) {
  93. st.setObject(i++, param);
  94. }
  95. ResultSet result = st.executeQuery();
  96. T obj = mapper.map(result);
  97. return (obj == null) ? Optional.empty() : Optional.of(obj);
  98. } catch (SQLException | IllegalStateException e) {
  99. LOGGER.warning(e.getMessage());
  100. return Optional.empty();
  101. }
  102. }
  103. public static boolean execute(String sql) {
  104. try(Statement st = db.createStatement()) {
  105. int result = st.executeUpdate(sql);
  106. return result == 1;
  107. } catch (SQLException e) {
  108. LOGGER.warning(e.getMessage());
  109. return false;
  110. }
  111. }
  112. public static boolean execute(String sql, List<Object> params) {
  113. try(PreparedStatement st = db.prepareStatement(sql)) {
  114. int i = 1;
  115. for (Object param : params) {
  116. st.setObject(i++, param);
  117. }
  118. int result = st.executeUpdate();
  119. return result == 1;
  120. } catch (SQLException e) {
  121. LOGGER.warning(e.getMessage());
  122. return false;
  123. }
  124. }
  125. public static Map<String, Object> insert(String sql, List<Object> params, String[] idField) {
  126. Map<String, Object> ids = new HashMap<>();
  127. try(PreparedStatement st = db.prepareStatement(sql, idField)) {
  128. // Ajout parametre
  129. int i = 1;
  130. for(Object param : params) {
  131. st.setObject(i++, param);
  132. }
  133. // Execution requete
  134. int result = st.executeUpdate();
  135. if(result != 1) {
  136. return ids;
  137. }
  138. // Recuperation des ids genere
  139. ResultSet rs = st.getGeneratedKeys();
  140. rs.next();
  141. i = 1;
  142. for (String field : idField) {
  143. ids.put(field, rs.getObject(i));
  144. i++;
  145. }
  146. return ids;
  147. } catch (SQLException e) {
  148. LOGGER.warning(e.getMessage());
  149. return ids;
  150. }
  151. }
  152. public static boolean isSet() {
  153. return query("Select * From " + DatabaseProperties.get("verification"));
  154. }
  155. public static Connection getDb() {
  156. return db;
  157. }
  158. private static DatabaseManager getDatabaseManager() {
  159. try {
  160. String className = DatabaseProperties.get("manager");
  161. Class<?> clazz = Class.forName(className);
  162. DatabaseManager md = (DatabaseManager) clazz.getMethod("getInstance").invoke(null);
  163. return md;
  164. } catch (ClassNotFoundException e) {
  165. throw new IllegalStateException("Unable to find Database Manager Class", e);
  166. } catch (IllegalAccessException | IllegalArgumentException | InvocationTargetException | NoSuchMethodException | SecurityException e) {
  167. throw new IllegalStateException("Database Manager Class is not a child of ManagaDatabase Class or no getInstance method found", e);
  168. }
  169. }
  170. }