Guest User

Untitled

a guest
Sep 24th, 2018
163
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 12.51 KB | None | 0 0
  1. /*
  2. * To change this license header, choose License Headers in Project Properties.
  3. * To change this template file, choose Tools | Templates
  4. * and open the template in the editor.
  5. */
  6. package dk.webtrade.recipesolution.data;
  7.  
  8. import dk.webtrade.recipesolution.logik.entity.Ingredient;
  9. import dk.webtrade.recipesolution.logik.entity.Recipe;
  10. import dk.webtrade.recipesolution.logik.entity.RecipeIngredient;
  11. import dk.webtrade.recipesolution.logik.entity.User;
  12. import java.sql.Connection;
  13. import java.sql.PreparedStatement;
  14. import java.sql.ResultSet;
  15. import java.sql.SQLException;
  16. import java.sql.Statement;
  17. import java.util.ArrayList;
  18. import java.util.List;
  19. import java.util.logging.Level;
  20. import java.util.logging.Logger;
  21.  
  22. /**
  23. *
  24. * @author thomas
  25. */
  26. public class DataMapper {
  27.  
  28. /*
  29. Methods:
  30. getUsers()
  31. getUser(int id)
  32. getAllRecipes()
  33. getAllRecipes(User user)
  34. getRecipe(int id)
  35. getAllIngredients()
  36. getIngredientByName(String name)
  37. ----------------
  38. addUser(User user)
  39. addRecipe(Recipe recipe)
  40. addIngredient(Ingredient i)
  41.  
  42. */
  43. private final String GET_ALL_USERS = "SELECT id, username, password FROM recipesDB.User";
  44. private final String GET_USER_BY_ID = "SELECT id, username, password FROM recipesDB.User WHERE id = ?";
  45. private final String GET_ALL_RECIPES = "SELECT id, name, description, todo, cookingtime, image FROM recipesDB.Recipe;";
  46. private final String GET_RECIPES_BY_USER = "SELECT id, name, description, todo, cookingtime, image FROM recipesDB.Recipe WHERE User_id = ? ORDER BY id ASC";
  47. private final String GET_RECIPE_BY_ID = "SELECT User_id, id, name, description, todo, cookingtime, image FROM recipesDB.Recipe WHERE id = ?";
  48. private final String GET_ALL_INGREDIENTS = "SELECT id, name FROM recipesDB.Ingredient";
  49. private final String GET_INGREDIENT_BY_NAME = "SELECT id, name FROM recipesDB.Ingredient WHERE name = ?";
  50. private final String GET_INGREDIENTS_BY_RECIPE_ID = "SELECT Ingredient_id, name, amount, measure FROM Recipe_has_Ingredient,Ingredient WHERE Recipe_has_Ingredient.Ingredient_id = Ingredient.id AND Recipe_has_Ingredient.Recipe_id = ?";
  51. private final String ADD_NEW_USER = "INSERT INTO User(username,password) VALUES (?,?);";
  52. private final String ADD_NEW_RECIPE = "INSERT INTO Recipe (name,description,todo,cookingtime,image,User_id)VALUES(?,?,?,?,?,?)";
  53. private final String ADD_INGREDIENT_TO_RECIPE = "INSERT INTO Recipe_has_Ingredient(Recipe_id,Ingredient_id,amount,measure)VALUES(?,?,?,?);";
  54. private final String ADD_NEW_INGREDIENT = "INSERT INTO Ingredient(name)VALUES(?)";
  55.  
  56. public static void main(String[] args) {
  57. try {
  58. DataMapper dm = new DataMapper();
  59. System.out.println("---------------------------------------------TEST: getUsers");
  60. dm.getUsers().forEach((user) -> {System.out.println(user.getUsername());});
  61. System.out.println("---------------------------------------------TEST: getIngredientByName()");
  62. String ingredientName = dm.getIngredientByName("mel").getName();
  63. System.out.println("Ingredient found: "+ingredientName);
  64. System.out.println("---------------------------------------------TEST: getUser()");
  65. User u = dm.getUser(1);
  66. String username = u.getUsername();
  67. System.out.println("USER found: "+username);
  68. System.out.println("---------------------------------------------TEST: addRecipe");
  69. Recipe recipe = new Recipe("Naan brød", "Indisk brød bagt på pande", "Bland ingredienserne sammen og ælt dejen grundigt. Rul små kugler af dejen. Rul kuglerne til flade brød og steg dem på panden", 20, "naan.jpg");
  70. recipe.addIngredient(new RecipeIngredient(dm.getIngredientByName("mel"), "500", "ml"));
  71. recipe.addIngredient(new RecipeIngredient(dm.getIngredientByName("salt"), "1", "tskf"));
  72. recipe.addIngredient(new RecipeIngredient(dm.getIngredientByName("mælk"), "200", "ml"));
  73. recipe.setUser(u);
  74. // dm.addRecipe(recipe); //THIS WILL ADD ANOTHER NAAN BRØD
  75. System.out.println("----------------------------------------------TEST: getAllRecipes");
  76. dm.getAllRecipes().forEach((r) -> {
  77. System.out.println(r.getName() + " from " + r.getUser().getUsername());
  78. });
  79. System.out.println("----------------------------------------------TEST: getRecipe(int id)");
  80. Recipe r = dm.getRecipe(1);
  81. System.out.println("Recipe id: 1: "+r.getName());
  82. System.out.println("----------------------------------------------TEST: getAllIngredients");
  83. dm.getAllIngredients().forEach((ingredient) -> {
  84. System.out.println(ingredient.getId() + " : " + ingredient.getName());
  85. });
  86. } catch (Exception ex) {
  87. ex.printStackTrace();
  88. }
  89. }
  90.  
  91. public List<User> getUsers() {
  92. List<User> users = new ArrayList();
  93. try {
  94. Connection con = DBConnector.getConnection();
  95. PreparedStatement pstmt = con.prepareStatement(GET_ALL_USERS);
  96. ResultSet rs = pstmt.executeQuery();
  97. while (rs.next()) {
  98. int id = rs.getInt("id");
  99. String username = rs.getString("username");
  100. String password = rs.getString("password");
  101. User user = new User(id, username, password);
  102. List<Recipe> recipes = getAllRecipesByUser(user);
  103. user.setRecipes(recipes);
  104. users.add(user);
  105. }
  106. } catch (SQLException ex) {
  107. ex.printStackTrace();
  108. }
  109. return users;
  110. }
  111.  
  112. public List<Recipe> getAllRecipesByUser(User user) {
  113. List<Recipe> recipes = new ArrayList();
  114. try {
  115. Connection con = DBConnector.getConnection();
  116. PreparedStatement pstmt = con.prepareStatement(GET_RECIPES_BY_USER);
  117. pstmt.setInt(1, user.getId());
  118. ResultSet rs = pstmt.executeQuery();
  119. while (rs.next()) {
  120. int id = rs.getInt("id");
  121. String name = rs.getString("name");
  122. String description = rs.getString("description");
  123. String todo = rs.getString("todo");
  124. int cookingtime = rs.getInt("cookingtime");
  125. String image = rs.getString("image");
  126. Recipe recipe = new Recipe(id, name, description, todo, cookingtime, image);
  127. recipe.setUser(user);
  128. recipes.add(recipe);
  129. }
  130. } catch (SQLException ex) {
  131. ex.printStackTrace();
  132. }
  133. return recipes;
  134. }
  135.  
  136. public List<Recipe> getAllRecipes() {
  137. List<Recipe> recipes = new ArrayList();
  138. getUsers().forEach((user) -> {
  139. user.getRecipes().forEach((recipe) -> {
  140. recipes.add(recipe);
  141. });
  142. });
  143. return recipes;
  144. }
  145.  
  146. //This one is complex because to persist a recipe we must also persist each individual ingredient.
  147. public Recipe addRecipe(Recipe recipe) throws Exception {
  148. List<RecipeIngredient> ingredientItems = recipe.getIngredients();
  149. try {
  150. Connection con = DBConnector.getConnection();
  151. PreparedStatement pstmt = con.prepareStatement(ADD_NEW_RECIPE, Statement.RETURN_GENERATED_KEYS);
  152. pstmt.setString(1, recipe.getName());
  153. pstmt.setString(2, recipe.getDescription());
  154. pstmt.setString(3, recipe.getTodo());
  155. pstmt.setInt(4, recipe.getCookingTime());
  156. pstmt.setString(5, null);
  157. pstmt.setInt(6, recipe.getUser().getId());
  158. int result = pstmt.executeUpdate();
  159. if (result == 0) {
  160. throw new Exception("Recipe could not be added to database");
  161. } else {
  162. ResultSet rs = pstmt.getGeneratedKeys();
  163. if (rs.next()) {
  164. int id = rs.getInt(1);
  165. recipe.setId(id);
  166. }
  167. rs.close();
  168. }
  169. pstmt.close();
  170.  
  171. for (RecipeIngredient ingredientItem : ingredientItems) {
  172. PreparedStatement pstmt2 = con.prepareStatement(ADD_INGREDIENT_TO_RECIPE);
  173. pstmt2.setInt(1, recipe.getId());
  174. pstmt2.setInt(2, ingredientItem.getIngredient().getId());
  175. pstmt2.setString(3, ingredientItem.getAmount());
  176. pstmt2.setString(4, ingredientItem.getMeasure());
  177. int result2 = pstmt2.executeUpdate();
  178. if (result2 == 0) {
  179. throw new Exception("Ingredient " + ingredientItem.getIngredient().getName() + " could not be persisted");
  180. }
  181. pstmt2.close();
  182. }
  183. } catch (SQLException ex) {
  184. ex.printStackTrace();
  185. }
  186. return recipe;
  187. }
  188. public Recipe getRecipe(int id) throws Exception{
  189.  
  190. Recipe recipe = null;
  191. try {
  192. Connection con = DBConnector.getConnection();
  193. PreparedStatement pstmt = con.prepareStatement(GET_RECIPE_BY_ID);
  194. pstmt.setInt(1, id);
  195. ResultSet rs = pstmt.executeQuery();
  196. if (rs.next()) {
  197. int userId = rs.getInt("User_id");
  198. String name = rs.getString("name");
  199. String description = rs.getString("description");
  200. String todo = rs.getString("todo");
  201. int cookingtime = rs.getInt("cookingtime");
  202. String image = rs.getString("image");
  203. recipe = new Recipe(id, name, description, todo, cookingtime, image);
  204. recipe.setUser(getUser(userId));
  205.  
  206. } else {
  207. throw new Exception("No such User found");
  208. }
  209. pstmt.close();
  210. rs.close();
  211. PreparedStatement pstmt2 = con.prepareStatement(GET_INGREDIENTS_BY_RECIPE_ID);
  212. pstmt2.setInt(1, id);
  213. ResultSet rs2 = pstmt2.executeQuery();
  214. while(rs2.next()){
  215. int ingId = rs2.getInt("Ingredient_id");
  216. String name = rs2.getString("name");
  217. String amount = rs2.getString("amount");
  218. String measure = rs2.getString("measure");
  219. Ingredient in = new Ingredient(ingId, name);
  220. RecipeIngredient rIng = new RecipeIngredient(in, amount, measure);
  221. recipe.addIngredient(rIng);
  222. }
  223. } catch (SQLException ex) {
  224. ex.printStackTrace();
  225. }
  226. return recipe;
  227.  
  228. }
  229.  
  230. public List<Ingredient> getAllIngredients() {
  231. List<Ingredient> ingredients = new ArrayList();
  232. try {
  233. Connection con = DBConnector.getConnection();
  234. PreparedStatement pstmt = con.prepareStatement(GET_ALL_INGREDIENTS);
  235. ResultSet rs = pstmt.executeQuery();
  236. while (rs.next()) {
  237. int id = rs.getInt("id");
  238. String username = rs.getString("name");
  239. Ingredient ingredient = new Ingredient(id, username);
  240. ingredients.add(ingredient);
  241. }
  242. } catch (SQLException ex) {
  243. ex.printStackTrace();
  244. }
  245. return ingredients;
  246. }
  247.  
  248. public Ingredient getIngredientByName(String name) throws Exception {
  249. Ingredient ingredient = null;
  250. try {
  251. Connection con = DBConnector.getConnection();
  252. PreparedStatement pstmt = con.prepareStatement(GET_INGREDIENT_BY_NAME);
  253. pstmt.setString(1, name);
  254. ResultSet rs = pstmt.executeQuery();
  255. if (rs.next()) {
  256. int id = rs.getInt("id");
  257. String ingredientName = rs.getString("name");
  258. ingredient = new Ingredient(id, ingredientName);
  259. } else {
  260. throw new Exception("No such ingredient found");
  261. }
  262. } catch (SQLException ex) {
  263. ex.printStackTrace();
  264. }
  265. return ingredient;
  266. }
  267. public User getUser(int id) throws Exception{
  268. User user = null;
  269. try {
  270. Connection con = DBConnector.getConnection();
  271. PreparedStatement pstmt = con.prepareStatement(GET_USER_BY_ID);
  272. pstmt.setInt(1, id);
  273. ResultSet rs = pstmt.executeQuery();
  274. if (rs.next()) {
  275. String username = rs.getString("username");
  276. user = new User(id, username);
  277. } else {
  278. throw new Exception("No such User found");
  279. }
  280. } catch (SQLException ex) {
  281. ex.printStackTrace();
  282. }
  283. return user;
  284. }
  285. }
Add Comment
Please, Sign In to add comment