Database.java 5.1 KB

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