Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
6 changes: 6 additions & 0 deletions pom.xml
Original file line number Diff line number Diff line change
Expand Up @@ -43,6 +43,12 @@
<groupId>org.slf4j</groupId>
<artifactId>slf4j-api</artifactId>
</dependency>

<dependency>
<groupId>org.zalando</groupId>
<artifactId>logbook-spring-boot-starter</artifactId>
<version>3.7.2</version>
</dependency>
</dependencies>

<build>
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -8,4 +8,4 @@ public class FilmorateApplication {
public static void main(String[] args) {
SpringApplication.run(FilmorateApplication.class, args);
}
}
}
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());
}
}

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Добавь еще метод для обработки всех оставшихся исключений (Throwable в статус INTERNAL_SERVER_ERROR)

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);
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -2,81 +2,70 @@

import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.*;
import ru.yandex.practicum.filmorate.exception.ValidationException;
import ru.yandex.practicum.filmorate.model.User;
import ru.yandex.practicum.filmorate.service.UserService;
import ru.yandex.practicum.filmorate.storage.InMemoryUserStorage;

import java.time.LocalDate;
import java.util.Collection;
import java.util.HashMap;
import java.util.Map;

@Slf4j
@RestController
@RequestMapping("/users")
public class UserController {

private final Map<Integer, User> users = new HashMap<>();
private final InMemoryUserStorage inMemoryUserStorage;
private final UserService userService;

public UserController(InMemoryUserStorage inMemoryUserStorage, UserService userService) {
this.inMemoryUserStorage = inMemoryUserStorage;
this.userService = userService;
}

@GetMapping
public Collection<User> findAll() {
log.info("Список фильмов выведен");
return users.values();
log.info("Список пользователей выведен");
return inMemoryUserStorage.findAll();
}

@GetMapping("/{id}")
public User findUserById(@PathVariable("id") int userId) {
log.info("Пользователь с id: {} выведен", userId);
return inMemoryUserStorage.findUserById(userId);
}

private int getNextId() {
int currentMaxId = users.keySet()
.stream()
.mapToInt(id -> id)
.max()
.orElse(0);
return ++currentMaxId;
@GetMapping("/{id}/friends")
public Collection<User> findAllFriends(@PathVariable("id") int userId) {
log.info("Список друзей пользователя с id: {} выведен", userId);
return userService.getFriendList(userId);
}

@GetMapping("/{id}/friends/common/{otherId}")
public Collection<User> findAllCommonFriends(@PathVariable int id, @PathVariable int otherId) {
log.info("Список общих друзей пользователей с id: {} и {} выведен", id, otherId);
return userService.getCommonFriendList(id, otherId);
}

@PostMapping
public User create(@RequestBody User user) {
validateUser(user);
user.setId(getNextId());
users.put(user.getId(), user);
log.info("Пользователь: {} добавлен в базу", user);
return user;
log.info("Пользоввтель: {} создан и добавлен", user);
return inMemoryUserStorage.create(user);
}

@PutMapping
public User update(@RequestBody User newUser) {
if (newUser.getId() == null) {
log.warn("Не указан id");
throw new ValidationException("Id должен быть указан");
}
if (!users.containsKey(newUser.getId())) {
log.warn("Пользователь с указанным id не найден");
throw new ValidationException("Пользователь с id = " + newUser.getId() + " не найден");
}
validateUser(newUser);
User oldUser = users.get(newUser.getId());
oldUser.setEmail(newUser.getEmail());
oldUser.setName(newUser.getName());
oldUser.setLogin(newUser.getLogin());
oldUser.setBirthday(newUser.getBirthday());
log.info("Данные о пользователе: {} обновлены", oldUser);
return oldUser;
log.info("Данные о пользователе: {} обновлены", newUser);
return inMemoryUserStorage.update(newUser);
}

@PutMapping("/{id}/friends/{friendId}")
public void addFriend(@PathVariable("id") int userId, @PathVariable int friendId) {
log.info("Пользователь с id: {} добавил пользователя с id: {} в друзья", userId, friendId);
userService.addFriend(userId, friendId);
}

private void validateUser(User user) {
if (!user.getEmail().contains("@")) {
log.warn("Ошибка в формате почты");
throw new ValidationException("Неверная почта");
}
if (user.getBirthday().isAfter(LocalDate.now())) {
log.warn("Ошибка в дате рождения");
throw new ValidationException("Неверная дата рождения");
}
if (user.getLogin().contains(" ")) {
log.warn("Ошибка в формате логина");
throw new ValidationException("Неправильный формат логина");
}
if (user.getName() == null || user.getName().trim().isEmpty()) {
log.info("Пустое имя пользователя заменено на логин");
user.setName(user.getLogin());
}
@DeleteMapping("/{id}/friends/{friendId}")
public void deleteFriend(@PathVariable("id") int userId, @PathVariable int friendId) {
log.info("Пользователь с id: {} удалил пользователя с id: {} из друзей", userId, friendId);
userService.deleteFriend(userId, friendId);
}
}
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);
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -4,4 +4,4 @@ public class ValidationException extends RuntimeException {
public ValidationException(String message) {
super(message);
}
}
}
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 src/main/java/ru/yandex/practicum/filmorate/model/Film.java
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();
}
}
3 changes: 3 additions & 0 deletions src/main/java/ru/yandex/practicum/filmorate/model/User.java
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,8 @@
import lombok.Data;

import java.time.LocalDate;
import java.util.HashSet;
import java.util.Set;

@Data
public class User {
Expand All @@ -11,4 +13,5 @@ public class User {
private String login;
private String name;
private LocalDate birthday;
private Set<Integer> friends = new HashSet<>();
}
Loading