|
| 1 | +package eu.happycoders.virtualthread.controller; |
| 2 | + |
| 3 | +import eu.happycoders.virtualthread.model.ProductPageResponse; |
| 4 | +import eu.happycoders.virtualthread.service.ProductService; |
| 5 | +import eu.happycoders.virtualthread.service.SupplierService; |
| 6 | +import eu.happycoders.virtualthread.service.WarehouseService; |
| 7 | +import java.util.concurrent.CompletableFuture; |
| 8 | +import java.util.concurrent.CompletionStage; |
| 9 | +import org.springframework.http.ResponseEntity; |
| 10 | +import org.springframework.web.bind.annotation.GetMapping; |
| 11 | +import org.springframework.web.bind.annotation.PathVariable; |
| 12 | +import org.springframework.web.bind.annotation.RestController; |
| 13 | + |
| 14 | +@RestController |
| 15 | +public class ControllerEvolution2_CompletableFuture { |
| 16 | + |
| 17 | + private final ProductService productService; |
| 18 | + private final SupplierService supplierService; |
| 19 | + private final WarehouseService warehouseService; |
| 20 | + |
| 21 | + public ControllerEvolution2_CompletableFuture( |
| 22 | + ProductService productService, |
| 23 | + SupplierService supplierService, |
| 24 | + WarehouseService warehouseService) { |
| 25 | + this.productService = productService; |
| 26 | + this.supplierService = supplierService; |
| 27 | + this.warehouseService = warehouseService; |
| 28 | + } |
| 29 | + |
| 30 | + @GetMapping("/stage2-cf/product/{productId}") |
| 31 | + public CompletionStage<ResponseEntity<ProductPageResponse>> getProduct( |
| 32 | + @PathVariable("productId") String productId) { |
| 33 | + return productService |
| 34 | + .getProductAsync(productId) |
| 35 | + .thenCompose( |
| 36 | + product -> { |
| 37 | + if (product.isEmpty()) { |
| 38 | + return CompletableFuture.completedFuture(ResponseEntity.notFound().build()); |
| 39 | + } |
| 40 | + |
| 41 | + return warehouseService |
| 42 | + .isAvailableAsync(productId) |
| 43 | + .thenCompose( |
| 44 | + available -> |
| 45 | + available |
| 46 | + ? CompletableFuture.completedFuture(0) |
| 47 | + : supplierService.getDeliveryTimeAsync( |
| 48 | + product.get().supplier(), productId)) |
| 49 | + .thenApply( |
| 50 | + daysUntilShippable -> |
| 51 | + ResponseEntity.ok( |
| 52 | + new ProductPageResponse( |
| 53 | + product.get(), |
| 54 | + daysUntilShippable, |
| 55 | + Thread.currentThread().toString()))); |
| 56 | + }); |
| 57 | + } |
| 58 | +} |
0 commit comments