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
5,181 changes: 5,181 additions & 0 deletions PostmanSprint12_add-database.json

Large diffs are not rendered by default.

23 changes: 21 additions & 2 deletions README.md
Original file line number Diff line number Diff line change
@@ -1,9 +1,28 @@
_java-filmorate_

# Рейтинг фильмов
### Согласно задания спринта № 11
### Согласно задания спринта № 12 (добавление Базы данных)
## выполнено Филипповских Сергеем

_**Когорта-53**_

в файле PostmanSprint11_add-friends-likes.json находится скрипт для проверки API
![](/er_diagram_filmrate.png)

Примеры запросов:
1. Получение пользователя с ID = 1:
SELECT *
FROM users
WHERE user_id = 1;

2. Получение фильма с ID = 10:
SELECT *
FROM films
WHERE film_id = 10.

3. Получение списка фильмов, понравившихся пользователю с ID = 5:
SELECT title
FROM films
WHERE film_id IN (SELECT film_id FROM likes WHERE user_id = 5);

_**Для 12 спринта есть файла для проверки через postman:
PostmanSprint12_add-database.json**_
Binary file added er_diagram_filmrate.png
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
45 changes: 40 additions & 5 deletions pom.xml
Original file line number Diff line number Diff line change
Expand Up @@ -2,20 +2,24 @@
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>

<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>3.2.4</version>
<relativePath/> <!-- lookup parent from repository -->
<version>3.4.1</version>
<relativePath/>
</parent>

<groupId>ru.yandex.practicum</groupId>
<artifactId>filmorate</artifactId>
<version>0.0.1-SNAPSHOT</version>
<name>filmorate</name>
<description>filmorate</description>

<properties>
<java.version>21</java.version>
<java.version>17</java.version>
</properties>

<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
Expand All @@ -38,9 +42,17 @@
<dependency>
<groupId>org.zalando</groupId>
<artifactId>logbook-spring-boot-starter</artifactId>
<version> 3.9.0</version>
<version>3.9.0</version>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-jdbc</artifactId>
</dependency>
<dependency>
<groupId>com.h2database</groupId>
<artifactId>h2</artifactId>
<scope>runtime</scope>
</dependency>

</dependencies>

<build>
Expand All @@ -49,6 +61,29 @@
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId>
</plugin>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-checkstyle-plugin</artifactId>
<version>3.6.0</version>
<configuration>
<configLocation>checkstyle.xml</configLocation>
<failOnViolation>true</failOnViolation>
<logViolationsToConsole>true</logViolationsToConsole>
<includeTestSourceDirectory>true</includeTestSourceDirectory>
</configuration>
<executions>
<execution>
<goals>
<goal>check</goal>
</goals>
<phase>compile</phase>
</execution>
</executions>
</plugin>
</plugins>
</build>

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -22,7 +22,7 @@ public class ErrorHandler {
@ExceptionHandler
@ResponseStatus(HttpStatus.BAD_REQUEST)
public ErrorResponse handleValidationException(final ValidationException e) {
log.error(HttpStatus.BAD_REQUEST + " - " + e.getMessage());
log.error("{} - {}", HttpStatus.BAD_REQUEST, e.getMessage());
return new ErrorResponse(e.getMessage());
}

Expand All @@ -34,26 +34,26 @@ public ErrorResponse handleMethodArgumentNotValidException(final MethodArgumentN
String defaultMessage = allErrors.stream()
.map(error -> Objects.requireNonNull(error.getDefaultMessage()))
.collect(Collectors.joining(", "));
log.error(HttpStatus.BAD_REQUEST + " - " + defaultMessage);
log.error("{} - {}", HttpStatus.BAD_REQUEST, defaultMessage);
return new ErrorResponse(defaultMessage);
}

@ExceptionHandler
@ResponseStatus(HttpStatus.NOT_FOUND)
public ErrorResponse handleNotFoundException(final NotFoundException e) {
log.error(HttpStatus.NOT_FOUND + " - " + e.getMessage());
log.error("{} - {}", HttpStatus.NOT_FOUND, e.getMessage());
return new ErrorResponse(e.getMessage());
}

@ExceptionHandler
@ResponseStatus(HttpStatus.INTERNAL_SERVER_ERROR)
public ErrorResponse handleRunTimeException(final RuntimeException e) {
log.error(HttpStatus.INTERNAL_SERVER_ERROR + " - " + e.getMessage());
log.error("{} - {}", HttpStatus.INTERNAL_SERVER_ERROR, e.getMessage());
return new ErrorResponse(e.getMessage());
}

@Getter
private static class ErrorResponse {
public static class ErrorResponse {
private final String error;

public ErrorResponse(String error) {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -2,57 +2,49 @@

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

import java.util.List;

@Slf4j
@RestController
@RequestMapping("/films")
@RequiredArgsConstructor
public class FilmController {

private final FilmService filmService;

// добавляем фильм
@ResponseStatus(HttpStatus.CREATED)
@PostMapping
public Film create(@RequestBody @Valid Film film) {
filmService.create(film);
return film;
}

// обновляем данные о фильме
@PutMapping
public Film update(@RequestBody @Valid Film film) {
filmService.update(film);
return film;
}

// получаем список фильмов
@GetMapping
public List<Film> findAll() {
return filmService.findAll();
}

// Получаем фильм по id
@GetMapping("/{filmId}")
public Film getFilmById(@PathVariable Integer filmId) {
return filmService.getById(filmId);
}

// Добавляем like пользователя userId к фильму filmId
@PutMapping("/{filmId}/like/{userId}")
public Film addLike(@PathVariable Integer filmId, @PathVariable Integer userId) {
filmService.addLike(filmId, userId);
return filmService.getById(filmId);
}

// Удаляем like пользователя userId к фильму filmId
@DeleteMapping("/{filmId}/like/{userId}")
public Film deleteLike(@PathVariable Integer filmId, @PathVariable Integer userId) {
filmService.deleteLike(filmId, userId);
Expand All @@ -63,5 +55,4 @@ public Film deleteLike(@PathVariable Integer filmId, @PathVariable Integer userI
public List<Film> getListBestFilms(@RequestParam(defaultValue = "10") Integer count) {
return filmService.listBestFilms(count);
}

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

import lombok.RequiredArgsConstructor;
import org.springframework.web.bind.annotation.*;
import ru.yandex.practicum.filmorate.model.Genre;
import ru.yandex.practicum.filmorate.service.GenreService;

import java.util.List;

@RestController
@RequestMapping("/genres")
@RequiredArgsConstructor
public class GenreController {
private final GenreService genreService;

@GetMapping
public List<Genre> findAll() {
return genreService.findAll();
}

@GetMapping("/{id}")
public Genre getById(@PathVariable Integer id) {
return genreService.getById(id);
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,28 @@
package ru.yandex.practicum.filmorate.controller;

import lombok.RequiredArgsConstructor;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import ru.yandex.practicum.filmorate.model.Rating;
import ru.yandex.practicum.filmorate.service.RatingService;

import java.util.List;

@RestController
@RequestMapping("/mpa")
@RequiredArgsConstructor
public class RatingController {
private final RatingService ratingService;

@GetMapping
public List<Rating> findAll() {
return ratingService.findAll();
}

@GetMapping("/{id}")
public Rating getById(@PathVariable Integer id) {
return ratingService.getById(id);
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -2,70 +2,60 @@

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

import java.util.List;

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

private final UserService userService;

// Добавляем пользователя
@ResponseStatus(HttpStatus.CREATED)
@PostMapping
public User create(@RequestBody @Valid User user) {
userService.create(user);
return user;
}

// Обновляем данные пользователя
@PutMapping
public User update(@RequestBody @Valid User user) {
userService.update(user);
return user;
}

// Получаем список всех пользователей
@GetMapping
public List<User> findAll() {
return userService.findAll();
}

// Получаем пользователя по id
@GetMapping("/{userId}")
public User getUserById(@PathVariable Integer userId) {
return userService.getById(userId);
}

// Добавляем друга friendId для пользователя userId
@PutMapping("/{userId}/friends/{friendId}")
public User addFriend(@PathVariable Integer userId, @PathVariable Integer friendId) {
userService.addFriend(userId, friendId);
return userService.getById(userId);
}

// Удаляем друга friendId у пользователя userId
@DeleteMapping("/{userId}/friends/{friendId}")
public User deleteFriend(@PathVariable Integer userId, @PathVariable Integer friendId) {
userService.deleteFriend(userId, friendId);
return userService.getById(userId);
}

// Получаем список друзей пользователя userId
@GetMapping("/{userId}/friends")
public List<User> getUserFriends(@PathVariable Integer userId) {
return userService.userFriends(userId);
}

// Получаем общий список друзей пользователя userId и и пользователя otherUserId
@GetMapping("/{userId}/friends/common/{otherUserId}")
public List<User> getCrossingFriends(@PathVariable Integer userId, @PathVariable Integer otherUserId) {
return userService.crossingFriends(userId, otherUserId);
Expand Down
24 changes: 13 additions & 11 deletions src/main/java/ru/yandex/practicum/filmorate/model/Film.java
Original file line number Diff line number Diff line change
@@ -1,23 +1,22 @@
package ru.yandex.practicum.filmorate.model;


import jakarta.validation.constraints.Min;
import jakarta.validation.constraints.NotBlank;
import jakarta.validation.constraints.NotNull;
import jakarta.validation.constraints.Size;
import lombok.Data;
import lombok.extern.slf4j.Slf4j;

import java.time.LocalDate;
import java.util.HashSet;
import java.util.Set;
import java.sql.Date;
import java.util.ArrayList;
import java.util.List;

@Data
@Slf4j
public class Film {
private Integer id;

private Set<Integer> likes = new HashSet<>();
private List<Integer> likes = new ArrayList<>();

private List<Genre> genres = new ArrayList<>();

@NotNull(message = "Необходимо указать название фильма")
@NotBlank(message = "Название фильма не может быть пустым")
Expand All @@ -26,12 +25,14 @@ public class Film {
@Size(min = 1, max = 200, message = "Описание фильма должно быть от 1 до 200 символов")
private String description;

@MinimumDate(message = "Фильм не может выйти в прокат ранее 28.12.1895")
private LocalDate releaseDate;

@NotNull(message = "Необходимо указать продолжительность фильма")
@Min(value = 1, message = "Продолжительность фильма должна быть не меньше 1 секунды")
private int duration;
private Integer duration;

@MinimumDate(message = "Фильм не может выйти в прокат ранее 28.12.1895")
private Date releaseDate;

private Rating mpa;

public void addLike(Integer id) {
likes.add(id);
Expand All @@ -40,4 +41,5 @@ public void addLike(Integer id) {
public void removeLike(Integer id) {
likes.remove(id);
}

}
Loading