|
| 1 | +package org.soujava.samples.mongodb.products; |
| 2 | + |
| 3 | +import jakarta.data.Order; |
| 4 | +import jakarta.data.Sort; |
| 5 | +import jakarta.data.page.PageRequest; |
| 6 | +import jakarta.enterprise.context.ApplicationScoped; |
| 7 | +import jakarta.ws.rs.DELETE; |
| 8 | +import jakarta.ws.rs.DefaultValue; |
| 9 | +import jakarta.ws.rs.GET; |
| 10 | +import jakarta.ws.rs.POST; |
| 11 | +import jakarta.ws.rs.Path; |
| 12 | +import jakarta.ws.rs.PathParam; |
| 13 | +import jakarta.ws.rs.QueryParam; |
| 14 | +import jakarta.ws.rs.WebApplicationException; |
| 15 | +import jakarta.ws.rs.core.Response; |
| 16 | + |
| 17 | +import java.util.List; |
| 18 | +import java.util.logging.Logger; |
| 19 | + |
| 20 | +@ApplicationScoped |
| 21 | +@Path("/products") |
| 22 | +public class ProductResource { |
| 23 | + |
| 24 | + private static final Order<Product> ORDER = Order.by(Sort.asc("name")); |
| 25 | + |
| 26 | + private static final Logger LOGGER = Logger.getLogger(ProductResource.class.getName()); |
| 27 | + |
| 28 | + private final ProductRepository repository; |
| 29 | + |
| 30 | + public ProductResource(ProductRepository repository) { |
| 31 | + this.repository = repository; |
| 32 | + } |
| 33 | + |
| 34 | + @Deprecated |
| 35 | + public ProductResource() { |
| 36 | + this(null); |
| 37 | + } |
| 38 | + |
| 39 | + @GET |
| 40 | + public List<Product> get( |
| 41 | + @QueryParam("page") @DefaultValue("1") int page, |
| 42 | + @QueryParam("size") @DefaultValue("10") int size) { |
| 43 | + LOGGER.info("The page number is: " + page + " and the size is: " + size); |
| 44 | + var request = PageRequest.ofPage(page).size(size); |
| 45 | + return repository.findAll(request, ORDER).content(); |
| 46 | + } |
| 47 | + |
| 48 | + @POST |
| 49 | + public Product insert(Product product) { |
| 50 | + return repository.save(product); |
| 51 | + } |
| 52 | + |
| 53 | + @DELETE |
| 54 | + @Path("{id}") |
| 55 | + public void delete(@PathParam("id") String id) { |
| 56 | + repository.deleteById(id); |
| 57 | + } |
| 58 | + |
| 59 | + @GET |
| 60 | + @Path("{id}") |
| 61 | + public Product findById(@PathParam("id") String id) { |
| 62 | + return repository.findById(id) |
| 63 | + .orElseThrow(() -> new WebApplicationException("Product not found, with id: " + id, Response.Status.NOT_FOUND)); |
| 64 | + } |
| 65 | +} |
0 commit comments