Commit 1eb39279 authored by George Novikov's avatar George Novikov

обработка ошибок с учётом ProcessLogger, парсинг X-API-Key

parent 26fd39b2
Pipeline #361 canceled with stage
......@@ -3,9 +3,14 @@ package kz.project.printedFormsService.controller;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import kz.project.printedFormsService.data.dto.DTemplateTypeDto;
import kz.project.printedFormsService.logging.ProcessLogger;
import kz.project.printedFormsService.service.DTemplateTypeService;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
......@@ -16,18 +21,31 @@ import static kz.project.printedFormsService.controller.DTemplateTypeController.
@RestController
@RequestMapping(BASE_PATH)
@RequiredArgsConstructor
@Slf4j
@Tag(name = "DTemplate Controller", description = "API TemplateService")
public class DTemplateTypeController {
private static final Logger LOGGER = LoggerFactory.getLogger(DTemplateTypeController.class);
public final static String BASE_PATH = "/api/dict";
public final static String GET_ALL = "/get/all";
private final DTemplateTypeService service;
private ProcessLogger processLogger;
@GetMapping("get/all")
public DTemplateTypeController(DTemplateTypeService service, ProcessLogger processLogger) {
this.service = service;
this.processLogger = processLogger;
}
@GetMapping("get/all")
@Operation(description = "Метод для получения шаблона по идентификатору")
public List<DTemplateTypeDto> getDict() {
return service.getAllTemplateType();
public ResponseEntity getDict() {
try {
List<DTemplateTypeDto> dtoList = service.getAllTemplateType();
return ResponseEntity.ok(dtoList);
} catch (Exception e){
LOGGER.error(e.getMessage(), e);
processLogger.error(TemplateController.class, new Throwable().getStackTrace()[0].getMethodName(), "Получение типов шаблонов");
return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body(e.getMessage());
}
}
}
......@@ -14,7 +14,11 @@ import kz.project.printedFormsService.logging.ProcessLogger;
import kz.project.printedFormsService.service.DocumentsService;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.aspectj.apache.bcel.generic.LocalVariableGen;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.format.annotation.DateTimeFormat;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestParam;
......@@ -25,11 +29,10 @@ import java.util.List;
import java.util.Map;
@RestController
@RequiredArgsConstructor
@Slf4j
@Tag(name = "Documents Controller", description = "API DocumentsService")
public class DocumentsController {
private static final Logger LOGGER = LoggerFactory.getLogger(DocumentsController.class);
private final DocumentsService documentsService;
public static final String BASE_PATH = "/api/documents";
......@@ -37,6 +40,12 @@ public class DocumentsController {
public static final String BY_TEMPLATE = BASE_PATH + "/by-template";
private ProcessLogger processLogger;
public DocumentsController(DocumentsService documentsService,
ProcessLogger processLogger) {
this.documentsService = documentsService;
this.processLogger = processLogger;
}
@GetMapping(BY_DAY)
@Operation(description = "Метод для получения данных по общему количеству генерации по всем доступным пользователю шаблонам")
@ApiResponses(value = {
......@@ -62,20 +71,24 @@ public class DocumentsController {
})
})
public ResponseEntity<DocumentByDateDto> getDocumentsCountByDay(
public ResponseEntity getDocumentsCountByDay(
@RequestParam("startDate")
@DateTimeFormat(iso = DateTimeFormat.ISO.DATE) LocalDate startDate,
@RequestParam("endDate")
@DateTimeFormat(iso = DateTimeFormat.ISO.DATE) LocalDate endDate) {
processLogger.start(TemplateController.class, new Throwable().getStackTrace()[0].getMethodName(), "Получение данных генераций всех отчётов за диапазон времени");
Map<String, List<String>> projectRoleMap = SecurityContextUtils.getProjectRoleMap();
DocumentByDateDto documentsByDate = documentsService.getDocumentCountsByDate(startDate, endDate, projectRoleMap.keySet());
processLogger.finish(TemplateController.class, new Throwable().getStackTrace()[0].getMethodName(), "Получение данных генераций всех отчётов за диапазон времени");
return ResponseEntity.ok(documentsByDate);
try {
processLogger.start(TemplateController.class, new Throwable().getStackTrace()[0].getMethodName(), "Получение данных генераций всех отчётов за диапазон времени");
Map<String, List<String>> projectRoleMap = SecurityContextUtils.getProjectRoleMap();
DocumentByDateDto documentsByDate = documentsService.getDocumentCountsByDate(startDate, endDate, projectRoleMap.keySet());
processLogger.finish(TemplateController.class, new Throwable().getStackTrace()[0].getMethodName(), "Получение данных генераций всех отчётов за диапазон времени");
return ResponseEntity.ok(documentsByDate);
} catch (Exception e){
LOGGER.error(e.getMessage(), e);
processLogger.start(TemplateController.class, new Throwable().getStackTrace()[0].getMethodName(), "Получение данных генераций всех отчётов за диапазон времени");
return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body(e.getMessage());
}
}
@GetMapping(BY_TEMPLATE)
@Operation(description = "Метод для получения данных по общему количеству генерации по каждому доступному пользователю шаблонам")
@ApiResponses(value = {
......@@ -88,8 +101,6 @@ public class DocumentsController {
schema = @Schema(implementation = DocumentByTemplateDto.class))
}),
@ApiResponse(
responseCode = "400",
description = "Ошибка валидации параметров запроса",
......@@ -101,15 +112,21 @@ public class DocumentsController {
})
})
public ResponseEntity<DocumentByTemplateDto> getDocumentsCountByTemplate(
public ResponseEntity getDocumentsCountByTemplate(
@RequestParam("startDate")
@DateTimeFormat(iso = DateTimeFormat.ISO.DATE) LocalDate startDate,
@RequestParam("endDate")
@DateTimeFormat(iso = DateTimeFormat.ISO.DATE) LocalDate endDate) {
processLogger.start(TemplateController.class, new Throwable().getStackTrace()[0].getMethodName(), "Получение данных генераций по шаблону за диапазон времени");
Map<String, List<String>> projectRoleMap = SecurityContextUtils.getProjectRoleMap();
DocumentByTemplateDto documentCountsByTemplate = documentsService.getDocumentCountsByTemplate(startDate, endDate, projectRoleMap.keySet());
processLogger.start(TemplateController.class, new Throwable().getStackTrace()[0].getMethodName(), "Получение данных генераций по шаблону за диапазон времени");
return ResponseEntity.ok(documentCountsByTemplate);
try {
processLogger.start(TemplateController.class, new Throwable().getStackTrace()[0].getMethodName(), "Получение данных генераций по шаблону за диапазон времени");
Map<String, List<String>> projectRoleMap = SecurityContextUtils.getProjectRoleMap();
DocumentByTemplateDto documentCountsByTemplate = documentsService.getDocumentCountsByTemplate(startDate, endDate, projectRoleMap.keySet());
processLogger.start(TemplateController.class, new Throwable().getStackTrace()[0].getMethodName(), "Получение данных генераций по шаблону за диапазон времени");
return ResponseEntity.ok(documentCountsByTemplate);
} catch (Exception e){
LOGGER.error(e.getMessage(), e);
processLogger.start(TemplateController.class, new Throwable().getStackTrace()[0].getMethodName(), "Получение данных генераций по шаблону за диапазон времени");
return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body(e.getMessage());
}
}
}
......@@ -36,6 +36,8 @@ public class ProcessLogger {
private String startPrefix;
@Value("${process-logger.finish-prefix}")
private String finishPrefix;
@Value("${process-logger.error-prefix}")
private String errorPrefix;
private DateFormatter dateFormatter;
private Locale locale;
......@@ -55,6 +57,10 @@ public class ProcessLogger {
write(javaClass, processName, finishPrefix, description);
}
public void error(Class javaClass, String processName, String description){
write(javaClass, processName, errorPrefix, description);
}
public void write(Class javaClass, String processName, String descriptionPrefix, String description){
try {
HttpServletRequest request = getRequest();
......@@ -62,9 +68,15 @@ public class ProcessLogger {
String delimiter = this.delimiter != null ? this.delimiter : DEFAULT_DELIMITER;
String fileName = this.logFileName != null ? this.logFileName : DEFAULT_FILENAME;
String ip = request.getRemoteAddr();
String userName = null;
String authHeader = request.getHeader(HttpHeaders.AUTHORIZATION);
String userName = JwtAuthConverter.getUsername(authHeader.substring(7));
if (authHeader != null){
userName = JwtAuthConverter.getUsername(authHeader.substring(7));
} else {
authHeader = request.getHeader("X-API-Key");
if (authHeader != null) userName = authHeader.substring(9);
}
String logRow = String.format(
"%s%s%s.%s%s%s%s%s%s%s%s%s%s",
......@@ -75,7 +87,7 @@ public class ProcessLogger {
delimiter,
getTodayDateTimeString(),
delimiter,
userName,
userName != null ? userName : "system-request",
delimiter,
ip,
delimiter,
......
......@@ -12,11 +12,15 @@ import org.springframework.stereotype.Service;
import java.util.List;
@Service
@RequiredArgsConstructor
public class DTemplateTypeServiceImpl implements DTemplateTypeService {
private final DTemplateTypeRepository repository;
private ProcessLogger processLogger;
public DTemplateTypeServiceImpl(DTemplateTypeRepository repository, ProcessLogger processLogger) {
this.repository = repository;
this.processLogger = processLogger;
}
public List<DTemplateTypeDto> getAllTemplateType(){
processLogger.start(TemplateController.class, new Throwable().getStackTrace()[0].getMethodName(), "Получение типов шаблонов");
List<DTemplateType> all = repository.findAll();
......
......@@ -79,4 +79,5 @@ process-logger:
date-format: "dd.MM.yyyy HH:mm:ss"
locale: kk_KZ
start-prefix: "Начало процесса: "
finish-prefix: "Конец процесса: "
\ No newline at end of file
finish-prefix: "Конец процесса: "
error-prefix: "Неуспешный процесс: "
\ No newline at end of file
Markdown is supported
0%
or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment