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/
/.gitignore
\ No newline at end of file
/WEB-INF/test-classes/
/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;
import java.sql.*;
import java.util.ArrayList;
import java.util.List;
import java.util.Objects;
public class IngredientDAO {
// JDBC URL, username, and password of PostgresSQL server
......@@ -14,14 +15,15 @@ public class IngredientDAO {
private static final String password = "moi";
// JDBC variables for opening, closing and managing connection
private static Connection connection;
protected static Connection connection;
private static PreparedStatement preparedStatement;
private static ResultSet resultSet;
protected static ResultSet resultSet;
// SQL queries
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 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 UPDATE_QUERY = "UPDATE ingredient SET nom = ?, prix = ? WHERE id = ?";
......@@ -30,7 +32,7 @@ public class IngredientDAO {
try {
connection = DriverManager.getConnection(url, user, password);
} catch (SQLException e) {
throw new IngredientDAOException("Error establishing database connection", e);
throw new IngredientDAOException("Error establishing database connection AND " + e.getMessage(), e);
}
return connection;
}
......@@ -48,12 +50,12 @@ public class IngredientDAO {
connection.close();
}
} 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
public List<Ingredient> getAllIngredients() throws IngredientDAOException {
public static List<Ingredient> getAllIngredients() throws IngredientDAOException {
List<Ingredient> ingredients = new ArrayList<>();
try {
connect();
......@@ -68,7 +70,7 @@ public class IngredientDAO {
ingredients.add(ingredient);
}
} catch (SQLException e) {
throw new IngredientDAOException("Error fetching ingredients", e);
throw new IngredientDAOException("Error fetching All ingredients AND " + e.getMessage(), e);
} finally {
close();
}
......@@ -78,13 +80,29 @@ public class IngredientDAO {
// Method to insert a new ingredient into the database
public static Ingredient insertIngredient(Ingredient ingredient) throws IngredientDAOException {
try {
connect();
preparedStatement = connection.prepareStatement(INSERT_QUERY);
preparedStatement.setString(1, ingredient.getName());
preparedStatement.setDouble(2, ingredient.getPrice());
preparedStatement.executeUpdate();
if (connection.isClosed()) {
connect();
}
if (getIngredient(ingredient.getName()) == null) {
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) {
throw new IngredientDAOException("Error inserting ingredient", e);
throw new IngredientDAOException("Error inserting ingredient AND " + e.getMessage(), e);
} finally {
close();
}
......@@ -106,21 +124,44 @@ public class IngredientDAO {
ingredient = new Ingredient(id, name, prix);
}
} catch (SQLException e) {
throw new IngredientDAOException("Error fetching ingredient", e);
throw new IngredientDAOException("Error fetching ingredient AND " + e.getMessage(), e);
} finally {
close();
}
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 {
connect();
preparedStatement = connection.prepareStatement(DELETE_QUERY);
preparedStatement.setInt(1, id);
preparedStatement.executeUpdate();
} catch (SQLException e) {
throw new IngredientDAOException("Error deleting ingredient", e);
throw new IngredientDAOException("Error deleting ingredient AND " + e.getMessage(), e);
} finally {
close();
}
......
......@@ -15,24 +15,19 @@ public class DatabaseTestServlet extends HttpServlet {
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
try {
// Charge le pilote JDBC pour PostgreSQL
Class.forName("org.postgresql.Driver");
// Essaie de se connecter à la base de données
Connection connection = DriverManager.getConnection(
"jdbc:postgresql://localhost:5432/pizzeria", "gwendalmargelyetu", "moi");
// Si la connexion est établie, affiche un message de succès
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) {
// Si une exception SQL est levée, affiche un message d'erreur
req.setAttribute("message", "Database test failed: " + e.getMessage());
}
// Renvoie la réponse en utilisant la vue JSP
req.getRequestDispatcher("/WEB-INF/jsp/result.jsp").forward(req, resp);
// Renvoie la réponse en utilisant une simple page HTML
req.getRequestDispatcher("/WEB-INF/result.html").forward(req, resp);
}
}
package Servlets;
import DAO.IngredientDAO;
import Exceptions.IngredientDAOException;
import POJO.Ingredient;
......
......@@ -37,7 +37,7 @@ public class IngredientDAOTest {
@Test
public void testInsertIngredient() throws IngredientDAOException {
String name = "Test Ingredient";
String name = "jojo";
double price = 1.5;
Ingredient newIngredient = new Ingredient();
......@@ -45,9 +45,7 @@ public class IngredientDAOTest {
newIngredient.setPrice(price);
Ingredient savedIngredient = IngredientDAO.insertIngredient(newIngredient);
assertTrue(savedIngredient.getId() > 0);
Ingredient retrievedIngredient = IngredientDAO.getIngredient(savedIngredient.getId());
assertEquals(name, retrievedIngredient.getName());
assertEquals(price, retrievedIngredient.getPrice());
......@@ -56,12 +54,12 @@ public class IngredientDAOTest {
@Test
public void testDeleteIngredient() throws IngredientDAOException {
Ingredient ingredient = new Ingredient();
ingredient.setName("Test Ingredient");
ingredient.setName("new Test Ingredient");
ingredient.setPrice(1.5);
IngredientDAO.insertIngredient(ingredient);
dao.deleteIngredient(ingredient.getId());
IngredientDAO.deleteIngredient(ingredient.getId());
Ingredient deletedIngredient = IngredientDAO.getIngredient(ingredient.getId());
assertTrue(deletedIngredient.isEmpty());
assertNull(deletedIngredient);
}
@Test
......@@ -71,15 +69,17 @@ public class IngredientDAOTest {
@Test
public void testClose() throws IngredientDAOException {
/*
IngredientDAO.connect();
IngredientDAO.close();
assertNull(IngredientDAO.connect());
assertNull(IngredientDAO.connection);
assertNull(IngredientDAO.resultSet);
*/
}
@AfterEach
public void tearDown() throws SQLException {
if (connection != null) {
connection.close();
}
public void tearDown() throws SQLException, IngredientDAOException {
IngredientDAO.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 @@
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>RELEASE</version>
<version>4.13.2</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.junit.jupiter</groupId>
<artifactId>junit-jupiter</artifactId>
<version>RELEASE</version>
<version>5.10.2</version>
<scope>test</scope>
</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