Delete Utils and add ExceptionHandler for exceptions

This commit is contained in:
Denis Oleynik 2025-02-20 15:58:48 +03:00
parent b5a88952ff
commit 52c75deff8
12 changed files with 96 additions and 55 deletions

@ -1,24 +0,0 @@
package com.example.nto;
import com.example.nto.entity.ResponseData;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
public class Utils {
public ResponseEntity<ResponseData> NotFound(String message) {
return new ResponseEntity<>(new ResponseData(HttpStatus.UNAUTHORIZED.value(), message), HttpStatus.UNAUTHORIZED);
}
public ResponseEntity<ResponseData> BadRequest(String message) {
return new ResponseEntity<>(new ResponseData(HttpStatus.BAD_REQUEST.value(), message), HttpStatus.BAD_REQUEST);
}
public ResponseEntity<ResponseData> Ok(String message) {
return new ResponseEntity<>(new ResponseData(HttpStatus.OK.value(), message), HttpStatus.OK);
}
public ResponseEntity<ResponseData> Forbidden(String message) {
return new ResponseEntity<>(new ResponseData(HttpStatus.FORBIDDEN.value(), message), HttpStatus.FORBIDDEN);
}
}

@ -1,8 +1,10 @@
package com.example.nto.controller;
import com.example.nto.Utils;
import com.example.nto.entity.Employee;
import com.example.nto.entity.Visits;
import com.example.nto.exception.EmployeeIsAdminException;
import com.example.nto.exception.EmployeeNotFoundException;
import com.example.nto.exception.VisitsEmptyException;
import com.example.nto.service.EmployeeService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
@ -18,8 +20,6 @@ public class AdminController {
@Autowired
private EmployeeService employeeService;
private final Utils utils = new Utils();
@GetMapping("/employees")
public List<Employee> getEmployees() {
return employeeService.getAllEmployees();
@ -29,7 +29,7 @@ public class AdminController {
public ResponseEntity<?> getEmployeeInfo(@PathVariable("username") String username) {
Optional<Employee> employee = employeeService.findByLogin(username);
if (employee.isEmpty()) {
return utils.NotFound("EmployeeNotFound");
throw new EmployeeNotFoundException();
}
return new ResponseEntity<>(employee.get(), HttpStatus.OK);
@ -39,22 +39,22 @@ public class AdminController {
public ResponseEntity<?> getEmployeeLastVisit(@PathVariable("username") String username) {
Optional<Employee> employee = employeeService.findByLogin(username);
if (employee.isEmpty()) {
return utils.NotFound("EmployeeNotFound");
throw new EmployeeNotFoundException();
}
return new ResponseEntity<>(employee.get(), HttpStatus.OK);
return new ResponseEntity<>(employee.get().getLastVisit(), HttpStatus.OK);
}
@GetMapping("/{username}/visits")
public ResponseEntity<?> getEmployeeVisits(@PathVariable("username") String username) {
if (!employeeService.existsByLogin(username)) {
return utils.NotFound("EmployeeNotFound");
throw new EmployeeNotFoundException();
}
Optional<List<Visits>> visits = Optional.ofNullable(employeeService.getEmployeeVisits(username));
if (visits.isEmpty()) {
return utils.BadRequest("VisitsIsEmpty");
throw new VisitsEmptyException();
}
return new ResponseEntity<>(visits.get(), HttpStatus.OK);
@ -64,7 +64,7 @@ public class AdminController {
public ResponseEntity<?> blockEmployee(@PathVariable("username") String username) {
Optional<Employee> employee = employeeService.findByLogin(username);
if (employee.isEmpty()) {
return utils.NotFound("EmployeeNotFound");
throw new EmployeeNotFoundException();
}
@ -76,6 +76,6 @@ public class AdminController {
prefix = "Unb";
}
return utils.Ok("Employee" + prefix + "lockedSuccess");
return new ResponseEntity<>("Employee" + prefix + "lockedSuccess", HttpStatus.OK);
}
}

@ -33,8 +33,6 @@ public class EmployeeController {
@Autowired
private CodeService codeService;
private final Utils utils = new Utils();
@Operation(summary = "Get employee info")
@ApiResponses(value = {
@ApiResponse(responseCode = "200",
@ -57,13 +55,13 @@ public class EmployeeController {
Optional<Employee> employee = employeeService.findByLogin(username);
if (employee.isEmpty()) {
return utils.NotFound("EmployeeNotFound");
throw new EmployeeNotFoundException();
}
return new ResponseEntity<>(employee.get(), HttpStatus.OK);
} catch (Exception e) {
System.out.println("Exception: " + e.getMessage());
return utils.BadRequest(e.getLocalizedMessage());
return new ResponseEntity<>(new ResponseData(HttpStatus.BAD_REQUEST.value(), e.getLocalizedMessage()), HttpStatus.BAD_REQUEST);
}
}
@ -89,18 +87,18 @@ public class EmployeeController {
Optional<Employee> employee = employeeService.findByLogin(username);
if (employee.isEmpty()) {
return utils.NotFound("EmployeeNotFound");
throw new EmployeeNotFoundException();
}
Optional<List<Visits>> visits = Optional.ofNullable(employeeService.getEmployeeVisits(username));
if (visits.isEmpty()) {
return utils.BadRequest("VisitsIsEmpty");
throw new VisitsEmptyException();
}
return new ResponseEntity<>(visits.get(), HttpStatus.OK);
} catch (Exception e) {
System.out.println("Exception: " + e.getMessage());
return utils.BadRequest(e.getLocalizedMessage());
return new ResponseEntity<>(new ResponseData(HttpStatus.BAD_REQUEST.value(), e.getLocalizedMessage()), HttpStatus.BAD_REQUEST);
}
}
@ -130,23 +128,23 @@ public class EmployeeController {
Optional<Employee> employee = employeeService.findByLogin(username);
if (employee.isEmpty()) {
return utils.NotFound("EmployeeNotFound");
throw new EmployeeNotFoundException();
}
if (employee.get().getBlocked()) {
return utils.Forbidden("YouAreBlocked");
throw new YouAreBlockedException();
}
if (!codeService.exists(body.getValue())) {
return utils.BadRequest("CodeIsInvalid");
throw new CodeNotFoundException();
}
LocalDateTime time = LocalDateTime.now();
employeeService.setLastVisitEmployee(employee.get().getId(), time);
employeeService.addVisit(employee.get().getLogin(), time, "" + body.getValue());
return utils.Ok("OpenedSuccess");
return new ResponseEntity<>(new ResponseData(HttpStatus.OK.value(), "DoorOpenedSuccess"), HttpStatus.OK);
} catch (Exception e) {
System.out.println("Exception: " + e.getMessage());
return utils.BadRequest(e.getLocalizedMessage());
return new ResponseEntity<>(new ResponseData(HttpStatus.BAD_REQUEST.value(), e.getLocalizedMessage()), HttpStatus.BAD_REQUEST);
}
}
}

@ -1,33 +1,31 @@
package com.example.nto.controller;
import com.example.nto.Utils;
import com.example.nto.entity.ResponseData;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.media.Content;
import io.swagger.v3.oas.annotations.media.Schema;
import io.swagger.v3.oas.annotations.responses.ApiResponse;
import io.swagger.v3.oas.annotations.responses.ApiResponses;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
@RestController
public class GlobalController {
Utils utils = new Utils();
@PostMapping("/api/login")
@Operation(summary = "Auth employee with login")
@Operation(summary = "Auth employee with login and pass")
@ApiResponses(value = {
@ApiResponse(responseCode = "200",
description = "Auth employee with login success",
description = "Auth employee with login and password success",
content = {@Content(mediaType = "application/json",
schema = @Schema(implementation = ResponseData.class))}),
@ApiResponse(responseCode = "401",
description = "Login not found or invalid"),
description = "Login/Password not found or invalid"),
@ApiResponse(responseCode = "400",
description = "Something went wrong")
})
public ResponseEntity<ResponseData> login() {
return utils.Ok("AuthSuccess");
return new ResponseEntity<>(new ResponseData(HttpStatus.OK.value(), "AuthSuccess"), HttpStatus.OK);
}
}

@ -10,5 +10,5 @@ import lombok.*;
@AllArgsConstructor
public class ResponseData {
private int status;
private String message;
private String type;
}

@ -0,0 +1,7 @@
package com.example.nto.exception;
public class CodeNotFoundException extends RuntimeException {
public CodeNotFoundException() {
super();
}
}

@ -0,0 +1,7 @@
package com.example.nto.exception;
public class EmployeeIsAdminException extends RuntimeException {
public EmployeeIsAdminException() {
super();
}
}

@ -0,0 +1,7 @@
package com.example.nto.exception;
public class EmployeeNotFoundException extends RuntimeException {
public EmployeeNotFoundException() {
super();
}
}

@ -0,0 +1,34 @@
package com.example.nto.exception;
import com.example.nto.entity.ResponseData;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.ControllerAdvice;
@ControllerAdvice
public class ExceptionHandler {
@org.springframework.web.bind.annotation.ExceptionHandler(EmployeeNotFoundException.class)
public ResponseEntity<ResponseData> handleEmployeeNotFoundException(EmployeeNotFoundException e) {
return new ResponseEntity<ResponseData>(new ResponseData(HttpStatus.UNAUTHORIZED.value(), "EmployeeNotFound"), HttpStatus.UNAUTHORIZED);
}
@org.springframework.web.bind.annotation.ExceptionHandler(CodeNotFoundException.class)
public ResponseEntity<ResponseData> handleCodeNotFoundException(CodeNotFoundException e) {
return new ResponseEntity<ResponseData>(new ResponseData(HttpStatus.BAD_REQUEST.value(), "CodeNotFound"), HttpStatus.BAD_REQUEST);
}
@org.springframework.web.bind.annotation.ExceptionHandler(VisitsEmptyException.class)
public ResponseEntity<ResponseData> handleVisitsEmptyException(VisitsEmptyException e) {
return new ResponseEntity<ResponseData>(new ResponseData(HttpStatus.BAD_REQUEST.value(), "VisitsEmpty"), HttpStatus.BAD_REQUEST);
}
@org.springframework.web.bind.annotation.ExceptionHandler(YouAreBlockedException.class)
public ResponseEntity<ResponseData> handleYouAreBlockedException(YouAreBlockedException e) {
return new ResponseEntity<ResponseData>(new ResponseData(HttpStatus.FORBIDDEN.value(), "YouAreBlocked"), HttpStatus.FORBIDDEN);
}
@org.springframework.web.bind.annotation.ExceptionHandler(EmployeeIsAdminException.class)
public ResponseEntity<ResponseData> handleEmployeeIsAdminException(EmployeeIsAdminException e) {
return new ResponseEntity<ResponseData>(new ResponseData(HttpStatus.BAD_REQUEST.value(), "EmloyeeIsAdmin"), HttpStatus.BAD_REQUEST);
}
}

@ -0,0 +1,7 @@
package com.example.nto.exception;
public class VisitsEmptyException extends RuntimeException {
public VisitsEmptyException() {
super();
}
}

@ -0,0 +1,7 @@
package com.example.nto.exception;
public class YouAreBlockedException extends RuntimeException {
public YouAreBlockedException() {
super();
}
}

@ -7,7 +7,7 @@ VALUES -- p1v@n0V | p3Tr0V1van | anaT0S3m3n4ik | al3X!fedOr0v | v0VkaS1gmA
(5, 'v228a', '$2a$08$KkEI/BUVduYlzCln2YkxIOsqCPjqO.jFDL1/dPl.hfLkBXDXfSA4m', 'USER', true, 'Владимир Попов Сигмович', 'https://avatars.dzeninfra.ru/get-zen_doc/1540250/pub_616565b90f14316c72058d22_616566ec8a4f2d46b116b324/scale_1200', 'Сеньор помидор', '2024-02-12T08:36'),
(6, 'evgsimga', '$2a$12$FqBz9snyFHjmd.A1Ks4zwO4Ny3De4RsdH2R56lvpIFhVnxvZPwIOu', 'ADMIN', false, 'Евгений Пикми Сигмович', 'https://i.imgur.com/eOaBA9S.jpeg', 'Разработчик', '2025-02-12T08:15'),
(7, 'maksanna', '$2a$12$2mzcYp/wnEhMKO7ue9S/UuJcdkrVNZicPL.rbrB2F13S9R0rGdTOG', 'USER', true, 'Максим Аннов Евгеньевич', 'https://i.imgur.com/YdAgWst.jpeg', 'Тестировщик', '2025-02-12T08:30'),
(8, 'sonechka', '$2a$12$1FPQdHGfyMu.kNREnRFmlexQ8v7q2T19/Eu.PBW4MLMWWQtrWRWna', 'ADMIN', false, 'София Иванова Евгеньевна', 'https://i.imgur.com/YdAgWst.jpeg', 'Тестировщик', '2025-02-12T08:30');
(8, 'sonechka', '$2a$12$1FPQdHGfyMu.kNREnRFmlexQ8v7q2T19/Eu.PBW4MLMWWQtrWRWna', 'ADMIN', false, 'София Иванова Евгеньевна', 'https://i.imgur.com/Zvc7pZZ.jpeg', 'Тестировщик', '2025-02-12T08:30');
INSERT INTO code (value)