generated from yandex-praktikum/java-filmorate
-
Notifications
You must be signed in to change notification settings - Fork 0
Add friends likes #2
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
Merged
Merged
Changes from all commits
Commits
Show all changes
7 commits
Select commit
Hold shift + click to select a range
c624b1e
Добавлены основные классы для тз
dendzim 6d89c5f
Реализован функционал согласно ТЗ
dendzim b9a7007
Реализован функционал согласно ТЗ
dendzim 29b606b
Реализован функционал согласно ТЗ
dendzim ece15f1
исправлен check style
dendzim 41df520
исправлен check style
dendzim db63eed
Добавлен метод для обработки всех оставшихся исключений
dendzim File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
31 changes: 31 additions & 0 deletions
31
src/main/java/ru/yandex/practicum/filmorate/controller/ErrorHandler.java
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,31 @@ | ||
| package ru.yandex.practicum.filmorate.controller; | ||
|
|
||
| import org.springframework.http.HttpStatus; | ||
| import org.springframework.web.bind.annotation.ExceptionHandler; | ||
| import org.springframework.web.bind.annotation.ResponseStatus; | ||
| import org.springframework.web.bind.annotation.RestControllerAdvice; | ||
| import ru.yandex.practicum.filmorate.exception.NotFoundException; | ||
| import ru.yandex.practicum.filmorate.exception.ValidationException; | ||
| import ru.yandex.practicum.filmorate.model.ErrorResponse; | ||
|
|
||
| @RestControllerAdvice | ||
| public class ErrorHandler { | ||
|
|
||
| @ExceptionHandler | ||
| @ResponseStatus(HttpStatus.BAD_REQUEST) | ||
| public ErrorResponse handleValidationException(final ValidationException e) { | ||
| return new ErrorResponse(e.getMessage()); | ||
| } | ||
|
|
||
| @ExceptionHandler | ||
| @ResponseStatus(HttpStatus.NOT_FOUND) | ||
| public ErrorResponse handleNotFoundException(final NotFoundException e) { | ||
| return new ErrorResponse(e.getMessage()); | ||
| } | ||
|
|
||
| @ExceptionHandler | ||
| @ResponseStatus(HttpStatus.INTERNAL_SERVER_ERROR) | ||
| public ErrorResponse handleAllOtherExceptions(Throwable e) { | ||
| return new ErrorResponse(e.getMessage()); | ||
| } | ||
| } | ||
90 changes: 36 additions & 54 deletions
90
src/main/java/ru/yandex/practicum/filmorate/controller/FilmController.java
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -1,85 +1,67 @@ | ||
| package ru.yandex.practicum.filmorate.controller; | ||
|
|
||
| import jakarta.validation.Valid; | ||
| import lombok.extern.slf4j.Slf4j; | ||
| import org.springframework.beans.factory.annotation.Autowired; | ||
| import org.springframework.web.bind.annotation.*; | ||
| import ru.yandex.practicum.filmorate.model.Film; | ||
| import jakarta.validation.ValidationException; | ||
| import ru.yandex.practicum.filmorate.service.FilmService; | ||
| import ru.yandex.practicum.filmorate.storage.FilmStorage; | ||
|
|
||
| import java.time.LocalDate; | ||
| import java.util.Collection; | ||
| import java.util.HashMap; | ||
| import java.util.Map; | ||
|
|
||
| @Slf4j | ||
| @RestController | ||
| @RequestMapping("/films") | ||
| public class FilmController { | ||
|
|
||
| private final Map<Integer, Film> films = new HashMap<>(); | ||
| private final FilmStorage inMemoryFilmStorage; | ||
| private final FilmService filmService; | ||
|
|
||
| @Autowired | ||
| public FilmController(FilmStorage inMemoryFilmStorage, FilmService filmService) { | ||
| this.inMemoryFilmStorage = inMemoryFilmStorage; | ||
| this.filmService = filmService; | ||
| } | ||
|
|
||
| @GetMapping | ||
| public Collection<Film> findAll() { | ||
| log.info("Список фильмов выведен"); | ||
| return films.values(); | ||
| return inMemoryFilmStorage.findAll(); | ||
| } | ||
|
|
||
| @GetMapping("/{id}") | ||
| public Film findById(@PathVariable("id") int filmId) { | ||
| log.info("Фильм с id: {} выведен", filmId); | ||
| return inMemoryFilmStorage.findFilmById(filmId); | ||
| } | ||
|
|
||
| private int getNextId() { | ||
| int currentMaxId = films.keySet() | ||
| .stream() | ||
| .mapToInt(id -> id) | ||
| .max() | ||
| .orElse(0); | ||
| return ++currentMaxId; | ||
| @GetMapping("/popular") | ||
| public Collection<Film> getPopular(@RequestParam(defaultValue = "10") int count) { | ||
| log.info("Список популярных фильмов выведен"); | ||
| return filmService.getPopular(count); | ||
| } | ||
|
|
||
| @PostMapping | ||
| public Film create(@Valid @RequestBody Film film) { | ||
| validateFilm(film); | ||
| film.setId(getNextId()); | ||
| films.put(film.getId(), film); | ||
| public Film create(@RequestBody Film film) { | ||
| log.info("Фильм: {} добавлен в базу", film); | ||
| return film; | ||
| return inMemoryFilmStorage.create(film); | ||
| } | ||
|
|
||
| @PutMapping | ||
| public Film update(@Valid @RequestBody Film newFilm) { | ||
| if (newFilm.getId() == null) { | ||
| log.warn("Не указан id"); | ||
| throw new ValidationException("Id должен быть указан"); | ||
| } | ||
| if (!films.containsKey(newFilm.getId())) { | ||
| log.warn("Фильм с указанным id не найден"); | ||
| throw new ValidationException("Фильм с id = " + newFilm.getId() + " не найден"); | ||
| } | ||
| validateFilm(newFilm); | ||
| Film oldFilm = films.get(newFilm.getId()); | ||
| oldFilm.setDescription(newFilm.getDescription()); | ||
| oldFilm.setDuration(newFilm.getDuration()); | ||
| oldFilm.setName(newFilm.getName()); | ||
| oldFilm.setReleaseDate(newFilm.getReleaseDate()); | ||
| log.info("Данные о фильме: {} обновлены", oldFilm); | ||
| return oldFilm; | ||
| public Film update(@RequestBody Film newFilm) { | ||
| log.info("Данные о фильме: {} обновлены", newFilm); | ||
| return inMemoryFilmStorage.update(newFilm); | ||
| } | ||
|
|
||
| private void validateFilm(Film film) { | ||
| if (film.getDescription().length() > 200) { | ||
| log.warn("Ошибка лимита"); | ||
| throw new ValidationException("Описание превышает 200 символов"); | ||
| } | ||
| if (film.getReleaseDate().isBefore(LocalDate.of(1895, 12, 28))) { | ||
| log.warn("Ошибка даты"); | ||
| throw new ValidationException("Неверная дата релиза"); | ||
| } | ||
|
|
||
| if (film.getName() == null || film.getName().isBlank()) { | ||
| log.warn("Пустое название фильма"); | ||
| throw new ValidationException("Название не может быть пустым"); | ||
| } | ||
| @PutMapping("/{id}/like/{userId}") | ||
| public void addLike(@PathVariable int id, @PathVariable int userId) { | ||
| log.info("Фильму с id: {} поставил лайк пользователь с id: {}", id, userId); | ||
| filmService.addLike(id, userId); | ||
| } | ||
|
|
||
| if (film.getDuration() < 1) { | ||
| log.warn("Ошибка длительности"); | ||
| throw new ValidationException("Длительность не может быть меньше 1"); | ||
| } | ||
| @DeleteMapping("/{id}/like/{userId}") | ||
| public void deleteLike(@PathVariable int id, @PathVariable int userId) { | ||
| log.info("У фильма с id: {} убрал лайк пользователь с id: {}", id, userId); | ||
| filmService.deleteLike(id, userId); | ||
| } | ||
| } |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
7 changes: 7 additions & 0 deletions
7
src/main/java/ru/yandex/practicum/filmorate/exception/NotFoundException.java
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,7 @@ | ||
| package ru.yandex.practicum.filmorate.exception; | ||
|
|
||
| public class NotFoundException extends RuntimeException { | ||
| public NotFoundException(String message) { | ||
| super(message); | ||
| } | ||
| } |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
13 changes: 13 additions & 0 deletions
13
src/main/java/ru/yandex/practicum/filmorate/model/ErrorResponse.java
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,13 @@ | ||
| package ru.yandex.practicum.filmorate.model; | ||
|
|
||
| public class ErrorResponse { | ||
| String error; | ||
|
|
||
| public ErrorResponse(String error) { | ||
| this.error = error; | ||
| } | ||
|
|
||
| public String getError() { | ||
| return error; | ||
| } | ||
| } |
15 changes: 8 additions & 7 deletions
15
src/main/java/ru/yandex/practicum/filmorate/model/Film.java
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -1,23 +1,24 @@ | ||
| package ru.yandex.practicum.filmorate.model; | ||
|
|
||
| import jakarta.validation.constraints.Min; | ||
| import jakarta.validation.constraints.NotBlank; | ||
| import jakarta.validation.constraints.NotNull; | ||
| import lombok.Data; | ||
|
|
||
| import java.time.LocalDate; | ||
| import java.util.HashSet; | ||
| import java.util.Set; | ||
|
|
||
| /** | ||
| * Film. | ||
| */ | ||
| @Data | ||
| public class Film { | ||
| private Integer id; | ||
| @NotBlank | ||
| private String name; | ||
| private String description; | ||
| @NotNull | ||
| private LocalDate releaseDate; | ||
| @Min(1) | ||
| private int duration; | ||
| } | ||
| private Set<Integer> likes = new HashSet<>(); | ||
|
|
||
| public int getRating() { | ||
| return likes.size(); | ||
| } | ||
| } |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Добавь еще метод для обработки всех оставшихся исключений (Throwable в статус INTERNAL_SERVER_ERROR)