Skip to content

Commit

Permalink
Предметы - исправление по ревью
Browse files Browse the repository at this point in the history
  • Loading branch information
Vitalii Ungurean committed Feb 17, 2025
1 parent a2fbb15 commit 1f4ddd5
Show file tree
Hide file tree
Showing 4 changed files with 35 additions and 29 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -2,12 +2,11 @@

import club.ttg.dnd5.dto.ErrorResponseDto;
import club.ttg.dnd5.exception.ApiException;
import club.ttg.dnd5.exception.ContentNotFoundException;
import club.ttg.dnd5.exception.EntityExistException;
import club.ttg.dnd5.exception.EntityNotFoundException;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import lombok.RequiredArgsConstructor;
import lombok.extern.log4j.Log4j2;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.exception.ExceptionUtils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.HttpStatus;
Expand All @@ -21,17 +20,16 @@

import java.io.IOException;

@Log4j2
@Slf4j
@ControllerAdvice
@RequiredArgsConstructor
public class ExceptionController {
@Value("${spring.servlet.multipart.max-file-size}")
private String MAX_FILE_SIZE;

@ExceptionHandler(ApiException.class)
public ResponseEntity<ErrorResponseDto> handleApiException(ApiException ex, HttpServletRequest request, HttpServletResponse response) {
public ResponseEntity<ErrorResponseDto> handleApiException(ApiException ex) {
log.error(ExceptionUtils.getStackTrace(ex));

return convertToResponseEntity(ex.getStatus(), ex.getMessage());
}

Expand All @@ -41,24 +39,24 @@ public ResponseEntity<ErrorResponseDto> handleSecurityException() {
}

@ExceptionHandler(MissingServletRequestParameterException.class)
public ResponseEntity<ErrorResponseDto> handleRequestParamException(MissingServletRequestParameterException ex, HttpServletRequest request, HttpServletResponse response) {
String message = String.format("Отсутствует необходимый параметр \"%s\"", ex.getParameterName());
public ResponseEntity<ErrorResponseDto> handleRequestParamException(MissingServletRequestParameterException exception) {
String message = String.format("Отсутствует необходимый параметр \"%s\"", exception.getParameterName());

return convertToResponseEntity(HttpStatus.BAD_REQUEST, message);
}

@ExceptionHandler(MaxUploadSizeExceededException.class)
public ResponseEntity<ErrorResponseDto> handleMaxUploadSizeExceededException(MaxUploadSizeExceededException ex, HttpServletRequest request, HttpServletResponse response) {
public ResponseEntity<ErrorResponseDto> handleMaxUploadSizeExceededException() {
String message = String.format("Максимальный размер загружаемых файлов – %s", MAX_FILE_SIZE);

return convertToResponseEntity(HttpStatus.BAD_REQUEST, message);
}

@ExceptionHandler({NoHandlerFoundException.class, IOException.class, Exception.class})
public ResponseEntity<ErrorResponseDto> handleOtherExceptions(Exception ex, HttpServletRequest request, HttpServletResponse response) {
log.error(ExceptionUtils.getStackTrace(ex));
public ResponseEntity<ErrorResponseDto> handleOtherExceptions(Exception exception) {
log.error(ExceptionUtils.getStackTrace(exception));

return convertToResponseEntity(HttpStatus.INTERNAL_SERVER_ERROR, ex.getMessage());
return convertToResponseEntity(HttpStatus.INTERNAL_SERVER_ERROR, exception.getMessage());
}

@ExceptionHandler(EntityNotFoundException.class)
Expand All @@ -71,6 +69,11 @@ public ResponseEntity<ErrorResponseDto> handleHandleEntityExistException(Excepti
return convertToResponseEntity(HttpStatus.BAD_REQUEST, exception.getMessage());
}

@ExceptionHandler(ContentNotFoundException.class)
public ResponseEntity<ErrorResponseDto> handleContentNotFoundException(Exception exception) {
return convertToResponseEntity(HttpStatus.NO_CONTENT, exception.getMessage());
}

private ResponseEntity<ErrorResponseDto> convertToResponseEntity(HttpStatus status, String message) {
return ResponseEntity.status(status).body(new ErrorResponseDto(status, message));
}
Expand Down
15 changes: 3 additions & 12 deletions src/main/java/club/ttg/dnd5/controller/item/ItemController.java
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,6 @@
import io.swagger.v3.oas.annotations.tags.Tag;
import lombok.RequiredArgsConstructor;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import java.util.Collection;
Expand All @@ -34,21 +33,16 @@ public class ItemController {
@ApiResponse(responseCode = "409", description = "Предмет с указанным URL уже существует.")
})
@RequestMapping(value = "/{url}", method = RequestMethod.HEAD)
public ResponseEntity<Void> handleOptions(@PathVariable("url") String url) {
boolean exists = itemService.existsByUrl(url);
if (exists) {
return ResponseEntity.status(HttpStatus.CONFLICT).build();
} else {
return ResponseEntity.status(HttpStatus.NO_CONTENT).build();
}
@ResponseStatus(HttpStatus.CONFLICT)
public boolean exists(@PathVariable("url") String url) {
return itemService.existsByUrl(url);
}

@Operation(summary = "Получение детального описания предмета")
@ApiResponses(value = {
@ApiResponse(responseCode = "200", description = "Предмет успешно получен"),
@ApiResponse(responseCode = "404", description = "Предмет не найден")
})
@ResponseStatus(HttpStatus.OK)
@GetMapping("/{itemUtl}")
public ItemDto getItem(@PathVariable final String itemUtl) {
return itemService.getItem(itemUtl);
Expand All @@ -58,7 +52,6 @@ public ItemDto getItem(@PathVariable final String itemUtl) {
@ApiResponses(value = {
@ApiResponse(responseCode = "200", description = "Предметы успешно получены")
})
@ResponseStatus(HttpStatus.OK)
@PostMapping("/search")
public Collection<ItemDto> getItems() {
return itemService.getItems();
Expand All @@ -82,7 +75,6 @@ public ItemDto addItem(@RequestBody final ItemDto itemDto) {
@ApiResponse(responseCode = "404", description = "Предмет не существует"),
@ApiResponse(responseCode = "403", description = "Доступ запрещен")
})
@ResponseStatus(HttpStatus.OK)
@PostMapping("{itemUrl}")
public ItemDto updateItem(@PathVariable final String itemUrl,
@RequestBody final ItemDto itemDto) {
Expand All @@ -94,7 +86,6 @@ public ItemDto updateItem(@PathVariable final String itemUrl,
@ApiResponse(responseCode = "200", description = "Предмет удален из общего списка"),
@ApiResponse(responseCode = "403", description = "Доступ запрещен")
})
@ResponseStatus(HttpStatus.OK)
@DeleteMapping("{itemUrl}")
public ItemDto deleteItem(@PathVariable final String itemUrl) {
return itemService.delete(itemUrl);
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
package club.ttg.dnd5.exception;

public class ContentNotFoundException extends RuntimeException{
public ContentNotFoundException(String message) {
super(message);
}
}
15 changes: 10 additions & 5 deletions src/main/java/club/ttg/dnd5/service/item/ItemServiceImpl.java
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
package club.ttg.dnd5.service.item;

import club.ttg.dnd5.dto.item.ItemDto;
import club.ttg.dnd5.exception.ContentNotFoundException;
import club.ttg.dnd5.exception.EntityExistException;
import club.ttg.dnd5.exception.EntityNotFoundException;
import club.ttg.dnd5.model.item.Item;
Expand All @@ -17,6 +18,15 @@
public class ItemServiceImpl implements ItemService {
private final ItemRepository itemRepository;

@Override
public boolean existsByUrl(final String url) {
var exists = itemRepository.existsById(url);
if (!exists) {
throw new ContentNotFoundException("Item not found by uls: " + url);
}
return true;
}

@Override
public ItemDto getItem(final String itemUrl) {
return toDTO(findByUrl(itemUrl));
Expand Down Expand Up @@ -52,11 +62,6 @@ public ItemDto delete(final String itemUrl) {
return toDTO(itemRepository.save(item));
}

@Override
public boolean existsByUrl(final String url) {
return itemRepository.existsById(url);
}

private ItemDto toDTO(Item item) {
return toDTO(item, false);
}
Expand Down

0 comments on commit 1f4ddd5

Please sign in to comment.