Skip to content

Commit 30d3d20

Browse files
committed
version 0.9
1 parent 91a3ce7 commit 30d3d20

15 files changed

+170
-74
lines changed

src/main/java/com/cibertec/shoesformen_api/MySQLConfig.java

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -20,7 +20,7 @@
2020
@EnableJpaRepositories(
2121
entityManagerFactoryRef = "msqlEntityManagerFactory", // <----
2222
transactionManagerRef = "msqlTransactionManager", // <----
23-
basePackages = { "com.cibertec.shoesformen_api.a_empresa" } // <-- REPOSITORIO Y MODEL EN MI ESTE CASO ESTAN EL MISMO PAQUETE
23+
basePackages = { "com.cibertec.shoesformen_api.a_empresa" } // <-- REPOSITORIO Y MODEL EN MI CASO ESTAN EL MISMO PAQUETE
2424
)
2525
public class MySQLConfig {
2626

src/main/java/com/cibertec/shoesformen_api/a_empresa/EmpresaRepository.java

Lines changed: 0 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -7,6 +7,4 @@
77
@Repository
88
public interface EmpresaRepository extends JpaRepository<Empresa, String> {
99

10-
11-
1210
}

src/main/java/com/cibertec/shoesformen_api/controller/DistritoController.java

Lines changed: 29 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -3,22 +3,49 @@
33
import com.cibertec.shoesformen_api.model.Distrito;
44
import com.cibertec.shoesformen_api.repository.DistritoRepository;
55
import org.springframework.beans.factory.annotation.Autowired;
6+
import org.springframework.data.domain.Page;
7+
import org.springframework.data.domain.PageRequest;
8+
import org.springframework.data.domain.Pageable;
9+
import org.springframework.data.domain.Sort;
10+
import org.springframework.http.HttpStatus;
11+
import org.springframework.http.ResponseEntity;
612
import org.springframework.web.bind.annotation.GetMapping;
13+
import org.springframework.web.bind.annotation.RequestMapping;
14+
import org.springframework.web.bind.annotation.RequestParam;
715
import org.springframework.web.bind.annotation.RestController;
816

17+
18+
import java.util.ArrayList;
919
import java.util.List;
1020

1121
@RestController
12-
//@RequestMapping("/")
22+
@RequestMapping("/distritos")
1323
public class DistritoController {
1424

1525
@Autowired
1626
private DistritoRepository distritoRepo;
1727

1828

19-
@GetMapping("/distritos")
29+
@GetMapping()
2030
public List<Distrito> all() {
2131
return distritoRepo.findAll();
2232
}
2333

34+
@GetMapping("/list")
35+
public ResponseEntity<List<Distrito>> getAllEmployees(
36+
@RequestParam(defaultValue = "0") Integer pageNo,
37+
@RequestParam(defaultValue = "3") Integer pageSize,
38+
@RequestParam(defaultValue = "codDistrito") String sortBy)
39+
{
40+
Pageable paging = PageRequest.of(pageNo, pageSize, Sort.by(sortBy));
41+
Page<Distrito> pagedResult = distritoRepo.findAll(paging);
42+
List<Distrito> lista;
43+
if (pagedResult.hasContent()){
44+
lista = pagedResult.getContent();
45+
} else {
46+
lista = new ArrayList<Distrito>();
47+
}
48+
return new ResponseEntity<List<Distrito>>(lista, HttpStatus.OK);
49+
}
50+
2451
}

src/main/java/com/cibertec/shoesformen_api/controller/EmpleadoController.java

Lines changed: 41 additions & 14 deletions
Original file line numberDiff line numberDiff line change
@@ -1,15 +1,13 @@
11
package com.cibertec.shoesformen_api.controller;
22

33
import com.cibertec.shoesformen_api.exception.EntidadNotFoundException;
4-
import com.cibertec.shoesformen_api.exception.ListEmptyException;
54
import com.cibertec.shoesformen_api.model.Empleado;
65
import com.cibertec.shoesformen_api.model.dto.EmpleadoDTO;
76
import com.cibertec.shoesformen_api.repository.DistritoRepository;
87
import com.cibertec.shoesformen_api.repository.EmpleadoRepository;
98
import com.cibertec.shoesformen_api.repository.EstadoRepository;
109
import com.cibertec.shoesformen_api.service.EmpleadoService;
1110
import jakarta.servlet.http.HttpServletResponse;
12-
import jakarta.validation.Valid;
1311
import net.sf.jasperreports.engine.JRException;
1412
import org.springframework.beans.factory.annotation.Autowired;
1513
import org.springframework.core.io.Resource;
@@ -21,6 +19,7 @@
2119

2220
import java.io.IOException;
2321
import java.util.List;
22+
import java.util.Optional;
2423

2524
@Controller
2625
@RequestMapping("/empleados")
@@ -42,35 +41,65 @@ public class EmpleadoController {
4241

4342

4443
@GetMapping() // al entrar a la ruta principal "/empleados" se activa el metodo GET sin ruta especificada.
45-
public ResponseEntity<List<Empleado>> getAll() throws ListEmptyException{
44+
public ResponseEntity<List<Empleado>> getAll() {
4645
return ResponseEntity.ok(empleadoServ.listar());
4746
}
4847

4948
@PostMapping // post por defecto
50-
public ResponseEntity<Empleado> newEmpleado (@RequestBody @Valid EmpleadoDTO dto) throws IllegalArgumentException, EntidadNotFoundException {
51-
Empleado empleado = empleadoServ.buildEmpleado(dto); // -> construyo el empleado sin cod_empleado
49+
public ResponseEntity<Empleado> newEmpleado (@RequestBody EmpleadoDTO dto) { // @Valid -> quitado, porque la validacion lo realiza en el servicio
50+
Empleado empleado = empleadoServ.buildEmpleado(dto); // -> VALIDA y construye el empleado sin cod_empleado
5251
empleado.setCodEmpleado(empleadoServ.createNewCodigo()); // -> insertamos el codigo que debe tener
5352
return new ResponseEntity<>(empleadoServ.guardar(empleado), HttpStatus.CREATED); // -> insertamos el empleado
5453
}
5554

56-
@PutMapping("/{id}") // ACTUALIZACION, su objetivo es actualizar no crear, por eso debe verificar si existe.
57-
public ResponseEntity replaceEmpleado(@RequestBody @Valid EmpleadoDTO dto, @PathVariable String id) throws IllegalArgumentException, EntidadNotFoundException{ // imaginate que el id no coincida con el de empleado que envia. Ademas el empleado no deberia venir con ID, ¿porque?
58-
if(empleadoServ.getEmpleadoByCodigo(id).isPresent() ){
59-
Empleado empleado = empleadoServ.buildEmpleado(dto);
55+
// @PutMapping("/{id}") // ACTUALIZACION enviando toda la entidad. su objetivo es actualizar no crear, por eso debe verificar si existe.
56+
// public ResponseEntity replaceEmpleado(@RequestBody @Valid EmpleadoDTO dto, @PathVariable String id) { // El EmpleadoDTO no deberia venir con ID, y todos los demas campos deberian ser opcionales, es decir solo debe llegar los campos que se quieran actualizar
57+
// if(empleadoServ.getEmpleadoByCodigo(id).isPresent()){
58+
// //BeanUtils.copyProperties();
59+
// Empleado empleado = empleadoServ.buildEmpleado(dto);
60+
// empleado.setCodEmpleado(id);
61+
// return new ResponseEntity(empleadoServ.guardar(empleado), HttpStatus.OK);
62+
// } else {
63+
// throw new EntidadNotFoundException("EMPLEADO", id);
64+
// }
65+
// }
66+
67+
/** 1. Empleado --> eDTO : con el id obtenemos el empleado y lo comvertirmos a eDTO
68+
* 2. eDTO <-- DTO(cliente) : seteamos solo los valores existentes del DTO(cliente) al eDTO
69+
* 3. eDTO --> Empleado : eDTO validamos los datos y lo convertimos a Empleado para poder guardar.
70+
* 4. save(Empleado) : con el Empleado actualizado guardamos(update) en la BD. */
71+
@PutMapping("/{id}") // ACTUALIZACION enviando solo los campos que se van actualizar.
72+
public ResponseEntity replaceEmpleado(@RequestBody EmpleadoDTO dto, @PathVariable String id) { // la validacion se realiza en el servicio
73+
Optional<Empleado> optional = empleadoServ.getEmpleadoByCodigo(id);
74+
if(optional.isPresent()){
75+
EmpleadoDTO eDTO = empleadoServ.buildEmpleadoDTO(optional.get());
76+
77+
if (dto.getCodDistrito() != null) eDTO.setCodDistrito(dto.getCodDistrito());
78+
if (dto.getCodEstado() != null) eDTO.setCodEstado(dto.getCodEstado());
79+
if (dto.getNombre() != null) eDTO.setNombre(dto.getNombre());
80+
if (dto.getApellidos() != null) eDTO.setApellidos(dto.getApellidos());
81+
if (dto.getDni() != null) eDTO.setDni(dto.getDni());
82+
if (dto.getDireccion() != null) eDTO.setDireccion(dto.getDireccion());
83+
if (dto.getTelefono() != null) eDTO.setTelefono(dto.getTelefono());
84+
if (dto.getEmail() != null) eDTO.setEmail(dto.getEmail());
85+
if (dto.getUsuario() != null) eDTO.setUsuario(dto.getUsuario());
86+
if (dto.getContrasena() != null) eDTO.setContrasena(dto.getContrasena());
87+
88+
Empleado empleado = empleadoServ.buildEmpleado(eDTO);
6089
empleado.setCodEmpleado(id);
6190
return new ResponseEntity(empleadoServ.guardar(empleado), HttpStatus.OK);
6291
} else {
63-
throw new EntidadNotFoundException(id);
92+
throw new EntidadNotFoundException("EMPLEADO", id);
6493
}
6594
}
6695

6796
@DeleteMapping("/{id}")
68-
public ResponseEntity delete(@PathVariable String id) throws IllegalArgumentException, EntidadNotFoundException{
97+
public ResponseEntity delete(@PathVariable String id) {
6998
if(empleadoServ.getEmpleadoByCodigo(id).isPresent() ){
7099
empleadoServ.eliminarByCodigo(id);
71100
return new ResponseEntity<>(HttpStatus.OK);
72101
} else {
73-
throw new EntidadNotFoundException(id + " - No eliminado");
102+
throw new EntidadNotFoundException("EMPLEADO",id + " - NO ELIMINADO");
74103
}
75104
}
76105

@@ -87,12 +116,10 @@ private ResponseEntity<Void> reporteEmpleadoPDF(HttpServletResponse response) th
87116
return ResponseEntity.ok().build();
88117
}
89118

90-
91119
/* Configurar la respuesta HTTP
92120
* ResponseEntity: representa la respuesta completa HTTP: status code, headers y body.
93121
* @ResponseBody: por defecto en un @Controller devuelve un HTML, pero con esta anotacion permite devolver directamente el resultado del metodo como respuesta HTTP.
94122
* @ResponseStatus: permite personalizar el status de la respuesta en caso de ERROR
95123
* */
96124

97-
98125
}

src/main/java/com/cibertec/shoesformen_api/exception/ApplicationExceptionHandler.java

Lines changed: 22 additions & 13 deletions
Original file line numberDiff line numberDiff line change
@@ -1,8 +1,9 @@
11
package com.cibertec.shoesformen_api.exception;
22

3+
import com.cibertec.shoesformen_api.model.dto.EmpleadoDTO;
4+
import jakarta.validation.ConstraintViolation;
35
import org.springframework.http.HttpStatus;
46
import org.springframework.http.ResponseEntity;
5-
import org.springframework.web.bind.MethodArgumentNotValidException;
67
import org.springframework.web.bind.annotation.ExceptionHandler;
78
import org.springframework.web.bind.annotation.ResponseStatus;
89
import org.springframework.web.bind.annotation.RestControllerAdvice;
@@ -15,18 +16,14 @@
1516
@RestControllerAdvice
1617
public class ApplicationExceptionHandler {
1718

18-
@ExceptionHandler({EmpleadoNotFoundException.class})
19-
public ResponseEntity<Objects> handleBusinessException(EmpleadoNotFoundException ex) {
20-
return new ResponseEntity<>(HttpStatus.NO_CONTENT);
21-
}
2219

2320
// Cuando la lista que devuelve esta vacia.
2421
@ExceptionHandler({ListEmptyException.class})
2522
public ResponseEntity<Objects> handleListEmptyException(ListEmptyException ex) {
2623
return new ResponseEntity<>(HttpStatus.NO_CONTENT);
2724
}
2825

29-
// Cuando el ID es NULL
26+
// Cuando el parametro ID es NULL
3027
@ResponseStatus(HttpStatus.BAD_REQUEST)
3128
@ExceptionHandler({IllegalArgumentException.class})
3229
public Map<String, String> handleFoundException(IllegalArgumentException ex) {
@@ -35,7 +32,7 @@ public Map<String, String> handleFoundException(IllegalArgumentException ex) {
3532
return errorMap;
3633
}
3734

38-
// Cuando no encuentra la entidad con el ID proporcionado
35+
// Cuando no encuentra la Entidad con el ID proporcionado
3936
@ResponseStatus(HttpStatus.BAD_REQUEST)
4037
@ExceptionHandler({EntidadNotFoundException.class})
4138
public Map<String, String> handleEntityNotFoundException(EntidadNotFoundException ex) {
@@ -44,17 +41,29 @@ public Map<String, String> handleEntityNotFoundException(EntidadNotFoundExceptio
4441
return errorMap;
4542
}
4643

47-
// Cuando los campos no cumplen las restricciones
44+
// Cuando los campos no cumplen las restricciones - VALIDACIONES EN EL CONTROLADOR
45+
// @ResponseStatus(HttpStatus.BAD_REQUEST)
46+
// @ExceptionHandler(MethodArgumentNotValidException.class)
47+
// public Map<String, String> handleInvalidArgument(MethodArgumentNotValidException ex) {
48+
// Map<String, String> errorMap = new HashMap<>();
49+
// ex.getBindingResult().getFieldErrors().forEach(error -> {
50+
// errorMap.put(error.getField(), error.getDefaultMessage());
51+
// });
52+
// return errorMap;
53+
// }
54+
55+
// Cuando los campos no cumplen las restricciones - VALIDACIONES EN EL SERVICIO PERSONALIZADA
4856
@ResponseStatus(HttpStatus.BAD_REQUEST)
49-
@ExceptionHandler(MethodArgumentNotValidException.class)
50-
public Map<String, String> handleInvalidArgument(MethodArgumentNotValidException ex) {
57+
@ExceptionHandler(ValidacionException.class)
58+
public Map<String, String> handleValidArgument(ValidacionException ex) {
5159
Map<String, String> errorMap = new HashMap<>();
52-
ex.getBindingResult().getFieldErrors().forEach(error -> {
53-
errorMap.put(error.getField(), error.getDefaultMessage());
54-
});
60+
for (ConstraintViolation<EmpleadoDTO> restriccion : ex.getRestricciones()){
61+
errorMap.put(restriccion.getPropertyPath().toString(), restriccion.getMessage()); // getPropertyPath : obtiene el campo - getMessage : obtiene el mensaje por defecto
62+
}
5563
return errorMap;
5664
}
5765

66+
// Error final en la Base de Datos
5867
@ResponseStatus(HttpStatus.BAD_REQUEST)
5968
@ExceptionHandler({SQLException.class})
6069
public Map<String, String> handlePSQLException(SQLException ex) {

src/main/java/com/cibertec/shoesformen_api/exception/EmpleadoNotFoundException.java

Lines changed: 0 additions & 7 deletions
This file was deleted.
Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1,7 +1,7 @@
11
package com.cibertec.shoesformen_api.exception;
22

33
public class EntidadNotFoundException extends RuntimeException{
4-
public EntidadNotFoundException(String id){
5-
super("No se encontro Entidad con codigo " + id);
4+
public EntidadNotFoundException(String entidad, String id){
5+
super("No se encontro " + entidad + " con codigo " + id);
66
}
77
}
Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1,7 +1,7 @@
11
package com.cibertec.shoesformen_api.exception;
22

33
public class ListEmptyException extends RuntimeException{
4-
public ListEmptyException(String message){
5-
super(message);
4+
public ListEmptyException(String entidad){
5+
super("Lista " + entidad + " vacia");
66
}
77
}
Lines changed: 17 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,17 @@
1+
package com.cibertec.shoesformen_api.exception;
2+
3+
import com.cibertec.shoesformen_api.model.dto.EmpleadoDTO;
4+
import jakarta.validation.ConstraintViolation;
5+
import lombok.Data;
6+
7+
import java.util.Set;
8+
9+
@Data
10+
public class ValidacionException extends RuntimeException{
11+
private Set<ConstraintViolation<EmpleadoDTO>> restricciones; // creado para obtener todas las violaciones a las restricciones
12+
public ValidacionException(Set<ConstraintViolation<EmpleadoDTO>> restricciones){
13+
this.restricciones = restricciones;
14+
}
15+
16+
17+
}

src/main/java/com/cibertec/shoesformen_api/model/dto/EmpleadoDTO.java

Lines changed: 0 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -36,8 +36,4 @@ public class EmpleadoDTO {
3636
private String contrasena;
3737
//private Collection<String> codRoles;
3838

39-
//
40-
// no encuentra el estado ni el distrito con le codigo enviado
41-
// datos, validador, codigo existentes, pero la BD detecta campos que deberia ser unico repetidos.
42-
4339
}

0 commit comments

Comments
 (0)