Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Feature/item #55

Merged
merged 11 commits into from
Feb 21, 2025
Merged
1 change: 1 addition & 0 deletions .gitignore
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@ target/
!**/src/main/**/target/
!**/src/test/**/target/
application-local.properties
/local.env

### STS ###
.apt_generated
Expand Down
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
14 changes: 0 additions & 14 deletions src/main/java/club/ttg/dnd5/controller/item/ArmorController.java

This file was deleted.

89 changes: 84 additions & 5 deletions src/main/java/club/ttg/dnd5/controller/item/ItemController.java
Original file line number Diff line number Diff line change
@@ -1,14 +1,93 @@
package club.ttg.dnd5.controller.item;

import club.ttg.dnd5.dto.item.ItemDto;
import club.ttg.dnd5.service.item.ItemService;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.responses.ApiResponse;
import io.swagger.v3.oas.annotations.responses.ApiResponses;
import io.swagger.v3.oas.annotations.tags.Tag;
import lombok.NoArgsConstructor;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import lombok.RequiredArgsConstructor;
import org.springframework.http.HttpStatus;
import org.springframework.web.bind.annotation.*;

@Tag(name = "Снаряжение", description = "REST API снаряжение и прочие предметы")
import java.util.Collection;

@RestController
@NoArgsConstructor
@RequiredArgsConstructor
@RequestMapping("/api/v2/item")
@Tag(name = "Снаряжение и предметы", description = "REST API снаряжение и прочие предметы")
public class ItemController {
private final ItemService itemService;
/**
* Проверка существования вида по URL.
*
* @param url URL вида.
* @return 204, если вида с таким URL не существует; 409, если вид существует.
*/
@Operation(
summary = "Проверка существования предмета",
description = "Возвращает 204 (No Content), если предмет с указанным URL не существует, или 409 (Conflict), если существует."
)
@ApiResponses(value = {
@ApiResponse(responseCode = "204", description = "Предмет с указанным URL не найден."),
@ApiResponse(responseCode = "409", description = "Предмет с указанным URL уже существует.")
})
@RequestMapping(value = "/{url}", method = RequestMethod.HEAD)
@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 = "Предмет не найден")
})
@GetMapping("/{itemUtl}")
public ItemDto getItem(@PathVariable final String itemUtl) {
return itemService.getItem(itemUtl);
}

@Operation(summary = "Получение списка краткого описания предметов")
@ApiResponses(value = {
@ApiResponse(responseCode = "200", description = "Предметы успешно получены")
})
@PostMapping("/search")
public Collection<ItemDto> getItems() {
return itemService.getItems();
}

@Operation(summary = "Добавление предмета")
@ApiResponses(value = {
@ApiResponse(responseCode = "201", description = "Предмет успешно добавлен"),
@ApiResponse(responseCode = "400", description = "Предмет уже существует"),
@ApiResponse(responseCode = "403", description = "Доступ запрещен")
})
@ResponseStatus(HttpStatus.CREATED)
@PostMapping
public ItemDto addItem(@RequestBody final ItemDto itemDto) {
return itemService.addItem(itemDto);
}

@Operation(summary = "Обновление предмета")
@ApiResponses(value = {
@ApiResponse(responseCode = "201", description = "Предмет успешно обновлен"),
@ApiResponse(responseCode = "404", description = "Предмет не существует"),
@ApiResponse(responseCode = "403", description = "Доступ запрещен")
})
@PostMapping("{itemUrl}")
public ItemDto updateItem(@PathVariable final String itemUrl,
@RequestBody final ItemDto itemDto) {
return itemService.updateItem(itemUrl, itemDto);
}

@Operation(summary = "Скрывает предмет")
@ApiResponses(value = {
@ApiResponse(responseCode = "200", description = "Предмет удален из общего списка"),
@ApiResponse(responseCode = "403", description = "Доступ запрещен")
})
@DeleteMapping("{itemUrl}")
public ItemDto deleteItem(@PathVariable final String itemUrl) {
return itemService.delete(itemUrl);
}
}
14 changes: 0 additions & 14 deletions src/main/java/club/ttg/dnd5/controller/item/WeaponController.java

This file was deleted.

This file was deleted.

Loading
Loading