Mon premier commit

This commit is contained in:
DahoudG
2024-08-30 00:19:32 +00:00
commit 4ccf1b0349
26 changed files with 2122 additions and 0 deletions

View File

@@ -0,0 +1,97 @@
####
# This Dockerfile is used in order to build a container that runs the Quarkus application in JVM mode
#
# Before building the container image run:
#
# ./mvnw package
#
# Then, build the image with:
#
# docker build -f src/main/docker/Dockerfile.jvm -t quarkus/mic-after-work-jvm .
#
# Then run the container using:
#
# docker run -i --rm -p 8080:8080 quarkus/mic-after-work-jvm
#
# If you want to include the debug port into your docker image
# you will have to expose the debug port (default 5005 being the default) like this : EXPOSE 8080 5005.
# Additionally you will have to set -e JAVA_DEBUG=true and -e JAVA_DEBUG_PORT=*:5005
# when running the container
#
# Then run the container using :
#
# docker run -i --rm -p 8080:8080 quarkus/mic-after-work-jvm
#
# This image uses the `run-java.sh` script to run the application.
# This scripts computes the command line to execute your Java application, and
# includes memory/GC tuning.
# You can configure the behavior using the following environment properties:
# - JAVA_OPTS: JVM options passed to the `java` command (example: "-verbose:class")
# - JAVA_OPTS_APPEND: User specified Java options to be appended to generated options
# in JAVA_OPTS (example: "-Dsome.property=foo")
# - JAVA_MAX_MEM_RATIO: Is used when no `-Xmx` option is given in JAVA_OPTS. This is
# used to calculate a default maximal heap memory based on a containers restriction.
# If used in a container without any memory constraints for the container then this
# option has no effect. If there is a memory constraint then `-Xmx` is set to a ratio
# of the container available memory as set here. The default is `50` which means 50%
# of the available memory is used as an upper boundary. You can skip this mechanism by
# setting this value to `0` in which case no `-Xmx` option is added.
# - JAVA_INITIAL_MEM_RATIO: Is used when no `-Xms` option is given in JAVA_OPTS. This
# is used to calculate a default initial heap memory based on the maximum heap memory.
# If used in a container without any memory constraints for the container then this
# option has no effect. If there is a memory constraint then `-Xms` is set to a ratio
# of the `-Xmx` memory as set here. The default is `25` which means 25% of the `-Xmx`
# is used as the initial heap size. You can skip this mechanism by setting this value
# to `0` in which case no `-Xms` option is added (example: "25")
# - JAVA_MAX_INITIAL_MEM: Is used when no `-Xms` option is given in JAVA_OPTS.
# This is used to calculate the maximum value of the initial heap memory. If used in
# a container without any memory constraints for the container then this option has
# no effect. If there is a memory constraint then `-Xms` is limited to the value set
# here. The default is 4096MB which means the calculated value of `-Xms` never will
# be greater than 4096MB. The value of this variable is expressed in MB (example: "4096")
# - JAVA_DIAGNOSTICS: Set this to get some diagnostics information to standard output
# when things are happening. This option, if set to true, will set
# `-XX:+UnlockDiagnosticVMOptions`. Disabled by default (example: "true").
# - JAVA_DEBUG: If set remote debugging will be switched on. Disabled by default (example:
# true").
# - JAVA_DEBUG_PORT: Port used for remote debugging. Defaults to 5005 (example: "8787").
# - CONTAINER_CORE_LIMIT: A calculated core limit as described in
# https://www.kernel.org/doc/Documentation/scheduler/sched-bwc.txt. (example: "2")
# - CONTAINER_MAX_MEMORY: Memory limit given to the container (example: "1024").
# - GC_MIN_HEAP_FREE_RATIO: Minimum percentage of heap free after GC to avoid expansion.
# (example: "20")
# - GC_MAX_HEAP_FREE_RATIO: Maximum percentage of heap free after GC to avoid shrinking.
# (example: "40")
# - GC_TIME_RATIO: Specifies the ratio of the time spent outside the garbage collection.
# (example: "4")
# - GC_ADAPTIVE_SIZE_POLICY_WEIGHT: The weighting given to the current GC time versus
# previous GC times. (example: "90")
# - GC_METASPACE_SIZE: The initial metaspace size. (example: "20")
# - GC_MAX_METASPACE_SIZE: The maximum metaspace size. (example: "100")
# - GC_CONTAINER_OPTIONS: Specify Java GC to use. The value of this variable should
# contain the necessary JRE command-line options to specify the required GC, which
# will override the default of `-XX:+UseParallelGC` (example: -XX:+UseG1GC).
# - HTTPS_PROXY: The location of the https proxy. (example: "myuser@127.0.0.1:8080")
# - HTTP_PROXY: The location of the http proxy. (example: "myuser@127.0.0.1:8080")
# - NO_PROXY: A comma separated lists of hosts, IP addresses or domains that can be
# accessed directly. (example: "foo.example.com,bar.example.com")
#
###
FROM registry.access.redhat.com/ubi8/openjdk-17:1.19
ENV LANGUAGE='en_US:en'
# We make four distinct layers so if there are application changes the library layers can be re-used
COPY --chown=185 target/quarkus-app/lib/ /deployments/lib/
COPY --chown=185 target/quarkus-app/*.jar /deployments/
COPY --chown=185 target/quarkus-app/app/ /deployments/app/
COPY --chown=185 target/quarkus-app/quarkus/ /deployments/quarkus/
EXPOSE 8080
USER 185
ENV JAVA_OPTS_APPEND="-Dquarkus.http.host=0.0.0.0 -Djava.util.logging.manager=org.jboss.logmanager.LogManager"
ENV JAVA_APP_JAR="/deployments/quarkus-run.jar"
ENTRYPOINT [ "/opt/jboss/container/java/run/run-java.sh" ]

View File

@@ -0,0 +1,93 @@
####
# This Dockerfile is used in order to build a container that runs the Quarkus application in JVM mode
#
# Before building the container image run:
#
# ./mvnw package -Dquarkus.package.jar.type=legacy-jar
#
# Then, build the image with:
#
# docker build -f src/main/docker/Dockerfile.legacy-jar -t quarkus/mic-after-work-legacy-jar .
#
# Then run the container using:
#
# docker run -i --rm -p 8080:8080 quarkus/mic-after-work-legacy-jar
#
# If you want to include the debug port into your docker image
# you will have to expose the debug port (default 5005 being the default) like this : EXPOSE 8080 5005.
# Additionally you will have to set -e JAVA_DEBUG=true and -e JAVA_DEBUG_PORT=*:5005
# when running the container
#
# Then run the container using :
#
# docker run -i --rm -p 8080:8080 quarkus/mic-after-work-legacy-jar
#
# This image uses the `run-java.sh` script to run the application.
# This scripts computes the command line to execute your Java application, and
# includes memory/GC tuning.
# You can configure the behavior using the following environment properties:
# - JAVA_OPTS: JVM options passed to the `java` command (example: "-verbose:class")
# - JAVA_OPTS_APPEND: User specified Java options to be appended to generated options
# in JAVA_OPTS (example: "-Dsome.property=foo")
# - JAVA_MAX_MEM_RATIO: Is used when no `-Xmx` option is given in JAVA_OPTS. This is
# used to calculate a default maximal heap memory based on a containers restriction.
# If used in a container without any memory constraints for the container then this
# option has no effect. If there is a memory constraint then `-Xmx` is set to a ratio
# of the container available memory as set here. The default is `50` which means 50%
# of the available memory is used as an upper boundary. You can skip this mechanism by
# setting this value to `0` in which case no `-Xmx` option is added.
# - JAVA_INITIAL_MEM_RATIO: Is used when no `-Xms` option is given in JAVA_OPTS. This
# is used to calculate a default initial heap memory based on the maximum heap memory.
# If used in a container without any memory constraints for the container then this
# option has no effect. If there is a memory constraint then `-Xms` is set to a ratio
# of the `-Xmx` memory as set here. The default is `25` which means 25% of the `-Xmx`
# is used as the initial heap size. You can skip this mechanism by setting this value
# to `0` in which case no `-Xms` option is added (example: "25")
# - JAVA_MAX_INITIAL_MEM: Is used when no `-Xms` option is given in JAVA_OPTS.
# This is used to calculate the maximum value of the initial heap memory. If used in
# a container without any memory constraints for the container then this option has
# no effect. If there is a memory constraint then `-Xms` is limited to the value set
# here. The default is 4096MB which means the calculated value of `-Xms` never will
# be greater than 4096MB. The value of this variable is expressed in MB (example: "4096")
# - JAVA_DIAGNOSTICS: Set this to get some diagnostics information to standard output
# when things are happening. This option, if set to true, will set
# `-XX:+UnlockDiagnosticVMOptions`. Disabled by default (example: "true").
# - JAVA_DEBUG: If set remote debugging will be switched on. Disabled by default (example:
# true").
# - JAVA_DEBUG_PORT: Port used for remote debugging. Defaults to 5005 (example: "8787").
# - CONTAINER_CORE_LIMIT: A calculated core limit as described in
# https://www.kernel.org/doc/Documentation/scheduler/sched-bwc.txt. (example: "2")
# - CONTAINER_MAX_MEMORY: Memory limit given to the container (example: "1024").
# - GC_MIN_HEAP_FREE_RATIO: Minimum percentage of heap free after GC to avoid expansion.
# (example: "20")
# - GC_MAX_HEAP_FREE_RATIO: Maximum percentage of heap free after GC to avoid shrinking.
# (example: "40")
# - GC_TIME_RATIO: Specifies the ratio of the time spent outside the garbage collection.
# (example: "4")
# - GC_ADAPTIVE_SIZE_POLICY_WEIGHT: The weighting given to the current GC time versus
# previous GC times. (example: "90")
# - GC_METASPACE_SIZE: The initial metaspace size. (example: "20")
# - GC_MAX_METASPACE_SIZE: The maximum metaspace size. (example: "100")
# - GC_CONTAINER_OPTIONS: Specify Java GC to use. The value of this variable should
# contain the necessary JRE command-line options to specify the required GC, which
# will override the default of `-XX:+UseParallelGC` (example: -XX:+UseG1GC).
# - HTTPS_PROXY: The location of the https proxy. (example: "myuser@127.0.0.1:8080")
# - HTTP_PROXY: The location of the http proxy. (example: "myuser@127.0.0.1:8080")
# - NO_PROXY: A comma separated lists of hosts, IP addresses or domains that can be
# accessed directly. (example: "foo.example.com,bar.example.com")
#
###
FROM registry.access.redhat.com/ubi8/openjdk-17:1.19
ENV LANGUAGE='en_US:en'
COPY target/lib/* /deployments/lib/
COPY target/*-runner.jar /deployments/quarkus-run.jar
EXPOSE 8080
USER 185
ENV JAVA_OPTS_APPEND="-Dquarkus.http.host=0.0.0.0 -Djava.util.logging.manager=org.jboss.logmanager.LogManager"
ENV JAVA_APP_JAR="/deployments/quarkus-run.jar"
ENTRYPOINT [ "/opt/jboss/container/java/run/run-java.sh" ]

View File

@@ -0,0 +1,27 @@
####
# This Dockerfile is used in order to build a container that runs the Quarkus application in native (no JVM) mode.
#
# Before building the container image run:
#
# ./mvnw package -Dnative
#
# Then, build the image with:
#
# docker build -f src/main/docker/Dockerfile.native -t quarkus/mic-after-work .
#
# Then run the container using:
#
# docker run -i --rm -p 8080:8080 quarkus/mic-after-work
#
###
FROM registry.access.redhat.com/ubi8/ubi-minimal:8.9
WORKDIR /work/
RUN chown 1001 /work \
&& chmod "g+rwX" /work \
&& chown 1001:root /work
COPY --chown=1001:root target/*-runner /work/application
EXPOSE 8080
USER 1001
ENTRYPOINT ["./application", "-Dquarkus.http.host=0.0.0.0"]

View File

@@ -0,0 +1,30 @@
####
# This Dockerfile is used in order to build a container that runs the Quarkus application in native (no JVM) mode.
# It uses a micro base image, tuned for Quarkus native executables.
# It reduces the size of the resulting container image.
# Check https://quarkus.io/guides/quarkus-runtime-base-image for further information about this image.
#
# Before building the container image run:
#
# ./mvnw package -Dnative
#
# Then, build the image with:
#
# docker build -f src/main/docker/Dockerfile.native-micro -t quarkus/mic-after-work .
#
# Then run the container using:
#
# docker run -i --rm -p 8080:8080 quarkus/mic-after-work
#
###
FROM quay.io/quarkus/quarkus-micro-image:2.0
WORKDIR /work/
RUN chown 1001 /work \
&& chmod "g+rwX" /work \
&& chown 1001:root /work
COPY --chown=1001:root target/*-runner /work/application
EXPOSE 8080
USER 1001
ENTRYPOINT ["./application", "-Dquarkus.http.host=0.0.0.0"]

View File

@@ -0,0 +1,16 @@
package com.lions.dev;
import jakarta.ws.rs.GET;
import jakarta.ws.rs.Path;
import jakarta.ws.rs.Produces;
import jakarta.ws.rs.core.MediaType;
@Path("/hello")
public class GreetingResource {
@GET
@Produces(MediaType.TEXT_PLAIN)
public String hello() {
return "Hello RESTEasy";
}
}

View File

@@ -0,0 +1,44 @@
package com.lions.dev.entity;
import io.quarkus.hibernate.orm.panache.PanacheEntityBase;
import jakarta.persistence.*;
import java.time.LocalDateTime;
import java.util.UUID;
import lombok.Getter;
import lombok.Setter;
import org.hibernate.annotations.UuidGenerator;
@Getter
@Setter
@MappedSuperclass
public abstract class BaseEntity extends PanacheEntityBase {
@Id
@UuidGenerator
@Column(name = "id", updatable = false, nullable = false)
private UUID id;
@Column(name = "created_at", updatable = false)
private LocalDateTime createdAt;
@Column(name = "updated_at")
private LocalDateTime updatedAt;
@Column(name = "created_by")
private String createdBy;
@Column(name = "updated_by")
private String updatedBy;
@PrePersist
protected void onCreate() {
this.createdAt = LocalDateTime.now();
// Logique pour définir `createdBy` à partir du contexte utilisateur
}
@PreUpdate
protected void onUpdate() {
this.updatedAt = LocalDateTime.now();
// Logique pour définir `updatedBy` à partir du contexte utilisateur
}
}

View File

@@ -0,0 +1,123 @@
package com.lions.dev.entity;
import com.fasterxml.jackson.annotation.JsonIgnore;
import com.fasterxml.jackson.annotation.JsonProperty;
import jakarta.persistence.*;
import jakarta.validation.constraints.NotNull;
import jakarta.validation.constraints.Size;
import java.time.LocalDateTime;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import java.util.UUID;
import lombok.Getter;
import lombok.Setter;
@Getter
@Setter
@Entity
@Table(name = "Events")
public class Events extends BaseEntity {
@NotNull
@Size(max = 100)
@Column(name = "title", nullable = false, length = 100)
@JsonProperty("title")
private String title;
@NotNull
@Size(max = 255)
@Column(name = "description", nullable = false, length = 255)
@JsonProperty("description")
private String description;
@NotNull
@Column(name = "event_date", nullable = false)
@JsonProperty("date")
private LocalDateTime eventDate;
@NotNull
@Size(max = 100)
@Column(name = "location", nullable = false, length = 100)
@JsonProperty("location")
private String location;
@Size(max = 100)
@Column(name = "category", length = 100)
@JsonProperty("category")
private String category;
@Column(name = "link", length = 255)
@JsonProperty("link")
private String link;
@Column(name = "image_url", length = 255)
@JsonProperty("imageUrl")
private String imageUrl;
@ManyToOne(fetch = FetchType.LAZY)
@JoinColumn(name = "creator_id")
@JsonProperty("creator")
private Users creator;
@ManyToMany(mappedBy = "participatedEvents", fetch = FetchType.LAZY)
@JsonIgnore
private Set<Users> participants = new HashSet<>();
// Méthode pour ajouter un participant
public void addParticipant(Users user) {
if (participants == null) {
participants = new HashSet<>();
}
if (!participants.contains(user)) {
participants.add(user);
user.getParticipatedEvents().add(this);
}
}
// Méthode pour retirer un participant
public void removeParticipant(Users user) {
if (participants != null && participants.contains(user)) {
participants.remove(user);
user.getParticipatedEvents().remove(this);
}
}
// Si vous avez une fonctionnalité de "like", vous pouvez ajouter une collection et des méthodes similaires
@ManyToMany(fetch = FetchType.LAZY)
@JoinTable(
name = "event_likes",
joinColumns = @JoinColumn(name = "event_id"),
inverseJoinColumns = @JoinColumn(name = "user_id")
)
@JsonIgnore
private Set<Users> likes = new HashSet<>();
public void addLike(Users user) {
if (likes == null) {
likes = new HashSet<>();
}
likes.add(user);
}
public void removeLike(Users user) {
if (likes != null) {
likes.remove(user);
}
}
@Override
public String toString() {
return "Events{" +
"id=" + getId() +
", title='" + title + '\'' +
", description='" + description + '\'' +
", eventDate=" + eventDate +
", location='" + location + '\'' +
", category='" + category + '\'' +
", link='" + link + '\'' +
", imageUrl='" + imageUrl + '\'' +
", creator=" + (creator != null ? creator.getId() : null) +
'}';
}
}

View File

@@ -0,0 +1,104 @@
package com.lions.dev.entity;
import com.fasterxml.jackson.annotation.JsonIgnore;
import com.fasterxml.jackson.annotation.JsonProperty;
import jakarta.persistence.*;
import jakarta.validation.constraints.Email;
import jakarta.validation.constraints.NotNull;
import jakarta.validation.constraints.Size;
import java.nio.charset.StandardCharsets;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.List;
import java.util.UUID;
import lombok.Getter;
import lombok.Setter;
@Getter
@Setter
@Entity
@Table(name = "Users")
public class Users extends BaseEntity {
@NotNull
@Size(max = 100)
@Column(name = "nom", nullable = false, length = 100)
@JsonProperty("nom")
private String nom;
@NotNull
@Size(max = 100)
@Column(name = "prenoms", nullable = false, length = 100)
@JsonProperty("prenoms")
private String prenoms;
@NotNull
@Email
@Size(max = 100)
@Column(name = "email", nullable = false, length = 100, unique = true)
@JsonProperty("email")
private String email;
@NotNull
@Size(min = 8, max = 255)
@Column(name = "mot_de_passe", nullable = false, length = 255)
@JsonProperty(access = JsonProperty.Access.READ_WRITE)
private String motDePasse;
@Size(max = 50)
@Column(name = "role", nullable = false, length = 50)
@JsonProperty("role")
private String role;
@OneToMany(mappedBy = "creator", cascade = CascadeType.ALL, orphanRemoval = true, fetch = FetchType.LAZY)
@JsonIgnore
private List<Events> createdEvents;
@ManyToMany(fetch = FetchType.LAZY)
@JoinTable(
name = "User_Event_Participation",
joinColumns = @JoinColumn(name = "user_id"),
inverseJoinColumns = @JoinColumn(name = "event_id")
)
@JsonIgnore
private List<Events> participatedEvents;
// Méthode pour définir un mot de passe haché avec SHA-256
public void setMotDePasse(String motDePasse) {
this.motDePasse = hashPasswordSHA256(motDePasse);
}
// Hachage du mot de passe avec SHA-256
private String hashPasswordSHA256(String motDePasse) {
try {
MessageDigest digest = MessageDigest.getInstance("SHA-256");
byte[] encodedhash = digest.digest(motDePasse.getBytes(StandardCharsets.UTF_8));
return bytesToHex(encodedhash);
} catch (NoSuchAlgorithmException e) {
throw new RuntimeException(e);
}
}
private String bytesToHex(byte[] hash) {
StringBuilder hexString = new StringBuilder(2 * hash.length);
for (byte b : hash) {
String hex = Integer.toHexString(0xff & b);
if (hex.length() == 1) {
hexString.append('0');
}
hexString.append(hex);
}
return hexString.toString();
}
@Override
public String toString() {
return "Users{" +
"id=" + getId() +
", nom='" + nom + '\'' +
", prenoms='" + prenoms + '\'' +
", email='" + email + '\'' +
", role='" + role + '\'' +
'}';
}
}

View File

@@ -0,0 +1,55 @@
package com.lions.dev.repository;
import com.lions.dev.entity.Events;
import jakarta.enterprise.context.ApplicationScoped;
import jakarta.persistence.EntityManager;
import jakarta.persistence.PersistenceContext;
import jakarta.transaction.Transactional;
import java.util.List;
import java.util.UUID;
@ApplicationScoped
public class EventsRepository {
@PersistenceContext
EntityManager entityManager;
/**
* Trouver tous les événements.
*
* @return Liste de tous les événements.
*/
public List<Events> findAllEvents() {
return entityManager.createQuery("SELECT e FROM Events e", Events.class).getResultList();
}
/**
* Trouver un événement par son ID.
*
* @param id L'ID de l'événement.
* @return L'événement trouvé ou null.
*/
public Events findById(UUID id) {
return entityManager.find(Events.class, id);
}
/**
* Persister un événement.
*
* @param event L'événement à persister.
*/
@Transactional
public void persist(Events event) {
entityManager.persist(event);
}
/**
* Supprimer un événement.
*
* @param event L'événement à supprimer.
*/
@Transactional
public void delete(Events event) {
entityManager.remove(entityManager.contains(event) ? event : entityManager.merge(event));
}
}

View File

@@ -0,0 +1,231 @@
package com.lions.dev.repository;
import com.lions.dev.entity.Users;
import io.quarkus.hibernate.orm.panache.PanacheRepositoryBase;
import jakarta.enterprise.context.ApplicationScoped;
import jakarta.transaction.Transactional;
import java.nio.charset.StandardCharsets;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.List;
import java.util.UUID;
/**
* Repository pour l'entité Users.
* Fournit des méthodes CRUD de base ainsi que des méthodes personnalisées.
*/
@ApplicationScoped
public class UsersRepository implements PanacheRepositoryBase<Users, UUID> {
/**
* Recherche les utilisateurs par nom.
*
* @param nom Le nom à rechercher.
* @return La liste des utilisateurs avec le nom donné.
*/
public List<Users> findByNom(String nom) {
return find("nom", nom).list();
}
/**
* Recherche un utilisateur par email.
*
* @param email L'email à rechercher.
* @return L'utilisateur avec l'email donné, ou null s'il n'existe pas.
*/
public Users findByEmail(String email) {
return find("email", email).firstResult();
}
/**
* Recherche les utilisateurs par nom et prénom.
*
* @param nom Le nom à rechercher.
* @param prenoms Le prénom à rechercher.
* @return La liste des utilisateurs correspondant au nom et prénom donnés.
*/
public List<Users> findByNomAndPrenoms(String nom, String prenoms) {
return find("nom = ?1 and prenoms = ?2", nom, prenoms).list();
}
/**
* Vérifie si un utilisateur avec un email donné existe.
*
* @param email L'email à vérifier.
* @return true si l'utilisateur existe, sinon false.
*/
public boolean existsByEmail(String email) {
return count("email", email) > 0;
}
/**
* Supprime un utilisateur par email.
*
* @param email L'email de l'utilisateur à supprimer.
* @return Le nombre d'entrées supprimées (0 ou 1).
*/
@Transactional
public long deleteByEmail(String email) {
return delete("email", email);
}
/**
* Recherche les utilisateurs par rôle.
*
* @param role Le rôle à rechercher.
* @return La liste des utilisateurs avec le rôle donné.
*/
public List<Users> findByRole(String role) {
return find("role", role).list();
}
/**
* Récupère une liste paginée d'utilisateurs.
*
* @param page Le numéro de la page (commençant à 0).
* @param size Le nombre d'éléments par page.
* @return Une liste paginée d'utilisateurs.
*/
public List<Users> findAllPaged(int page, int size) {
return findAll().page(page, size).list();
}
/**
* Compte le nombre total d'utilisateurs.
*
* @return Le nombre total d'utilisateurs.
*/
public long countAllUsers() {
return count();
}
/**
* Met à jour le mot de passe d'un utilisateur identifié par son email.
*
* @param email Le courriel de l'utilisateur.
* @param nouveauMotDePasse Le nouveau mot de passe.
* @return true si la mise à jour a réussi, sinon false.
*/
@Transactional
public boolean updatePasswordByEmail(String email, String nouveauMotDePasse) {
Users user = findByEmail(email);
if (user != null) {
user.setMotDePasse(hashPasswordSHA256(nouveauMotDePasse));
return true;
}
return false;
}
/**
* Recherche les utilisateurs qui ont créé un nombre spécifique d'événements.
*
* @param minEvents Le nombre minimum d'événements créés.
* @return La liste des utilisateurs ayant créé au moins le nombre d'événements spécifié.
*/
public List<Users> findByMinimumEventsCreated(int minEvents) {
return find("size(createdEvents) >= ?1", minEvents).list();
}
/**
* Recherche les utilisateurs participant à un événement spécifique.
*
* @param eventId L'ID de l'événement.
* @return La liste des utilisateurs participant à l'événement.
*/
public List<Users> findParticipantsByEventId(UUID eventId) {
return find("SELECT u FROM Users u JOIN u.participatedEvents e WHERE e.id = ?1", eventId).list();
}
/**
* Recherche les utilisateurs ayant aimé un événement spécifique.
*
* @param eventId L'ID de l'événement.
* @return La liste des utilisateurs ayant aimé l'événement.
*/
public List<Users> findUsersWhoLikedEvent(UUID eventId) {
// Remplacez par la logique de recherche appropriée en fonction du modèle de données "likes"
return find("SELECT u FROM Users u JOIN u.likedEvents e WHERE e.id = ?1", eventId).list();
}
/**
* Recherche les utilisateurs ayant créé un événement avec un titre spécifique.
*
* @param title Le titre de l'événement.
* @return La liste des utilisateurs ayant créé un événement avec le titre donné.
*/
public List<Users> findUsersByCreatedEventTitle(String title) {
return find("SELECT u FROM Users u JOIN u.createdEvents e WHERE e.title = ?1", title).list();
}
/**
* Met à jour le rôle d'un utilisateur par son ID.
*
* @param id L'ID de l'utilisateur.
* @param nouveauRole Le nouveau rôle.
* @return true si la mise à jour a réussi, sinon false.
*/
@Transactional
public boolean updateRoleById(UUID id, String nouveauRole) {
Users user = findById(id);
if (user != null) {
user.setRole(nouveauRole);
return true;
}
return false;
}
/**
* Recherche les utilisateurs qui ne participent à aucun événement.
*
* @return La liste des utilisateurs ne participant à aucun événement.
*/
public List<Users> findUsersWithNoParticipation() {
return find("SELECT u FROM Users u WHERE size(u.participatedEvents) = 0").list();
}
/**
* Recherche les utilisateurs ayant un mot de passe spécifique (recherche de mot de passe).
* Note : Ceci est un cas d'usage rare et devrait être utilisé avec prudence.
*
* @param motDePasse Le mot de passe à rechercher.
* @return La liste des utilisateurs avec le mot de passe donné.
*/
public List<Users> findByMotDePasse(String motDePasse) {
return find("motDePasse", hashPasswordSHA256(motDePasse)).list();
}
/**
* Hachage du mot de passe avec SHA-256.
*
* @param motDePasse Le mot de passe à hacher.
* @return Le mot de passe haché en SHA-256.
*/
private String hashPasswordSHA256(String motDePasse) {
try {
MessageDigest digest = MessageDigest.getInstance("SHA-256");
byte[] encodedhash = digest.digest(motDePasse.getBytes(StandardCharsets.UTF_8));
return bytesToHex(encodedhash);
} catch (NoSuchAlgorithmException e) {
throw new RuntimeException(e);
}
}
/**
* Convertit un tableau de bytes en chaîne hexadécimale.
*
* @param hash Le tableau de bytes.
* @return La chaîne hexadécimale représentant le hash.
*/
private String bytesToHex(byte[] hash) {
StringBuilder hexString = new StringBuilder(2 * hash.length);
for (byte b : hash) {
String hex = Integer.toHexString(0xff & b);
if (hex.length() == 1) {
hexString.append('0');
}
hexString.append(hex);
}
return hexString.toString();
}
}

View File

@@ -0,0 +1,191 @@
package com.lions.dev.resource;
import com.lions.dev.entity.Events;
import com.lions.dev.entity.Users;
import com.lions.dev.repository.EventsRepository;
import com.lions.dev.repository.UsersRepository;
import jakarta.inject.Inject;
import jakarta.transaction.Transactional;
import jakarta.validation.Valid;
import jakarta.ws.rs.*;
import jakarta.ws.rs.core.MediaType;
import jakarta.ws.rs.core.Response;
import org.eclipse.microprofile.openapi.annotations.Operation;
import org.eclipse.microprofile.openapi.annotations.tags.Tag;
import java.util.List;
import java.util.UUID;
@Path("/events")
@Produces(MediaType.APPLICATION_JSON)
@Consumes(MediaType.APPLICATION_JSON)
@Tag(name = "Events", description = "Opérations liées à l'entité Events")
public class EventsResource {
@Inject
UsersRepository usersRepository;
@Inject
EventsRepository eventsRepository;
@GET
@Operation(summary = "Récupérer tous les événements", description = "Retourne une liste de tous les événements")
public List<Events> getAllEvents() {
return eventsRepository.findAllEvents();
}
@POST
@Transactional
@Operation(summary = "Créer un nouvel événement", description = "Crée un nouvel événement")
public Response createEvent(@Valid Events event) {
try {
if (event.getCreator() != null) {
UUID creatorId = event.getCreator().getId();
if (creatorId == null) {
return Response.status(Response.Status.BAD_REQUEST)
.entity("L'ID du créateur est nul.")
.build();
}
Users creator = usersRepository.findById(creatorId);
if (creator == null) {
return Response.status(Response.Status.BAD_REQUEST)
.entity("Créateur non trouvé.")
.build();
}
event.setCreator(creator);
event.addParticipant(creator);
eventsRepository.persist(event);
return Response.status(Response.Status.CREATED).entity(event).build();
} else {
return Response.status(Response.Status.BAD_REQUEST)
.entity("Les informations du créateur sont manquantes.")
.build();
}
} catch (Exception e) {
e.printStackTrace();
return Response.status(Response.Status.INTERNAL_SERVER_ERROR)
.entity("Une erreur est survenue lors de la création de l'événement : " + e.getMessage())
.build();
}
}
@GET
@Path("{id}")
@Operation(summary = "Récupérer un événement par ID", description = "Retourne un événement par son ID")
public Response getEventById(@PathParam("id") UUID id) {
Events event = eventsRepository.findById(id);
if (event == null) {
return Response.status(Response.Status.NOT_FOUND).build();
}
return Response.ok(event).build();
}
@PUT
@Path("{id}")
@Transactional
@Operation(summary = "Mettre à jour un événement", description = "Met à jour un événement existant par ID")
public Response updateEvent(@PathParam("id") UUID id, @Valid Events event) {
Events entity = eventsRepository.findById(id);
if (entity == null) {
return Response.status(Response.Status.NOT_FOUND).build();
}
entity.setTitle(event.getTitle());
entity.setDescription(event.getDescription());
entity.setEventDate(event.getEventDate());
entity.setLocation(event.getLocation());
entity.setCategory(event.getCategory());
entity.setLink(event.getLink());
entity.setImageUrl(event.getImageUrl());
return Response.ok(entity).build();
}
@DELETE
@Path("{id}")
@Transactional
@Operation(summary = "Supprimer un événement", description = "Supprime un événement existant par ID")
public Response deleteEvent(@PathParam("id") UUID id) {
Events event = eventsRepository.findById(id);
if (event == null) {
return Response.status(Response.Status.NOT_FOUND).build();
}
eventsRepository.delete(event);
return Response.noContent().build();
}
@POST
@Path("{eventId}/participants/{userId}")
@Transactional
@Operation(summary = "Ajouter un participant à un événement", description = "Ajoute un utilisateur en tant que participant à un événement")
public Response addParticipant(@PathParam("eventId") UUID eventId, @PathParam("userId") UUID userId) {
Events event = eventsRepository.findById(eventId);
Users user = usersRepository.findById(userId);
if (event == null || user == null) {
return Response.status(Response.Status.NOT_FOUND)
.entity("Événement ou utilisateur non trouvé.")
.build();
}
event.addParticipant(user);
return Response.ok(event).build();
}
@DELETE
@Path("{eventId}/participants/{userId}")
@Transactional
@Operation(summary = "Retirer un participant d'un événement", description = "Retire un utilisateur en tant que participant d'un événement")
public Response removeParticipant(@PathParam("eventId") UUID eventId, @PathParam("userId") UUID userId) {
Events event = eventsRepository.findById(eventId);
Users user = usersRepository.findById(userId);
if (event == null || user == null) {
return Response.status(Response.Status.NOT_FOUND)
.entity("Événement ou utilisateur non trouvé.")
.build();
}
event.removeParticipant(user);
return Response.ok(event).build();
}
@POST
@Path("{eventId}/like/{userId}")
@Transactional
@Operation(summary = "Ajouter un 'j'aime' à un événement", description = "Ajoute un utilisateur aux 'j'aime' d'un événement")
public Response likeEvent(@PathParam("eventId") UUID eventId, @PathParam("userId") UUID userId) {
Events event = eventsRepository.findById(eventId);
Users user = usersRepository.findById(userId);
if (event == null || user == null) {
return Response.status(Response.Status.NOT_FOUND)
.entity("Événement ou utilisateur non trouvé.")
.build();
}
event.addLike(user);
return Response.ok(event).build();
}
@DELETE
@Path("{eventId}/like/{userId}")
@Transactional
@Operation(summary = "Retirer un 'j'aime' d'un événement", description = "Retire un utilisateur des 'j'aime' d'un événement")
public Response unlikeEvent(@PathParam("eventId") UUID eventId, @PathParam("userId") UUID userId) {
Events event = eventsRepository.findById(eventId);
Users user = usersRepository.findById(userId);
if (event == null || user == null) {
return Response.status(Response.Status.NOT_FOUND)
.entity("Événement ou utilisateur non trouvé.")
.build();
}
event.removeLike(user);
return Response.ok(event).build();
}
}

View File

@@ -0,0 +1,143 @@
package com.lions.dev.resource;
import com.lions.dev.entity.Users;
import com.lions.dev.repository.UsersRepository;
import jakarta.inject.Inject;
import jakarta.transaction.Transactional;
import jakarta.validation.Valid;
import jakarta.validation.constraints.Email;
import jakarta.validation.constraints.NotNull;
import jakarta.ws.rs.*;
import jakarta.ws.rs.core.MediaType;
import jakarta.ws.rs.core.Response;
import lombok.Getter;
import lombok.Setter;
import org.eclipse.microprofile.openapi.annotations.Operation;
import org.eclipse.microprofile.openapi.annotations.tags.Tag;
import java.util.List;
import java.util.UUID;
/**
* Ressource REST pour gérer les entités Users.
*/
@Path("/users")
@Produces(MediaType.APPLICATION_JSON)
@Consumes(MediaType.APPLICATION_JSON)
@Tag(name = "Users", description = "Opérations liées à l'entité Users")
public class UsersResource {
@Inject
UsersRepository usersRepository;
/**
* Récupère tous les utilisateurs.
*
* @return Liste des utilisateurs.
*/
@GET
@Operation(summary = "Récupérer tous les utilisateurs", description = "Retourne une liste de tous les utilisateurs")
public List<Users> getAllUsers() {
return usersRepository.listAll();
}
/**
* Crée un nouvel utilisateur.
*
* @param user L'utilisateur à créer.
* @return L'utilisateur créé.
*/
@POST
@Transactional
@Operation(summary = "Créer un nouvel utilisateur", description = "Crée un nouvel utilisateur")
public Response createUser(@Valid Users user) {
if (user.getId() != null && usersRepository.findById(user.getId()) != null) {
return Response.status(Response.Status.CONFLICT)
.entity("L'utilisateur avec l'ID " + user.getId() + " existe déjà.")
.build();
}
if (user.getMotDePasse() == null || user.getMotDePasse().isEmpty()) {
return Response.status(Response.Status.BAD_REQUEST)
.entity("Le mot de passe est obligatoire.")
.build();
}
usersRepository.persist(user);
return Response.status(Response.Status.CREATED).entity(user).build();
}
/**
* Authentifie un utilisateur avec son email et mot de passe.
*
* @param credentials Les identifiants de l'utilisateur.
* @return L'utilisateur authentifié.
*/
@POST
@Path("/authenticate")
@Transactional
@Operation(summary = "Authentifier un utilisateur", description = "Authentifie un utilisateur avec email et mot de passe")
public Response authenticateUser(@Valid UserCredentials credentials) {
Users user = usersRepository.find("email", credentials.getEmail()).firstResult();
if (user == null || !user.getMotDePasse().equals(credentials.getMotDePasse())) {
return Response.status(Response.Status.UNAUTHORIZED)
.entity("Email ou mot de passe incorrect")
.build();
}
return Response.ok(user).build();
}
/**
* Met à jour un utilisateur existant.
*
* @param id L'ID de l'utilisateur à mettre à jour.
* @param user Les nouvelles informations de l'utilisateur.
* @return L'utilisateur mis à jour.
*/
@PUT
@Path("{id}")
@Transactional
@Operation(summary = "Mettre à jour un utilisateur", description = "Met à jour un utilisateur existant par ID")
public Response updateUser(@PathParam("id") UUID id, @Valid Users user) {
Users entity = usersRepository.findById(id);
if (entity == null) {
return Response.status(Response.Status.NOT_FOUND).build();
}
entity.setNom(user.getNom());
entity.setPrenoms(user.getPrenoms());
entity.setEmail(user.getEmail());
entity.setMotDePasse(user.getMotDePasse());
return Response.ok(entity).build();
}
/**
* Supprime un utilisateur existant.
*
* @param id L'ID de l'utilisateur à supprimer.
* @return Une réponse vide avec le statut HTTP approprié.
*/
@DELETE
@Path("{id}")
@Transactional
@Operation(summary = "Supprimer un utilisateur", description = "Supprime un utilisateur existant par ID")
public Response deleteUser(@PathParam("id") UUID id) {
boolean deleted = usersRepository.deleteById(id);
if (!deleted) {
return Response.status(Response.Status.NOT_FOUND).build();
}
return Response.noContent().build();
}
/**
* Classe pour les identifiants de l'utilisateur lors de l'authentification.
*/
@Setter
@Getter
public static class UserCredentials {
@NotNull
@Email
private String email;
@NotNull
private String motDePasse;
}
}

View File

@@ -0,0 +1,14 @@
quarkus.http.port=8085
quarkus.swagger-ui.always-include=true
quarkus.swagger-ui.path=/q/swagger-ui
]quarkus.smallrye-openapi.path=/openapi
quarkus.datasource.db-kind=oracle
quarkus.datasource.jdbc.url=jdbc:oracle:thin:@localhost:1521:ORCLCDB
quarkus.datasource.username=C##AFTERWORK
quarkus.datasource.password=afterwork
quarkus.hibernate-orm.database.generation=drop-and-create
quarkus.datasource.jdbc.driver=oracle.jdbc.OracleDriver
quarkus.hibernate-orm.log.sql=true
quarkus.datasource.devservices.enabled=false

View File

@@ -0,0 +1,6 @@
-- This file allow to write SQL commands that will be emitted in test and dev.
-- The commands are commented as their support depends of the database
-- insert into myentity (id, field) values(1, 'field-1');
-- insert into myentity (id, field) values(2, 'field-2');
-- insert into myentity (id, field) values(3, 'field-3');
-- alter sequence myentity_seq restart with 4;

View File

@@ -0,0 +1,8 @@
package com.lions.dev;
import io.quarkus.test.junit.QuarkusIntegrationTest;
@QuarkusIntegrationTest
class GreetingResourceIT extends GreetingResourceTest {
// Execute the same tests but in packaged mode.
}

View File

@@ -0,0 +1,20 @@
package com.lions.dev;
import io.quarkus.test.junit.QuarkusTest;
import org.junit.jupiter.api.Test;
import static io.restassured.RestAssured.given;
import static org.hamcrest.CoreMatchers.is;
@QuarkusTest
class GreetingResourceTest {
@Test
void testHelloEndpoint() {
given()
.when().get("/hello")
.then()
.statusCode(200)
.body(is("Hello RESTEasy"));
}
}