Skip to content

Commit

Permalink
Финальный проект спринта 11
Browse files Browse the repository at this point in the history
  • Loading branch information
AidarJava committed Sep 16, 2024
1 parent 749876b commit 7f6c640
Show file tree
Hide file tree
Showing 17 changed files with 513 additions and 90 deletions.
5 changes: 5 additions & 0 deletions pom.xml
Original file line number Diff line number Diff line change
Expand Up @@ -53,6 +53,11 @@
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-validation</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
@@ -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.ecxeption.NotFoundException;
import ru.yandex.practicum.filmorate.ecxeption.OccurredException;
import ru.yandex.practicum.filmorate.ecxeption.ValidationException;
import ru.yandex.practicum.filmorate.model.ErrorResponse;

@RestControllerAdvice
public class ErrorHandler {
@ExceptionHandler
@ResponseStatus(HttpStatus.BAD_REQUEST)
public ErrorResponse validationException(final ValidationException e) {
return new ErrorResponse(e.getMessage());
}

@ExceptionHandler
@ResponseStatus(HttpStatus.INTERNAL_SERVER_ERROR)
public ErrorResponse occurredException(final OccurredException e) {
return new ErrorResponse(e.getMessage());
}

@ExceptionHandler
@ResponseStatus(HttpStatus.NOT_FOUND)
public ErrorResponse notFoundException(final NotFoundException e) {
return new ErrorResponse(e.getMessage());
}
}
Original file line number Diff line number Diff line change
@@ -1,62 +1,55 @@
package ru.yandex.practicum.filmorate.controller;

import jakarta.validation.Valid;
import lombok.extern.slf4j.Slf4j;
import ru.yandex.practicum.filmorate.ecxeption.ValidationException;
import ru.yandex.practicum.filmorate.model.Film;
import org.springframework.web.bind.annotation.*;
import ru.yandex.practicum.filmorate.service.FilmService;

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

@Slf4j
@RestController
//@RequiredArgsConstructor
@RequestMapping("/films")
public class FilmController {
private final Map<Long, Film> films = new HashMap<>();
private final FilmService filmService;

public FilmController(FilmService filmService) {
this.filmService = filmService;
}

@GetMapping
public Collection<Film> getAllFilms() {
return films.values();
return filmService.getAllFilms();
}

@GetMapping("/{id}")
public Film getFilmById(@PathVariable("id") long id) {
return filmService.getFilmById(id);
}

@PostMapping
public Film createFilm(@Valid @RequestBody Film film) {
if (film.getReleaseDate().isBefore(LocalDate.of(1895, 12, 28))) {
throw new ValidationException("Дата релиза — не раньше 28 декабря 1895 года!");
}
film.setId(getNextId());
log.debug("Валидация пройдена.");
films.put(film.getId(), film);
log.debug("Фильм добавлен в список.");
return film;
return filmService.createFilm(film);
}

@PutMapping
public Film ubdateFilm(@Valid @RequestBody Film film) {
if (film.getId() == null) {
throw new ValidationException("Id должен быть указан!");
}
if (films.containsKey(film.getId())) {
if (film.getReleaseDate().isBefore(LocalDate.of(1895, 12, 28))) {
throw new ValidationException("Дата релиза — не раньше 28 декабря 1895 года!");
}
film.setDescription(film.getDescription());
film.setName(film.getName());
film.setReleaseDate(film.getReleaseDate());
film.setDuration(film.getDuration());
return film;
} else throw new ValidationException("Такого фильма нет в списке!");
}

private Long getNextId() {
long currentMaxId = films.keySet()
.stream()
.mapToLong(id -> id)
.max()
.orElse(0);
return ++currentMaxId;
public Film updateFilm(@Valid @RequestBody Film film) {
return filmService.updateFilm(film);
}

@PutMapping("/{id}/like/{userId}")
public Film userLikesFilm(@PathVariable("id") Long id, @PathVariable("userId") Long userId) {
return filmService.userLikesFilm(id, userId);
}

@DeleteMapping("/{id}/like/{userId}")
public Film deleteLikesFilm(@PathVariable("id") Long id, @PathVariable("userId") Long userId) {
return filmService.deleteLikesFilm(id, userId);
}

@GetMapping("/popular")
public Collection<Film> listFirstCountFilm(@RequestParam(defaultValue = "10") int count) {
return filmService.listFirstCountFilm(count);
}

}
Original file line number Diff line number Diff line change
@@ -1,62 +1,60 @@
package ru.yandex.practicum.filmorate.controller;

import jakarta.validation.Valid;
import lombok.extern.slf4j.Slf4j;
import ru.yandex.practicum.filmorate.ecxeption.ValidationException;
import ru.yandex.practicum.filmorate.model.User;
import org.springframework.web.bind.annotation.*;
import ru.yandex.practicum.filmorate.service.UserService;

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

@Slf4j
@RestController
@RequestMapping("/users")
public class UserController {
private final Map<Long, User> users = new HashMap<>();

private UserService userService;

UserController(UserService userService) {
this.userService = userService;
}

@GetMapping
public Collection<User> getAllUsers() {
return users.values();
return userService.getAllUsers();
}

@GetMapping("/{id}")
public User getUserById(@PathVariable("id") long id) {
return userService.getUserById(id);
}

@PostMapping
public User createUser(@Valid @RequestBody User user) {
user.setId(getNextId());
log.debug("Валидация пройдена.");
if (user.getName() == null) {
user.setName(user.getLogin());
}
users.put(user.getId(), user);
return user;
return userService.createUser(user);
}

@PutMapping
public User updateUser(@Valid @RequestBody User user) {
if (user.getId() == null) {
throw new ValidationException("Id должен быть указан!");
}
if (users.containsKey(user.getId())) {
user.setBirthday(user.getBirthday());
user.setLogin(user.getLogin());
user.setEmail(user.getEmail());
if (user.getName() == null) {
user.setName(user.getLogin());
log.debug("Заменили имя на логин.");
} else {
user.setName(user.getName());
}
return user;
} else throw new ValidationException("Такого пользователя нет в списке!");
}

private Long getNextId() {
long currentMaxId = users.keySet()
.stream()
.mapToLong(id -> id)
.max()
.orElse(0);
return ++currentMaxId;
return userService.updateUser(user);
}

@PutMapping("/{id}/friends/{friendId}")
public User putFriends(@PathVariable("id") long id, @PathVariable("friendId") long friendId) {
return userService.makeFriendship(id, friendId);
}

@DeleteMapping("/{id}/friends/{friendId}")
public User deleteFriends(@PathVariable("id") long id, @PathVariable("friendId") long friendId) {
return userService.deleteFriendship(id, friendId);
}

@GetMapping("/{id}/friends")
public Collection<User> listFriends(@PathVariable("id") long id) {
return userService.listOfFriends(id);
}

@GetMapping("/{id}/friends/common/{otherId}")
public Collection<User> commonFriends(@PathVariable("id") long id, @PathVariable("otherId") long otherId) {
return userService.listOfCommonFriends(id, otherId);
}

}
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
package ru.yandex.practicum.filmorate.ecxeption;

public class NotFoundException extends RuntimeException {
public NotFoundException(String message) {
super(message);
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
package ru.yandex.practicum.filmorate.ecxeption;

public class OccurredException extends RuntimeException {
public OccurredException(String message) {
super(message);
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,11 @@
package ru.yandex.practicum.filmorate.model;

import lombok.AllArgsConstructor;
import lombok.Getter;

@Getter
@AllArgsConstructor
public class ErrorResponse {
String error;
}

3 changes: 3 additions & 0 deletions src/main/java/ru/yandex/practicum/filmorate/model/Film.java
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,8 @@
import lombok.NoArgsConstructor;

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

@Data
@AllArgsConstructor
Expand All @@ -21,4 +23,5 @@ public class Film {
LocalDate releaseDate;
@Positive(message = "Продолжительность фильма должна быть положительным числом!")
int duration;
Set<Long> likes = new HashSet<>();
}
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 @@ -8,6 +8,8 @@
import lombok.NoArgsConstructor;

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

@Data
@AllArgsConstructor
Expand All @@ -21,4 +23,5 @@ public class User {
String name;
@Past(message = "Дата рождения не может быть в будущем!")
LocalDate birthday;
Set<Long> friends = new HashSet<>();
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,79 @@
package ru.yandex.practicum.filmorate.service;

import org.springframework.stereotype.Service;
import ru.yandex.practicum.filmorate.ecxeption.NotFoundException;
import ru.yandex.practicum.filmorate.model.Film;
import ru.yandex.practicum.filmorate.storage.film.FilmStorage;
import ru.yandex.practicum.filmorate.storage.user.UserStorage;

import java.util.*;

@Service
public class FilmService {
FilmStorage filmStorage;
UserStorage userStorage;

public FilmService(FilmStorage filmStorage, UserStorage userStorage) {
this.filmStorage = filmStorage;
this.userStorage = userStorage;
}

public Film getFilmById(Long id) {
if (filmStorage.getFilmById(id) == null) {
throw new NotFoundException("Такого фильма нет в списке!");
}
return filmStorage.getFilmById(id);
}

public Film userLikesFilm(Long id, Long userId) {
Film film = filmStorage.getFilmById(id);
if (userStorage.getUserById(userId) == null) {
throw new NotFoundException("Такого юзера нет в списке!");
}
if (film == null) {
throw new NotFoundException("Такого фильма нет в списке!");
}
film.getLikes().add(userId);
return film;
}

public Film deleteLikesFilm(Long id, Long userId) {
if (userStorage.getUserById(userId) == null) {
throw new NotFoundException("Такого юзера нет!");
}
Film film = filmStorage.getFilmById(id);
if (film == null) {
throw new NotFoundException("Такого фильма нет в списке!");
}
film.getLikes().remove(userId);
return film;
}

public Collection<Film> listFirstCountFilm(int count) {
Collection<Film> films;
films = sortingToDown().stream()
.limit(count)
.toList();
return films;
}

public List<Film> sortingToDown() {
ArrayList<Film> listFilms = new ArrayList<>(filmStorage.getAllFilms());
listFilms.sort((Film film1, Film film2) ->
Integer.compare(film2.getLikes().size(), film1.getLikes().size())
);
return listFilms;
}

public Collection<Film> getAllFilms() {
return filmStorage.getAllFilms();
}

public Film createFilm(Film film) {
return filmStorage.createFilm(film);
}

public Film updateFilm(Film film) {
return filmStorage.ubdateFilm(film);
}
}
Loading

0 comments on commit 7f6c640

Please sign in to comment.