From 6b0202173ee48848f9dd9b96896e67620b8c1c85 Mon Sep 17 00:00:00 2001 From: Gwendal Margely <gwendal.margely.etu@univ-lille.fr> Date: Sun, 17 Mar 2024 00:38:37 +0100 Subject: [PATCH] psql implementation --- META-INF/fill.sql | 39 +++++++------ META-INF/tables.sql | 20 +++---- WEB-INF/src/DAO/IngredientDAO.java | 18 +++++- WEB-INF/src/Servlets/IngredientServlet.java | 62 +++++++++++++++++---- pom.xml | 6 ++ 5 files changed, 100 insertions(+), 45 deletions(-) diff --git a/META-INF/fill.sql b/META-INF/fill.sql index 8a84cf0..1ed44d7 100644 --- a/META-INF/fill.sql +++ b/META-INF/fill.sql @@ -1,21 +1,20 @@ -INSERT INTO TABLE ingredients(id,nom,price) VALUES (1,'jambon',2.00), - (2,'poivrons',3.00), - (3,'mozzarella',2.50), - (4,'lardons',2.20), - (5,'miel',3.50), - (6,'chorizo',4.00), - (7,'olives',2.00), - (8,'basilic',3.50), - (9,'ail',2.50), - (10,'champignons',5.00), - (11,'artichauts',3.00), - (12,'provolone', 7.00), - (13,'parmesan',7.00), - (14,'gorgonzola',7.00), - (15,'roquefort',7.00), - (16,'reblochon',7.00), - (17,'aubergine',3.00), - (18,'chorizo',4.00), - (19,'creme fraiche',1.00), - (20,'sauce tomate',1.00); +INSERT INTO ingredient(nom,prix) VALUES ('jambon',2.00), + ('poivrons',3.00), + ('mozzarella',2.50), + ('lardons',2.20), + ('miel',3.50), + ('chorizo',4.00), + ('olives',2.00), + ('basilic',3.50), + ('ail',2.50), + ('champignons',5.00), + ('artichauts',3.00), + ('provolone', 7.00), + ('parmesan',7.00), + ('gorgonzola',7.00), + ('roquefort',7.00), + ('reblochon',7.00), + ('aubergine',3.00), + ('creme fraiche',1.00), + ('sauce tomate',1.00); diff --git a/META-INF/tables.sql b/META-INF/tables.sql index a062ee5..669dfa6 100644 --- a/META-INF/tables.sql +++ b/META-INF/tables.sql @@ -1,21 +1,15 @@ DROP TABLE IF EXISTS ingredient CASCADE; -CREATE TABLE ingredient (id INTEGER PRIMARY KEY, nom TEXT UNIQUE, prix REAL); +CREATE TABLE ingredient (id SERIAL PRIMARY KEY, nom TEXT UNIQUE, prix REAL); DROP TABLE IF EXISTS pate CASCADE; -CREATE TABLE pate (id INT PRIMARY KEY, nom TEXT UNIQUE); +CREATE TABLE pate (id SERIAL PRIMARY KEY, nom TEXT UNIQUE); DROP TABLE IF EXISTS pizza CASCADE; -CREATE TABLE pizza (id INTEGER PRIMARY KEY, nom TEXT UNIQUE, pate_id INTEGER, prix REAL, FOREIGN KEY (pate_id) REFERENCES pate(id)); - -DROP TABLE IF EXISTS pizza_ingredient; -CREATE TABLE pizza_ingredient (pizza_id INT, ingredient_id INT, PRIMARY KEY (pizza_id, ingredient_id), FOREIGN KEY (pizza_id) REFERENCES pizza(id) ON UPDATE CASCADE ON DELETE CASCADE, FOREIGN KEY (ingredient_id) REFERENCES ingredient(id) ON UPDATE CASCADE ON DELETE CASCADE); - -DROP TABLE IF EXISTS utilisateur CASCADE; -CREATE TABLE utilisateur (id INT PRIMARY KEY, login TEXT, password TEXT); -INSERT INTO utilisateur VALUES (1, 'default', 'default'); +CREATE TABLE pizza (id SERIAL PRIMARY KEY, nom TEXT UNIQUE, pate_id INTEGER, prix REAL, FOREIGN KEY (pate_id) REFERENCES pate(id)); DROP TABLE IF EXISTS commande CASCADE; -CREATE TABLE commande (id INT PRIMARY KEY, utilisateur_id INT, date CHAR(10), prix REAL, FOREIGN KEY (utilisateur_id) REFERENCES utilisateur(id) ON UPDATE CASCADE ON DELETE CASCADE); +CREATE TABLE commande (id SERIAL PRIMARY KEY, utilisateur_id INT, date CHAR(10), prix REAL, FOREIGN KEY (utilisateur_id) REFERENCES utilisateur(id) ON UPDATE CASCADE ON DELETE CASCADE); -DROP TABLE IF EXISTS commande_pizza; -CREATE TABLE commande_pizza (commande_id INT, pizza_id INT, FOREIGN KEY (commande_id) REFERENCES commande(id) ON UPDATE CASCADE ON DELETE CASCADE, FOREIGN KEY (pizza_id) REFERENCES pizza(id) ON UPDATE CASCADE ON DELETE CASCADE); +DROP TABLE IF EXISTS utilisateur CASCADE; +CREATE TABLE utilisateur (id SERIAL PRIMARY KEY, login TEXT UNIQUE, password TEXT); +INSERT INTO utilisateur VALUES (1, 'default', 'default'); \ No newline at end of file diff --git a/WEB-INF/src/DAO/IngredientDAO.java b/WEB-INF/src/DAO/IngredientDAO.java index 5eec7f8..f15f270 100644 --- a/WEB-INF/src/DAO/IngredientDAO.java +++ b/WEB-INF/src/DAO/IngredientDAO.java @@ -9,7 +9,7 @@ import java.util.List; public class IngredientDAO { // JDBC URL, username, and password of PostgresSQL server - private static final String url = "jdbc:postgresql://"; //CHANGE URL + private static final String url = "jdbc:postgresql://localhost:5432/pizzeria"; private static final String user = "gwendalmargelyetu"; private static final String password = "moi"; @@ -23,6 +23,7 @@ public class IngredientDAO { private static final String INSERT_QUERY = "INSERT INTO ingredients(nom, price) VALUES (?, ?)"; private static final String SELECT_BY_ID_QUERY = "SELECT nom,price FROM ingredients WHERE id = ?"; private static final String DELETE_QUERY = "DELETE FROM ingredients WHERE id = ?"; + private static final String UPDATE_QUERY = "UPDATE ingredients SET nom = ?, price = ? WHERE id = ?"; // Method to establish database connection static Connection connect() throws IngredientDAOException { @@ -124,4 +125,19 @@ public class IngredientDAO { close(); } } + + public static void updateIngredient(Ingredient ingredient) throws IngredientDAOException { + try { + connect(); + preparedStatement = connection.prepareStatement(UPDATE_QUERY); + preparedStatement.setString(1, ingredient.getName()); + preparedStatement.setDouble(2, ingredient.getPrice()); + preparedStatement.setInt(3, ingredient.getId()); + preparedStatement.executeUpdate(); + } catch (SQLException e) { + throw new IngredientDAOException("Error updating ingredient", e); + } finally { + close(); + } + } } diff --git a/WEB-INF/src/Servlets/IngredientServlet.java b/WEB-INF/src/Servlets/IngredientServlet.java index 328d5d8..2898d39 100644 --- a/WEB-INF/src/Servlets/IngredientServlet.java +++ b/WEB-INF/src/Servlets/IngredientServlet.java @@ -3,7 +3,9 @@ package Servlets; import DAO.IngredientDAO; +import Exceptions.IngredientDAOException; import POJO.Ingredient; +import com.fasterxml.jackson.core.JsonProcessingException; import com.fasterxml.jackson.databind.ObjectMapper; import javax.servlet.ServletException; @@ -20,13 +22,13 @@ public class IngredientServlet extends HttpServlet { private ObjectMapper objectMapper; @Override - public void init() throws ServletException { + public void init() { ingredientDAO = new IngredientDAO(); objectMapper = new ObjectMapper(); } @Override - protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { + protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws IOException { String pathInfo = req.getPathInfo(); if (pathInfo == null || pathInfo.equals("/")) { // Get all ingredients @@ -86,20 +88,58 @@ public class IngredientServlet extends HttpServlet { } @Override - protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { - // Add new ingredient + protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws IOException { + // Parse the request body as a JSON object + ObjectMapper objectMapper = new ObjectMapper(); + Ingredient ingredient; try { - Ingredient ingredient = objectMapper.readValue(req.getInputStream(), Ingredient.class); - IngredientDAO.insertIngredient(ingredient); - resp.setStatus(HttpServletResponse.SC_CREATED); - } catch (Exception e) { - resp.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR); - resp.getWriter().write("Error adding ingredient: " + e.getMessage()); + ingredient = objectMapper.readValue(req.getInputStream(), Ingredient.class); + } catch (JsonProcessingException e) { + // If the request body cannot be parsed as a JSON object, send a bad request response + resp.setStatus(HttpServletResponse.SC_BAD_REQUEST); + resp.getWriter().write("Error parsing request body"); + return; + } + + // Check if the ingredient already exists in the database + Ingredient existingIngredient = null; + try { + existingIngredient = IngredientDAO.getIngredient(ingredient.getId()); + } catch (IngredientDAOException e) { + throw new RuntimeException(e); + } + + if (existingIngredient == null) { + // If the ingredient doesn't exist, add it to the database + try { + IngredientDAO.insertIngredient(ingredient); + } catch (IngredientDAOException e) { + // If there was an error inserting the ingredient, send an internal server error response + resp.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR); + resp.getWriter().write("Error inserting ingredient: " + e.getMessage()); + return; + } + } else { + // If the ingredient already exists, update it in the database + existingIngredient.setName(ingredient.getName()); + existingIngredient.setPrice(ingredient.getPrice()); + try { + IngredientDAO.updateIngredient(existingIngredient); + } catch (IngredientDAOException e) { + // If there was an error updating the ingredient, send an internal server error response + resp.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR); + resp.getWriter().write("Error updating ingredient: " + e.getMessage()); + return; + } } + + // Send a response to the client + resp.setStatus(HttpServletResponse.SC_CREATED); + resp.getWriter().write("Ingredient added or updated successfully"); } @Override - protected void doDelete(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { + protected void doDelete(HttpServletRequest req, HttpServletResponse resp) throws IOException { String pathInfo = req.getPathInfo(); if (pathInfo != null && !pathInfo.equals("/")) { String[] pathParts = pathInfo.split("/"); diff --git a/pom.xml b/pom.xml index 4100924..05a4823 100644 --- a/pom.xml +++ b/pom.xml @@ -15,6 +15,12 @@ </properties> <dependencies> + <!-- https://mvnrepository.com/artifact/org.postgresql/postgresql --> + <dependency> + <groupId>org.postgresql</groupId> + <artifactId>postgresql</artifactId> + <version>42.7.3</version> + </dependency> <dependency> <groupId>com.fasterxml.jackson.core</groupId> <artifactId>jackson-databind</artifactId> -- GitLab