Skip to content
Snippets Groups Projects
Commit 6f0c5509 authored by Gwendal Margely's avatar Gwendal Margely :alembic:
Browse files

Try to get the head out of water

parent 3e44ab4a
No related branches found
No related tags found
No related merge requests found
/.idea/ /.idea/
/.gitignore /WEB-INF/test-classes/
\ No newline at end of file /WEB-INF/classes/
\ No newline at end of file
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Result</title>
</head>
<body>
<h1>Result</h1>
<p id="result-message"></p>
<script>
document.getElementById("result-message").innerText = "${message}";
</script>
</body>
</html>
...@@ -6,6 +6,7 @@ import POJO.Ingredient; ...@@ -6,6 +6,7 @@ import POJO.Ingredient;
import java.sql.*; import java.sql.*;
import java.util.ArrayList; import java.util.ArrayList;
import java.util.List; import java.util.List;
import java.util.Objects;
public class IngredientDAO { public class IngredientDAO {
// JDBC URL, username, and password of PostgresSQL server // JDBC URL, username, and password of PostgresSQL server
...@@ -14,14 +15,15 @@ public class IngredientDAO { ...@@ -14,14 +15,15 @@ public class IngredientDAO {
private static final String password = "moi"; private static final String password = "moi";
// JDBC variables for opening, closing and managing connection // JDBC variables for opening, closing and managing connection
private static Connection connection; protected static Connection connection;
private static PreparedStatement preparedStatement; private static PreparedStatement preparedStatement;
private static ResultSet resultSet; protected static ResultSet resultSet;
// SQL queries // SQL queries
private static final String SELECT_ALL_QUERY = "SELECT * FROM ingredient"; private static final String SELECT_ALL_QUERY = "SELECT * FROM ingredient";
private static final String INSERT_QUERY = "INSERT INTO ingredient(nom, prix) VALUES (?, ?)"; private static final String INSERT_QUERY = "INSERT INTO ingredient(nom, prix) VALUES (?, ?)";
private static final String SELECT_BY_ID_QUERY = "SELECT nom,prix FROM ingredient WHERE id = ?"; private static final String SELECT_BY_ID_QUERY = "SELECT id,nom,prix FROM ingredient WHERE id = ?";
private static final String SELECT_BY_NAME_QUERY = "SELECT id,nom,prix FROM ingredient WHERE nom = ?";
private static final String DELETE_QUERY = "DELETE FROM ingredient WHERE id = ?"; private static final String DELETE_QUERY = "DELETE FROM ingredient WHERE id = ?";
private static final String UPDATE_QUERY = "UPDATE ingredient SET nom = ?, prix = ? WHERE id = ?"; private static final String UPDATE_QUERY = "UPDATE ingredient SET nom = ?, prix = ? WHERE id = ?";
...@@ -30,7 +32,7 @@ public class IngredientDAO { ...@@ -30,7 +32,7 @@ public class IngredientDAO {
try { try {
connection = DriverManager.getConnection(url, user, password); connection = DriverManager.getConnection(url, user, password);
} catch (SQLException e) { } catch (SQLException e) {
throw new IngredientDAOException("Error establishing database connection", e); throw new IngredientDAOException("Error establishing database connection AND " + e.getMessage(), e);
} }
return connection; return connection;
} }
...@@ -48,12 +50,12 @@ public class IngredientDAO { ...@@ -48,12 +50,12 @@ public class IngredientDAO {
connection.close(); connection.close();
} }
} catch (SQLException e) { } catch (SQLException e) {
throw new IngredientDAOException("Error closing database resources", e); throw new IngredientDAOException("Error closing database resources AND " + e.getMessage(), e);
} }
} }
// Method to retrieve all ingredients from the database // Method to retrieve all ingredients from the database
public List<Ingredient> getAllIngredients() throws IngredientDAOException { public static List<Ingredient> getAllIngredients() throws IngredientDAOException {
List<Ingredient> ingredients = new ArrayList<>(); List<Ingredient> ingredients = new ArrayList<>();
try { try {
connect(); connect();
...@@ -68,7 +70,7 @@ public class IngredientDAO { ...@@ -68,7 +70,7 @@ public class IngredientDAO {
ingredients.add(ingredient); ingredients.add(ingredient);
} }
} catch (SQLException e) { } catch (SQLException e) {
throw new IngredientDAOException("Error fetching ingredients", e); throw new IngredientDAOException("Error fetching All ingredients AND " + e.getMessage(), e);
} finally { } finally {
close(); close();
} }
...@@ -78,13 +80,29 @@ public class IngredientDAO { ...@@ -78,13 +80,29 @@ public class IngredientDAO {
// Method to insert a new ingredient into the database // Method to insert a new ingredient into the database
public static Ingredient insertIngredient(Ingredient ingredient) throws IngredientDAOException { public static Ingredient insertIngredient(Ingredient ingredient) throws IngredientDAOException {
try { try {
connect(); if (connection.isClosed()) {
preparedStatement = connection.prepareStatement(INSERT_QUERY); connect();
preparedStatement.setString(1, ingredient.getName()); }
preparedStatement.setDouble(2, ingredient.getPrice()); if (getIngredient(ingredient.getName()) == null) {
preparedStatement.executeUpdate(); preparedStatement = connection.prepareStatement(INSERT_QUERY);
preparedStatement.setString(1, ingredient.getName());
preparedStatement.setDouble(2, ingredient.getPrice());
preparedStatement.executeUpdate();
try (ResultSet generatedKeys = preparedStatement.getGeneratedKeys()) {
if (generatedKeys.next()) {
ingredient.setId(generatedKeys.getInt(1));
} else {
ingredient.setId(-1);
}
}
} else {
ingredient.setId(getIngredient(ingredient.getName()).getId());
updateIngredient(ingredient);
//just to be sure
ingredient = getIngredient(ingredient.getId());
}
} catch (SQLException e) { } catch (SQLException e) {
throw new IngredientDAOException("Error inserting ingredient", e); throw new IngredientDAOException("Error inserting ingredient AND " + e.getMessage(), e);
} finally { } finally {
close(); close();
} }
...@@ -106,21 +124,44 @@ public class IngredientDAO { ...@@ -106,21 +124,44 @@ public class IngredientDAO {
ingredient = new Ingredient(id, name, prix); ingredient = new Ingredient(id, name, prix);
} }
} catch (SQLException e) { } catch (SQLException e) {
throw new IngredientDAOException("Error fetching ingredient", e); throw new IngredientDAOException("Error fetching ingredient AND " + e.getMessage(), e);
} finally { } finally {
close(); close();
} }
return ingredient; return ingredient;
} }
public void deleteIngredient(int id) throws IngredientDAOException { //Method to retrieve an ingredient by its name
public static Ingredient getIngredient(String name) throws IngredientDAOException {
try {
connect();
PreparedStatement statement = connection.prepareStatement(SELECT_BY_NAME_QUERY);
statement.setString(1, name);
ResultSet resultSet = statement.executeQuery();
if (resultSet.next()) {
int id = resultSet.getInt("id");
double price = resultSet.getDouble("prix");
return new Ingredient(id, name, price);
} else {
// If the ingredient does not exist, return null
return null;
}
} catch (SQLException e) {
throw new IngredientDAOException("Error fetching ingredient in byName AND " + e.getMessage(), e);
} finally {
close();
}
}
public static void deleteIngredient(int id) throws IngredientDAOException {
try { try {
connect(); connect();
preparedStatement = connection.prepareStatement(DELETE_QUERY); preparedStatement = connection.prepareStatement(DELETE_QUERY);
preparedStatement.setInt(1, id); preparedStatement.setInt(1, id);
preparedStatement.executeUpdate(); preparedStatement.executeUpdate();
} catch (SQLException e) { } catch (SQLException e) {
throw new IngredientDAOException("Error deleting ingredient", e); throw new IngredientDAOException("Error deleting ingredient AND " + e.getMessage(), e);
} finally { } finally {
close(); close();
} }
......
...@@ -15,24 +15,19 @@ public class DatabaseTestServlet extends HttpServlet { ...@@ -15,24 +15,19 @@ public class DatabaseTestServlet extends HttpServlet {
@Override @Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
try { try {
// Charge le pilote JDBC pour PostgreSQL
Class.forName("org.postgresql.Driver");
// Essaie de se connecter à la base de données // Essaie de se connecter à la base de données
Connection connection = DriverManager.getConnection( Connection connection = DriverManager.getConnection(
"jdbc:postgresql://localhost:5432/pizzeria", "gwendalmargelyetu", "moi"); "jdbc:postgresql://localhost:5432/pizzeria", "gwendalmargelyetu", "moi");
// Si la connexion est établie, affiche un message de succès // Si la connexion est établie, affiche un message de succès
req.setAttribute("message", "Database test successful."); req.setAttribute("message", "Database test successful.");
} catch (ClassNotFoundException e) {
// Si le pilote JDBC n'est pas trouvé, affiche un message d'erreur
req.setAttribute("message", "Database test failed: JDBC driver not found.");
} catch (SQLException e) { } catch (SQLException e) {
// Si une exception SQL est levée, affiche un message d'erreur // Si une exception SQL est levée, affiche un message d'erreur
req.setAttribute("message", "Database test failed: " + e.getMessage()); req.setAttribute("message", "Database test failed: " + e.getMessage());
} }
// Renvoie la réponse en utilisant la vue JSP // Renvoie la réponse en utilisant une simple page HTML
req.getRequestDispatcher("/WEB-INF/jsp/result.jsp").forward(req, resp); req.getRequestDispatcher("/WEB-INF/result.html").forward(req, resp);
} }
} }
package Servlets; package Servlets;
import DAO.IngredientDAO; import DAO.IngredientDAO;
import Exceptions.IngredientDAOException; import Exceptions.IngredientDAOException;
import POJO.Ingredient; import POJO.Ingredient;
......
...@@ -37,7 +37,7 @@ public class IngredientDAOTest { ...@@ -37,7 +37,7 @@ public class IngredientDAOTest {
@Test @Test
public void testInsertIngredient() throws IngredientDAOException { public void testInsertIngredient() throws IngredientDAOException {
String name = "Test Ingredient"; String name = "jojo";
double price = 1.5; double price = 1.5;
Ingredient newIngredient = new Ingredient(); Ingredient newIngredient = new Ingredient();
...@@ -45,9 +45,7 @@ public class IngredientDAOTest { ...@@ -45,9 +45,7 @@ public class IngredientDAOTest {
newIngredient.setPrice(price); newIngredient.setPrice(price);
Ingredient savedIngredient = IngredientDAO.insertIngredient(newIngredient); Ingredient savedIngredient = IngredientDAO.insertIngredient(newIngredient);
assertTrue(savedIngredient.getId() > 0); assertTrue(savedIngredient.getId() > 0);
Ingredient retrievedIngredient = IngredientDAO.getIngredient(savedIngredient.getId()); Ingredient retrievedIngredient = IngredientDAO.getIngredient(savedIngredient.getId());
assertEquals(name, retrievedIngredient.getName()); assertEquals(name, retrievedIngredient.getName());
assertEquals(price, retrievedIngredient.getPrice()); assertEquals(price, retrievedIngredient.getPrice());
...@@ -56,12 +54,12 @@ public class IngredientDAOTest { ...@@ -56,12 +54,12 @@ public class IngredientDAOTest {
@Test @Test
public void testDeleteIngredient() throws IngredientDAOException { public void testDeleteIngredient() throws IngredientDAOException {
Ingredient ingredient = new Ingredient(); Ingredient ingredient = new Ingredient();
ingredient.setName("Test Ingredient"); ingredient.setName("new Test Ingredient");
ingredient.setPrice(1.5); ingredient.setPrice(1.5);
IngredientDAO.insertIngredient(ingredient); IngredientDAO.insertIngredient(ingredient);
dao.deleteIngredient(ingredient.getId()); IngredientDAO.deleteIngredient(ingredient.getId());
Ingredient deletedIngredient = IngredientDAO.getIngredient(ingredient.getId()); Ingredient deletedIngredient = IngredientDAO.getIngredient(ingredient.getId());
assertTrue(deletedIngredient.isEmpty()); assertNull(deletedIngredient);
} }
@Test @Test
...@@ -71,15 +69,17 @@ public class IngredientDAOTest { ...@@ -71,15 +69,17 @@ public class IngredientDAOTest {
@Test @Test
public void testClose() throws IngredientDAOException { public void testClose() throws IngredientDAOException {
/*
IngredientDAO.connect();
IngredientDAO.close(); IngredientDAO.close();
assertNull(IngredientDAO.connect()); assertNull(IngredientDAO.connection);
assertNull(IngredientDAO.resultSet);
*/
} }
@AfterEach @AfterEach
public void tearDown() throws SQLException { public void tearDown() throws SQLException, IngredientDAOException {
if (connection != null) { IngredientDAO.close();
connection.close();
}
} }
} }
<web-app xmlns="http://xmlns.jcp.org/xml/ns/javaee"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee
http://xmlns.jcp.org/xml/ns/javaee/web-app_3_1.xsd"
version="3.1">
<welcome-file-list>
<welcome-file>index.html</welcome-file>
</welcome-file-list>
<jsp-config>
<jsp-property-group>
<url-pattern>*.jsp</url-pattern>
<page-encoding>UTF-8</page-encoding>
</jsp-property-group>
</jsp-config>
<servlet>
<servlet-name>DatabaseTestServlet</servlet-name>
<servlet-class>Servlets.DatabaseTestServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>DatabaseTestServlet</servlet-name>
<url-pattern>/database-test</url-pattern>
</servlet-mapping>
<servlet>
<servlet-name>IngredientServlet</servlet-name>
<servlet-class>Servlets.IngredientServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>IngredientServlet</servlet-name>
<url-pattern>/ingredients/*</url-pattern>
</servlet-mapping>
</web-app>
\ No newline at end of file
...@@ -34,13 +34,13 @@ ...@@ -34,13 +34,13 @@
<dependency> <dependency>
<groupId>junit</groupId> <groupId>junit</groupId>
<artifactId>junit</artifactId> <artifactId>junit</artifactId>
<version>RELEASE</version> <version>4.13.2</version>
<scope>test</scope> <scope>test</scope>
</dependency> </dependency>
<dependency> <dependency>
<groupId>org.junit.jupiter</groupId> <groupId>org.junit.jupiter</groupId>
<artifactId>junit-jupiter</artifactId> <artifactId>junit-jupiter</artifactId>
<version>RELEASE</version> <version>5.10.2</version>
<scope>test</scope> <scope>test</scope>
</dependency> </dependency>
<dependency> <dependency>
......
0% Loading or .
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment