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

Controllers films users #114

Closed
wants to merge 3 commits into from
Closed
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
46 changes: 46 additions & 0 deletions pom.xml
Original file line number Diff line number Diff line change
@@ -0,0 +1,46 @@
<?xml version="1.0" encoding="UTF-8"?>
<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 -->
</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>
</properties>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>

<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
</dependencies>

<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
</plugins>
</build>

</project>
Original file line number Diff line number Diff line change
@@ -0,0 +1,12 @@
package ru.yandex.practicum.filmorate;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;

@SpringBootApplication
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,102 @@
package ru.yandex.practicum.filmorate.controller;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.bind.annotation.*;
import ru.yandex.practicum.filmorate.exception.NotFoundException;
import ru.yandex.practicum.filmorate.exception.ValidationException;
import ru.yandex.practicum.filmorate.model.Film;

import java.time.LocalDate;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

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

private static final LocalDate BEGINNING_OF_THE_DATE = LocalDate.of(1895, 12, 28);

private static Logger log = LoggerFactory.getLogger(FilmController.class);

private Map<Long, Film> films = new HashMap<>();

@GetMapping
public List<Film> allListFilm() {
return new ArrayList<>(films.values());
}

@PostMapping
public Film create(@RequestBody Film film) {
log.info("Начало создание фильма");

if (film.getName() == null || film.getName().isEmpty()) {
log.debug("Наименование фильма {}", film.getName());
throw new ValidationException("Имя не должно быть пустым");
}
if (film.getDescription().length() >= 200) {
log.warn("Описание фильма {}", film.getDescription());
throw new ValidationException("Максимальная длина описания — 200 символов");
}
if (film.getReleaseDate().isBefore(BEGINNING_OF_THE_DATE)) {
log.warn("Дата релиза фильма {}", film.getReleaseDate());
throw new ValidationException("Дата релиза — не раньше 28 декабря 1895 года");
}
if (film.getDuration() == null || film.getDuration().isNegative()) {
log.warn("Продолжительность фильма {}", film.getDuration());
throw new ValidationException("Продолжительность фильма должна быть положительным числом");
}

Film createFilm = Film.builder()
.id(generationId())
.name(film.getName())
.description(film.getDescription())
.releaseDate(film.getReleaseDate())
.duration(film.getDuration())
.build();

log.debug("Фильм создан {}", createFilm);
films.put(createFilm.getId(), film);
log.debug("Фильм добавлен в хранилище {}", createFilm.getId());

return createFilm;
}

@PutMapping
public Film update(@RequestBody Film newFilm) {
log.info("Начало обновление фильма");

if (newFilm.getId() == null) {
log.debug("Id не указан для обновления");
throw new ValidationException("Id должен быть указан");
}
if (!films.containsKey(newFilm.getId())) {
log.warn(" Фильм не найден с Id {}", newFilm.getId());
throw new NotFoundException("Фильм не найден");
}
Film existingFilm = films.get(newFilm.getId());
log.debug("Обновление фильма с Id: {}", existingFilm.getId());

Film updateFilm = Film.builder()
.id(existingFilm.getId())
.name(newFilm.getName())
.description(newFilm.getDescription())
.releaseDate(newFilm.getReleaseDate())
.duration(newFilm.getDuration())
.build();
films.put(updateFilm.getId(), updateFilm);
log.debug("Фильм обновлён с Id {}", updateFilm.getId());
return updateFilm;
}

private long generationId() {
long currentMaxId = films.keySet()
.stream()
.mapToLong(id -> id)
.max()
.orElse(0);
return ++currentMaxId;
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,96 @@
package ru.yandex.practicum.filmorate.controller;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.bind.annotation.*;
import ru.yandex.practicum.filmorate.exception.NotFoundException;
import ru.yandex.practicum.filmorate.exception.ValidationException;
import ru.yandex.practicum.filmorate.model.User;

import java.time.LocalDate;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

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

private static Logger log = LoggerFactory.getLogger(UserController.class);

private Map<Long, User> users = new HashMap<>();

@GetMapping
public List<User> allListUsers() {
return new ArrayList<>(users.values());
}

@PostMapping
public User create(@RequestBody User user) {
log.info("Начало создания пользователя");

if (user.getEmail() == null || user.getEmail().isEmpty() || user.getEmail().isBlank() ||
!user.getEmail().contains("@")) {
log.warn("Электронная почта пользователя {}", user.getEmail());
throw new ValidationException("электронная почта не может быть пустой и должна содержать символ @");
}
if (user.getLogin() == null || user.getLogin().isBlank() || user.getLogin().isEmpty()) {
log.warn("Логин пользователя пуст");
throw new ValidationException("Логин не может быть пустым и содержать пробелы");
}
if (user.getBirthday().isAfter(LocalDate.now())) {
log.warn("Дата рождения {}", user.getBirthday());
throw new ValidationException("Дата рождения не может быть в будущем");
}
if (user.getName() == null || user.getName().trim().isEmpty() || user.getName().isBlank()) {
log.debug("Имя пользователя пустое, используется логин: {}", user.getLogin());
user.setName(user.getLogin());
}
User createUser = User.builder().id(generationId())
.name(user.getName())
.login(user.getLogin())
.email(user.getEmail())
.birthday(user.getBirthday())
.build();

log.debug("Пользователь создан {}", createUser);
users.put(createUser.getId(), createUser);
log.debug("Пользователь добавлен в хранилище {}", createUser.getId());

return createUser;
}

@PutMapping
public User update(@RequestBody User newUser) {
log.info("Начало обновления пользователя");

if (newUser.getId() == null) {
log.debug("Id не указан для обновления");
throw new ValidationException("Id должен быть указан");
}
if (!users.containsKey(newUser.getId())) {
log.warn("Id пользователя не найден {}", newUser.getId());
throw new NotFoundException("Пользователь с таким Id не найден");
}
User existing = users.get(newUser.getId());

log.debug("Обновление пользователя с Id: {}", existing.getId());

User updateUser = User.builder().id(existing.getId())
.name(newUser.getName())
.login(newUser.getLogin())
.email(newUser.getEmail())
.birthday(newUser.getBirthday())
.build();

users.put(updateUser.getId(), updateUser);
log.info("Пользователь обновлён с Id: {}", updateUser.getId());
return updateUser;
}

private long generationId() {
long currentMaxId = users.keySet().stream().mapToLong(id -> id).max().orElse(0);
return ++currentMaxId;
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,8 @@
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
@@ -0,0 +1,8 @@
package ru.yandex.practicum.filmorate.exception;

public class ValidationException extends RuntimeException {

public ValidationException(String message) {
super(message);
}
}
20 changes: 20 additions & 0 deletions src/main/java/ru/yandex/practicum/filmorate/model/Film.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,20 @@
package ru.yandex.practicum.filmorate.model;

import lombok.AllArgsConstructor;
import lombok.Builder;
import lombok.Data;

import java.time.Duration;
import java.time.LocalDate;

@Builder
@AllArgsConstructor
@Data
public class Film {

private Long id;
private String name;
private String description;
private LocalDate releaseDate;
private Duration duration;
}
19 changes: 19 additions & 0 deletions src/main/java/ru/yandex/practicum/filmorate/model/User.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,19 @@
package ru.yandex.practicum.filmorate.model;

import lombok.AllArgsConstructor;
import lombok.Builder;
import lombok.Data;

import java.time.LocalDate;

@Builder
@AllArgsConstructor
@Data
public class User {

private Long id;
private String email;
private String login;
private String name;
private LocalDate birthday;
}
1 change: 1 addition & 0 deletions src/main/resources/application.properties
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@

Loading
Loading