Compare commits
5 Commits
Author | SHA1 | Date | |
---|---|---|---|
34e82cc1d8 | |||
9cfdbef69b | |||
44e70f8bf5 | |||
f40022719b | |||
344336fbf7 |
37
.gitignore
vendored
Normal file
37
.gitignore
vendored
Normal file
@ -0,0 +1,37 @@
|
||||
HELP.md
|
||||
.gradle
|
||||
build/
|
||||
!gradle/wrapper/gradle-wrapper.jar
|
||||
!**/src/main/**/build/
|
||||
!**/src/test/**/build/
|
||||
|
||||
### STS ###
|
||||
.apt_generated
|
||||
.classpath
|
||||
.factorypath
|
||||
.project
|
||||
.settings
|
||||
.springBeans
|
||||
.sts4-cache
|
||||
bin/
|
||||
!**/src/main/**/bin/
|
||||
!**/src/test/**/bin/
|
||||
|
||||
### IntelliJ IDEA ###
|
||||
.idea
|
||||
*.iws
|
||||
*.iml
|
||||
*.ipr
|
||||
out/
|
||||
!**/src/main/**/out/
|
||||
!**/src/test/**/out/
|
||||
|
||||
### NetBeans ###
|
||||
/nbproject/private/
|
||||
/nbbuild/
|
||||
/dist/
|
||||
/nbdist/
|
||||
/.nb-gradle/
|
||||
|
||||
### VS Code ###
|
||||
.vscode/
|
@ -1,6 +1 @@
|
||||
# Отчёты по лабораторным работам по дисциплине "Интернет-программирование", 4 семестр
|
||||
|
||||
Список лабораторных работ:
|
||||
- **[Лабораторная работа №1](https://git.is.ulstu.ru/olshab/PIbd-22_Shabunov_O.A._InternetProgramming_Backend/src/branch/Lab1)**
|
||||
- **[Лабораторная работа №2](https://git.is.ulstu.ru/olshab/PIbd-22_Shabunov_O.A._InternetProgramming_Backend/src/branch/Lab2)**
|
||||
- [Лабораторная работа №3](https://git.is.ulstu.ru/olshab/PIbd-22_Shabunov_O.A._InternetProgramming_Backend/src/branch/Lab3)
|
||||
**[Отчёт](https://git.is.ulstu.ru/olshab/PIbd-22_Shabunov_O.A._InternetProgramming_Backend/src/branch/Lab3/%D0%9E%D1%82%D1%87%D1%91%D1%82%20%28%D0%BB%D0%B0%D0%B1%D0%BE%D1%80%D0%B0%D1%82%D0%BE%D1%80%D0%BD%D0%B0%D1%8F%20%D1%80%D0%B0%D0%B1%D0%BE%D1%82%D0%B0%20%E2%84%963%29.docx)**
|
43
build.gradle
Normal file
43
build.gradle
Normal file
@ -0,0 +1,43 @@
|
||||
plugins {
|
||||
id 'java'
|
||||
id 'org.springframework.boot' version '3.2.5'
|
||||
id 'io.spring.dependency-management' version '1.1.4'
|
||||
}
|
||||
|
||||
group = 'com.example'
|
||||
version = '0.0.1-SNAPSHOT'
|
||||
|
||||
defaultTasks 'bootRun'
|
||||
|
||||
jar {
|
||||
enabled = false
|
||||
}
|
||||
|
||||
bootJar {
|
||||
archiveFileName = String.format('%s-%s.jar', rootProject.name, version)
|
||||
}
|
||||
|
||||
assert System.properties['java.specification.version'] == '17' || '21'
|
||||
java {
|
||||
sourceCompatibility = '17'
|
||||
}
|
||||
|
||||
repositories {
|
||||
mavenCentral()
|
||||
}
|
||||
|
||||
dependencies {
|
||||
implementation 'org.springframework.boot:spring-boot-starter-web'
|
||||
implementation 'org.springframework.boot:spring-boot-starter-validation'
|
||||
implementation 'org.springdoc:springdoc-openapi-starter-webmvc-ui:2.3.0'
|
||||
implementation 'org.modelmapper:modelmapper:3.2.0'
|
||||
|
||||
implementation 'org.springframework.boot:spring-boot-starter-data-jpa'
|
||||
implementation 'com.h2database:h2:2.2.224'
|
||||
|
||||
testImplementation 'org.springframework.boot:spring-boot-starter-test'
|
||||
}
|
||||
|
||||
tasks.named('test') {
|
||||
useJUnitPlatform()
|
||||
}
|
BIN
gradle/wrapper/gradle-wrapper.jar
vendored
Normal file
BIN
gradle/wrapper/gradle-wrapper.jar
vendored
Normal file
Binary file not shown.
7
gradle/wrapper/gradle-wrapper.properties
vendored
Normal file
7
gradle/wrapper/gradle-wrapper.properties
vendored
Normal file
@ -0,0 +1,7 @@
|
||||
distributionBase=GRADLE_USER_HOME
|
||||
distributionPath=wrapper/dists
|
||||
distributionUrl=https\://services.gradle.org/distributions/gradle-8.5-bin.zip
|
||||
networkTimeout=10000
|
||||
validateDistributionUrl=true
|
||||
zipStoreBase=GRADLE_USER_HOME
|
||||
zipStorePath=wrapper/dists
|
249
gradlew
vendored
Normal file
249
gradlew
vendored
Normal file
@ -0,0 +1,249 @@
|
||||
#!/bin/sh
|
||||
|
||||
#
|
||||
# Copyright © 2015-2021 the original authors.
|
||||
#
|
||||
# Licensed under the Apache License, Version 2.0 (the "License");
|
||||
# you may not use this file except in compliance with the License.
|
||||
# You may obtain a copy of the License at
|
||||
#
|
||||
# https://www.apache.org/licenses/LICENSE-2.0
|
||||
#
|
||||
# Unless required by applicable law or agreed to in writing, software
|
||||
# distributed under the License is distributed on an "AS IS" BASIS,
|
||||
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
# See the License for the specific language governing permissions and
|
||||
# limitations under the License.
|
||||
#
|
||||
|
||||
##############################################################################
|
||||
#
|
||||
# Gradle start up script for POSIX generated by Gradle.
|
||||
#
|
||||
# Important for running:
|
||||
#
|
||||
# (1) You need a POSIX-compliant shell to run this script. If your /bin/sh is
|
||||
# noncompliant, but you have some other compliant shell such as ksh or
|
||||
# bash, then to run this script, type that shell name before the whole
|
||||
# command line, like:
|
||||
#
|
||||
# ksh Gradle
|
||||
#
|
||||
# Busybox and similar reduced shells will NOT work, because this script
|
||||
# requires all of these POSIX shell features:
|
||||
# * functions;
|
||||
# * expansions «$var», «${var}», «${var:-default}», «${var+SET}»,
|
||||
# «${var#prefix}», «${var%suffix}», and «$( cmd )»;
|
||||
# * compound commands having a testable exit status, especially «case»;
|
||||
# * various built-in commands including «command», «set», and «ulimit».
|
||||
#
|
||||
# Important for patching:
|
||||
#
|
||||
# (2) This script targets any POSIX shell, so it avoids extensions provided
|
||||
# by Bash, Ksh, etc; in particular arrays are avoided.
|
||||
#
|
||||
# The "traditional" practice of packing multiple parameters into a
|
||||
# space-separated string is a well documented source of bugs and security
|
||||
# problems, so this is (mostly) avoided, by progressively accumulating
|
||||
# options in "$@", and eventually passing that to Java.
|
||||
#
|
||||
# Where the inherited environment variables (DEFAULT_JVM_OPTS, JAVA_OPTS,
|
||||
# and GRADLE_OPTS) rely on word-splitting, this is performed explicitly;
|
||||
# see the in-line comments for details.
|
||||
#
|
||||
# There are tweaks for specific operating systems such as AIX, CygWin,
|
||||
# Darwin, MinGW, and NonStop.
|
||||
#
|
||||
# (3) This script is generated from the Groovy template
|
||||
# https://github.com/gradle/gradle/blob/HEAD/subprojects/plugins/src/main/resources/org/gradle/api/internal/plugins/unixStartScript.txt
|
||||
# within the Gradle project.
|
||||
#
|
||||
# You can find Gradle at https://github.com/gradle/gradle/.
|
||||
#
|
||||
##############################################################################
|
||||
|
||||
# Attempt to set APP_HOME
|
||||
|
||||
# Resolve links: $0 may be a link
|
||||
app_path=$0
|
||||
|
||||
# Need this for daisy-chained symlinks.
|
||||
while
|
||||
APP_HOME=${app_path%"${app_path##*/}"} # leaves a trailing /; empty if no leading path
|
||||
[ -h "$app_path" ]
|
||||
do
|
||||
ls=$( ls -ld "$app_path" )
|
||||
link=${ls#*' -> '}
|
||||
case $link in #(
|
||||
/*) app_path=$link ;; #(
|
||||
*) app_path=$APP_HOME$link ;;
|
||||
esac
|
||||
done
|
||||
|
||||
# This is normally unused
|
||||
# shellcheck disable=SC2034
|
||||
APP_BASE_NAME=${0##*/}
|
||||
# Discard cd standard output in case $CDPATH is set (https://github.com/gradle/gradle/issues/25036)
|
||||
APP_HOME=$( cd "${APP_HOME:-./}" > /dev/null && pwd -P ) || exit
|
||||
|
||||
# Use the maximum available, or set MAX_FD != -1 to use that value.
|
||||
MAX_FD=maximum
|
||||
|
||||
warn () {
|
||||
echo "$*"
|
||||
} >&2
|
||||
|
||||
die () {
|
||||
echo
|
||||
echo "$*"
|
||||
echo
|
||||
exit 1
|
||||
} >&2
|
||||
|
||||
# OS specific support (must be 'true' or 'false').
|
||||
cygwin=false
|
||||
msys=false
|
||||
darwin=false
|
||||
nonstop=false
|
||||
case "$( uname )" in #(
|
||||
CYGWIN* ) cygwin=true ;; #(
|
||||
Darwin* ) darwin=true ;; #(
|
||||
MSYS* | MINGW* ) msys=true ;; #(
|
||||
NONSTOP* ) nonstop=true ;;
|
||||
esac
|
||||
|
||||
CLASSPATH=$APP_HOME/gradle/wrapper/gradle-wrapper.jar
|
||||
|
||||
|
||||
# Determine the Java command to use to start the JVM.
|
||||
if [ -n "$JAVA_HOME" ] ; then
|
||||
if [ -x "$JAVA_HOME/jre/sh/java" ] ; then
|
||||
# IBM's JDK on AIX uses strange locations for the executables
|
||||
JAVACMD=$JAVA_HOME/jre/sh/java
|
||||
else
|
||||
JAVACMD=$JAVA_HOME/bin/java
|
||||
fi
|
||||
if [ ! -x "$JAVACMD" ] ; then
|
||||
die "ERROR: JAVA_HOME is set to an invalid directory: $JAVA_HOME
|
||||
|
||||
Please set the JAVA_HOME variable in your environment to match the
|
||||
location of your Java installation."
|
||||
fi
|
||||
else
|
||||
JAVACMD=java
|
||||
if ! command -v java >/dev/null 2>&1
|
||||
then
|
||||
die "ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH.
|
||||
|
||||
Please set the JAVA_HOME variable in your environment to match the
|
||||
location of your Java installation."
|
||||
fi
|
||||
fi
|
||||
|
||||
# Increase the maximum file descriptors if we can.
|
||||
if ! "$cygwin" && ! "$darwin" && ! "$nonstop" ; then
|
||||
case $MAX_FD in #(
|
||||
max*)
|
||||
# In POSIX sh, ulimit -H is undefined. That's why the result is checked to see if it worked.
|
||||
# shellcheck disable=SC2039,SC3045
|
||||
MAX_FD=$( ulimit -H -n ) ||
|
||||
warn "Could not query maximum file descriptor limit"
|
||||
esac
|
||||
case $MAX_FD in #(
|
||||
'' | soft) :;; #(
|
||||
*)
|
||||
# In POSIX sh, ulimit -n is undefined. That's why the result is checked to see if it worked.
|
||||
# shellcheck disable=SC2039,SC3045
|
||||
ulimit -n "$MAX_FD" ||
|
||||
warn "Could not set maximum file descriptor limit to $MAX_FD"
|
||||
esac
|
||||
fi
|
||||
|
||||
# Collect all arguments for the java command, stacking in reverse order:
|
||||
# * args from the command line
|
||||
# * the main class name
|
||||
# * -classpath
|
||||
# * -D...appname settings
|
||||
# * --module-path (only if needed)
|
||||
# * DEFAULT_JVM_OPTS, JAVA_OPTS, and GRADLE_OPTS environment variables.
|
||||
|
||||
# For Cygwin or MSYS, switch paths to Windows format before running java
|
||||
if "$cygwin" || "$msys" ; then
|
||||
APP_HOME=$( cygpath --path --mixed "$APP_HOME" )
|
||||
CLASSPATH=$( cygpath --path --mixed "$CLASSPATH" )
|
||||
|
||||
JAVACMD=$( cygpath --unix "$JAVACMD" )
|
||||
|
||||
# Now convert the arguments - kludge to limit ourselves to /bin/sh
|
||||
for arg do
|
||||
if
|
||||
case $arg in #(
|
||||
-*) false ;; # don't mess with options #(
|
||||
/?*) t=${arg#/} t=/${t%%/*} # looks like a POSIX filepath
|
||||
[ -e "$t" ] ;; #(
|
||||
*) false ;;
|
||||
esac
|
||||
then
|
||||
arg=$( cygpath --path --ignore --mixed "$arg" )
|
||||
fi
|
||||
# Roll the args list around exactly as many times as the number of
|
||||
# args, so each arg winds up back in the position where it started, but
|
||||
# possibly modified.
|
||||
#
|
||||
# NB: a `for` loop captures its iteration list before it begins, so
|
||||
# changing the positional parameters here affects neither the number of
|
||||
# iterations, nor the values presented in `arg`.
|
||||
shift # remove old arg
|
||||
set -- "$@" "$arg" # push replacement arg
|
||||
done
|
||||
fi
|
||||
|
||||
|
||||
# Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script.
|
||||
DEFAULT_JVM_OPTS='"-Xmx64m" "-Xms64m"'
|
||||
|
||||
# Collect all arguments for the java command:
|
||||
# * DEFAULT_JVM_OPTS, JAVA_OPTS, JAVA_OPTS, and optsEnvironmentVar are not allowed to contain shell fragments,
|
||||
# and any embedded shellness will be escaped.
|
||||
# * For example: A user cannot expect ${Hostname} to be expanded, as it is an environment variable and will be
|
||||
# treated as '${Hostname}' itself on the command line.
|
||||
|
||||
set -- \
|
||||
"-Dorg.gradle.appname=$APP_BASE_NAME" \
|
||||
-classpath "$CLASSPATH" \
|
||||
org.gradle.wrapper.GradleWrapperMain \
|
||||
"$@"
|
||||
|
||||
# Stop when "xargs" is not available.
|
||||
if ! command -v xargs >/dev/null 2>&1
|
||||
then
|
||||
die "xargs is not available"
|
||||
fi
|
||||
|
||||
# Use "xargs" to parse quoted args.
|
||||
#
|
||||
# With -n1 it outputs one arg per line, with the quotes and backslashes removed.
|
||||
#
|
||||
# In Bash we could simply go:
|
||||
#
|
||||
# readarray ARGS < <( xargs -n1 <<<"$var" ) &&
|
||||
# set -- "${ARGS[@]}" "$@"
|
||||
#
|
||||
# but POSIX shell has neither arrays nor command substitution, so instead we
|
||||
# post-process each arg (as a line of input to sed) to backslash-escape any
|
||||
# character that might be a shell metacharacter, then use eval to reverse
|
||||
# that process (while maintaining the separation between arguments), and wrap
|
||||
# the whole thing up as a single "set" statement.
|
||||
#
|
||||
# This will of course break if any of these variables contains a newline or
|
||||
# an unmatched quote.
|
||||
#
|
||||
|
||||
eval "set -- $(
|
||||
printf '%s\n' "$DEFAULT_JVM_OPTS $JAVA_OPTS $GRADLE_OPTS" |
|
||||
xargs -n1 |
|
||||
sed ' s~[^-[:alnum:]+,./:=@_]~\\&~g; ' |
|
||||
tr '\n' ' '
|
||||
)" '"$@"'
|
||||
|
||||
exec "$JAVACMD" "$@"
|
92
gradlew.bat
vendored
Normal file
92
gradlew.bat
vendored
Normal file
@ -0,0 +1,92 @@
|
||||
@rem
|
||||
@rem Copyright 2015 the original author or authors.
|
||||
@rem
|
||||
@rem Licensed under the Apache License, Version 2.0 (the "License");
|
||||
@rem you may not use this file except in compliance with the License.
|
||||
@rem You may obtain a copy of the License at
|
||||
@rem
|
||||
@rem https://www.apache.org/licenses/LICENSE-2.0
|
||||
@rem
|
||||
@rem Unless required by applicable law or agreed to in writing, software
|
||||
@rem distributed under the License is distributed on an "AS IS" BASIS,
|
||||
@rem WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
@rem See the License for the specific language governing permissions and
|
||||
@rem limitations under the License.
|
||||
@rem
|
||||
|
||||
@if "%DEBUG%"=="" @echo off
|
||||
@rem ##########################################################################
|
||||
@rem
|
||||
@rem Gradle startup script for Windows
|
||||
@rem
|
||||
@rem ##########################################################################
|
||||
|
||||
@rem Set local scope for the variables with windows NT shell
|
||||
if "%OS%"=="Windows_NT" setlocal
|
||||
|
||||
set DIRNAME=%~dp0
|
||||
if "%DIRNAME%"=="" set DIRNAME=.
|
||||
@rem This is normally unused
|
||||
set APP_BASE_NAME=%~n0
|
||||
set APP_HOME=%DIRNAME%
|
||||
|
||||
@rem Resolve any "." and ".." in APP_HOME to make it shorter.
|
||||
for %%i in ("%APP_HOME%") do set APP_HOME=%%~fi
|
||||
|
||||
@rem Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script.
|
||||
set DEFAULT_JVM_OPTS="-Xmx64m" "-Xms64m"
|
||||
|
||||
@rem Find java.exe
|
||||
if defined JAVA_HOME goto findJavaFromJavaHome
|
||||
|
||||
set JAVA_EXE=java.exe
|
||||
%JAVA_EXE% -version >NUL 2>&1
|
||||
if %ERRORLEVEL% equ 0 goto execute
|
||||
|
||||
echo.
|
||||
echo ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH.
|
||||
echo.
|
||||
echo Please set the JAVA_HOME variable in your environment to match the
|
||||
echo location of your Java installation.
|
||||
|
||||
goto fail
|
||||
|
||||
:findJavaFromJavaHome
|
||||
set JAVA_HOME=%JAVA_HOME:"=%
|
||||
set JAVA_EXE=%JAVA_HOME%/bin/java.exe
|
||||
|
||||
if exist "%JAVA_EXE%" goto execute
|
||||
|
||||
echo.
|
||||
echo ERROR: JAVA_HOME is set to an invalid directory: %JAVA_HOME%
|
||||
echo.
|
||||
echo Please set the JAVA_HOME variable in your environment to match the
|
||||
echo location of your Java installation.
|
||||
|
||||
goto fail
|
||||
|
||||
:execute
|
||||
@rem Setup the command line
|
||||
|
||||
set CLASSPATH=%APP_HOME%\gradle\wrapper\gradle-wrapper.jar
|
||||
|
||||
|
||||
@rem Execute Gradle
|
||||
"%JAVA_EXE%" %DEFAULT_JVM_OPTS% %JAVA_OPTS% %GRADLE_OPTS% "-Dorg.gradle.appname=%APP_BASE_NAME%" -classpath "%CLASSPATH%" org.gradle.wrapper.GradleWrapperMain %*
|
||||
|
||||
:end
|
||||
@rem End local scope for the variables with windows NT shell
|
||||
if %ERRORLEVEL% equ 0 goto mainEnd
|
||||
|
||||
:fail
|
||||
rem Set variable GRADLE_EXIT_CONSOLE if you need the _script_ return code instead of
|
||||
rem the _cmd.exe /c_ return code!
|
||||
set EXIT_CODE=%ERRORLEVEL%
|
||||
if %EXIT_CODE% equ 0 set EXIT_CODE=1
|
||||
if not ""=="%GRADLE_EXIT_CONSOLE%" exit %EXIT_CODE%
|
||||
exit /b %EXIT_CODE%
|
||||
|
||||
:mainEnd
|
||||
if "%OS%"=="Windows_NT" endlocal
|
||||
|
||||
:omega
|
1
settings.gradle
Normal file
1
settings.gradle
Normal file
@ -0,0 +1 @@
|
||||
rootProject.name = 'demo'
|
88
src/main/java/com/example/demo/DemoApplication.java
Normal file
88
src/main/java/com/example/demo/DemoApplication.java
Normal file
@ -0,0 +1,88 @@
|
||||
package com.example.demo;
|
||||
|
||||
import java.time.Period;
|
||||
import java.util.Objects;
|
||||
|
||||
import org.slf4j.Logger;
|
||||
import org.slf4j.LoggerFactory;
|
||||
import org.springframework.boot.CommandLineRunner;
|
||||
import org.springframework.boot.SpringApplication;
|
||||
import org.springframework.boot.autoconfigure.SpringBootApplication;
|
||||
|
||||
import com.example.demo.ageRatings.model.AgeRatingEntity;
|
||||
import com.example.demo.ageRatings.service.AgeRatingService;
|
||||
import com.example.demo.movies.model.MovieEntity;
|
||||
import com.example.demo.movies.service.MovieService;
|
||||
import com.example.demo.subscriptions.model.SubscriptionEntity;
|
||||
import com.example.demo.subscriptions.service.SubscriptionService;
|
||||
import com.example.demo.types.model.TypeEntity;
|
||||
import com.example.demo.types.service.TypeService;
|
||||
import com.example.demo.users.model.UserEntity;
|
||||
import com.example.demo.users.service.UserService;
|
||||
|
||||
@SpringBootApplication
|
||||
public class DemoApplication implements CommandLineRunner {
|
||||
private final Logger log = LoggerFactory.getLogger(DemoApplication.class);
|
||||
|
||||
private final TypeService typeService;
|
||||
private final AgeRatingService ageRatingService;
|
||||
private final MovieService movieService;
|
||||
private final UserService userService;
|
||||
private final SubscriptionService subscriptionService;
|
||||
|
||||
public DemoApplication(TypeService typeService, AgeRatingService ageRatingService, MovieService movieService,
|
||||
UserService userService, SubscriptionService subscriptionService) {
|
||||
this.typeService = typeService;
|
||||
this.ageRatingService = ageRatingService;
|
||||
this.movieService = movieService;
|
||||
this.userService = userService;
|
||||
this.subscriptionService = subscriptionService;
|
||||
}
|
||||
|
||||
public static void main(String[] args) {
|
||||
SpringApplication.run(DemoApplication.class, args);
|
||||
}
|
||||
|
||||
@Override
|
||||
public void run(String... args) throws Exception {
|
||||
if (args.length > 0 && Objects.equals("--populate", args[0])) {
|
||||
log.info("Create default types values");
|
||||
final var type1 = typeService.create(new TypeEntity("Фильм"));
|
||||
final var type2 = typeService.create(new TypeEntity("Сериал"));
|
||||
|
||||
log.info("Create default ageRatings values");
|
||||
// final var ageRating1 = ageRatingService.create(new AgeRatingEntity("0+"));
|
||||
// final var ageRating2 = ageRatingService.create(new AgeRatingEntity("6+"));
|
||||
// final var ageRating3 = ageRatingService.create(new AgeRatingEntity("12+"));
|
||||
final var ageRating4 = ageRatingService.create(new AgeRatingEntity("16+"));
|
||||
final var ageRating5 = ageRatingService.create(new AgeRatingEntity("18+"));
|
||||
|
||||
log.info("Create default movies values");
|
||||
movieService.create(new MovieEntity("Бойцовский клуб", type1, false,
|
||||
"src/assets/main-page/posters/PeakyBlinders.png",
|
||||
"Сотрудник страховой компании страдает хронической бессонницей и отчаянно пытается вырваться из мучительно скучной жизни...",
|
||||
1999, "США", "Интриги. Хаос. Мыло", "Дэвид Финчер", ageRating5,
|
||||
"https://www.youtube.com/embed/dfeUzm6KF4g?si=U2D-2WNsJzkcxlBX"));
|
||||
movieService.create(new MovieEntity("Американский психопат", type1, true,
|
||||
"src/assets/main-page/posters/AmericanPsycho.jpg",
|
||||
"Днем он ничем не отличается от окружающих, и в толпе вы не обратите на него внимания...",
|
||||
2000, "США, Канада", "Респектабельная внешность дьявола", "Мэри Хэррон", ageRating5,
|
||||
"https://www.youtube.com/embed/PpUWjff_OcM?si=e7tSm4V6qYkz406B"));
|
||||
movieService.create(new MovieEntity("Острые козырьки", type2, false,
|
||||
"src/assets/main-page/posters/PeakyBlinders.png",
|
||||
"Сериал рассказывает историю восхождения одной ирландской семьи...",
|
||||
2013, "Великобритания", "The streets are theirs", "Энтони Бирн, Колм МакКарти", ageRating4,
|
||||
"https://www.youtube.com/embed/7cOfn_sjlXM?si=fxNoZjlUon1SZd70"));
|
||||
|
||||
log.info("Create default subscription values");
|
||||
subscriptionService.create(new SubscriptionEntity("Подписка 1", Period.of(0, 0, 7), 199.99));
|
||||
subscriptionService.create(new SubscriptionEntity("Подписка 2", Period.of(0, 1, 0), 299.99));
|
||||
subscriptionService.create(new SubscriptionEntity("Подписка 3", Period.of(0, 6, 0), 799.99));
|
||||
|
||||
log.info("Create default users values");
|
||||
userService.create(new UserEntity("email01@mail.com", "12345"));
|
||||
userService.create(new UserEntity("email002@mail.com", "admin"));
|
||||
userService.create(new UserEntity("email0003@mail.com", "qwerty"));
|
||||
}
|
||||
}
|
||||
}
|
@ -0,0 +1,64 @@
|
||||
package com.example.demo.ageRatings.api;
|
||||
|
||||
import java.util.List;
|
||||
|
||||
import org.modelmapper.ModelMapper;
|
||||
import org.springframework.web.bind.annotation.DeleteMapping;
|
||||
import org.springframework.web.bind.annotation.GetMapping;
|
||||
import org.springframework.web.bind.annotation.PathVariable;
|
||||
import org.springframework.web.bind.annotation.PostMapping;
|
||||
import org.springframework.web.bind.annotation.PutMapping;
|
||||
import org.springframework.web.bind.annotation.RequestBody;
|
||||
import org.springframework.web.bind.annotation.RequestMapping;
|
||||
import org.springframework.web.bind.annotation.RestController;
|
||||
|
||||
import com.example.demo.core.configuration.Constants;
|
||||
import com.example.demo.ageRatings.model.AgeRatingEntity;
|
||||
import com.example.demo.ageRatings.service.AgeRatingService;
|
||||
|
||||
import jakarta.validation.Valid;
|
||||
|
||||
@RestController
|
||||
@RequestMapping(Constants.API_URL + "/ageRating")
|
||||
public class AgeRatingController {
|
||||
private final AgeRatingService ageRatingService;
|
||||
private final ModelMapper modelMapper;
|
||||
|
||||
public AgeRatingController(AgeRatingService ageRatingService, ModelMapper modelMapper) {
|
||||
this.ageRatingService = ageRatingService;
|
||||
this.modelMapper = modelMapper;
|
||||
}
|
||||
|
||||
private AgeRatingDto toDto(AgeRatingEntity entity) {
|
||||
return modelMapper.map(entity, AgeRatingDto.class);
|
||||
}
|
||||
|
||||
private AgeRatingEntity toEntity(AgeRatingDto dto) {
|
||||
return modelMapper.map(dto, AgeRatingEntity.class);
|
||||
}
|
||||
|
||||
@GetMapping
|
||||
public List<AgeRatingDto> getAll() {
|
||||
return ageRatingService.getAll().stream().map(this::toDto).toList();
|
||||
}
|
||||
|
||||
@GetMapping("/{id}")
|
||||
public AgeRatingDto get(@PathVariable(name = "id") Long id) {
|
||||
return toDto(ageRatingService.get(id));
|
||||
}
|
||||
|
||||
@PostMapping
|
||||
public AgeRatingDto create(@RequestBody @Valid AgeRatingDto dto) {
|
||||
return toDto(ageRatingService.create(toEntity(dto)));
|
||||
}
|
||||
|
||||
@PutMapping("/{id}")
|
||||
public AgeRatingDto update(@PathVariable(name = "id") Long id, @RequestBody @Valid AgeRatingDto dto) {
|
||||
return toDto(ageRatingService.update(id, toEntity(dto)));
|
||||
}
|
||||
|
||||
@DeleteMapping("/{id}")
|
||||
public AgeRatingDto delete(@PathVariable(name = "id") Long id) {
|
||||
return toDto(ageRatingService.delete(id));
|
||||
}
|
||||
}
|
@ -0,0 +1,31 @@
|
||||
package com.example.demo.ageRatings.api;
|
||||
|
||||
import com.fasterxml.jackson.annotation.JsonProperty;
|
||||
|
||||
import jakarta.validation.constraints.NotBlank;
|
||||
import jakarta.validation.constraints.Size;
|
||||
|
||||
public class AgeRatingDto {
|
||||
@JsonProperty(access = JsonProperty.Access.READ_ONLY)
|
||||
private Long id;
|
||||
|
||||
@NotBlank
|
||||
@Size(min = 2, max = 4)
|
||||
private String name;
|
||||
|
||||
public Long getId() {
|
||||
return id;
|
||||
}
|
||||
|
||||
public void setId(Long id) {
|
||||
this.id = id;
|
||||
}
|
||||
|
||||
public String getName() {
|
||||
return name;
|
||||
}
|
||||
|
||||
public void setName(String name) {
|
||||
this.name = name;
|
||||
}
|
||||
}
|
@ -0,0 +1,48 @@
|
||||
package com.example.demo.ageRatings.model;
|
||||
|
||||
import java.util.Objects;
|
||||
|
||||
import com.example.demo.core.model.BaseEntity;
|
||||
|
||||
import jakarta.persistence.Column;
|
||||
import jakarta.persistence.Entity;
|
||||
import jakarta.persistence.Table;
|
||||
|
||||
@Entity
|
||||
@Table(name = "ageRatings")
|
||||
public class AgeRatingEntity extends BaseEntity {
|
||||
@Column(nullable = false, unique = true, length = 20)
|
||||
private String name;
|
||||
|
||||
public AgeRatingEntity() {
|
||||
}
|
||||
|
||||
public AgeRatingEntity(String name) {
|
||||
this.name = name;
|
||||
}
|
||||
|
||||
public String getName() {
|
||||
return name;
|
||||
}
|
||||
|
||||
public void setName(String name) {
|
||||
this.name = name;
|
||||
}
|
||||
|
||||
@Override
|
||||
public int hashCode() {
|
||||
return Objects.hash(id, name);
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean equals(Object obj) {
|
||||
if (this == obj)
|
||||
return true;
|
||||
|
||||
if (obj == null || getClass() != obj.getClass())
|
||||
return false;
|
||||
|
||||
final AgeRatingEntity other = (AgeRatingEntity) obj;
|
||||
return Objects.equals(other.getId(), id) && Objects.equals(other.getName(), name);
|
||||
}
|
||||
}
|
@ -0,0 +1,10 @@
|
||||
package com.example.demo.ageRatings.repository;
|
||||
|
||||
import java.util.Optional;
|
||||
import org.springframework.data.repository.CrudRepository;
|
||||
|
||||
import com.example.demo.ageRatings.model.AgeRatingEntity;
|
||||
|
||||
public interface AgeRatingRepository extends CrudRepository<AgeRatingEntity, Long> {
|
||||
Optional<AgeRatingEntity> findByNameIgnoreCase(String name);
|
||||
}
|
@ -0,0 +1,70 @@
|
||||
package com.example.demo.ageRatings.service;
|
||||
|
||||
import java.util.List;
|
||||
import java.util.stream.StreamSupport;
|
||||
|
||||
import org.springframework.stereotype.Service;
|
||||
import org.springframework.transaction.annotation.Transactional;
|
||||
|
||||
import com.example.demo.ageRatings.model.AgeRatingEntity;
|
||||
import com.example.demo.ageRatings.repository.AgeRatingRepository;
|
||||
import com.example.demo.core.error.AlreadyExistsException;
|
||||
import com.example.demo.core.error.NotFoundException;
|
||||
|
||||
@Service
|
||||
public class AgeRatingService {
|
||||
private final AgeRatingRepository repository;
|
||||
|
||||
public AgeRatingService(AgeRatingRepository repository) {
|
||||
this.repository = repository;
|
||||
}
|
||||
|
||||
private void checkNameUnique(String name) {
|
||||
if (repository.findByNameIgnoreCase(name).isPresent()) {
|
||||
throw new AlreadyExistsException();
|
||||
}
|
||||
}
|
||||
|
||||
@Transactional(readOnly = true)
|
||||
public List<AgeRatingEntity> getAll() {
|
||||
return StreamSupport.stream(repository.findAll().spliterator(), false).toList();
|
||||
}
|
||||
|
||||
@Transactional(readOnly = true)
|
||||
public AgeRatingEntity get(Long id) {
|
||||
return repository.findById(id)
|
||||
.orElseThrow(() -> new NotFoundException(AgeRatingEntity.class, id));
|
||||
}
|
||||
|
||||
@Transactional
|
||||
public AgeRatingEntity create(AgeRatingEntity entity) {
|
||||
if (entity == null) {
|
||||
throw new IllegalArgumentException("Entity is null");
|
||||
}
|
||||
|
||||
checkNameUnique(entity.getName());
|
||||
return repository.save(entity);
|
||||
}
|
||||
|
||||
@Transactional
|
||||
public AgeRatingEntity update(Long id, AgeRatingEntity entity) {
|
||||
final AgeRatingEntity existsEntity = get(id);
|
||||
|
||||
checkNameUnique(entity.getName());
|
||||
existsEntity.setName(entity.getName());
|
||||
return repository.save(existsEntity);
|
||||
}
|
||||
|
||||
@Transactional
|
||||
public AgeRatingEntity delete(Long id) {
|
||||
final AgeRatingEntity existsEntity = get(id);
|
||||
repository.delete(existsEntity);
|
||||
|
||||
return existsEntity;
|
||||
}
|
||||
|
||||
@Transactional
|
||||
public void deleteAll() {
|
||||
repository.deleteAll();
|
||||
}
|
||||
}
|
97
src/main/java/com/example/demo/core/api/PageDto.java
Normal file
97
src/main/java/com/example/demo/core/api/PageDto.java
Normal file
@ -0,0 +1,97 @@
|
||||
package com.example.demo.core.api;
|
||||
|
||||
import java.util.ArrayList;
|
||||
import java.util.List;
|
||||
|
||||
public class PageDto<D> {
|
||||
private List<D> items = new ArrayList<>();
|
||||
private int itemsCount;
|
||||
private int currentPage;
|
||||
private int currentSize;
|
||||
private int totalPages;
|
||||
private long totalItems;
|
||||
private boolean isFirst;
|
||||
private boolean isLast;
|
||||
private boolean hasNext;
|
||||
private boolean hasPrevious;
|
||||
|
||||
public List<D> getItems() {
|
||||
return items;
|
||||
}
|
||||
|
||||
public void setItems(List<D> items) {
|
||||
this.items = items;
|
||||
}
|
||||
|
||||
public int getItemsCount() {
|
||||
return itemsCount;
|
||||
}
|
||||
|
||||
public void setItemsCount(int itemsCount) {
|
||||
this.itemsCount = itemsCount;
|
||||
}
|
||||
|
||||
public int getCurrentPage() {
|
||||
return currentPage;
|
||||
}
|
||||
|
||||
public void setCurrentPage(int currentPage) {
|
||||
this.currentPage = currentPage;
|
||||
}
|
||||
|
||||
public int getCurrentSize() {
|
||||
return currentSize;
|
||||
}
|
||||
|
||||
public void setCurrentSize(int currentSize) {
|
||||
this.currentSize = currentSize;
|
||||
}
|
||||
|
||||
public int getTotalPages() {
|
||||
return totalPages;
|
||||
}
|
||||
|
||||
public void setTotalPages(int totalPages) {
|
||||
this.totalPages = totalPages;
|
||||
}
|
||||
|
||||
public long getTotalItems() {
|
||||
return totalItems;
|
||||
}
|
||||
|
||||
public void setTotalItems(long totalItems) {
|
||||
this.totalItems = totalItems;
|
||||
}
|
||||
|
||||
public boolean isFirst() {
|
||||
return isFirst;
|
||||
}
|
||||
|
||||
public void setFirst(boolean isFirst) {
|
||||
this.isFirst = isFirst;
|
||||
}
|
||||
|
||||
public boolean isLast() {
|
||||
return isLast;
|
||||
}
|
||||
|
||||
public void setLast(boolean isLast) {
|
||||
this.isLast = isLast;
|
||||
}
|
||||
|
||||
public boolean isHasNext() {
|
||||
return hasNext;
|
||||
}
|
||||
|
||||
public void setHasNext(boolean hasNext) {
|
||||
this.hasNext = hasNext;
|
||||
}
|
||||
|
||||
public boolean isHasPrevious() {
|
||||
return hasPrevious;
|
||||
}
|
||||
|
||||
public void setHasPrevious(boolean hasPrevious) {
|
||||
this.hasPrevious = hasPrevious;
|
||||
}
|
||||
}
|
25
src/main/java/com/example/demo/core/api/PageDtoMapper.java
Normal file
25
src/main/java/com/example/demo/core/api/PageDtoMapper.java
Normal file
@ -0,0 +1,25 @@
|
||||
package com.example.demo.core.api;
|
||||
|
||||
import java.util.function.Function;
|
||||
|
||||
import org.springframework.data.domain.Page;
|
||||
|
||||
public class PageDtoMapper {
|
||||
private PageDtoMapper() {
|
||||
}
|
||||
|
||||
public static <D, E> PageDto<D> toDto(Page<E> page, Function<E, D> mapper) {
|
||||
final PageDto<D> dto = new PageDto<>();
|
||||
dto.setItems(page.getContent().stream().map(mapper::apply).toList());
|
||||
dto.setItemsCount(page.getNumberOfElements());
|
||||
dto.setCurrentPage(page.getNumber());
|
||||
dto.setCurrentSize(page.getSize());
|
||||
dto.setTotalPages(page.getTotalPages());
|
||||
dto.setTotalItems(page.getTotalElements());
|
||||
dto.setFirst(page.isFirst());
|
||||
dto.setLast(page.isLast());
|
||||
dto.setHasNext(page.hasNext());
|
||||
dto.setHasPrevious(page.hasPrevious());
|
||||
return dto;
|
||||
}
|
||||
}
|
@ -0,0 +1,10 @@
|
||||
package com.example.demo.core.configuration;
|
||||
|
||||
public class Constants {
|
||||
public static final String SEQUENCE_NAME = "hibernate_sequence";
|
||||
public static final String API_URL = "/api/1.0";
|
||||
public static final String DEFAULT_PAGE_SIZE = "5";
|
||||
|
||||
private Constants() {
|
||||
}
|
||||
}
|
@ -0,0 +1,13 @@
|
||||
package com.example.demo.core.configuration;
|
||||
|
||||
import org.modelmapper.ModelMapper;
|
||||
import org.springframework.context.annotation.Bean;
|
||||
import org.springframework.context.annotation.Configuration;
|
||||
|
||||
@Configuration
|
||||
public class MapperConfiguration {
|
||||
@Bean
|
||||
ModelMapper modelMapper() {
|
||||
return new ModelMapper();
|
||||
}
|
||||
}
|
@ -0,0 +1,15 @@
|
||||
package com.example.demo.core.configuration;
|
||||
|
||||
import org.springframework.context.annotation.Configuration;
|
||||
import org.springframework.lang.NonNull;
|
||||
import org.springframework.web.servlet.config.annotation.CorsRegistry;
|
||||
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
|
||||
|
||||
@Configuration
|
||||
public class WebConfiguration implements WebMvcConfigurer {
|
||||
@Override
|
||||
public void addCorsMappings(@NonNull CorsRegistry registry) {
|
||||
registry.addMapping("/**")
|
||||
.allowedMethods("GET", "POST", "PUT", "DELETE");
|
||||
}
|
||||
}
|
@ -0,0 +1,7 @@
|
||||
package com.example.demo.core.error;
|
||||
|
||||
public class AlreadyExistsException extends RuntimeException {
|
||||
public AlreadyExistsException() {
|
||||
super("Entity already exists");
|
||||
}
|
||||
}
|
@ -0,0 +1,7 @@
|
||||
package com.example.demo.core.error;
|
||||
|
||||
public class NotFoundException extends RuntimeException {
|
||||
public <T> NotFoundException(Class<T> inClass, Long id) {
|
||||
super(String.format("%s with id [%s] is not found or not exists", inClass.getSimpleName(), id));
|
||||
}
|
||||
}
|
28
src/main/java/com/example/demo/core/model/BaseEntity.java
Normal file
28
src/main/java/com/example/demo/core/model/BaseEntity.java
Normal file
@ -0,0 +1,28 @@
|
||||
package com.example.demo.core.model;
|
||||
|
||||
import com.example.demo.core.configuration.Constants;
|
||||
|
||||
import jakarta.persistence.GeneratedValue;
|
||||
import jakarta.persistence.GenerationType;
|
||||
import jakarta.persistence.Id;
|
||||
import jakarta.persistence.MappedSuperclass;
|
||||
import jakarta.persistence.SequenceGenerator;
|
||||
|
||||
@MappedSuperclass
|
||||
public abstract class BaseEntity {
|
||||
@Id
|
||||
@GeneratedValue(strategy = GenerationType.SEQUENCE, generator = Constants.SEQUENCE_NAME)
|
||||
@SequenceGenerator(name = Constants.SEQUENCE_NAME, sequenceName = Constants.SEQUENCE_NAME, allocationSize = 1)
|
||||
protected Long id;
|
||||
|
||||
protected BaseEntity() {
|
||||
}
|
||||
|
||||
public Long getId() {
|
||||
return id;
|
||||
}
|
||||
|
||||
public void setId(Long id) {
|
||||
this.id = id;
|
||||
}
|
||||
}
|
@ -0,0 +1,86 @@
|
||||
package com.example.demo.movies.api;
|
||||
|
||||
import org.modelmapper.ModelMapper;
|
||||
import org.springframework.web.bind.annotation.DeleteMapping;
|
||||
import org.springframework.web.bind.annotation.GetMapping;
|
||||
import org.springframework.web.bind.annotation.PathVariable;
|
||||
import org.springframework.web.bind.annotation.PostMapping;
|
||||
import org.springframework.web.bind.annotation.PutMapping;
|
||||
import org.springframework.web.bind.annotation.RequestBody;
|
||||
import org.springframework.web.bind.annotation.RequestMapping;
|
||||
import org.springframework.web.bind.annotation.RequestParam;
|
||||
import org.springframework.web.bind.annotation.RestController;
|
||||
|
||||
import com.example.demo.ageRatings.service.AgeRatingService;
|
||||
import com.example.demo.core.api.PageDto;
|
||||
import com.example.demo.core.api.PageDtoMapper;
|
||||
import com.example.demo.core.configuration.Constants;
|
||||
import com.example.demo.movies.model.MovieEntity;
|
||||
import com.example.demo.movies.service.MovieService;
|
||||
import com.example.demo.types.service.TypeService;
|
||||
|
||||
import jakarta.validation.Valid;
|
||||
|
||||
@RestController
|
||||
@RequestMapping(Constants.API_URL + "/movie")
|
||||
public class MovieController {
|
||||
private final MovieService movieService;
|
||||
private final TypeService typeService;
|
||||
private final AgeRatingService ageRatingService;
|
||||
private final ModelMapper modelMapper;
|
||||
|
||||
public MovieController(MovieService movieService, TypeService typeService, AgeRatingService ageRatingService,
|
||||
ModelMapper modelMapper) {
|
||||
this.movieService = movieService;
|
||||
this.typeService = typeService;
|
||||
this.ageRatingService = ageRatingService;
|
||||
this.modelMapper = modelMapper;
|
||||
}
|
||||
|
||||
private MovieDto toDto(MovieEntity entity) {
|
||||
return modelMapper.map(entity, MovieDto.class);
|
||||
}
|
||||
|
||||
private MovieEntity toEntity(MovieDto dto) {
|
||||
final MovieEntity entity = modelMapper.map(dto, MovieEntity.class);
|
||||
|
||||
entity.setType(typeService.get(dto.getTypeId()));
|
||||
entity.setAgeRating(ageRatingService.get(dto.getAgeRatingId()));
|
||||
|
||||
return entity;
|
||||
}
|
||||
|
||||
@GetMapping
|
||||
public PageDto<MovieDto> getAll(
|
||||
@RequestParam(name = "typeId", defaultValue = "0") Long typeId,
|
||||
@RequestParam(name = "ageRatingId", defaultValue = "0") Long ageRatingId,
|
||||
@RequestParam(name = "page", defaultValue = "0") int page,
|
||||
@RequestParam(name = "size", defaultValue = Constants.DEFAULT_PAGE_SIZE) int size) {
|
||||
return PageDtoMapper.toDto(movieService.getAll(typeId, ageRatingId, page, size), this::toDto);
|
||||
}
|
||||
|
||||
@GetMapping("/{id}")
|
||||
public MovieDto get(@PathVariable(name = "id") Long id) {
|
||||
return toDto(movieService.get(id));
|
||||
}
|
||||
|
||||
@PostMapping
|
||||
public MovieDto create(@RequestBody @Valid MovieDto dto) {
|
||||
return toDto(movieService.create(toEntity(dto)));
|
||||
}
|
||||
|
||||
@PutMapping("/{id}")
|
||||
public MovieDto update(@PathVariable(name = "id") Long id, @RequestBody @Valid MovieDto dto) {
|
||||
return toDto(movieService.update(id, toEntity(dto)));
|
||||
}
|
||||
|
||||
@DeleteMapping("/{id}")
|
||||
public MovieDto delete(@PathVariable(name = "id") Long id) {
|
||||
return toDto(movieService.delete(id));
|
||||
}
|
||||
|
||||
@GetMapping("/{id}/rating")
|
||||
public Double getAverageRating(@PathVariable(name = "id") Long id) {
|
||||
return movieService.getAverageRating(id);
|
||||
}
|
||||
}
|
149
src/main/java/com/example/demo/movies/api/MovieDto.java
Normal file
149
src/main/java/com/example/demo/movies/api/MovieDto.java
Normal file
@ -0,0 +1,149 @@
|
||||
package com.example.demo.movies.api;
|
||||
|
||||
import com.fasterxml.jackson.annotation.JsonProperty;
|
||||
|
||||
import jakarta.validation.constraints.Min;
|
||||
import jakarta.validation.constraints.NotBlank;
|
||||
import jakarta.validation.constraints.NotNull;
|
||||
|
||||
public class MovieDto {
|
||||
@JsonProperty(access = JsonProperty.Access.READ_ONLY)
|
||||
private Long id;
|
||||
|
||||
@NotNull
|
||||
@NotBlank
|
||||
private String title;
|
||||
|
||||
@NotNull
|
||||
@Min(1)
|
||||
private Long typeId;
|
||||
|
||||
@NotNull
|
||||
private boolean requiresSubscription;
|
||||
|
||||
private String poster;
|
||||
|
||||
@NotNull
|
||||
@NotBlank
|
||||
private String description;
|
||||
|
||||
@NotNull
|
||||
private Integer releaseDate;
|
||||
|
||||
@NotNull
|
||||
@NotBlank
|
||||
private String country;
|
||||
|
||||
@NotNull
|
||||
@NotBlank
|
||||
private String tagline;
|
||||
|
||||
@NotNull
|
||||
@NotBlank
|
||||
private String director;
|
||||
|
||||
@NotNull
|
||||
@Min(1)
|
||||
private Long ageRatingId;
|
||||
|
||||
@NotNull
|
||||
@NotBlank
|
||||
private String video;
|
||||
|
||||
@JsonProperty(access = JsonProperty.Access.READ_ONLY)
|
||||
public Long getId() {
|
||||
return id;
|
||||
}
|
||||
|
||||
public void setId(Long id) {
|
||||
this.id = id;
|
||||
}
|
||||
|
||||
public Long getTypeId() {
|
||||
return typeId;
|
||||
}
|
||||
|
||||
public String getTitle() {
|
||||
return title;
|
||||
}
|
||||
|
||||
public void setTitle(String title) {
|
||||
this.title = title;
|
||||
}
|
||||
|
||||
public void setTypeId(Long typeId) {
|
||||
this.typeId = typeId;
|
||||
}
|
||||
|
||||
public boolean getRequiresSubscription() {
|
||||
return requiresSubscription;
|
||||
}
|
||||
|
||||
public void setRequiresSubscription(boolean requiresSubscription) {
|
||||
this.requiresSubscription = requiresSubscription;
|
||||
}
|
||||
|
||||
public String getPoster() {
|
||||
return poster;
|
||||
}
|
||||
|
||||
public void setPoster(String poster) {
|
||||
this.poster = poster;
|
||||
}
|
||||
|
||||
public String getDescription() {
|
||||
return description;
|
||||
}
|
||||
|
||||
public void getDescription(String description) {
|
||||
this.description = description;
|
||||
}
|
||||
|
||||
public Integer getReleaseDate() {
|
||||
return releaseDate;
|
||||
}
|
||||
|
||||
public void setReleaseDate(Integer releaseDate) {
|
||||
this.releaseDate = releaseDate;
|
||||
}
|
||||
|
||||
public String getCountry() {
|
||||
return country;
|
||||
}
|
||||
|
||||
public void setCountry(String country) {
|
||||
this.country = country;
|
||||
}
|
||||
|
||||
public String getTagline() {
|
||||
return tagline;
|
||||
}
|
||||
|
||||
public void setTagline(String tagline) {
|
||||
this.tagline = tagline;
|
||||
}
|
||||
|
||||
public String getDirector() {
|
||||
return director;
|
||||
}
|
||||
|
||||
public void setDirector(String director) {
|
||||
this.director = director;
|
||||
}
|
||||
|
||||
public Long getAgeRatingId() {
|
||||
return ageRatingId;
|
||||
}
|
||||
|
||||
public void setAgeRatingId(Long ageRatingId) {
|
||||
this.ageRatingId = ageRatingId;
|
||||
}
|
||||
|
||||
public String getVideo() {
|
||||
return video;
|
||||
}
|
||||
|
||||
public void setVideo(String video) {
|
||||
this.video = video;
|
||||
}
|
||||
}
|
186
src/main/java/com/example/demo/movies/model/MovieEntity.java
Normal file
186
src/main/java/com/example/demo/movies/model/MovieEntity.java
Normal file
@ -0,0 +1,186 @@
|
||||
package com.example.demo.movies.model;
|
||||
|
||||
import java.util.Objects;
|
||||
|
||||
import com.example.demo.core.model.BaseEntity;
|
||||
import com.example.demo.types.model.TypeEntity;
|
||||
|
||||
import jakarta.persistence.Column;
|
||||
import jakarta.persistence.Entity;
|
||||
import jakarta.persistence.JoinColumn;
|
||||
import jakarta.persistence.ManyToOne;
|
||||
import jakarta.persistence.Table;
|
||||
|
||||
import com.example.demo.ageRatings.model.AgeRatingEntity;
|
||||
|
||||
@Entity
|
||||
@Table(name = "movies")
|
||||
public class MovieEntity extends BaseEntity {
|
||||
@Column(nullable = false, unique = true, length = 30)
|
||||
private String title;
|
||||
|
||||
@ManyToOne
|
||||
@JoinColumn(name = "typeId", nullable = false)
|
||||
private TypeEntity type;
|
||||
|
||||
@Column(nullable = false)
|
||||
private boolean requiresSubscription;
|
||||
|
||||
@Column(length = 50)
|
||||
private String poster;
|
||||
|
||||
@Column(nullable = false, length = 200)
|
||||
private String description;
|
||||
|
||||
private Integer releaseDate;
|
||||
|
||||
@Column(nullable = false, length = 20)
|
||||
private String country;
|
||||
|
||||
@Column(nullable = false, length = 50)
|
||||
private String tagline;
|
||||
|
||||
@Column(nullable = false, length = 50)
|
||||
private String director;
|
||||
|
||||
@ManyToOne
|
||||
@JoinColumn(name = "ageRatingId", nullable = false)
|
||||
private AgeRatingEntity ageRating;
|
||||
|
||||
@Column(nullable = false, length = 100)
|
||||
private String video;
|
||||
|
||||
public MovieEntity() {
|
||||
}
|
||||
|
||||
public MovieEntity(String title, TypeEntity type, boolean requiresSubscription, String poster,
|
||||
String description, Integer releaseDate, String country, String tagline, String director,
|
||||
AgeRatingEntity ageRating, String video) {
|
||||
this.title = title;
|
||||
this.type = type;
|
||||
this.requiresSubscription = requiresSubscription;
|
||||
this.poster = poster;
|
||||
this.description = description;
|
||||
this.releaseDate = releaseDate;
|
||||
this.country = country;
|
||||
this.tagline = tagline;
|
||||
this.director = director;
|
||||
this.ageRating = ageRating;
|
||||
this.video = video;
|
||||
}
|
||||
|
||||
public String getTitle() {
|
||||
return title;
|
||||
}
|
||||
|
||||
public void setTitle(String title) {
|
||||
this.title = title;
|
||||
}
|
||||
|
||||
public TypeEntity getType() {
|
||||
return type;
|
||||
}
|
||||
|
||||
public void setType(TypeEntity type) {
|
||||
this.type = type;
|
||||
}
|
||||
|
||||
public boolean getRequiresSubscription() {
|
||||
return requiresSubscription;
|
||||
}
|
||||
|
||||
public void setRequiresSubscription(boolean requiresSubscription) {
|
||||
this.requiresSubscription = requiresSubscription;
|
||||
}
|
||||
|
||||
public String getPoster() {
|
||||
return poster;
|
||||
}
|
||||
|
||||
public void setPoster(String poster) {
|
||||
this.poster = poster;
|
||||
}
|
||||
|
||||
public String getDescription() {
|
||||
return description;
|
||||
}
|
||||
|
||||
public void setDescription(String description) {
|
||||
this.description = description;
|
||||
}
|
||||
|
||||
public Integer getReleaseDate() {
|
||||
return releaseDate;
|
||||
}
|
||||
|
||||
public void setReleaseDate(Integer releaseDate) {
|
||||
this.releaseDate = releaseDate;
|
||||
}
|
||||
|
||||
public String getCountry() {
|
||||
return country;
|
||||
}
|
||||
|
||||
public void setCountry(String country) {
|
||||
this.country = country;
|
||||
}
|
||||
|
||||
public String getTagline() {
|
||||
return tagline;
|
||||
}
|
||||
|
||||
public void setTagline(String tagline) {
|
||||
this.tagline = tagline;
|
||||
}
|
||||
|
||||
public String getDirector() {
|
||||
return director;
|
||||
}
|
||||
|
||||
public void setDirector(String director) {
|
||||
this.director = director;
|
||||
}
|
||||
|
||||
public AgeRatingEntity getAgeRating() {
|
||||
return ageRating;
|
||||
}
|
||||
|
||||
public void setAgeRating(AgeRatingEntity ageRating) {
|
||||
this.ageRating = ageRating;
|
||||
}
|
||||
|
||||
public String getVideo() {
|
||||
return video;
|
||||
}
|
||||
|
||||
public void setVideo(String video) {
|
||||
this.video = video;
|
||||
}
|
||||
|
||||
@Override
|
||||
public int hashCode() {
|
||||
return Objects.hash(id, title, type, requiresSubscription, poster, description, releaseDate, country, tagline,
|
||||
director, ageRating, video);
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean equals(Object obj) {
|
||||
if (this == obj)
|
||||
return true;
|
||||
if (obj == null || getClass() != obj.getClass())
|
||||
return false;
|
||||
final MovieEntity other = (MovieEntity) obj;
|
||||
return Objects.equals(other.getId(), id)
|
||||
&& Objects.equals(other.getTitle(), title)
|
||||
&& Objects.equals(other.getType(), type)
|
||||
&& Objects.equals(other.getRequiresSubscription(), requiresSubscription)
|
||||
&& Objects.equals(other.getPoster(), poster)
|
||||
&& Objects.equals(other.getDescription(), description)
|
||||
&& Objects.equals(other.getReleaseDate(), releaseDate)
|
||||
&& Objects.equals(other.getCountry(), country)
|
||||
&& Objects.equals(other.getTagline(), tagline)
|
||||
&& Objects.equals(other.getDirector(), director)
|
||||
&& Objects.equals(other.getAgeRating(), ageRating)
|
||||
&& Objects.equals(other.getVideo(), video);
|
||||
}
|
||||
}
|
@ -0,0 +1,32 @@
|
||||
package com.example.demo.movies.repository;
|
||||
|
||||
import java.util.List;
|
||||
import java.util.Optional;
|
||||
|
||||
import org.springframework.data.domain.Page;
|
||||
import org.springframework.data.domain.Pageable;
|
||||
import org.springframework.data.jpa.repository.Query;
|
||||
import org.springframework.data.repository.CrudRepository;
|
||||
import org.springframework.data.repository.PagingAndSortingRepository;
|
||||
|
||||
import com.example.demo.movies.model.MovieEntity;
|
||||
|
||||
public interface MovieRepository
|
||||
extends CrudRepository<MovieEntity, Long>, PagingAndSortingRepository<MovieEntity, Long> {
|
||||
Optional<MovieEntity> findByTitleIgnoreCase(String title);
|
||||
|
||||
List<MovieEntity> findByTypeId(Long typeId);
|
||||
|
||||
Page<MovieEntity> findByTypeId(long typeId, Pageable pageable);
|
||||
|
||||
List<MovieEntity> findByAgeRatingId(Long ageRatingId);
|
||||
|
||||
Page<MovieEntity> findByAgeRatingId(Long ageRatingId, Pageable pageable);
|
||||
|
||||
List<MovieEntity> findByTypeIdAndAgeRatingId(Long typeId, Long ageRatingId);
|
||||
|
||||
Page<MovieEntity> findByTypeIdAndAgeRatingId(Long typeId, Long ageRatingId, Pageable pageable);
|
||||
|
||||
@Query("SELECT CAST(SUM(r.rate) as double) / COUNT(*) as average_rate FROM MovieEntity as m JOIN ReviewEntity as r ON r.movie.id=m.id WHERE m.id=?1")
|
||||
Double getAverageRating(long id);
|
||||
}
|
126
src/main/java/com/example/demo/movies/service/MovieService.java
Normal file
126
src/main/java/com/example/demo/movies/service/MovieService.java
Normal file
@ -0,0 +1,126 @@
|
||||
package com.example.demo.movies.service;
|
||||
|
||||
import java.util.ArrayList;
|
||||
import java.util.List;
|
||||
import java.util.stream.StreamSupport;
|
||||
|
||||
import org.springframework.data.domain.Page;
|
||||
import org.springframework.data.domain.PageRequest;
|
||||
import org.springframework.data.domain.Pageable;
|
||||
import org.springframework.stereotype.Service;
|
||||
import org.springframework.transaction.annotation.Transactional;
|
||||
|
||||
import com.example.demo.core.error.AlreadyExistsException;
|
||||
import com.example.demo.core.error.NotFoundException;
|
||||
import com.example.demo.movies.model.MovieEntity;
|
||||
import com.example.demo.movies.repository.MovieRepository;
|
||||
|
||||
@Service
|
||||
public class MovieService {
|
||||
private final MovieRepository repository;
|
||||
|
||||
public MovieService(MovieRepository repository) {
|
||||
this.repository = repository;
|
||||
}
|
||||
|
||||
private void checkTitleUnique(String title) {
|
||||
if (repository.findByTitleIgnoreCase(title).isPresent()) {
|
||||
throw new AlreadyExistsException();
|
||||
}
|
||||
}
|
||||
|
||||
@Transactional(readOnly = true)
|
||||
public List<MovieEntity> getAll(Long typeId, Long ageRatingId) {
|
||||
if (typeId <= 0L && ageRatingId <= 0L) {
|
||||
return StreamSupport.stream(repository.findAll().spliterator(), false).toList();
|
||||
} else if (typeId <= 0L) {
|
||||
return repository.findByAgeRatingId(ageRatingId);
|
||||
} else if (ageRatingId <= 0L) {
|
||||
return repository.findByTypeId(typeId);
|
||||
}
|
||||
|
||||
return repository.findByTypeIdAndAgeRatingId(typeId, ageRatingId);
|
||||
}
|
||||
|
||||
@Transactional(readOnly = true)
|
||||
public Page<MovieEntity> getAll(Long typeId, Long ageRatingId, int page, int size) {
|
||||
final Pageable pageRequest = PageRequest.of(page, size);
|
||||
|
||||
if (typeId <= 0L && ageRatingId <= 0L) {
|
||||
return repository.findAll(pageRequest);
|
||||
} else if (typeId <= 0L) {
|
||||
return repository.findByAgeRatingId(ageRatingId, pageRequest);
|
||||
} else if (ageRatingId <= 0L) {
|
||||
return repository.findByTypeId(typeId, pageRequest);
|
||||
}
|
||||
|
||||
return repository.findByTypeIdAndAgeRatingId(typeId, ageRatingId, pageRequest);
|
||||
}
|
||||
|
||||
@Transactional(readOnly = true)
|
||||
public MovieEntity get(Long id) {
|
||||
return repository.findById(id)
|
||||
.orElseThrow(() -> new NotFoundException(MovieEntity.class, id));
|
||||
}
|
||||
|
||||
@Transactional
|
||||
public MovieEntity create(MovieEntity entity) {
|
||||
if (entity == null) {
|
||||
throw new IllegalArgumentException("Entity is null");
|
||||
}
|
||||
|
||||
checkTitleUnique(entity.getTitle());
|
||||
return repository.save(entity);
|
||||
}
|
||||
|
||||
@Transactional
|
||||
public MovieEntity update(Long id, MovieEntity entity) {
|
||||
final MovieEntity existsEntity = get(id);
|
||||
|
||||
existsEntity.setTitle(entity.getTitle());
|
||||
existsEntity.setType(entity.getType());
|
||||
existsEntity.setRequiresSubscription(entity.getRequiresSubscription());
|
||||
existsEntity.setPoster(entity.getPoster());
|
||||
existsEntity.setDescription(entity.getDescription());
|
||||
existsEntity.setReleaseDate(entity.getReleaseDate());
|
||||
existsEntity.setCountry(entity.getCountry());
|
||||
existsEntity.setTagline(entity.getTagline());
|
||||
existsEntity.setDirector(entity.getDirector());
|
||||
existsEntity.setAgeRating(entity.getAgeRating());
|
||||
existsEntity.setVideo(entity.getVideo());
|
||||
|
||||
return repository.save(existsEntity);
|
||||
}
|
||||
|
||||
@Transactional
|
||||
public MovieEntity delete(Long id) {
|
||||
final MovieEntity existsEntity = get(id);
|
||||
repository.delete(existsEntity);
|
||||
|
||||
return existsEntity;
|
||||
}
|
||||
|
||||
@Transactional
|
||||
public void deleteAll() {
|
||||
repository.deleteAll();
|
||||
}
|
||||
|
||||
@Transactional
|
||||
public Double getAverageRating(Long id) {
|
||||
final MovieEntity existsEntity = get(id);
|
||||
Double rating = repository.getAverageRating(existsEntity.getId());
|
||||
|
||||
if (rating == null) {
|
||||
return 0D;
|
||||
}
|
||||
return rating;
|
||||
}
|
||||
|
||||
@Transactional
|
||||
public List<MovieEntity> getItemsByIds(List<Long> ids) {
|
||||
List<MovieEntity> items = new ArrayList<>();
|
||||
repository.findAllById(ids).forEach(item -> items.add(item));
|
||||
|
||||
return items;
|
||||
}
|
||||
}
|
@ -0,0 +1,81 @@
|
||||
package com.example.demo.reviews.api;
|
||||
|
||||
import org.modelmapper.ModelMapper;
|
||||
import org.springframework.web.bind.annotation.DeleteMapping;
|
||||
import org.springframework.web.bind.annotation.GetMapping;
|
||||
import org.springframework.web.bind.annotation.PathVariable;
|
||||
import org.springframework.web.bind.annotation.PostMapping;
|
||||
import org.springframework.web.bind.annotation.PutMapping;
|
||||
import org.springframework.web.bind.annotation.RequestBody;
|
||||
import org.springframework.web.bind.annotation.RequestMapping;
|
||||
import org.springframework.web.bind.annotation.RequestParam;
|
||||
import org.springframework.web.bind.annotation.RestController;
|
||||
|
||||
import com.example.demo.core.api.PageDto;
|
||||
import com.example.demo.core.api.PageDtoMapper;
|
||||
import com.example.demo.core.configuration.Constants;
|
||||
import com.example.demo.reviews.model.ReviewEntity;
|
||||
import com.example.demo.reviews.service.ReviewService;
|
||||
|
||||
import jakarta.validation.Valid;
|
||||
|
||||
@RestController
|
||||
@RequestMapping(Constants.API_URL + "/review")
|
||||
public class ReviewController {
|
||||
private final ReviewService reviewService;
|
||||
private final ModelMapper modelMapper;
|
||||
|
||||
public ReviewController(ReviewService reviewService,
|
||||
ModelMapper modelMapper) {
|
||||
this.reviewService = reviewService;
|
||||
this.modelMapper = modelMapper;
|
||||
}
|
||||
|
||||
private ReviewDto toDto(ReviewEntity entity) {
|
||||
return modelMapper.map(entity, ReviewDto.class);
|
||||
}
|
||||
|
||||
private ReviewEntity toEntity(ReviewDto dto) {
|
||||
final ReviewEntity entity = modelMapper.map(dto, ReviewEntity.class);
|
||||
return entity;
|
||||
}
|
||||
|
||||
@GetMapping
|
||||
public PageDto<ReviewDto> getAll(
|
||||
@RequestParam(name = "userId") Long userId,
|
||||
@RequestParam(name = "movieId") Long movieId,
|
||||
@RequestParam(name = "page", defaultValue = "0") int page,
|
||||
@RequestParam(name = "size", defaultValue = Constants.DEFAULT_PAGE_SIZE) int size) {
|
||||
return PageDtoMapper.toDto(reviewService.getAll(movieId, userId, page, size), this::toDto);
|
||||
}
|
||||
|
||||
@GetMapping("/{id}")
|
||||
public ReviewDto get(
|
||||
@PathVariable(name = "id") Long id,
|
||||
@RequestParam(name = "userId") Long userId) {
|
||||
return toDto(reviewService.get(userId, id));
|
||||
}
|
||||
|
||||
@PostMapping
|
||||
public ReviewDto create(
|
||||
@RequestParam(name = "userId") Long userId,
|
||||
@RequestParam(name = "movieId") Long movieId,
|
||||
@RequestBody @Valid ReviewDto dto) {
|
||||
return toDto(reviewService.create(userId, movieId, toEntity(dto)));
|
||||
}
|
||||
|
||||
@PutMapping("/{id}")
|
||||
public ReviewDto update(
|
||||
@PathVariable(name = "id") Long id,
|
||||
@RequestParam(name = "userId") Long userId,
|
||||
@RequestBody ReviewDto dto) {
|
||||
return toDto(reviewService.update(userId, id, toEntity(dto)));
|
||||
}
|
||||
|
||||
@DeleteMapping("/{id}")
|
||||
public ReviewDto delete(
|
||||
@PathVariable(name = "userId") Long userId,
|
||||
@PathVariable(name = "id") Long id) {
|
||||
return toDto(reviewService.delete(userId, id));
|
||||
}
|
||||
}
|
43
src/main/java/com/example/demo/reviews/api/ReviewDto.java
Normal file
43
src/main/java/com/example/demo/reviews/api/ReviewDto.java
Normal file
@ -0,0 +1,43 @@
|
||||
package com.example.demo.reviews.api;
|
||||
|
||||
import com.fasterxml.jackson.annotation.JsonProperty;
|
||||
|
||||
import jakarta.validation.constraints.Max;
|
||||
import jakarta.validation.constraints.Min;
|
||||
import jakarta.validation.constraints.NotNull;
|
||||
|
||||
public class ReviewDto {
|
||||
private Long id;
|
||||
|
||||
private String description;
|
||||
|
||||
@NotNull
|
||||
@Min(1)
|
||||
@Max(5)
|
||||
private Integer rate;
|
||||
|
||||
@JsonProperty(access = JsonProperty.Access.READ_ONLY)
|
||||
public Long getId() {
|
||||
return id;
|
||||
}
|
||||
|
||||
public void setId(Long id) {
|
||||
this.id = id;
|
||||
}
|
||||
|
||||
public String getDescription() {
|
||||
return description;
|
||||
}
|
||||
|
||||
public void setDescription(String description) {
|
||||
this.description = description;
|
||||
}
|
||||
|
||||
public Integer getRate() {
|
||||
return rate;
|
||||
}
|
||||
|
||||
public void setRate(Integer rate) {
|
||||
this.rate = rate;
|
||||
}
|
||||
}
|
@ -0,0 +1,87 @@
|
||||
package com.example.demo.reviews.model;
|
||||
|
||||
import java.util.Objects;
|
||||
|
||||
import com.example.demo.core.model.BaseEntity;
|
||||
import com.example.demo.movies.model.MovieEntity;
|
||||
import com.example.demo.users.model.UserEntity;
|
||||
|
||||
import jakarta.persistence.Column;
|
||||
import jakarta.persistence.Entity;
|
||||
import jakarta.persistence.JoinColumn;
|
||||
import jakarta.persistence.ManyToOne;
|
||||
import jakarta.persistence.Table;
|
||||
|
||||
@Entity
|
||||
@Table(name = "reviews")
|
||||
public class ReviewEntity extends BaseEntity {
|
||||
@ManyToOne
|
||||
@JoinColumn(name = "userId", nullable = false)
|
||||
private UserEntity user;
|
||||
@ManyToOne
|
||||
@JoinColumn(name = "movieId", nullable = false)
|
||||
private MovieEntity movie;
|
||||
@Column(nullable = false)
|
||||
private String description;
|
||||
@Column(nullable = false)
|
||||
private Integer rate;
|
||||
|
||||
public ReviewEntity() {
|
||||
}
|
||||
|
||||
public ReviewEntity(String description, Integer rate) {
|
||||
this.description = description;
|
||||
this.rate = rate;
|
||||
}
|
||||
|
||||
public UserEntity getUser() {
|
||||
return user;
|
||||
}
|
||||
|
||||
public void setUser(UserEntity user) {
|
||||
this.user = user;
|
||||
}
|
||||
|
||||
public MovieEntity getMovie() {
|
||||
return movie;
|
||||
}
|
||||
|
||||
public void setMovie(MovieEntity movie) {
|
||||
this.movie = movie;
|
||||
}
|
||||
|
||||
public String getDescription() {
|
||||
return description;
|
||||
}
|
||||
|
||||
public void setDescription(String description) {
|
||||
this.description = description;
|
||||
}
|
||||
|
||||
public Integer getRate() {
|
||||
return rate;
|
||||
}
|
||||
|
||||
public void setRate(Integer rate) {
|
||||
this.rate = rate;
|
||||
}
|
||||
|
||||
@Override
|
||||
public int hashCode() {
|
||||
return Objects.hash(id, user, movie, description, rate);
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean equals(Object obj) {
|
||||
if (this == obj)
|
||||
return true;
|
||||
if (obj == null || getClass() != obj.getClass())
|
||||
return false;
|
||||
final ReviewEntity other = (ReviewEntity) obj;
|
||||
return Objects.equals(other.getId(), id)
|
||||
&& Objects.equals(other.getUser(), user)
|
||||
&& Objects.equals(other.getMovie(), movie)
|
||||
&& Objects.equals(other.getDescription(), description)
|
||||
&& Objects.equals(other.getRate(), rate);
|
||||
}
|
||||
}
|
@ -0,0 +1,30 @@
|
||||
package com.example.demo.reviews.repository;
|
||||
|
||||
import com.example.demo.reviews.model.ReviewEntity;
|
||||
|
||||
import java.util.List;
|
||||
import java.util.Optional;
|
||||
|
||||
import org.springframework.data.domain.Page;
|
||||
import org.springframework.data.domain.Pageable;
|
||||
import org.springframework.data.repository.CrudRepository;
|
||||
import org.springframework.data.repository.PagingAndSortingRepository;
|
||||
|
||||
public interface ReviewRepository
|
||||
extends CrudRepository<ReviewEntity, Long>, PagingAndSortingRepository<ReviewEntity, Long> {
|
||||
List<ReviewEntity> findByUserId(long userId);
|
||||
|
||||
Page<ReviewEntity> findByUserId(long userId, Pageable pageable);
|
||||
|
||||
List<ReviewEntity> findByMovieId(long movieId);
|
||||
|
||||
Page<ReviewEntity> findByMovieId(long movieId, Pageable pageable);
|
||||
|
||||
Optional<ReviewEntity> findOneByUserIdAndId(long userId, long id);
|
||||
|
||||
Optional<ReviewEntity> findOneByUserIdAndMovieId(long userId, long movieId);
|
||||
|
||||
List<ReviewEntity> findByUserIdAndMovieId(long userId, long movieId);
|
||||
|
||||
Page<ReviewEntity> findByUserIdAndMovieId(long userId, long movieId, Pageable pageable);
|
||||
}
|
@ -0,0 +1,110 @@
|
||||
package com.example.demo.reviews.service;
|
||||
|
||||
import java.util.List;
|
||||
import java.util.stream.StreamSupport;
|
||||
|
||||
import org.springframework.data.domain.Pageable;
|
||||
import org.springframework.data.domain.Page;
|
||||
import org.springframework.data.domain.PageRequest;
|
||||
import org.springframework.stereotype.Service;
|
||||
import org.springframework.transaction.annotation.Transactional;
|
||||
|
||||
import com.example.demo.core.error.AlreadyExistsException;
|
||||
import com.example.demo.core.error.NotFoundException;
|
||||
import com.example.demo.movies.model.MovieEntity;
|
||||
import com.example.demo.movies.service.MovieService;
|
||||
import com.example.demo.reviews.model.ReviewEntity;
|
||||
import com.example.demo.reviews.repository.ReviewRepository;
|
||||
import com.example.demo.users.model.UserEntity;
|
||||
import com.example.demo.users.service.UserService;
|
||||
|
||||
@Service
|
||||
public class ReviewService {
|
||||
private final ReviewRepository repository;
|
||||
private final UserService userService;
|
||||
private final MovieService movieService;
|
||||
|
||||
public ReviewService(ReviewRepository repository, UserService userService, MovieService movieService) {
|
||||
this.repository = repository;
|
||||
this.userService = userService;
|
||||
this.movieService = movieService;
|
||||
}
|
||||
|
||||
private void checkReview(Long userId, Long movieId) {
|
||||
if (repository.findByUserIdAndMovieId(userId, movieId).size() == 1) {
|
||||
throw new AlreadyExistsException();
|
||||
}
|
||||
}
|
||||
|
||||
@Transactional(readOnly = true)
|
||||
public List<ReviewEntity> getAll(Long movieId, Long userId) {
|
||||
if (movieId <= 0L && userId <= 0L) {
|
||||
return StreamSupport.stream(repository.findAll().spliterator(), false).toList();
|
||||
}
|
||||
if (userId <= 0L && movieId > 0L) {
|
||||
return repository.findByMovieId(movieId);
|
||||
}
|
||||
if (movieId <= 0L && userId > 0L) {
|
||||
return repository.findByUserId(userId);
|
||||
} else {
|
||||
return repository.findByUserIdAndMovieId(userId, movieId);
|
||||
}
|
||||
}
|
||||
|
||||
@Transactional(readOnly = true)
|
||||
public Page<ReviewEntity> getAll(Long movieId, Long userId, int page, int size) {
|
||||
final Pageable pageRequest = PageRequest.of(page, size);
|
||||
|
||||
if (movieId <= 0L && userId <= 0L) {
|
||||
return repository.findAll(pageRequest);
|
||||
}
|
||||
if (userId <= 0L && movieId > 0L) {
|
||||
return repository.findByMovieId(movieId, pageRequest);
|
||||
}
|
||||
if (movieId <= 0L && userId > 0L) {
|
||||
return repository.findByUserId(userId, pageRequest);
|
||||
} else {
|
||||
return repository.findByUserIdAndMovieId(userId, movieId, pageRequest);
|
||||
}
|
||||
}
|
||||
|
||||
@Transactional(readOnly = true)
|
||||
public ReviewEntity get(Long userId, Long id) {
|
||||
userService.get(userId);
|
||||
return repository.findOneByUserIdAndId(userId, id)
|
||||
.orElseThrow(() -> new NotFoundException(ReviewEntity.class, id));
|
||||
}
|
||||
|
||||
@Transactional
|
||||
public ReviewEntity create(long userId, long movieId, ReviewEntity entity) {
|
||||
checkReview(userId, movieId);
|
||||
|
||||
final UserEntity existsUser = userService.get(userId);
|
||||
final MovieEntity existsmovie = movieService.get(movieId);
|
||||
|
||||
entity.setMovie(existsmovie);
|
||||
entity.setUser(existsUser);
|
||||
return repository.save(entity);
|
||||
}
|
||||
|
||||
@Transactional
|
||||
public ReviewEntity update(Long userId, Long id, ReviewEntity entity) {
|
||||
final ReviewEntity existsEntity = get(userId, id);
|
||||
|
||||
existsEntity.setDescription(entity.getDescription());
|
||||
existsEntity.setRate(entity.getRate());
|
||||
return repository.save(existsEntity);
|
||||
}
|
||||
|
||||
@Transactional
|
||||
public ReviewEntity delete(Long userId, Long id) {
|
||||
final ReviewEntity existsEntity = get(userId, id);
|
||||
|
||||
repository.delete(existsEntity);
|
||||
return existsEntity;
|
||||
}
|
||||
|
||||
public void deleteAll() {
|
||||
repository.deleteAll();
|
||||
}
|
||||
}
|
@ -0,0 +1,68 @@
|
||||
package com.example.demo.subscriptions.api;
|
||||
|
||||
import java.util.List;
|
||||
|
||||
import org.modelmapper.ModelMapper;
|
||||
import org.springframework.web.bind.annotation.DeleteMapping;
|
||||
import org.springframework.web.bind.annotation.GetMapping;
|
||||
import org.springframework.web.bind.annotation.PathVariable;
|
||||
import org.springframework.web.bind.annotation.PostMapping;
|
||||
import org.springframework.web.bind.annotation.PutMapping;
|
||||
import org.springframework.web.bind.annotation.RequestBody;
|
||||
import org.springframework.web.bind.annotation.RequestMapping;
|
||||
import org.springframework.web.bind.annotation.RestController;
|
||||
|
||||
import com.example.demo.core.configuration.Constants;
|
||||
import com.example.demo.subscriptions.model.SubscriptionEntity;
|
||||
import com.example.demo.subscriptions.service.SubscriptionService;
|
||||
|
||||
import jakarta.validation.Valid;
|
||||
|
||||
@RestController
|
||||
@RequestMapping(Constants.API_URL + "/subsciption")
|
||||
public class SubscriptionController {
|
||||
private final SubscriptionService subscriptionService;
|
||||
private final ModelMapper modelMapper;
|
||||
|
||||
public SubscriptionController(SubscriptionService subscriptionService, ModelMapper modelMapper) {
|
||||
this.subscriptionService = subscriptionService;
|
||||
this.modelMapper = modelMapper;
|
||||
}
|
||||
|
||||
private SubscriptionDto toDto(SubscriptionEntity entity) {
|
||||
return modelMapper.map(entity, SubscriptionDto.class);
|
||||
}
|
||||
|
||||
private SubscriptionEntity toEntity(SubscriptionDto dto) {
|
||||
return modelMapper.map(dto, SubscriptionEntity.class);
|
||||
}
|
||||
|
||||
@GetMapping
|
||||
public List<SubscriptionDto> getAll() {
|
||||
return subscriptionService.getAll().stream()
|
||||
.map(this::toDto)
|
||||
.toList();
|
||||
}
|
||||
|
||||
@GetMapping("/{id}")
|
||||
public SubscriptionDto get(@PathVariable(name = "id") Long id) {
|
||||
return toDto(subscriptionService.get(id));
|
||||
}
|
||||
|
||||
@PostMapping
|
||||
public SubscriptionDto create(@RequestBody @Valid SubscriptionDto dto) {
|
||||
return toDto(subscriptionService.create(toEntity(dto)));
|
||||
}
|
||||
|
||||
@PutMapping("/{id}")
|
||||
public SubscriptionDto update(
|
||||
@PathVariable(name = "id") Long id,
|
||||
@RequestBody @Valid SubscriptionDto dto) {
|
||||
return toDto(subscriptionService.update(id, toEntity(dto)));
|
||||
}
|
||||
|
||||
@DeleteMapping("/{id}")
|
||||
public SubscriptionDto delete(@PathVariable(name = "id") Long id) {
|
||||
return toDto(subscriptionService.delete(id));
|
||||
}
|
||||
}
|
@ -0,0 +1,55 @@
|
||||
package com.example.demo.subscriptions.api;
|
||||
|
||||
import java.time.Period;
|
||||
|
||||
import com.fasterxml.jackson.annotation.JsonProperty;
|
||||
|
||||
import jakarta.validation.constraints.NotBlank;
|
||||
import jakarta.validation.constraints.Size;
|
||||
|
||||
public class SubscriptionDto {
|
||||
@JsonProperty(access = JsonProperty.Access.READ_ONLY)
|
||||
private Long id;
|
||||
|
||||
@NotBlank
|
||||
@Size(min = 5, max = 50)
|
||||
private String name;
|
||||
|
||||
@NotBlank
|
||||
private Period duration;
|
||||
|
||||
@NotBlank
|
||||
private Double price;
|
||||
|
||||
public Long getId() {
|
||||
return id;
|
||||
}
|
||||
|
||||
public void setId(Long id) {
|
||||
this.id = id;
|
||||
}
|
||||
|
||||
public String getName() {
|
||||
return name;
|
||||
}
|
||||
|
||||
public void setName(String name) {
|
||||
this.name = name;
|
||||
}
|
||||
|
||||
public Period getDuration() {
|
||||
return duration;
|
||||
}
|
||||
|
||||
public void setDuration(Period duration) {
|
||||
this.duration = duration;
|
||||
}
|
||||
|
||||
public Double getPrice() {
|
||||
return price;
|
||||
}
|
||||
|
||||
public void setPrice(Double price) {
|
||||
this.price = price;
|
||||
}
|
||||
}
|
@ -0,0 +1,74 @@
|
||||
package com.example.demo.subscriptions.model;
|
||||
|
||||
import java.time.Period;
|
||||
import java.util.Objects;
|
||||
|
||||
import com.example.demo.core.model.BaseEntity;
|
||||
|
||||
import jakarta.persistence.Column;
|
||||
import jakarta.persistence.Entity;
|
||||
import jakarta.persistence.Table;
|
||||
|
||||
@Entity
|
||||
@Table(name = "subscriptions")
|
||||
public class SubscriptionEntity extends BaseEntity {
|
||||
@Column(nullable = false, unique = true, length = 50)
|
||||
private String name;
|
||||
|
||||
@Column(nullable = false, unique = true)
|
||||
private Period duration;
|
||||
|
||||
@Column(nullable = false)
|
||||
private Double price;
|
||||
|
||||
public SubscriptionEntity() {
|
||||
}
|
||||
|
||||
public SubscriptionEntity(String name, Period duration, Double price) {
|
||||
this.name = name;
|
||||
this.duration = duration;
|
||||
this.price = price;
|
||||
}
|
||||
|
||||
public String getName() {
|
||||
return name;
|
||||
}
|
||||
|
||||
public void setName(String name) {
|
||||
this.name = name;
|
||||
}
|
||||
|
||||
public Period getDuration() {
|
||||
return duration;
|
||||
}
|
||||
|
||||
public void setDuration(Period duration) {
|
||||
this.duration = duration;
|
||||
}
|
||||
|
||||
public Double getPrice() {
|
||||
return price;
|
||||
}
|
||||
|
||||
public void setPrice(Double price) {
|
||||
this.price = price;
|
||||
}
|
||||
|
||||
@Override
|
||||
public int hashCode() {
|
||||
return Objects.hash(id, name, duration, price);
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean equals(Object obj) {
|
||||
if (this == obj)
|
||||
return true;
|
||||
if (obj == null || getClass() != obj.getClass())
|
||||
return false;
|
||||
SubscriptionEntity other = (SubscriptionEntity) obj;
|
||||
return Objects.equals(id, other.id)
|
||||
&& Objects.equals(name, other.name)
|
||||
&& Objects.equals(duration, other.duration)
|
||||
&& Objects.equals(price, other.price);
|
||||
}
|
||||
}
|
@ -0,0 +1,11 @@
|
||||
package com.example.demo.subscriptions.repository;
|
||||
|
||||
import java.util.Optional;
|
||||
|
||||
import org.springframework.data.repository.CrudRepository;
|
||||
|
||||
import com.example.demo.subscriptions.model.SubscriptionEntity;
|
||||
|
||||
public interface SubscriptionRepository extends CrudRepository<SubscriptionEntity, Long> {
|
||||
Optional<SubscriptionEntity> findByNameIgnoreCase(String name);
|
||||
}
|
@ -0,0 +1,70 @@
|
||||
package com.example.demo.subscriptions.service;
|
||||
|
||||
import java.util.List;
|
||||
import java.util.stream.StreamSupport;
|
||||
|
||||
import org.springframework.stereotype.Service;
|
||||
import org.springframework.transaction.annotation.Transactional;
|
||||
|
||||
import com.example.demo.core.error.NotFoundException;
|
||||
import com.example.demo.subscriptions.model.SubscriptionEntity;
|
||||
import com.example.demo.subscriptions.repository.SubscriptionRepository;
|
||||
|
||||
@Service
|
||||
public class SubscriptionService {
|
||||
private final SubscriptionRepository repository;
|
||||
|
||||
public SubscriptionService(SubscriptionRepository repository) {
|
||||
this.repository = repository;
|
||||
}
|
||||
|
||||
private void checkName(String name) {
|
||||
if (repository.findByNameIgnoreCase(name).isPresent()) {
|
||||
throw new IllegalArgumentException(
|
||||
String.format("Subscription with name %s is already exists", name));
|
||||
}
|
||||
}
|
||||
|
||||
@Transactional(readOnly = true)
|
||||
public List<SubscriptionEntity> getAll() {
|
||||
return StreamSupport.stream(repository.findAll().spliterator(), false).toList();
|
||||
}
|
||||
|
||||
@Transactional(readOnly = true)
|
||||
public SubscriptionEntity get(long id) {
|
||||
return repository.findById(id)
|
||||
.orElseThrow(() -> new NotFoundException(SubscriptionEntity.class, id));
|
||||
}
|
||||
|
||||
@Transactional
|
||||
public SubscriptionEntity create(SubscriptionEntity entity) {
|
||||
if (entity == null) {
|
||||
throw new IllegalArgumentException("Entity is null");
|
||||
}
|
||||
checkName(entity.getName());
|
||||
return repository.save(entity);
|
||||
}
|
||||
|
||||
@Transactional
|
||||
public SubscriptionEntity update(Long id, SubscriptionEntity entity) {
|
||||
final SubscriptionEntity existsEntity = get(id);
|
||||
checkName(entity.getName());
|
||||
|
||||
existsEntity.setName(entity.getName());
|
||||
existsEntity.setDuration(entity.getDuration());
|
||||
existsEntity.setPrice(existsEntity.getPrice());
|
||||
return repository.save(existsEntity);
|
||||
}
|
||||
|
||||
@Transactional
|
||||
public SubscriptionEntity delete(Long id) {
|
||||
final SubscriptionEntity existsEntity = get(id);
|
||||
repository.delete(existsEntity);
|
||||
return existsEntity;
|
||||
}
|
||||
|
||||
@Transactional
|
||||
public void deleteAll() {
|
||||
repository.deleteAll();
|
||||
}
|
||||
}
|
64
src/main/java/com/example/demo/types/api/TypeController.java
Normal file
64
src/main/java/com/example/demo/types/api/TypeController.java
Normal file
@ -0,0 +1,64 @@
|
||||
package com.example.demo.types.api;
|
||||
|
||||
import java.util.List;
|
||||
|
||||
import org.modelmapper.ModelMapper;
|
||||
import org.springframework.web.bind.annotation.DeleteMapping;
|
||||
import org.springframework.web.bind.annotation.GetMapping;
|
||||
import org.springframework.web.bind.annotation.PathVariable;
|
||||
import org.springframework.web.bind.annotation.PostMapping;
|
||||
import org.springframework.web.bind.annotation.PutMapping;
|
||||
import org.springframework.web.bind.annotation.RequestBody;
|
||||
import org.springframework.web.bind.annotation.RequestMapping;
|
||||
import org.springframework.web.bind.annotation.RestController;
|
||||
|
||||
import com.example.demo.core.configuration.Constants;
|
||||
import com.example.demo.types.model.TypeEntity;
|
||||
import com.example.demo.types.service.TypeService;
|
||||
|
||||
import jakarta.validation.Valid;
|
||||
|
||||
@RestController
|
||||
@RequestMapping(Constants.API_URL + "/type")
|
||||
public class TypeController {
|
||||
private final TypeService typeService;
|
||||
private final ModelMapper modelMapper;
|
||||
|
||||
public TypeController(TypeService typeService, ModelMapper modelMapper) {
|
||||
this.typeService = typeService;
|
||||
this.modelMapper = modelMapper;
|
||||
}
|
||||
|
||||
private TypeDto toDto(TypeEntity entity) {
|
||||
return modelMapper.map(entity, TypeDto.class);
|
||||
}
|
||||
|
||||
private TypeEntity toEntity(TypeDto dto) {
|
||||
return modelMapper.map(dto, TypeEntity.class);
|
||||
}
|
||||
|
||||
@GetMapping
|
||||
public List<TypeDto> getAll() {
|
||||
return typeService.getAll().stream().map(this::toDto).toList();
|
||||
}
|
||||
|
||||
@GetMapping("/{id}")
|
||||
public TypeDto get(@PathVariable(name = "id") Long id) {
|
||||
return toDto(typeService.get(id));
|
||||
}
|
||||
|
||||
@PostMapping
|
||||
public TypeDto create(@RequestBody @Valid TypeDto dto) {
|
||||
return toDto(typeService.create(toEntity(dto)));
|
||||
}
|
||||
|
||||
@PutMapping("/{id}")
|
||||
public TypeDto update(@PathVariable(name = "id") Long id, @RequestBody @Valid TypeDto dto) {
|
||||
return toDto(typeService.update(id, toEntity(dto)));
|
||||
}
|
||||
|
||||
@DeleteMapping("/{id}")
|
||||
public TypeDto delete(@PathVariable(name = "id") Long id) {
|
||||
return toDto(typeService.delete(id));
|
||||
}
|
||||
}
|
31
src/main/java/com/example/demo/types/api/TypeDto.java
Normal file
31
src/main/java/com/example/demo/types/api/TypeDto.java
Normal file
@ -0,0 +1,31 @@
|
||||
package com.example.demo.types.api;
|
||||
|
||||
import com.fasterxml.jackson.annotation.JsonProperty;
|
||||
|
||||
import jakarta.validation.constraints.NotBlank;
|
||||
import jakarta.validation.constraints.Size;
|
||||
|
||||
public class TypeDto {
|
||||
@JsonProperty(access = JsonProperty.Access.READ_ONLY)
|
||||
private Long id;
|
||||
|
||||
@NotBlank
|
||||
@Size(min = 3, max = 20)
|
||||
private String name;
|
||||
|
||||
public Long getId() {
|
||||
return id;
|
||||
}
|
||||
|
||||
public void setId(Long id) {
|
||||
this.id = id;
|
||||
}
|
||||
|
||||
public String getName() {
|
||||
return name;
|
||||
}
|
||||
|
||||
public void setName(String name) {
|
||||
this.name = name;
|
||||
}
|
||||
}
|
48
src/main/java/com/example/demo/types/model/TypeEntity.java
Normal file
48
src/main/java/com/example/demo/types/model/TypeEntity.java
Normal file
@ -0,0 +1,48 @@
|
||||
package com.example.demo.types.model;
|
||||
|
||||
import java.util.Objects;
|
||||
|
||||
import com.example.demo.core.model.BaseEntity;
|
||||
|
||||
import jakarta.persistence.Column;
|
||||
import jakarta.persistence.Entity;
|
||||
import jakarta.persistence.Table;
|
||||
|
||||
@Entity
|
||||
@Table(name = "types")
|
||||
public class TypeEntity extends BaseEntity {
|
||||
@Column(nullable = false, unique = true, length = 20)
|
||||
private String name;
|
||||
|
||||
public TypeEntity() {
|
||||
}
|
||||
|
||||
public TypeEntity(String name) {
|
||||
this.name = name;
|
||||
}
|
||||
|
||||
public String getName() {
|
||||
return name;
|
||||
}
|
||||
|
||||
public void setName(String name) {
|
||||
this.name = name;
|
||||
}
|
||||
|
||||
@Override
|
||||
public int hashCode() {
|
||||
return Objects.hash(id, name);
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean equals(Object obj) {
|
||||
if (this == obj)
|
||||
return true;
|
||||
|
||||
if (obj == null || getClass() != obj.getClass())
|
||||
return false;
|
||||
|
||||
final TypeEntity other = (TypeEntity) obj;
|
||||
return Objects.equals(other.getId(), id) && Objects.equals(other.getName(), name);
|
||||
}
|
||||
}
|
@ -0,0 +1,10 @@
|
||||
package com.example.demo.types.repository;
|
||||
|
||||
import java.util.Optional;
|
||||
import org.springframework.data.repository.CrudRepository;
|
||||
|
||||
import com.example.demo.types.model.TypeEntity;
|
||||
|
||||
public interface TypeRepository extends CrudRepository<TypeEntity, Long> {
|
||||
Optional<TypeEntity> findByNameIgnoreCase(String name);
|
||||
}
|
@ -0,0 +1,70 @@
|
||||
package com.example.demo.types.service;
|
||||
|
||||
import java.util.List;
|
||||
import java.util.stream.StreamSupport;
|
||||
|
||||
import org.springframework.stereotype.Service;
|
||||
import org.springframework.transaction.annotation.Transactional;
|
||||
|
||||
import com.example.demo.core.error.AlreadyExistsException;
|
||||
import com.example.demo.core.error.NotFoundException;
|
||||
import com.example.demo.types.model.TypeEntity;
|
||||
import com.example.demo.types.repository.TypeRepository;
|
||||
|
||||
@Service
|
||||
public class TypeService {
|
||||
private final TypeRepository repository;
|
||||
|
||||
public TypeService(TypeRepository repository) {
|
||||
this.repository = repository;
|
||||
}
|
||||
|
||||
private void checkNameUnique(String name) {
|
||||
if (repository.findByNameIgnoreCase(name).isPresent()) {
|
||||
throw new AlreadyExistsException();
|
||||
}
|
||||
}
|
||||
|
||||
@Transactional(readOnly = true)
|
||||
public List<TypeEntity> getAll() {
|
||||
return StreamSupport.stream(repository.findAll().spliterator(), false).toList();
|
||||
}
|
||||
|
||||
@Transactional(readOnly = true)
|
||||
public TypeEntity get(Long id) {
|
||||
return repository.findById(id)
|
||||
.orElseThrow(() -> new NotFoundException(TypeEntity.class, id));
|
||||
}
|
||||
|
||||
@Transactional
|
||||
public TypeEntity create(TypeEntity entity) {
|
||||
if (entity == null) {
|
||||
throw new IllegalArgumentException("Entity is null");
|
||||
}
|
||||
|
||||
checkNameUnique(entity.getName());
|
||||
return repository.save(entity);
|
||||
}
|
||||
|
||||
@Transactional
|
||||
public TypeEntity update(Long id, TypeEntity entity) {
|
||||
final TypeEntity existsEntity = get(id);
|
||||
|
||||
checkNameUnique(entity.getName());
|
||||
existsEntity.setName(entity.getName());
|
||||
return repository.save(existsEntity);
|
||||
}
|
||||
|
||||
@Transactional
|
||||
public TypeEntity delete(Long id) {
|
||||
final TypeEntity existsEntity = get(id);
|
||||
repository.delete(existsEntity);
|
||||
|
||||
return existsEntity;
|
||||
}
|
||||
|
||||
@Transactional
|
||||
public void deleteAll() {
|
||||
repository.deleteAll();
|
||||
}
|
||||
}
|
136
src/main/java/com/example/demo/users/api/UserController.java
Normal file
136
src/main/java/com/example/demo/users/api/UserController.java
Normal file
@ -0,0 +1,136 @@
|
||||
package com.example.demo.users.api;
|
||||
|
||||
import java.util.Date;
|
||||
import java.util.List;
|
||||
import java.util.Objects;
|
||||
|
||||
import org.modelmapper.ModelMapper;
|
||||
import org.springframework.web.bind.annotation.DeleteMapping;
|
||||
import org.springframework.web.bind.annotation.GetMapping;
|
||||
import org.springframework.web.bind.annotation.PathVariable;
|
||||
import org.springframework.web.bind.annotation.PostMapping;
|
||||
import org.springframework.web.bind.annotation.PutMapping;
|
||||
import org.springframework.web.bind.annotation.RequestBody;
|
||||
import org.springframework.web.bind.annotation.RequestMapping;
|
||||
import org.springframework.web.bind.annotation.RequestParam;
|
||||
import org.springframework.web.bind.annotation.RestController;
|
||||
|
||||
import com.example.demo.movies.api.MovieDto;
|
||||
import com.example.demo.core.api.PageDto;
|
||||
import com.example.demo.core.api.PageDtoMapper;
|
||||
import com.example.demo.core.configuration.Constants;
|
||||
import com.example.demo.movies.model.MovieEntity;
|
||||
import com.example.demo.movies.service.MovieService;
|
||||
import com.example.demo.users.model.UserEntity;
|
||||
import com.example.demo.users.service.UserService;
|
||||
import com.example.demo.usersubscription.api.SubscriptionInfoDto;
|
||||
import com.example.demo.usersubscription.model.UserSubscriptionEntity;
|
||||
|
||||
import jakarta.validation.Valid;
|
||||
|
||||
@RestController
|
||||
@RequestMapping(Constants.API_URL + "/user")
|
||||
public class UserController {
|
||||
private final UserService userService;
|
||||
private final MovieService movieService;
|
||||
private final ModelMapper modelMapper;
|
||||
|
||||
public UserController(UserService userService, MovieService movieService, ModelMapper modelMapper) {
|
||||
this.userService = userService;
|
||||
this.movieService = movieService;
|
||||
this.modelMapper = modelMapper;
|
||||
}
|
||||
|
||||
private UserDto toDto(UserEntity entity) {
|
||||
return modelMapper.map(entity, UserDto.class);
|
||||
}
|
||||
|
||||
private SubscriptionInfoDto toSubscriptionDto(UserSubscriptionEntity entity) {
|
||||
if (!Objects.isNull(entity)) {
|
||||
return new SubscriptionInfoDto(entity.getExpirationDate().after(new Date()), entity.getActivationDate(),
|
||||
entity.getExpirationDate());
|
||||
} else {
|
||||
return new SubscriptionInfoDto(false, null, null);
|
||||
}
|
||||
}
|
||||
|
||||
private MovieDto toMovieDto(MovieEntity entity) {
|
||||
return modelMapper.map(entity, MovieDto.class);
|
||||
}
|
||||
|
||||
private UserEntity toEntity(UserDto dto) {
|
||||
return modelMapper.map(dto, UserEntity.class);
|
||||
}
|
||||
|
||||
@GetMapping
|
||||
public PageDto<UserDto> getAll(
|
||||
@RequestParam(name = "page", defaultValue = "0") int page,
|
||||
@RequestParam(name = "size", defaultValue = Constants.DEFAULT_PAGE_SIZE) int size) {
|
||||
return PageDtoMapper.toDto(userService.getAll(page, size), this::toDto);
|
||||
}
|
||||
|
||||
@GetMapping("/{id}")
|
||||
public UserDto get(@PathVariable(name = "id") Long id) {
|
||||
return toDto(userService.get(id));
|
||||
}
|
||||
|
||||
@PostMapping
|
||||
public UserDto create(@RequestBody @Valid UserDto dto) {
|
||||
return toDto(userService.create(toEntity(dto)));
|
||||
}
|
||||
|
||||
@PutMapping("/{id}")
|
||||
public UserDto update(@PathVariable(name = "id") Long id, @RequestBody UserDto dto) {
|
||||
return toDto(userService.update(id, toEntity(dto)));
|
||||
}
|
||||
|
||||
@DeleteMapping("/{id}")
|
||||
public UserDto delete(@PathVariable(name = "id") Long id) {
|
||||
return toDto(userService.delete(id));
|
||||
}
|
||||
|
||||
@GetMapping("/{id}/subscription")
|
||||
public SubscriptionInfoDto getActiveSubscription(@PathVariable(name = "id") Long id) {
|
||||
return toSubscriptionDto(userService.getActiveSubscription(id));
|
||||
}
|
||||
|
||||
@PostMapping("/{id}/subscription/all")
|
||||
public List<SubscriptionInfoDto> getAllSubscriptions(@PathVariable(name = "id") Long id) {
|
||||
return userService.getUserSubscriptions(id).stream().map(this::toSubscriptionDto).toList();
|
||||
}
|
||||
|
||||
@PostMapping("/{id}/subscription")
|
||||
public SubscriptionInfoDto activateSubscription(
|
||||
@PathVariable(name = "id") Long id,
|
||||
@RequestParam(name = "subscriptionId", defaultValue = "") Long subscriptionId) {
|
||||
return toSubscriptionDto(userService.activateSubscription(id, subscriptionId));
|
||||
}
|
||||
|
||||
@DeleteMapping("/{id}/subscription")
|
||||
public SubscriptionInfoDto deactivateSubscription(@PathVariable(name = "id") Long id) {
|
||||
return toSubscriptionDto(userService.deactivateSubscription(id));
|
||||
}
|
||||
|
||||
@GetMapping("/{id}/watchLater")
|
||||
public List<MovieDto> getWatchLater(@PathVariable(name = "id") Long id) {
|
||||
return userService.getWatchLater(id).stream().map(this::toMovieDto).toList();
|
||||
}
|
||||
|
||||
@PostMapping("/{id}/watchLater")
|
||||
public UserDto addToWatchLater(@PathVariable(name = "id") Long id,
|
||||
@RequestParam(name = "movieId", defaultValue = "") Long movieId) {
|
||||
MovieEntity movie = movieService.get(movieId);
|
||||
UserEntity user = userService.addMovieToWatchLater(id, movie);
|
||||
|
||||
return toDto(user);
|
||||
}
|
||||
|
||||
@DeleteMapping("/{id}/watchLater")
|
||||
public UserDto deleteFromWatchLater(@PathVariable(name = "id") Long id,
|
||||
@RequestParam(name = "movieId", defaultValue = "") Long movieId) {
|
||||
MovieEntity movie = movieService.get(movieId);
|
||||
UserEntity user = userService.deleteMovieFromWatchLater(id, movie);
|
||||
|
||||
return toDto(user);
|
||||
}
|
||||
}
|
47
src/main/java/com/example/demo/users/api/UserDto.java
Normal file
47
src/main/java/com/example/demo/users/api/UserDto.java
Normal file
@ -0,0 +1,47 @@
|
||||
package com.example.demo.users.api;
|
||||
|
||||
import com.fasterxml.jackson.annotation.JsonProperty;
|
||||
import com.fasterxml.jackson.annotation.JsonProperty.Access;
|
||||
|
||||
import jakarta.validation.constraints.NotBlank;
|
||||
import jakarta.validation.constraints.NotNull;
|
||||
import jakarta.validation.constraints.Size;
|
||||
|
||||
public class UserDto {
|
||||
@JsonProperty(access = Access.READ_ONLY)
|
||||
private Long id;
|
||||
|
||||
@NotNull
|
||||
@NotBlank
|
||||
@Size(min = 5, max = 30)
|
||||
private String email;
|
||||
|
||||
@NotNull
|
||||
@NotBlank
|
||||
@Size(min = 5, max = 30)
|
||||
private String password;
|
||||
|
||||
public Long getId() {
|
||||
return id;
|
||||
}
|
||||
|
||||
public void setId(Long id) {
|
||||
this.id = id;
|
||||
}
|
||||
|
||||
public String getEmail() {
|
||||
return email;
|
||||
}
|
||||
|
||||
public void setEmail(String email) {
|
||||
this.email = email;
|
||||
}
|
||||
|
||||
public String getPassword() {
|
||||
return password;
|
||||
}
|
||||
|
||||
public void setPassword(String password) {
|
||||
this.password = password;
|
||||
}
|
||||
}
|
118
src/main/java/com/example/demo/users/model/UserEntity.java
Normal file
118
src/main/java/com/example/demo/users/model/UserEntity.java
Normal file
@ -0,0 +1,118 @@
|
||||
package com.example.demo.users.model;
|
||||
|
||||
import java.util.HashSet;
|
||||
import java.util.Collections;
|
||||
import java.util.Set;
|
||||
import java.util.Objects;
|
||||
import java.util.Optional;
|
||||
|
||||
import com.example.demo.core.model.BaseEntity;
|
||||
import com.example.demo.movies.model.MovieEntity;
|
||||
import com.example.demo.usersubscription.model.UserSubscriptionEntity;
|
||||
|
||||
import jakarta.persistence.CascadeType;
|
||||
import jakarta.persistence.Column;
|
||||
import jakarta.persistence.Entity;
|
||||
import jakarta.persistence.JoinColumn;
|
||||
import jakarta.persistence.JoinTable;
|
||||
import jakarta.persistence.ManyToMany;
|
||||
import jakarta.persistence.OneToMany;
|
||||
import jakarta.persistence.OrderBy;
|
||||
import jakarta.persistence.Table;
|
||||
|
||||
@Entity
|
||||
@Table(name = "users")
|
||||
public class UserEntity extends BaseEntity {
|
||||
@Column(nullable = false, unique = true, length = 30)
|
||||
private String email;
|
||||
|
||||
@Column(nullable = false, length = 30)
|
||||
private String password;
|
||||
|
||||
@OneToMany(mappedBy = "user", cascade = CascadeType.ALL, orphanRemoval = true)
|
||||
@OrderBy("id ASC")
|
||||
private Set<UserSubscriptionEntity> userSubscriptions = new HashSet<>();
|
||||
|
||||
@ManyToMany()
|
||||
@JoinTable(name = "user_movie", joinColumns = @JoinColumn(name = "userId"), inverseJoinColumns = @JoinColumn(name = "movieId"))
|
||||
@OrderBy("id ASC")
|
||||
private Set<MovieEntity> watchLater = new HashSet<>();
|
||||
|
||||
public UserEntity() {
|
||||
}
|
||||
|
||||
public UserEntity(String email, String password) {
|
||||
this.email = email;
|
||||
this.password = password;
|
||||
}
|
||||
|
||||
public String getEmail() {
|
||||
return email;
|
||||
}
|
||||
|
||||
public void setEmail(String email) {
|
||||
this.email = email;
|
||||
}
|
||||
|
||||
public String getPassword() {
|
||||
return password;
|
||||
}
|
||||
|
||||
public void setPassword(String password) {
|
||||
this.password = password;
|
||||
}
|
||||
|
||||
public Set<UserSubscriptionEntity> getUserSubscriptions() {
|
||||
return userSubscriptions;
|
||||
}
|
||||
|
||||
public void addSubscription(UserSubscriptionEntity userSubscription) {
|
||||
if (userSubscription.getUser() != this) {
|
||||
userSubscription.setUser(this);
|
||||
}
|
||||
userSubscriptions.add(userSubscription);
|
||||
}
|
||||
|
||||
public void deleteSubscription(UserSubscriptionEntity userSubscription) {
|
||||
if (userSubscription.getUser() != this) {
|
||||
return;
|
||||
}
|
||||
userSubscriptions.remove(userSubscription);
|
||||
}
|
||||
|
||||
public Set<MovieEntity> getWatchLater() {
|
||||
return watchLater;
|
||||
}
|
||||
|
||||
public void setWatchLater(Set<MovieEntity> watchLater) {
|
||||
Set<MovieEntity> newWatchLater = new HashSet<>();
|
||||
newWatchLater.addAll(watchLater);
|
||||
this.watchLater.clear();
|
||||
this.watchLater.addAll(Optional.ofNullable(newWatchLater).orElse(Collections.emptySet()));
|
||||
}
|
||||
|
||||
public void addMovieToWatchLater(MovieEntity movie) {
|
||||
watchLater.add(movie);
|
||||
}
|
||||
|
||||
public void deleteMovieFromWatchLater(MovieEntity movie) {
|
||||
watchLater.remove(movie);
|
||||
}
|
||||
|
||||
@Override
|
||||
public int hashCode() {
|
||||
return Objects.hash(id, email, password, userSubscriptions, watchLater);
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean equals(Object obj) {
|
||||
if (this == obj)
|
||||
return true;
|
||||
if (obj == null || getClass() != obj.getClass())
|
||||
return false;
|
||||
final UserEntity other = (UserEntity) obj;
|
||||
return Objects.equals(other.getId(), id)
|
||||
&& Objects.equals(other.getEmail(), email)
|
||||
&& Objects.equals(other.getPassword(), password);
|
||||
}
|
||||
}
|
@ -0,0 +1,20 @@
|
||||
package com.example.demo.users.repository;
|
||||
|
||||
import java.util.Date;
|
||||
import java.util.List;
|
||||
import java.util.Optional;
|
||||
|
||||
import org.springframework.data.jpa.repository.Query;
|
||||
import org.springframework.data.repository.CrudRepository;
|
||||
import org.springframework.data.repository.PagingAndSortingRepository;
|
||||
import org.springframework.data.repository.query.Param;
|
||||
|
||||
import com.example.demo.users.model.UserEntity;
|
||||
import com.example.demo.usersubscription.model.UserSubscriptionEntity;
|
||||
|
||||
public interface UserRepository extends CrudRepository<UserEntity, Long>, PagingAndSortingRepository<UserEntity, Long> {
|
||||
Optional<UserEntity> findByEmailIgnoreCase(String login);
|
||||
|
||||
@Query("SELECT us FROM UserSubscriptionEntity us WHERE us.user.id = :userId AND us.expirationDate > :now")
|
||||
List<UserSubscriptionEntity> getActiveSubscriptions(@Param("userId") Long userId, @Param("now") Date now);
|
||||
}
|
169
src/main/java/com/example/demo/users/service/UserService.java
Normal file
169
src/main/java/com/example/demo/users/service/UserService.java
Normal file
@ -0,0 +1,169 @@
|
||||
package com.example.demo.users.service;
|
||||
|
||||
import java.time.ZoneId;
|
||||
import java.util.Date;
|
||||
import java.util.List;
|
||||
import java.util.Objects;
|
||||
import java.util.stream.StreamSupport;
|
||||
|
||||
import org.springframework.data.domain.Page;
|
||||
import org.springframework.data.domain.PageRequest;
|
||||
import org.springframework.data.domain.Pageable;
|
||||
import org.springframework.stereotype.Service;
|
||||
import org.springframework.transaction.annotation.Transactional;
|
||||
|
||||
import com.example.demo.users.model.UserEntity;
|
||||
import com.example.demo.users.repository.UserRepository;
|
||||
import com.example.demo.usersubscription.model.UserSubscriptionEntity;
|
||||
import com.example.demo.core.error.NotFoundException;
|
||||
import com.example.demo.movies.model.MovieEntity;
|
||||
import com.example.demo.subscriptions.model.SubscriptionEntity;
|
||||
import com.example.demo.subscriptions.service.SubscriptionService;
|
||||
|
||||
@Service
|
||||
public class UserService {
|
||||
private final UserRepository repository;
|
||||
private final SubscriptionService subscriptionService;
|
||||
|
||||
public UserService(UserRepository repository, SubscriptionService subscriptionService) {
|
||||
this.repository = repository;
|
||||
this.subscriptionService = subscriptionService;
|
||||
}
|
||||
|
||||
private void checkEmail(String email) {
|
||||
if (repository.findByEmailIgnoreCase(email).isPresent()) {
|
||||
throw new IllegalArgumentException(
|
||||
String.format("User with email %s is already exists", email));
|
||||
}
|
||||
}
|
||||
|
||||
@Transactional(readOnly = true)
|
||||
public List<UserEntity> getAll() {
|
||||
return StreamSupport.stream(repository.findAll().spliterator(), false).toList();
|
||||
}
|
||||
|
||||
@Transactional(readOnly = true)
|
||||
public Page<UserEntity> getAll(int page, int size) {
|
||||
final Pageable pageRequest = PageRequest.of(page, size);
|
||||
return repository.findAll(pageRequest);
|
||||
}
|
||||
|
||||
@Transactional(readOnly = true)
|
||||
public UserEntity get(Long id) {
|
||||
return repository.findById(id)
|
||||
.orElseThrow(() -> new NotFoundException(UserEntity.class, id));
|
||||
}
|
||||
|
||||
@Transactional
|
||||
public UserEntity create(UserEntity entity) {
|
||||
if (entity == null) {
|
||||
throw new IllegalArgumentException("Entity is null");
|
||||
}
|
||||
|
||||
checkEmail(entity.getEmail());
|
||||
repository.save(entity);
|
||||
return repository.save(entity);
|
||||
}
|
||||
|
||||
@Transactional
|
||||
public UserEntity update(long id, UserEntity entity) {
|
||||
final UserEntity existsEntity = get(id);
|
||||
checkEmail(entity.getEmail());
|
||||
|
||||
existsEntity.setEmail(entity.getEmail());
|
||||
existsEntity.setPassword(entity.getPassword());
|
||||
return repository.save(existsEntity);
|
||||
}
|
||||
|
||||
@Transactional
|
||||
public UserEntity delete(long id) {
|
||||
final UserEntity existsEntity = get(id);
|
||||
repository.delete(existsEntity);
|
||||
|
||||
return existsEntity;
|
||||
}
|
||||
|
||||
@Transactional
|
||||
public void deleteAll() {
|
||||
repository.deleteAll();
|
||||
}
|
||||
|
||||
@Transactional(readOnly = true)
|
||||
public List<UserSubscriptionEntity> getUserSubscriptions(Long id) {
|
||||
return get(id).getUserSubscriptions().stream().toList();
|
||||
}
|
||||
|
||||
@Transactional(readOnly = true)
|
||||
public UserSubscriptionEntity getActiveSubscription(Long id) {
|
||||
List<UserSubscriptionEntity> activeSubscriptions = repository.getActiveSubscriptions(id, new Date());
|
||||
|
||||
if (activeSubscriptions.size() != 1) {
|
||||
return null;
|
||||
}
|
||||
return activeSubscriptions.get(0);
|
||||
}
|
||||
|
||||
@Transactional()
|
||||
public UserSubscriptionEntity activateSubscription(Long id, Long subscriptionId) {
|
||||
UserSubscriptionEntity activeSubscription = getActiveSubscription(id);
|
||||
if (!Objects.isNull(activeSubscription)) {
|
||||
return activeSubscription;
|
||||
}
|
||||
|
||||
final UserEntity existsUser = get(id);
|
||||
final SubscriptionEntity subscription = subscriptionService.get(subscriptionId);
|
||||
|
||||
Date now = new Date();
|
||||
Date expirationDate = Date
|
||||
.from(now.toInstant().atZone(ZoneId.systemDefault()).plus(subscription.getDuration()).toInstant());
|
||||
|
||||
final UserSubscriptionEntity newUserSubscription = new UserSubscriptionEntity(existsUser, subscription, now,
|
||||
expirationDate);
|
||||
newUserSubscription.setUser(existsUser);
|
||||
|
||||
repository.save(existsUser);
|
||||
return newUserSubscription;
|
||||
}
|
||||
|
||||
@Transactional
|
||||
public UserSubscriptionEntity deactivateSubscription(Long id) {
|
||||
UserSubscriptionEntity subscriptionToDeactivate = getActiveSubscription(id);
|
||||
if (Objects.isNull(subscriptionToDeactivate)) {
|
||||
return null;
|
||||
}
|
||||
|
||||
final UserEntity existsUser = get(id);
|
||||
subscriptionToDeactivate.setExpirationDate(new Date());
|
||||
repository.save(existsUser);
|
||||
return subscriptionToDeactivate;
|
||||
}
|
||||
|
||||
@Transactional(readOnly = true)
|
||||
public List<MovieEntity> getWatchLater(long id) {
|
||||
return get(id).getWatchLater().stream().toList();
|
||||
}
|
||||
|
||||
@Transactional
|
||||
public UserEntity addMovieToWatchLater(Long id, MovieEntity movie) {
|
||||
final UserEntity existsEntity = get(id);
|
||||
|
||||
if (!existsEntity.getWatchLater().contains(movie)) {
|
||||
existsEntity.addMovieToWatchLater(movie);
|
||||
return repository.save(existsEntity);
|
||||
}
|
||||
|
||||
return existsEntity;
|
||||
}
|
||||
|
||||
@Transactional
|
||||
public UserEntity deleteMovieFromWatchLater(Long id, MovieEntity movie) {
|
||||
final UserEntity existsEntity = get(id);
|
||||
|
||||
if (existsEntity.getWatchLater().contains(movie)) {
|
||||
existsEntity.deleteMovieFromWatchLater(movie);
|
||||
return repository.save(existsEntity);
|
||||
}
|
||||
|
||||
return existsEntity;
|
||||
}
|
||||
}
|
@ -0,0 +1,34 @@
|
||||
package com.example.demo.usersubscription.api;
|
||||
|
||||
import java.util.Date;
|
||||
|
||||
import jakarta.validation.constraints.NotBlank;
|
||||
import jakarta.validation.constraints.NotNull;
|
||||
|
||||
public class SubscriptionInfoDto {
|
||||
@NotNull
|
||||
@NotBlank
|
||||
private boolean isActive;
|
||||
|
||||
Date activationDate;
|
||||
|
||||
Date expirationDate;
|
||||
|
||||
public SubscriptionInfoDto(boolean isActive, Date activationDate, Date expirationDate) {
|
||||
this.isActive = isActive;
|
||||
this.activationDate = activationDate;
|
||||
this.expirationDate = expirationDate;
|
||||
}
|
||||
|
||||
public boolean getIsActive() {
|
||||
return isActive;
|
||||
}
|
||||
|
||||
public Date getActivationDate() {
|
||||
return activationDate;
|
||||
}
|
||||
|
||||
public Date getExpirationDate() {
|
||||
return expirationDate;
|
||||
}
|
||||
}
|
@ -0,0 +1,98 @@
|
||||
package com.example.demo.usersubscription.model;
|
||||
|
||||
import java.util.Date;
|
||||
import java.util.Objects;
|
||||
|
||||
import com.example.demo.core.model.BaseEntity;
|
||||
import com.example.demo.subscriptions.model.SubscriptionEntity;
|
||||
import com.example.demo.users.model.UserEntity;
|
||||
|
||||
import jakarta.persistence.Column;
|
||||
import jakarta.persistence.Entity;
|
||||
import jakarta.persistence.JoinColumn;
|
||||
import jakarta.persistence.ManyToOne;
|
||||
import jakarta.persistence.Table;
|
||||
|
||||
@Entity
|
||||
@Table(name = "users_subscriptions")
|
||||
public class UserSubscriptionEntity extends BaseEntity {
|
||||
@ManyToOne
|
||||
@JoinColumn(name = "user_id", nullable = false)
|
||||
private UserEntity user;
|
||||
|
||||
@ManyToOne
|
||||
@JoinColumn(name = "subscription_id", nullable = false)
|
||||
private SubscriptionEntity subscription;
|
||||
|
||||
@Column(nullable = false)
|
||||
private Date activationDate;
|
||||
|
||||
@Column(nullable = false)
|
||||
private Date expirationDate;
|
||||
|
||||
public UserSubscriptionEntity() {
|
||||
}
|
||||
|
||||
public UserSubscriptionEntity(UserEntity user, SubscriptionEntity subscription, Date activationDate,
|
||||
Date expirationDate) {
|
||||
this.user = user;
|
||||
this.subscription = subscription;
|
||||
this.activationDate = activationDate;
|
||||
this.expirationDate = expirationDate;
|
||||
}
|
||||
|
||||
public UserEntity getUser() {
|
||||
return user;
|
||||
}
|
||||
|
||||
public void setUser(UserEntity user) {
|
||||
this.user = user;
|
||||
|
||||
if (!user.getUserSubscriptions().contains(this)) {
|
||||
user.getUserSubscriptions().add(this);
|
||||
}
|
||||
}
|
||||
|
||||
public SubscriptionEntity getSubscription() {
|
||||
return subscription;
|
||||
}
|
||||
|
||||
public void setSubscription(SubscriptionEntity subscription) {
|
||||
this.subscription = subscription;
|
||||
}
|
||||
|
||||
public Date getExpirationDate() {
|
||||
return expirationDate;
|
||||
}
|
||||
|
||||
public void setExpirationDate(Date expirationDate) {
|
||||
this.expirationDate = expirationDate;
|
||||
}
|
||||
|
||||
public Date getActivationDate() {
|
||||
return activationDate;
|
||||
}
|
||||
|
||||
public void setActivationDate(Date activationDate) {
|
||||
this.activationDate = activationDate;
|
||||
}
|
||||
|
||||
@Override
|
||||
public int hashCode() {
|
||||
return Objects.hash(id, user.getId(), subscription.getId(), activationDate, expirationDate);
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean equals(Object obj) {
|
||||
if (this == obj)
|
||||
return true;
|
||||
if (obj == null || getClass() != obj.getClass())
|
||||
return false;
|
||||
UserSubscriptionEntity other = (UserSubscriptionEntity) obj;
|
||||
return Objects.equals(id, other.id)
|
||||
&& Objects.equals(user.getId(), other.user.getId())
|
||||
&& Objects.equals(subscription.getId(), other.subscription.getId())
|
||||
&& Objects.equals(activationDate, other.activationDate)
|
||||
&& Objects.equals(expirationDate, other.expirationDate);
|
||||
}
|
||||
}
|
17
src/main/resources/application.properties
Normal file
17
src/main/resources/application.properties
Normal file
@ -0,0 +1,17 @@
|
||||
# Server
|
||||
spring.main.banner-mode=off
|
||||
server.port=8080
|
||||
|
||||
# Logger settings
|
||||
logging.level.com.example.demo=DEBUG
|
||||
|
||||
# JPA settings
|
||||
spring.datasource.url=jdbc:h2:file:./data
|
||||
spring.datasource.username=sa
|
||||
spring.datasource.password=password
|
||||
spring.datasource.driver-class-name=org.h2.Driver
|
||||
spring.jpa.hibernate.ddl-auto=create
|
||||
spring.jpa.open-in-view=false
|
||||
|
||||
# H2 console
|
||||
spring.h2.console.enabled=true
|
84
src/test/java/com/example/demo/AgeRatingServiceTests.java
Normal file
84
src/test/java/com/example/demo/AgeRatingServiceTests.java
Normal file
@ -0,0 +1,84 @@
|
||||
package com.example.demo;
|
||||
|
||||
import org.junit.jupiter.api.AfterEach;
|
||||
import org.junit.jupiter.api.Assertions;
|
||||
import org.junit.jupiter.api.BeforeEach;
|
||||
import org.junit.jupiter.api.MethodOrderer.OrderAnnotation;
|
||||
import org.junit.jupiter.api.Test;
|
||||
import org.junit.jupiter.api.TestMethodOrder;
|
||||
import org.springframework.beans.factory.annotation.Autowired;
|
||||
import org.springframework.boot.test.context.SpringBootTest;
|
||||
import org.springframework.dao.DataIntegrityViolationException;
|
||||
|
||||
import com.example.demo.ageRatings.model.AgeRatingEntity;
|
||||
import com.example.demo.ageRatings.service.AgeRatingService;
|
||||
import com.example.demo.core.error.AlreadyExistsException;
|
||||
import com.example.demo.core.error.NotFoundException;
|
||||
|
||||
@SpringBootTest
|
||||
@TestMethodOrder(OrderAnnotation.class)
|
||||
class AgeRatingServiceTests {
|
||||
@Autowired
|
||||
private AgeRatingService ageRatingService;
|
||||
|
||||
private AgeRatingEntity ageRating;
|
||||
|
||||
@BeforeEach
|
||||
void createData() {
|
||||
removeData();
|
||||
|
||||
ageRating = ageRatingService.create(new AgeRatingEntity("12+"));
|
||||
ageRatingService.create(new AgeRatingEntity("16+"));
|
||||
ageRatingService.create(new AgeRatingEntity("18+"));
|
||||
}
|
||||
|
||||
@AfterEach
|
||||
void removeData() {
|
||||
ageRatingService.getAll().forEach(item -> ageRatingService.delete(item.getId()));
|
||||
}
|
||||
|
||||
@Test
|
||||
void getTest() {
|
||||
Assertions.assertThrows(NotFoundException.class, () -> ageRatingService.get(0L));
|
||||
}
|
||||
|
||||
@Test
|
||||
void createTest() {
|
||||
Assertions.assertEquals(3, ageRatingService.getAll().size());
|
||||
Assertions.assertEquals(ageRating, ageRatingService.get(ageRating.getId()));
|
||||
}
|
||||
|
||||
@Test
|
||||
void createNotUniqueTest() {
|
||||
final AgeRatingEntity nonUniqueAgeRating = new AgeRatingEntity("16+");
|
||||
Assertions.assertThrows(AlreadyExistsException.class, () -> ageRatingService.create(nonUniqueAgeRating));
|
||||
}
|
||||
|
||||
@Test
|
||||
void createNullableTest() {
|
||||
final AgeRatingEntity nullableType = new AgeRatingEntity(null);
|
||||
Assertions.assertThrows(DataIntegrityViolationException.class, () -> ageRatingService.create(nullableType));
|
||||
}
|
||||
|
||||
@Test
|
||||
void updateTest() {
|
||||
final String test = "TEST";
|
||||
final String oldName = ageRating.getName();
|
||||
final AgeRatingEntity newEntity = ageRatingService.update(ageRating.getId(), new AgeRatingEntity(test));
|
||||
|
||||
Assertions.assertEquals(3, ageRatingService.getAll().size());
|
||||
Assertions.assertEquals(newEntity, ageRatingService.get(ageRating.getId()));
|
||||
Assertions.assertEquals(test, newEntity.getName());
|
||||
Assertions.assertNotEquals(oldName, newEntity.getName());
|
||||
}
|
||||
|
||||
@Test
|
||||
void deleteTest() {
|
||||
ageRatingService.delete(ageRating.getId());
|
||||
Assertions.assertEquals(2, ageRatingService.getAll().size());
|
||||
|
||||
final AgeRatingEntity newEntity = ageRatingService.create(new AgeRatingEntity("12+"));
|
||||
Assertions.assertEquals(3, ageRatingService.getAll().size());
|
||||
Assertions.assertNotEquals(ageRating.getId(), newEntity.getId());
|
||||
}
|
||||
}
|
138
src/test/java/com/example/demo/MovieServiceTests.java
Normal file
138
src/test/java/com/example/demo/MovieServiceTests.java
Normal file
@ -0,0 +1,138 @@
|
||||
package com.example.demo;
|
||||
|
||||
import org.junit.jupiter.api.AfterEach;
|
||||
import org.junit.jupiter.api.Assertions;
|
||||
import org.junit.jupiter.api.BeforeEach;
|
||||
import org.junit.jupiter.api.MethodOrderer.OrderAnnotation;
|
||||
import org.junit.jupiter.api.Test;
|
||||
import org.junit.jupiter.api.TestMethodOrder;
|
||||
import org.springframework.beans.factory.annotation.Autowired;
|
||||
import org.springframework.boot.test.context.SpringBootTest;
|
||||
import org.springframework.dao.DataIntegrityViolationException;
|
||||
|
||||
import com.example.demo.ageRatings.model.AgeRatingEntity;
|
||||
import com.example.demo.ageRatings.service.AgeRatingService;
|
||||
import com.example.demo.core.error.AlreadyExistsException;
|
||||
import com.example.demo.core.error.NotFoundException;
|
||||
import com.example.demo.movies.model.MovieEntity;
|
||||
import com.example.demo.movies.service.MovieService;
|
||||
import com.example.demo.types.model.TypeEntity;
|
||||
import com.example.demo.types.service.TypeService;
|
||||
|
||||
@SpringBootTest
|
||||
@TestMethodOrder(OrderAnnotation.class)
|
||||
class MovieServiceTests {
|
||||
@Autowired
|
||||
private TypeService typeService;
|
||||
|
||||
@Autowired
|
||||
private AgeRatingService ageRatingService;
|
||||
|
||||
@Autowired
|
||||
private MovieService movieService;
|
||||
|
||||
private TypeEntity type1;
|
||||
private TypeEntity type2;
|
||||
private AgeRatingEntity ageRating1;
|
||||
private AgeRatingEntity ageRating2;
|
||||
|
||||
private MovieEntity last;
|
||||
|
||||
@BeforeEach
|
||||
void createData() {
|
||||
removeData();
|
||||
|
||||
type1 = typeService.create(new TypeEntity("Фильм"));
|
||||
type2 = typeService.create(new TypeEntity("Сериал"));
|
||||
|
||||
ageRating1 = ageRatingService.create(new AgeRatingEntity("16+"));
|
||||
ageRating2 = ageRatingService.create(new AgeRatingEntity("18+"));
|
||||
|
||||
movieService.create(new MovieEntity("Бойцовский клуб", type1, false,
|
||||
"src/assets/main-page/posters/PeakyBlinders.png",
|
||||
"Сотрудник страховой компании страдает хронической бессонницей...",
|
||||
1999, "США", "Интриги. Хаос. Мыло", "Дэвид Финчер", ageRating2,
|
||||
"https://www.youtube.com/embed/dfeUzm6KF4g?si=U2D-2WNsJzkcxlBX"));
|
||||
movieService.create(new MovieEntity("Американский психопат", type1, true,
|
||||
"src/assets/main-page/posters/AmericanPsycho.jpg",
|
||||
"Днем он ничем не отличается от окружающих, и в толпе вы не обратите на него внимания...",
|
||||
2000, "США, Канада", "Респектабельная внешность дьявола", "Мэри Хэррон", ageRating2,
|
||||
"https://www.youtube.com/embed/PpUWjff_OcM?si=e7tSm4V6qYkz406B"));
|
||||
last = movieService.create(new MovieEntity("Острые козырьки", type2, false,
|
||||
"src/assets/main-page/posters/PeakyBlinders.png",
|
||||
"Сериал рассказывает историю восхождения одной ирландской семьи...",
|
||||
2013, "Великобритания", "The streets are theirs", "Энтони Бирн, Колм МакКарти", ageRating1,
|
||||
"https://www.youtube.com/embed/7cOfn_sjlXM?si=fxNoZjlUon1SZd70"));
|
||||
}
|
||||
|
||||
@AfterEach
|
||||
void removeData() {
|
||||
movieService.deleteAll();
|
||||
typeService.deleteAll();
|
||||
ageRatingService.deleteAll();
|
||||
}
|
||||
|
||||
@Test
|
||||
void getTest() {
|
||||
Assertions.assertThrows(NotFoundException.class, () -> movieService.get(0L));
|
||||
}
|
||||
|
||||
@Test
|
||||
void createTest() {
|
||||
Assertions.assertEquals(3, movieService.getAll(0L, 0L).size());
|
||||
Assertions.assertEquals(2, movieService.getAll(type1.getId(), 0L).size());
|
||||
Assertions.assertEquals(last, movieService.get(last.getId()));
|
||||
}
|
||||
|
||||
@Test
|
||||
void createNotUniqueTest() {
|
||||
final MovieEntity nonUniqueMovie = new MovieEntity("Острые козырьки", type2, false,
|
||||
"src/assets/main-page/posters/PeakyBlinders.png",
|
||||
"Сериал рассказывает историю восхождения одной ирландской семьи...",
|
||||
2013, "Великобритания", "The streets are theirs", "Энтони Бирн, Колм МакКарти", ageRating1,
|
||||
"https://www.youtube.com/embed/7cOfn_sjlXM?si=fxNoZjlUon1SZd70");
|
||||
Assertions.assertThrows(AlreadyExistsException.class, () -> movieService.create(nonUniqueMovie));
|
||||
}
|
||||
|
||||
@Test
|
||||
void createNullableTest() {
|
||||
final MovieEntity nullableItem = new MovieEntity(null, null, false, null, null, null, null, null, null, null,
|
||||
null);
|
||||
Assertions.assertThrows(DataIntegrityViolationException.class, () -> movieService.create(nullableItem));
|
||||
}
|
||||
|
||||
@Test
|
||||
void updateTest() {
|
||||
final String test = "TEST";
|
||||
final MovieEntity entity = movieService.get(last.getId());
|
||||
final String oldName = entity.getTitle();
|
||||
final MovieEntity newEntity = movieService.update(last.getId(), new MovieEntity(
|
||||
test, entity.getType(), entity.getRequiresSubscription(),
|
||||
entity.getPoster(),
|
||||
entity.getDescription(),
|
||||
entity.getReleaseDate(), entity.getCountry(), entity.getTagline(), entity.getDirector(),
|
||||
entity.getAgeRating(),
|
||||
entity.getVideo()));
|
||||
|
||||
Assertions.assertEquals(3, movieService.getAll(0L, 0L).size());
|
||||
Assertions.assertEquals(newEntity, movieService.get(last.getId()));
|
||||
Assertions.assertEquals(test, newEntity.getTitle());
|
||||
Assertions.assertNotEquals(oldName, newEntity.getTitle());
|
||||
}
|
||||
|
||||
@Test
|
||||
void deleteTest() {
|
||||
movieService.delete(last.getId());
|
||||
Assertions.assertEquals(2, movieService.getAll(0L, 0L).size());
|
||||
|
||||
final MovieEntity newEntity = movieService.create(new MovieEntity(
|
||||
last.getTitle(), last.getType(), last.getRequiresSubscription(),
|
||||
last.getPoster(),
|
||||
last.getDescription(),
|
||||
last.getReleaseDate(), last.getCountry(), last.getTagline(), last.getDirector(),
|
||||
last.getAgeRating(),
|
||||
last.getVideo()));
|
||||
Assertions.assertEquals(3, movieService.getAll(0L, 0L).size());
|
||||
Assertions.assertNotEquals(last.getId(), newEntity.getId());
|
||||
}
|
||||
}
|
139
src/test/java/com/example/demo/ReviewServiceTests.java
Normal file
139
src/test/java/com/example/demo/ReviewServiceTests.java
Normal file
@ -0,0 +1,139 @@
|
||||
package com.example.demo;
|
||||
|
||||
import org.junit.jupiter.api.AfterEach;
|
||||
import org.junit.jupiter.api.Assertions;
|
||||
import org.junit.jupiter.api.BeforeEach;
|
||||
import org.junit.jupiter.api.MethodOrderer.OrderAnnotation;
|
||||
import org.junit.jupiter.api.Test;
|
||||
import org.junit.jupiter.api.TestMethodOrder;
|
||||
import org.springframework.beans.factory.annotation.Autowired;
|
||||
import org.springframework.boot.test.context.SpringBootTest;
|
||||
import org.springframework.dao.DataIntegrityViolationException;
|
||||
|
||||
import com.example.demo.ageRatings.model.AgeRatingEntity;
|
||||
import com.example.demo.ageRatings.service.AgeRatingService;
|
||||
import com.example.demo.core.error.AlreadyExistsException;
|
||||
import com.example.demo.core.error.NotFoundException;
|
||||
import com.example.demo.movies.model.MovieEntity;
|
||||
import com.example.demo.movies.service.MovieService;
|
||||
import com.example.demo.reviews.model.ReviewEntity;
|
||||
import com.example.demo.reviews.service.ReviewService;
|
||||
import com.example.demo.types.model.TypeEntity;
|
||||
import com.example.demo.types.service.TypeService;
|
||||
import com.example.demo.users.model.UserEntity;
|
||||
import com.example.demo.users.service.UserService;
|
||||
|
||||
@SpringBootTest
|
||||
@TestMethodOrder(OrderAnnotation.class)
|
||||
class ReviewServiceTests {
|
||||
@Autowired
|
||||
private MovieService movieService;
|
||||
@Autowired
|
||||
private TypeService typeService;
|
||||
@Autowired
|
||||
private AgeRatingService ageRatingService;
|
||||
@Autowired
|
||||
private ReviewService reviewService;
|
||||
@Autowired
|
||||
private UserService userService;
|
||||
|
||||
private MovieEntity movie1;
|
||||
private MovieEntity movie2;
|
||||
private UserEntity user1;
|
||||
private UserEntity user2;
|
||||
private ReviewEntity last;
|
||||
|
||||
@Test
|
||||
void getTest() {
|
||||
Assertions.assertThrows(NotFoundException.class, () -> reviewService.get(0L, 0L));
|
||||
}
|
||||
|
||||
@BeforeEach
|
||||
void createData() {
|
||||
removeData();
|
||||
|
||||
var type1 = typeService.create(new TypeEntity("Фильм"));
|
||||
var type2 = typeService.create(new TypeEntity("Сериал"));
|
||||
|
||||
var ageRating1 = ageRatingService.create(new AgeRatingEntity("16+"));
|
||||
var ageRating2 = ageRatingService.create(new AgeRatingEntity("18+"));
|
||||
|
||||
movie1 = movieService.create(new MovieEntity("Американский психопат", type1, true,
|
||||
"src/assets/main-page/posters/AmericanPsycho.jpg",
|
||||
"Днем он ничем не отличается от окружающих, и в толпе вы не обратите на него внимания...",
|
||||
2000, "США, Канада", "Респектабельная внешность дьявола", "Мэри Хэррон", ageRating2,
|
||||
"https://www.youtube.com/embed/PpUWjff_OcM?si=e7tSm4V6qYkz406B"));
|
||||
movie2 = movieService.create(new MovieEntity("Острые козырьки", type2, false,
|
||||
"src/assets/main-page/posters/PeakyBlinders.png",
|
||||
"Сериал рассказывает историю восхождения одной ирландской семьи...",
|
||||
2013, "Великобритания", "The streets are theirs", "Энтони Бирн, Колм МакКарти", ageRating1,
|
||||
"https://www.youtube.com/embed/7cOfn_sjlXM?si=fxNoZjlUon1SZd70"));
|
||||
|
||||
user1 = userService.create(new UserEntity("myemail@mail.com", "123"));
|
||||
user2 = userService.create(new UserEntity("secondemail@mail.com", "321"));
|
||||
|
||||
reviewService.create(user1.getId(), movie1.getId(), new ReviewEntity("dsdd", 5));
|
||||
reviewService.create(user2.getId(), movie1.getId(), new ReviewEntity("dggfg", 4));
|
||||
last = reviewService.create(user1.getId(), movie2.getId(), new ReviewEntity("dsddddd", 5));
|
||||
}
|
||||
|
||||
@AfterEach
|
||||
void removeData() {
|
||||
reviewService.deleteAll();
|
||||
movieService.deleteAll();
|
||||
typeService.deleteAll();
|
||||
ageRatingService.deleteAll();
|
||||
userService.deleteAll();
|
||||
}
|
||||
|
||||
@Test
|
||||
void createTest() {
|
||||
Assertions.assertEquals(3, reviewService.getAll(0L, 0L).size());
|
||||
Assertions.assertEquals(1, reviewService.getAll(movie1.getId(), user1.getId()).size());
|
||||
Assertions.assertEquals(last, reviewService.get(user1.getId(), last.getId()));
|
||||
Assertions.assertThrows(AlreadyExistsException.class,
|
||||
() -> reviewService.create(user1.getId(), movie1.getId(), new ReviewEntity("dsdd", 5)));
|
||||
}
|
||||
|
||||
@Test
|
||||
void createNotUniqueTest() {
|
||||
final ReviewEntity nonUniqueReview = new ReviewEntity("dsdd", 5);
|
||||
Assertions.assertThrows(AlreadyExistsException.class, () -> reviewService.create(user1.getId(), movie1.getId(),
|
||||
nonUniqueReview));
|
||||
}
|
||||
|
||||
@Test
|
||||
void createNullableTest() {
|
||||
final ReviewEntity nullableReview = new ReviewEntity(null, null);
|
||||
Assertions.assertThrows(NotFoundException.class,
|
||||
() -> reviewService.create(0L, 0L, nullableReview));
|
||||
Assertions.assertThrows(NotFoundException.class,
|
||||
() -> reviewService.create(user2.getId(), 0L, nullableReview));
|
||||
Assertions.assertThrows(DataIntegrityViolationException.class,
|
||||
() -> reviewService.create(user2.getId(), movie2.getId(), nullableReview));
|
||||
}
|
||||
|
||||
@Test
|
||||
void updateTest() {
|
||||
final String test = "TEST";
|
||||
final ReviewEntity entity = reviewService.get(user1.getId(), last.getId());
|
||||
final String oldDesc = entity.getDescription();
|
||||
final ReviewEntity newEntity = reviewService.update(user1.getId(), last.getId(),
|
||||
new ReviewEntity(test, 5));
|
||||
Assertions.assertEquals(3, reviewService.getAll(0L, 0L).size());
|
||||
Assertions.assertEquals(newEntity, reviewService.get(user1.getId(), last.getId()));
|
||||
Assertions.assertEquals(test, newEntity.getDescription());
|
||||
Assertions.assertNotEquals(oldDesc, newEntity.getDescription());
|
||||
}
|
||||
|
||||
@Test
|
||||
void deleteTest() {
|
||||
reviewService.delete(last.getUser().getId(), last.getId());
|
||||
Assertions.assertEquals(2, reviewService.getAll(0L, 0L).size());
|
||||
|
||||
final ReviewEntity newEntity = reviewService.create(user1.getId(), movie2.getId(),
|
||||
new ReviewEntity("3210", 5));
|
||||
Assertions.assertEquals(3, reviewService.getAll(0L, 0L).size());
|
||||
Assertions.assertNotEquals(last.getId(), newEntity.getId());
|
||||
}
|
||||
}
|
83
src/test/java/com/example/demo/TypeServiceTests.java
Normal file
83
src/test/java/com/example/demo/TypeServiceTests.java
Normal file
@ -0,0 +1,83 @@
|
||||
package com.example.demo;
|
||||
|
||||
import org.junit.jupiter.api.AfterEach;
|
||||
import org.junit.jupiter.api.Assertions;
|
||||
import org.junit.jupiter.api.BeforeEach;
|
||||
import org.junit.jupiter.api.MethodOrderer.OrderAnnotation;
|
||||
import org.junit.jupiter.api.Test;
|
||||
import org.junit.jupiter.api.TestMethodOrder;
|
||||
import org.springframework.beans.factory.annotation.Autowired;
|
||||
import org.springframework.boot.test.context.SpringBootTest;
|
||||
import org.springframework.dao.DataIntegrityViolationException;
|
||||
|
||||
import com.example.demo.core.error.AlreadyExistsException;
|
||||
import com.example.demo.core.error.NotFoundException;
|
||||
import com.example.demo.types.model.TypeEntity;
|
||||
import com.example.demo.types.service.TypeService;
|
||||
|
||||
@SpringBootTest
|
||||
@TestMethodOrder(OrderAnnotation.class)
|
||||
class TypeServiceTests {
|
||||
@Autowired
|
||||
private TypeService typeService;
|
||||
|
||||
private TypeEntity type;
|
||||
|
||||
@BeforeEach
|
||||
void createData() {
|
||||
removeData();
|
||||
|
||||
type = typeService.create(new TypeEntity("Фильм"));
|
||||
typeService.create(new TypeEntity("Сериал"));
|
||||
}
|
||||
|
||||
@AfterEach
|
||||
void removeData() {
|
||||
typeService.getAll().forEach(item -> typeService.delete(item.getId()));
|
||||
}
|
||||
|
||||
@Test
|
||||
void getTest() {
|
||||
Assertions.assertThrows(NotFoundException.class, () -> typeService.get(0L));
|
||||
}
|
||||
|
||||
@Test
|
||||
void createTest() {
|
||||
Assertions.assertEquals(2, typeService.getAll().size());
|
||||
Assertions.assertEquals(type, typeService.get(type.getId()));
|
||||
}
|
||||
|
||||
@Test
|
||||
void createNotUniqueTest() {
|
||||
final TypeEntity nonUniqueType = new TypeEntity("Фильм");
|
||||
Assertions.assertThrows(AlreadyExistsException.class, () -> typeService.create(nonUniqueType));
|
||||
}
|
||||
|
||||
@Test
|
||||
void createNullableTest() {
|
||||
final TypeEntity nullableType = new TypeEntity(null);
|
||||
Assertions.assertThrows(DataIntegrityViolationException.class, () -> typeService.create(nullableType));
|
||||
}
|
||||
|
||||
@Test
|
||||
void updateTest() {
|
||||
final String test = "TEST";
|
||||
final String oldName = type.getName();
|
||||
final TypeEntity newEntity = typeService.update(type.getId(), new TypeEntity(test));
|
||||
|
||||
Assertions.assertEquals(2, typeService.getAll().size());
|
||||
Assertions.assertEquals(newEntity, typeService.get(type.getId()));
|
||||
Assertions.assertEquals(test, newEntity.getName());
|
||||
Assertions.assertNotEquals(oldName, newEntity.getName());
|
||||
}
|
||||
|
||||
@Test
|
||||
void deleteTest() {
|
||||
typeService.delete(type.getId());
|
||||
Assertions.assertEquals(1, typeService.getAll().size());
|
||||
|
||||
final TypeEntity newEntity = typeService.create(new TypeEntity("Фильм"));
|
||||
Assertions.assertEquals(2, typeService.getAll().size());
|
||||
Assertions.assertNotEquals(type.getId(), newEntity.getId());
|
||||
}
|
||||
}
|
150
src/test/java/com/example/demo/UserServiceTests.java
Normal file
150
src/test/java/com/example/demo/UserServiceTests.java
Normal file
@ -0,0 +1,150 @@
|
||||
package com.example.demo;
|
||||
|
||||
import java.time.Period;
|
||||
import java.util.Date;
|
||||
|
||||
import org.junit.jupiter.api.AfterEach;
|
||||
import org.junit.jupiter.api.Assertions;
|
||||
import org.junit.jupiter.api.BeforeEach;
|
||||
import org.junit.jupiter.api.MethodOrderer.OrderAnnotation;
|
||||
import org.junit.jupiter.api.Test;
|
||||
import org.junit.jupiter.api.TestMethodOrder;
|
||||
import org.springframework.beans.factory.annotation.Autowired;
|
||||
import org.springframework.boot.test.context.SpringBootTest;
|
||||
|
||||
import com.example.demo.ageRatings.model.AgeRatingEntity;
|
||||
import com.example.demo.ageRatings.service.AgeRatingService;
|
||||
import com.example.demo.core.error.NotFoundException;
|
||||
import com.example.demo.movies.model.MovieEntity;
|
||||
import com.example.demo.movies.service.MovieService;
|
||||
import com.example.demo.subscriptions.model.SubscriptionEntity;
|
||||
import com.example.demo.subscriptions.service.SubscriptionService;
|
||||
import com.example.demo.types.model.TypeEntity;
|
||||
import com.example.demo.types.service.TypeService;
|
||||
import com.example.demo.users.model.UserEntity;
|
||||
import com.example.demo.users.service.UserService;
|
||||
import com.example.demo.usersubscription.model.UserSubscriptionEntity;
|
||||
|
||||
@SpringBootTest
|
||||
@TestMethodOrder(OrderAnnotation.class)
|
||||
class UserServiceTests {
|
||||
@Autowired
|
||||
private TypeService typeService;
|
||||
@Autowired
|
||||
private AgeRatingService ageRatingService;
|
||||
@Autowired
|
||||
private MovieService movieService;
|
||||
@Autowired
|
||||
private UserService userService;
|
||||
@Autowired
|
||||
private SubscriptionService subscriptionService;
|
||||
|
||||
private UserEntity last;
|
||||
private TypeEntity type1;
|
||||
private AgeRatingEntity ageRating1;
|
||||
private MovieEntity movie1;
|
||||
private MovieEntity movie2;
|
||||
private SubscriptionEntity subscription1;
|
||||
private SubscriptionEntity subscription2;
|
||||
|
||||
@Test
|
||||
void getTest() {
|
||||
Assertions.assertThrows(NotFoundException.class, () -> userService.get(0L));
|
||||
}
|
||||
|
||||
@BeforeEach
|
||||
void createData() {
|
||||
removeData();
|
||||
|
||||
userService.create(new UserEntity("myemail@mail.com", "123"));
|
||||
userService.create(new UserEntity("secondemail@mail.com", "321"));
|
||||
last = userService.create(new UserEntity("thirdemail@mail.com", "3210"));
|
||||
|
||||
type1 = typeService.create(new TypeEntity("Фильм"));
|
||||
ageRating1 = ageRatingService.create(new AgeRatingEntity("18+"));
|
||||
movie1 = movieService.create(new MovieEntity("Бойцовский клуб", type1, false,
|
||||
"src/assets/main-page/posters/PeakyBlinders.png",
|
||||
"Сотрудник страховой компании страдает хронической бессонницей и отчаянно пытается вырваться из мучительно скучной жизни...",
|
||||
1999, "США", "Интриги. Хаос. Мыло", "Дэвид Финчер", ageRating1,
|
||||
"https://www.youtube.com/embed/dfeUzm6KF4g?si=U2D-2WNsJzkcxlBX"));
|
||||
movie2 = movieService.create(new MovieEntity("Американский психопат", type1, true,
|
||||
"src/assets/main-page/posters/AmericanPsycho.jpg",
|
||||
"Днем он ничем не отличается от окружающих, и в толпе вы не обратите на него внимания...",
|
||||
2000, "США, Канада", "Респектабельная внешность дьявола", "Мэри Хэррон", ageRating1,
|
||||
"https://www.youtube.com/embed/PpUWjff_OcM?si=e7tSm4V6qYkz406B"));
|
||||
|
||||
subscription1 = subscriptionService.create(new SubscriptionEntity("Подписка 1", Period.of(0, 0, 7), 199.99));
|
||||
subscription2 = subscriptionService.create(new SubscriptionEntity("Подписка 2", Period.of(0, 1, 0), 299.99));
|
||||
}
|
||||
|
||||
@AfterEach
|
||||
void removeData() {
|
||||
userService.deleteAll();
|
||||
movieService.deleteAll();
|
||||
typeService.deleteAll();
|
||||
ageRatingService.deleteAll();
|
||||
subscriptionService.deleteAll();
|
||||
}
|
||||
|
||||
@Test
|
||||
void createTest() {
|
||||
Assertions.assertEquals(3, userService.getAll().size());
|
||||
Assertions.assertEquals(last, userService.get(last.getId()));
|
||||
}
|
||||
|
||||
@Test
|
||||
void updateTest() {
|
||||
final String test = "TEST";
|
||||
final UserEntity entity = userService.get(last.getId());
|
||||
final String oldEmail = entity.getEmail();
|
||||
final UserEntity newEntity = userService.update(entity.getId(),
|
||||
new UserEntity(test, entity.getPassword()));
|
||||
|
||||
Assertions.assertEquals(3, userService.getAll().size());
|
||||
Assertions.assertEquals(newEntity, userService.get(newEntity.getId()));
|
||||
Assertions.assertEquals(test, newEntity.getEmail());
|
||||
Assertions.assertNotEquals(oldEmail, newEntity.getEmail());
|
||||
}
|
||||
|
||||
@Test
|
||||
void deleteTest() {
|
||||
userService.delete(last.getId());
|
||||
Assertions.assertEquals(2, userService.getAll().size());
|
||||
|
||||
final var newEntity = userService.create(new UserEntity("thirdemail@mail.com", "3210"));
|
||||
Assertions.assertEquals(3, userService.getAll().size());
|
||||
Assertions.assertNotEquals(last.getId(), newEntity.getId());
|
||||
}
|
||||
|
||||
@Test
|
||||
void watchLaterTest() {
|
||||
userService.addMovieToWatchLater(last.getId(), movie1);
|
||||
userService.addMovieToWatchLater(last.getId(), movie1);
|
||||
Assertions.assertEquals(1, userService.getWatchLater(last.getId()).size());
|
||||
userService.addMovieToWatchLater(last.getId(), movie2);
|
||||
Assertions.assertEquals(2, userService.getWatchLater(last.getId()).size());
|
||||
|
||||
userService.deleteMovieFromWatchLater(last.getId(), movie1);
|
||||
Assertions.assertEquals(1, userService.getWatchLater(last.getId()).size());
|
||||
}
|
||||
|
||||
@Test
|
||||
void subscriptionsTest() {
|
||||
Assertions.assertNull(userService.getActiveSubscription(last.getId()));
|
||||
|
||||
userService.activateSubscription(last.getId(), subscription1.getId());
|
||||
userService.activateSubscription(last.getId(), subscription1.getId());
|
||||
Assertions.assertEquals(1, userService.getUserSubscriptions(last.getId()).size());
|
||||
|
||||
UserSubscriptionEntity activeSubscription = userService.getActiveSubscription(last.getId());
|
||||
Assertions.assertNotNull(activeSubscription);
|
||||
Assertions.assertTrue(activeSubscription.getExpirationDate().after(new Date()));
|
||||
|
||||
userService.deactivateSubscription(last.getId());
|
||||
Assertions.assertNull(userService.getActiveSubscription(last.getId()));
|
||||
|
||||
userService.activateSubscription(last.getId(), subscription2.getId());
|
||||
Assertions.assertNotNull(userService.getActiveSubscription(last.getId()));
|
||||
Assertions.assertEquals(2, userService.getUserSubscriptions(last.getId()).size());
|
||||
}
|
||||
}
|
14
src/test/resources/application.properties
Normal file
14
src/test/resources/application.properties
Normal file
@ -0,0 +1,14 @@
|
||||
# Server
|
||||
spring.main.banner-mode=off
|
||||
|
||||
# Logger settings
|
||||
# Available levels are: TRACE, DEBUG, INFO, WARN, ERROR, FATAL, OFF
|
||||
logging.level.com.example.demo=DEBUG
|
||||
|
||||
# JPA Settings
|
||||
spring.datasource.url=jdbc:h2:mem:testdb
|
||||
spring.datasource.username=sa
|
||||
spring.datasource.password=password
|
||||
spring.datasource.driver-class-name=org.h2.Driver
|
||||
spring.jpa.hibernate.ddl-auto=create
|
||||
spring.jpa.open-in-view=false
|
BIN
Отчёт (лабораторная работа №3).docx
Normal file
BIN
Отчёт (лабораторная работа №3).docx
Normal file
Binary file not shown.
Loading…
Reference in New Issue
Block a user