diff --git a/pom.xml b/pom.xml index 085d659..407c727 100644 --- a/pom.xml +++ b/pom.xml @@ -3,6 +3,7 @@ xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd"> 4.0.0 + org.springframework.boot spring-boot-starter-parent @@ -40,7 +41,7 @@ true - + org.springframework.boot spring-boot-starter-test diff --git a/src/main/java/com/api/rest/v1/config/validation/ValidationConfig.java b/src/main/java/com/api/rest/v1/config/validation/ValidationConfig.java index f250a14..cded55a 100644 --- a/src/main/java/com/api/rest/v1/config/validation/ValidationConfig.java +++ b/src/main/java/com/api/rest/v1/config/validation/ValidationConfig.java @@ -11,7 +11,7 @@ public class ValidationConfig { @Bean public ValidatingMongoEventListener validationMongoEventListener() { return new ValidatingMongoEventListener(validator()); - } + }//for commit @Bean public LocalValidatorFactoryBean validator() { diff --git a/src/main/java/com/api/rest/v1/controllers/ProductoController.java b/src/main/java/com/api/rest/v1/controllers/ProductoController.java index b31dc23..3573439 100644 --- a/src/main/java/com/api/rest/v1/controllers/ProductoController.java +++ b/src/main/java/com/api/rest/v1/controllers/ProductoController.java @@ -19,6 +19,7 @@ import com.api.rest.v1.entities.ProductoEntity; import com.api.rest.v1.services.productos.I_ProductoService; +import com.api.rest.v1.utils.http.JsonResponse; import io.swagger.annotations.ApiOperation; import io.swagger.annotations.ApiResponses; @@ -63,7 +64,9 @@ public ResponseEntity addProducto(@RequestBody ProductoEntity producto) { iProductoService.addProducto(producto); return new ResponseEntity(producto, HttpStatus.OK); } catch (Exception e) { - return new ResponseEntity<>(e.getMessage(), HttpStatus.UNPROCESSABLE_ENTITY); + JsonResponse jsonResponseMsg = new JsonResponse(); + jsonResponseMsg.setMessage(e.getMessage()); + return new ResponseEntity(jsonResponseMsg,HttpStatus.BAD_REQUEST); } } diff --git a/src/main/java/com/api/rest/v1/exceptions/producto/ProductoNotFoundException.java b/src/main/java/com/api/rest/v1/exceptions/producto/ProductoNotFoundException.java index 8424a53..ed989ca 100644 --- a/src/main/java/com/api/rest/v1/exceptions/producto/ProductoNotFoundException.java +++ b/src/main/java/com/api/rest/v1/exceptions/producto/ProductoNotFoundException.java @@ -1,10 +1,7 @@ package com.api.rest.v1.exceptions.producto; public class ProductoNotFoundException extends RuntimeException{ - - /** - * - */ + private static final long serialVersionUID = 1L; public ProductoNotFoundException() { diff --git a/src/main/java/com/api/rest/v1/exceptions/producto/ProductoValidationException.java b/src/main/java/com/api/rest/v1/exceptions/producto/ProductoValidationException.java new file mode 100644 index 0000000..4ea36d6 --- /dev/null +++ b/src/main/java/com/api/rest/v1/exceptions/producto/ProductoValidationException.java @@ -0,0 +1,27 @@ +package com.api.rest.v1.exceptions.producto; + +public class ProductoValidationException extends RuntimeException{ + + private static final long serialVersionUID = 1L; + + public ProductoValidationException() { + + } + + public ProductoValidationException(String msj) { + super(msj); + } + + public ProductoValidationException(Throwable cause) { + super(cause); + } + + public ProductoValidationException(String msj, Throwable cause) { + super(msj, cause); + } + + public ProductoValidationException(String msj, Throwable cause, boolean enableSuppression, boolean writableStackTrace) { + super(msj, cause, enableSuppression, writableStackTrace); + } + +} diff --git a/src/main/java/com/api/rest/v1/repositories/I_ProductoRepository.java b/src/main/java/com/api/rest/v1/repositories/I_ProductoRepository.java index 9a6429c..122f5c4 100644 --- a/src/main/java/com/api/rest/v1/repositories/I_ProductoRepository.java +++ b/src/main/java/com/api/rest/v1/repositories/I_ProductoRepository.java @@ -2,6 +2,8 @@ import java.util.Optional; +import javax.validation.constraints.NotNull; + import org.springframework.data.domain.Page; import org.springframework.data.domain.Pageable; import org.springframework.data.mongodb.repository.MongoRepository; @@ -47,11 +49,21 @@ public interface I_ProductoRepository extends MongoRepository findByCodigo(String codigo, Pageable pageable); + @Query("{'codigo': ?0}") + Optional findByCodigo(String codigo); + @Query(value = "{'nombre': {$regex : ?0, $options: 'i'}}") Page findByNombre(String nombre, Pageable pageable); + + @Query("{'nombre': ?0}") + Optional findByNombre(String nombre); @Query(value = "{'descripcion': {$regex : ?0, $options: 'i'}}") Page findByDescripcion(String descripcion, Pageable pageable); + + @Query("{'descripcion': ?0}") + Optional findByDescripcion(String descripcion); + @Query(value = "{'categoria': {$regex : ?0, $options: 'i'}}") Page findByCategoria(String categoria, Pageable pageable); @@ -92,4 +104,5 @@ public interface I_ProductoRepository extends MongoRepository findByFechaHora(String fecha, String hora, Pageable pageable); + } diff --git a/src/main/java/com/api/rest/v1/services/productos/ProductoServiceImpl.java b/src/main/java/com/api/rest/v1/services/productos/ProductoServiceImpl.java index 8081c31..aac684e 100644 --- a/src/main/java/com/api/rest/v1/services/productos/ProductoServiceImpl.java +++ b/src/main/java/com/api/rest/v1/services/productos/ProductoServiceImpl.java @@ -16,6 +16,7 @@ import com.api.rest.v1.entities.ProductoEntity; import com.api.rest.v1.exceptions.producto.ProductoIdMismatchException; import com.api.rest.v1.exceptions.producto.ProductoNotFoundException; +import com.api.rest.v1.exceptions.producto.ProductoValidationException; import com.api.rest.v1.repositories.I_ProductoRepository; @Service @@ -24,12 +25,10 @@ public class ProductoServiceImpl implements I_ProductoService { @Autowired I_ProductoRepository iProductoRepository; - // =============== LOGS ==================== + // For logging private static final Logger logger = org.apache.logging.log4j.LogManager.getLogger(ProductoServiceImpl.class); - // ================ AUTOGENERATE ==================== - - // Fecha y Hora Formateado + // For autogenerate LocalDate fecha = LocalDate.now(); LocalTime hora = LocalTime.now(); @@ -47,18 +46,26 @@ public class ProductoServiceImpl implements I_ProductoService { public void addProducto(ProductoEntity producto) { try { - if (producto == null || !(producto instanceof ProductoEntity)) { - logger.error("ERROR addProducto : EL PRODUCTO " + producto + " ES NULO!!"); - throw new ProductoNotFoundException("EL PRODUCTO ES NULO"); + if (producto == null || producto.toString().isBlank() || !(producto instanceof ProductoEntity)) { + logger.error("ERROR in addProducto service : EL PRODUCTO ES NULO!!"); + throw new ProductoNotFoundException("PRODUCTO NULO"); } else if (producto.getCodigo() == "" || producto.getNombre() == "" || producto.getMarca() == "" || producto.getDescripcion() == "" || producto.getCategoria() == "" || producto.getPrecio() == 0 || producto.getStock() == 0) { - logger.error( - "ERROR addProducto : LOS VALORES DE LOS CAMPOS DEL PRODUCTO " + producto + " NO SON VÁLIDOS!!"); - throw new ProductoNotFoundException("VALORES DE CAMPOS NO VÁLIDOS"); - } else { - System.out.println("\n PRODUCTO PRE:" + producto); + logger.error("ERROR in addProducto service : LOS VALORES DE LOS CAMPOS DEL PRODUCTO NO SON VÁLIDOS!!"); + throw new ProductoValidationException("VALORES DE CAMPOS NO VÁLIDOS"); + + } else if (iProductoRepository.findByCodigo(producto.getCodigo()).isPresent()) { + + logger.error("ERROR in addProducto service : CÓDIGO DE PRODUCTO DUPLICADO!!"); + throw new ProductoValidationException("CÓDIGO DE PRODUCTO DUPLICADO"); + } else if (iProductoRepository.findByNombre(producto.getNombre()).isPresent() + && iProductoRepository.findByDescripcion(producto.getDescripcion()).isPresent()) { + + logger.error("ERROR in addProducto service : NOMBRE Y DESCRIPCIÓN DE PRODUCTO DUPLICADO!!"); + throw new ProductoValidationException("NOMBRE Y DESCRIPCIÓN DE PRODUCTO DUPLICADO"); + } else { String id = new ObjectId().toString(); String fechaStr = String.valueOf(fecha.format(formatoFecha)); @@ -68,16 +75,16 @@ public void addProducto(ProductoEntity producto) { producto.setFecha(fechaStr); producto.setHora(horaStr); - System.out.println("\n PRODUCTO MODIFICADO:" + producto); - iProductoRepository.save(producto); logger.info("SE HA INSERTADO CORRECTAMENTE EL PRODUCTO CON EL ID " + producto.getId()); } } catch (Exception e) { - logger.error( - "ERROR addProducto : EL PRODUCTO " + producto + " NO SE HA INSERTADO EN LA DB!! CAUSADO POR " + e); - throw new ProductoNotFoundException("NO SE PUDO AGREGAR EL PRODUCTO. ", e, false, true); + logger.error("ERROR in addProducto service : EL PRODUCTO NO SE HA INSERTADO EN LA DB!! CAUSADO POR " + + e.getMessage()); + throw new ProductoNotFoundException( + "NO ES POSIBLE AGREGAR EL PRODUCTO. ERROR CAUSADO POR " + e.getMessage(), e.getCause(), false, + true); } } @@ -145,8 +152,8 @@ public void updateProducto(String id, ProductoEntity producto) { logger.error("ERROR updateProducto : EL PRODUCTO " + producto + " NO SE HA ACTUALIZADO EN LA DB!!CAUSADO POR " + e); throw new ProductoNotFoundException( - "NO SE PUDO ACTUALIZAR EL PRODUCTO. VALIDAR LA TOTALIDAD DE CAMPOS O PRODUCTO NO ENCONTRADO! ", e, true, - true); + "NO SE PUDO ACTUALIZAR EL PRODUCTO. VALIDAR LA TOTALIDAD DE CAMPOS O PRODUCTO NO ENCONTRADO! ", e, + true, true); } } diff --git a/src/main/java/com/api/rest/v1/utils/http/JsonResponse.java b/src/main/java/com/api/rest/v1/utils/http/JsonResponse.java new file mode 100644 index 0000000..0dd67b7 --- /dev/null +++ b/src/main/java/com/api/rest/v1/utils/http/JsonResponse.java @@ -0,0 +1,23 @@ +package com.api.rest.v1.utils.http; + +public class JsonResponse { + String message; + + public JsonResponse() { + } + + public JsonResponse(String message) { + super(); + this.message = message; + } + + public String getMessage() { + return message; + } + + public void setMessage(String message) { + this.message = message; + } + + +}