Skip to content
Draft
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
3 changes: 2 additions & 1 deletion pom.xml
Original file line number Diff line number Diff line change
Expand Up @@ -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">
<modelVersion>4.0.0</modelVersion>

<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
Expand Down Expand Up @@ -40,7 +41,7 @@
<optional>true</optional>
</dependency>

<!-- SPRING BOOT TEST, EXCLUIMOS JUNIT4 -->
<!-- SPRING BOOT TEST -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -11,7 +11,7 @@ public class ValidationConfig {
@Bean
public ValidatingMongoEventListener validationMongoEventListener() {
return new ValidatingMongoEventListener(validator());
}
}//for commit

@Bean
public LocalValidatorFactoryBean validator() {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -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;
Expand Down Expand Up @@ -63,7 +64,9 @@ public ResponseEntity<?> addProducto(@RequestBody ProductoEntity producto) {
iProductoService.addProducto(producto);
return new ResponseEntity<ProductoEntity>(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<JsonResponse>(jsonResponseMsg,HttpStatus.BAD_REQUEST);

}
}
Expand Down
Original file line number Diff line number Diff line change
@@ -1,10 +1,7 @@
package com.api.rest.v1.exceptions.producto;

public class ProductoNotFoundException extends RuntimeException{

/**
*
*/

private static final long serialVersionUID = 1L;

public ProductoNotFoundException() {
Expand Down
Original file line number Diff line number Diff line change
@@ -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);
}

}
Original file line number Diff line number Diff line change
Expand Up @@ -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;
Expand Down Expand Up @@ -47,11 +49,21 @@ public interface I_ProductoRepository extends MongoRepository<ProductoEntity, St
@Query(value = "{'codigo': {$regex : ?0, $options: 'i'}}")
Page<ProductoEntity> findByCodigo(String codigo, Pageable pageable);

@Query("{'codigo': ?0}")
Optional<ProductoEntity> findByCodigo(String codigo);

@Query(value = "{'nombre': {$regex : ?0, $options: 'i'}}")
Page<ProductoEntity> findByNombre(String nombre, Pageable pageable);

@Query("{'nombre': ?0}")
Optional<ProductoEntity> findByNombre(String nombre);

@Query(value = "{'descripcion': {$regex : ?0, $options: 'i'}}")
Page<ProductoEntity> findByDescripcion(String descripcion, Pageable pageable);

@Query("{'descripcion': ?0}")
Optional<ProductoEntity> findByDescripcion(String descripcion);


@Query(value = "{'categoria': {$regex : ?0, $options: 'i'}}")
Page<ProductoEntity> findByCategoria(String categoria, Pageable pageable);
Expand Down Expand Up @@ -92,4 +104,5 @@ public interface I_ProductoRepository extends MongoRepository<ProductoEntity, St
@Query(value = "{'fecha': {$regex : ?0, $options: 'i'}, 'hora': {$regex : ?1, $options: 'i'}}")
Page<ProductoEntity> findByFechaHora(String fecha, String hora, Pageable pageable);


}
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand All @@ -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();

Expand All @@ -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));
Expand All @@ -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);
}

}
Expand Down Expand Up @@ -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);
}
}

Expand Down
23 changes: 23 additions & 0 deletions src/main/java/com/api/rest/v1/utils/http/JsonResponse.java
Original file line number Diff line number Diff line change
@@ -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;
}


}