Skip to content

Commit

Permalink
+ Subscribe to the pricing copie 0
Browse files Browse the repository at this point in the history
  • Loading branch information
sarahjebali committed Dec 20, 2024
1 parent 2a91d53 commit 8a88ac5
Show file tree
Hide file tree
Showing 7 changed files with 144 additions and 3 deletions.
32 changes: 32 additions & 0 deletions cart/src/main/java/org/soa/dto/PriceEvent.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,32 @@
package org.soa.dto;

public class PriceEvent {
private String productId;
private double price;

// Getters et setters
public String getProductId() {
return productId;
}

public void setProductId(String productId) {
this.productId = productId;
}

public double getPrice() {
return price;
}

public void setPrice(double price) {
this.price = price;
}

@Override
public String toString() {
return "PriceEvent{" +
"productId='" + productId + '\'' +
", price=" + price +
'}';
}
}

31 changes: 31 additions & 0 deletions cart/src/main/java/org/soa/messaging/PricingEventConsumer.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,31 @@
package org.soa.messaging;

import org.eclipse.microprofile.reactive.messaging.Incoming;
import jakarta.enterprise.context.ApplicationScoped;
import java.util.HashMap;
import java.util.Map;
import java.util.UUID;

import org.soa.dto.PriceEvent;

@ApplicationScoped
public class PricingEventConsumer {

private final Map<UUID, Double> productPrices = new HashMap<>(); // Utilisation de UUID comme clé

@Incoming("pricing-price-channel") // Le canal Kafka configuré dans application.properties
public void consumePriceEvent(PriceEvent priceEvent) {
// Enregistrer le prix de l'article avec l'UUID comme clé
UUID productId = UUID.fromString(priceEvent.getProductId()); // Conversion de String en UUID
productPrices.put(productId, priceEvent.getPrice());
System.out.println("Prix reçu pour l'article : " + priceEvent);
}

public double getPrice(UUID productId) {
return productPrices.getOrDefault(productId, -1.0); // Retourne -1.0 si le produit n'est pas trouvé
}

public Map<UUID, Double> getAllPrices() {
return productPrices;
}
}
6 changes: 6 additions & 0 deletions cart/src/main/java/org/soa/model/Cart.java
Original file line number Diff line number Diff line change
Expand Up @@ -31,4 +31,10 @@ public Map<UUID, Item> getItems() {
public void setItems(Map<UUID, Item> items) {
this.items = items;
}

public double calculateTotalPrice() {
return items.values().stream()
.mapToDouble(Item::getTotalPrice)
.sum();
}
}
15 changes: 15 additions & 0 deletions cart/src/main/java/org/soa/serialization/CartDTOSerializer.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,15 @@
package org.soa.serialization;

import io.quarkus.kafka.client.serialization.ObjectMapperSerializer;
import org.soa.dto.CartDTO;

public class CartDTOSerializer extends ObjectMapperSerializer<CartDTO> {

/**
* Constructor for CartDTOSerializer.
* This ensures the ObjectMapper provided by Quarkus is used to serialize CartDTO objects.
*/
public CartDTOSerializer() {
super();
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,31 @@
package org.soa.serialization;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.apache.kafka.common.serialization.Deserializer;

import java.util.Map;
import org.soa.dto.PriceEvent;


public class PriceEventDeserializer implements Deserializer<PriceEvent> {

private final ObjectMapper objectMapper = new ObjectMapper();

@Override
public void configure(Map<String, ?> configs, boolean isKey) {
// Configuration si nécessaire
}

@Override
public PriceEvent deserialize(String topic, byte[] data) {
try {
return objectMapper.readValue(data, PriceEvent.class);
} catch (Exception e) {
throw new RuntimeException("Erreur lors de la désérialisation de l'événement de prix", e);
}
}

@Override
public void close() {
// Nettoyage si nécessaire
}
}
25 changes: 23 additions & 2 deletions cart/src/main/java/org/soa/service/CartService.java
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,8 @@
import org.soa.model.Cart;
import org.soa.model.Item;
import org.soa.messaging.CartPublisher;
import org.soa.messaging.PricingEventConsumer;
import java.util.Map;

import java.util.List;
import java.util.UUID;
Expand Down Expand Up @@ -65,11 +67,13 @@ public Cart getCart(UUID userId) {
throw new RuntimeException("An unexpected error occurred while fetching the cart.", e);
}
}

// Ajouter un item au panier
@Inject
PricingEventConsumer PricingEventConsumer;
public void addItem(UUID userId, Item item) {
try {
logger.info("Adding item to cart for userId: " + userId);

// Récupérer la carte des paniers
RMap<UUID, Cart> carts = getCartsMap();
Cart cart = carts.get(userId);

Expand All @@ -78,6 +82,21 @@ public void addItem(UUID userId, Item item) {
throw new IllegalArgumentException("Cart not found for userId: " + userId);
}

// Récupérer tous les prix depuis PricingEventConsumer
Map<UUID, Double> allPrices = PricingEventConsumer.getAllPrices();

// Récupérer le prix de l'article à partir de la map des prix
Double price = allPrices.get(item.getItemId());

if (price == null) {
logger.error("Price not found for itemId: " + item.getItemId());
throw new IllegalArgumentException("Price not found for itemId: " + item.getItemId());
}

// Mettre à jour l'article avec le prix récupéré
item.setPrice(price);

// Ajouter l'article au panier, en mettant à jour la quantité si l'article existe déjà
cart.getItems().compute(item.getItemId(), (key, existingItem) -> {
if (existingItem != null) {
existingItem.setQuantity(existingItem.getQuantity() + item.getQuantity());
Expand All @@ -86,6 +105,7 @@ public void addItem(UUID userId, Item item) {
return item;
});

// Mettre à jour le panier dans la carte
carts.put(userId, cart);
logger.info("Item added successfully to cart for userId: " + userId);
} catch (Exception e) {
Expand All @@ -94,6 +114,7 @@ public void addItem(UUID userId, Item item) {
}
}


// Mettre à jour un item dans le panier
public void updateItem(UUID userId, Item cartItem) {
try {
Expand Down
7 changes: 6 additions & 1 deletion cart/src/main/resources/application.properties
Original file line number Diff line number Diff line change
Expand Up @@ -4,11 +4,16 @@ quarkus.redis.hosts=redis://localhost:6379

mp.messaging.outgoing.cart-topic.connector=smallrye-kafka
mp.messaging.outgoing.cart-topic.topic=cart-topic
mp.messaging.outgoing.cart-topic.value.serializer=org.soa.serialization.CartEventSerializer
#mp.messaging.outgoing.cart-topic.value.serializer=org.soa.serialization.CartEventSerializer
mp.messaging.outgoing.cart-topic.value.serializer=org.soa.serialization.CartDTOSerializer
mp.messaging.outgoing.cart-topic.bootstrap.servers=localhost:9093
quarkus.kafka.devservices.enabled=false

# Kafka broker address

mp.messaging.incoming.pricing-price-channel.connector=smallrye-kafka
mp.messaging.incoming.pricing-price-channel.topic=pricing-prices
mp.messaging.incoming.pricing-price-channel.value.deserializer=org.soa.serialization.StringDeserializer



0 comments on commit 8a88ac5

Please sign in to comment.