Skip to content

Commit

Permalink
Ajout des patrons de conceptions
Browse files Browse the repository at this point in the history
  • Loading branch information
TahyeLehbib committed Dec 25, 2024
1 parent 9bbe84b commit 0c5b9dd
Show file tree
Hide file tree
Showing 14 changed files with 381 additions and 122 deletions.
15 changes: 13 additions & 2 deletions shipping/pom.xml
Original file line number Diff line number Diff line change
Expand Up @@ -66,16 +66,27 @@
<groupId>io.quarkus</groupId>
<artifactId>quarkus-hibernate-validator</artifactId>
</dependency>
<dependency>
<groupId>io.quarkus</groupId>
<artifactId>quarkus-scheduler</artifactId>
</dependency>
<dependency>
<groupId>io.quarkus</groupId>
<artifactId>quarkus-junit5</artifactId>
<scope>test</scope>
</dependency>
<dependency>
<groupId>io.rest-assured</groupId>
<artifactId>rest-assured</artifactId>
<groupId>io.rest-assured</groupId>
<artifactId>rest-assured</artifactId> <!-- Ensure you're using the latest version -->
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.assertj</groupId>
<artifactId>assertj-core</artifactId>
<version>3.24.2</version>
<scope>test</scope>
</dependency>

</dependencies>

<build>
Expand Down
28 changes: 22 additions & 6 deletions shipping/src/main/java/org/shipping/api/ShippingResource.java
Original file line number Diff line number Diff line change
Expand Up @@ -51,7 +51,7 @@ public Response createShipment(@Valid ShipmentDTO shipmentDTO) {
return Response.status(Status.NOT_FOUND).entity(e.getMessage()).build();
} catch (Exception e) {
logger.error("Unexpected error occurred during shipment creation: " + e.getMessage(), e);
return Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity(e.getMessage()).build();
return Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity("Error creating shipment").build();
}
}

Expand Down Expand Up @@ -87,6 +87,12 @@ public Response updateShipment(@PathParam("orderId") UUID orderId, @Valid Shipme
try {
logger.info("Updating shipment for Order ID: " + orderId);

Shipment shipment = shippingService.getShipmentByOrderId(orderId);
if (shipment.getStatus() == DeliveryStatus.DELIVERED) {
logger.error("Cannot update a delivered shipment");
return Response.status(Response.Status.BAD_REQUEST).entity("Cannot update a delivered shipment").build();
}

Shipment updatedShipment = shippingService.updateShipment(
orderId,
shipmentDTO.getDeliveryDate(),
Expand Down Expand Up @@ -141,7 +147,7 @@ public Response getUserShipmentHistory(@QueryParam("status") DeliveryStatus stat

if (shipments.isEmpty()) {
logger.warn("No shipments found for user with status: " + status);
return Response.status(Response.Status.NOT_FOUND).entity("No shipments found").build();
return Response.status(Response.Status.NOT_FOUND).entity("No shipments found for the given status").build();
}

return Response.ok(shipments).build();
Expand All @@ -162,16 +168,26 @@ public Response deleteShipment(@PathParam("shipmentId") UUID shipmentId) {
try {
logger.info("Deleting shipment with ID: " + shipmentId);

// Vérification de la livraison
Shipment shipment = shippingService.getShipmentById(shipmentId);
if (shipment == null) {
logger.error("No shipment found with ID: " + shipmentId);
return Response.status(Response.Status.NOT_FOUND).entity("Shipment not found").build();
}

// Vérification du statut
if (shipment.getStatus() == DeliveryStatus.DELIVERED) {
logger.error("Cannot delete a delivered shipment");
return Response.status(Response.Status.BAD_REQUEST).entity("Cannot delete a delivered shipment").build();
}

shippingService.deleteShipment(shipmentId);
logger.info("Shipment deleted successfully with ID: " + shipmentId);

return Response.noContent().build();
} catch (NoResultException e) {
logger.error("NoResultException: " + e.getMessage());
return Response.status(Response.Status.NOT_FOUND).entity(e.getMessage()).build();
} catch (Exception e) {
logger.error("Unexpected error occurred while deleting shipment: " + e.getMessage(), e);
return Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity(e.getMessage()).build();
return Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity("Error deleting shipment").build();
}
}
}
38 changes: 38 additions & 0 deletions shipping/src/main/java/org/shipping/config/EventMappingConfig.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,38 @@
package org.shipping.config;

import jakarta.enterprise.context.ApplicationScoped;
import org.eclipse.microprofile.config.Config;
import org.eclipse.microprofile.config.ConfigProvider;

import java.util.HashMap;
import java.util.Map;
import java.util.UUID;

@ApplicationScoped
public class EventMappingConfig {

private final Map<UUID, String> eventMappings = new HashMap<>();

public EventMappingConfig() {
Config config = ConfigProvider.getConfig();
config.getPropertyNames()
.forEach(property -> {
if (property.startsWith("event.mapping.")) {
String uuidString = property.replace("event.mapping.", "");
String status = config.getValue(property, String.class);
eventMappings.put(UUID.fromString(uuidString), status);
}
});
}

public String getDeliveryStatus(String eventType) {
try {
// Convert the eventType string to UUID
UUID eventTypeUUID = UUID.fromString(eventType);
return eventMappings.get(eventTypeUUID); // Return status if found
} catch (IllegalArgumentException e) {
// Handle invalid UUID format, log or return a default value
return null;
}
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
package org.shipping.exception;

public class AddressNotFoundException extends RuntimeException {
public AddressNotFoundException(String message) {
super(message);
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
package org.shipping.exception;

public class OrderAlreadyAssociatedException extends RuntimeException {
public OrderAlreadyAssociatedException(String message) {
super(message);
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,66 @@
package org.shipping.messaging;

import jakarta.enterprise.context.ApplicationScoped;
import jakarta.inject.Inject;

import org.shipping.config.EventMappingConfig;
import org.shipping.model.OutboxEvent;
import org.shipping.model.DeliveryStatus;
import org.shipping.repository.OutboxRepository;

import io.quarkus.scheduler.Scheduled;
import org.jboss.logging.Logger;

import java.util.List;
import java.util.UUID;

@ApplicationScoped
public class OutboxEventPublisher {

private static final Logger logger = Logger.getLogger(OutboxEventPublisher.class);

@Inject
OutboxRepository outboxRepository;

@Inject
DeliveryStatusPublisher deliveryStatusPublisher;

@Inject
EventMappingConfig eventMappingConfig;

@Scheduled(every = "60s")
public void processOutbox() {
// Récupération des événements non traités
List<OutboxEvent> events = outboxRepository.find("processed = 'false'").list();

for (OutboxEvent event : events) {
try {
// Extraction du type d'événement
String eventType = event.getEventType();
String statusName = eventMappingConfig.getDeliveryStatus(eventType);

if (statusName != null) {
// Conversion du statut et publication
DeliveryStatus status = DeliveryStatus.valueOf(statusName);
deliveryStatusPublisher.publishStatus(UUID.fromString(event.getPayload()), status);

// Journaux pour le débogage
logger.infof("Traitement de l'événement %s avec le type %s", event.getId(), event.getEventType());
logger.infof("Statut publié : %s", statusName);

// Marquage de l'événement comme traité
event.setProcessed("true");
outboxRepository.persist(event);
logger.info("L'événement a été marqué comme traité.");
} else {
// Aucun mappage trouvé
logger.warnf("Aucun mappage trouvé pour le type d'événement : %s", eventType);
}
} catch (Exception e) {
// Gestion des erreurs
logger.errorf("Erreur lors du traitement de l'événement %s : %s", event.getId(), e.getMessage());
e.printStackTrace();
}
}
}
}
5 changes: 5 additions & 0 deletions shipping/src/main/java/org/shipping/messaging/Scheduled.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
package org.shipping.messaging;

public @interface Scheduled {

}
22 changes: 22 additions & 0 deletions shipping/src/main/java/org/shipping/model/EventTypeMapper.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,22 @@
package org.shipping.model;

import java.util.HashMap;
import java.util.Map;

public class EventTypeMapper {
// Dictionnaire pour mappage d'événements
private static final Map<String, String> eventTypes = new HashMap<>();

static {
// Vous pouvez ajouter autant d'événements que vous le souhaitez
eventTypes.put("SHIPPING_CREATED", "shipping.created");
eventTypes.put("SHIPPING_UPDATED", "shipping.updated");
eventTypes.put("SHIPPING_DELETED", "shipping.deleted");
// Vous pouvez ajouter d'autres événements ici
}

// Récupère le type d'événement en fonction du nom
public static String getEventType(String eventType) {
return eventTypes.getOrDefault(eventType, "unknown.event");
}
}
68 changes: 68 additions & 0 deletions shipping/src/main/java/org/shipping/model/OutboxEvent.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,68 @@
package org.shipping.model;


import jakarta.persistence.Entity;
import jakarta.persistence.Id;
import java.util.UUID;

@Entity
public class OutboxEvent {

@Id
private UUID id;
private UUID aggregateId;
private String eventType;
private String payload;
private String processed ;

public OutboxEvent() {
}

public OutboxEvent(UUID id, UUID aggregateId, String eventType, String payload, String processed) {
this.id = id;
this.aggregateId = aggregateId;
this.eventType = eventType;
this.payload = payload;
this.processed = processed;
}

public OutboxEvent(UUID aggregateId, String eventType, String payload, String processed) {
this.aggregateId = aggregateId;
this.eventType = eventType;
this.payload = payload;
this.processed = processed;
}

public UUID getId() {
return id;
}
public void setId(UUID id) {
this.id = id;
}
public UUID getAggregateId() {
return aggregateId;
}
public void setAggregateId(UUID aggregateId) {
this.aggregateId = aggregateId;
}
public String getEventType() {
return eventType;
}
public void setEventType(String eventType) {
this.eventType = eventType;
}
public String getPayload() {
return payload;
}
public void setPayload(String payload) {
this.payload = payload;
}
public String isProcessed() {
return processed;
}
public void setProcessed(String processed) {
this.processed = processed;
}


}
37 changes: 29 additions & 8 deletions shipping/src/main/java/org/shipping/model/Shipment.java
Original file line number Diff line number Diff line change
Expand Up @@ -18,34 +18,50 @@
@Entity
@Table(uniqueConstraints = { @UniqueConstraint(columnNames = { "orderId" }) })
public class Shipment {

@Id
@GeneratedValue(strategy = GenerationType.AUTO)
private UUID shipmentId;

@Column(nullable = false, updatable = false)
private UUID orderId; // Identifiant de la commande associée
private UUID orderId;

@Column(nullable = false, updatable = false)
private LocalDateTime createdDate = LocalDateTime.now(); // Date de création
private LocalDateTime createdDate;

private LocalDateTime deliveryDate;

@ManyToOne
@JoinColumn(name = "addressId", referencedColumnName = "id")
private Address address;

private LocalDateTime deliveryDate = LocalDateTime.now().plusDays(2); // Date de livraison prévue/effective

@ManyToOne(optional = false)
@JoinColumn(name = "addressId", referencedColumnName = "addressId", nullable = false)
private Address deliveryAddress; // Relation avec l’entité Address
private Address deliveryAddress;

// Ajouter addressId en tant que UUID pour utiliser explicitement la colonne
@Column(name = "addressId", insertable = false, updatable = false)
private UUID addressId;
@Enumerated(EnumType.STRING)
@Column(nullable = false)
private DeliveryStatus status = DeliveryStatus.PENDING; // Statut de la livraison
private DeliveryStatus status;

// Constructeur sans paramètres
public Shipment() {
this.createdDate = LocalDateTime.now();
this.deliveryDate = LocalDateTime.now().plusDays(2);
this.status = DeliveryStatus.PENDING;
}



// Constructeur avec paramètres
public Shipment(UUID orderId, Address deliveryAddress) {
public Shipment(UUID orderId, Address deliveryAddress, LocalDateTime createdDate, LocalDateTime deliveryDate) {
this.orderId = orderId;
this.deliveryAddress = deliveryAddress;
this.addressId = deliveryAddress.getAddressId(); // Assurez-vous de récupérer l'ID de l'adresse
this.createdDate = createdDate != null ? createdDate : LocalDateTime.now();
this.deliveryDate = deliveryDate != null ? deliveryDate : LocalDateTime.now().plusDays(2);
this.status = DeliveryStatus.PENDING;
}

// Getters et setters
Expand Down Expand Up @@ -75,6 +91,11 @@ public Address getDeliveryAddress() {

public void setDeliveryAddress(Address deliveryAddress) {
this.deliveryAddress = deliveryAddress;
this.addressId = deliveryAddress.getAddressId(); // Mettez à jour l'ID de l'adresse
}

public UUID getAddressId() {
return addressId;
}

public DeliveryStatus getStatus() {
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,10 @@
package org.shipping.repository;

import io.quarkus.hibernate.orm.panache.PanacheRepository;
import jakarta.enterprise.context.ApplicationScoped;

import org.shipping.model.OutboxEvent;

@ApplicationScoped
public class OutboxRepository implements PanacheRepository<OutboxEvent> {
}
Loading

0 comments on commit 0c5b9dd

Please sign in to comment.