15 Commits

140 changed files with 11164 additions and 773 deletions

10
.gitignore vendored
View File

@@ -1,10 +0,0 @@
################################################################################
# Данный GITIGNORE-файл был автоматически создан Microsoft(R) Visual Studio.
################################################################################
/.vs/ип/v17
/.vs/ProjectSettings.json
/.vs/slnx.sqlite
/.vs/VSWorkspaceState.json
/.vs/ип/FileContentIndex
/.vs/ип/FileContentIndex/3a341ec4-c869-4b7b-a6d3-d3f2f68d21cc.vsidx

3
.idea/.gitignore generated vendored Normal file
View File

@@ -0,0 +1,3 @@
# Default ignored files
/shelf/
/workspace.xml

View File

@@ -0,0 +1,9 @@
<?xml version="1.0" encoding="UTF-8"?>
<module type="JAVA_MODULE" version="4">
<component name="NewModuleRootManager" inherit-compiler-output="true">
<exclude-output />
<content url="file://$MODULE_DIR$" />
<orderEntry type="inheritedJdk" />
<orderEntry type="sourceFolder" forTests="false" />
</component>
</module>

8
.idea/compiler.xml generated Normal file
View File

@@ -0,0 +1,8 @@
<?xml version="1.0" encoding="UTF-8"?>
<project version="4">
<component name="CompilerConfiguration">
<bytecodeTargetLevel>
<module name="movie-api" target="21" />
</bytecodeTargetLevel>
</component>
</project>

15
.idea/gradle.xml generated Normal file
View File

@@ -0,0 +1,15 @@
<?xml version="1.0" encoding="UTF-8"?>
<project version="4">
<component name="GradleSettings">
<option name="linkedExternalProjectsSettings">
<GradleProjectSettings>
<option name="externalProjectPath" value="$PROJECT_DIR$/backend" />
<option name="modules">
<set>
<option value="$PROJECT_DIR$/backend" />
</set>
</option>
</GradleProjectSettings>
</option>
</component>
</project>

7
.idea/misc.xml generated Normal file
View File

@@ -0,0 +1,7 @@
<?xml version="1.0" encoding="UTF-8"?>
<project version="4">
<component name="ExternalStorageConfigurationManager" enabled="true" />
<component name="ProjectRootManager" version="2" project-jdk-name="openjdk-23" project-jdk-type="JavaSDK">
<output url="file://$PROJECT_DIR$/out" />
</component>
</project>

8
.idea/modules.xml generated Normal file
View File

@@ -0,0 +1,8 @@
<?xml version="1.0" encoding="UTF-8"?>
<project version="4">
<component name="ProjectModuleManager">
<modules>
<module fileurl="file://$PROJECT_DIR$/.idea/PIbd-22_BuslaevRoman_InternetProgramming.iml" filepath="$PROJECT_DIR$/.idea/PIbd-22_BuslaevRoman_InternetProgramming.iml" />
</modules>
</component>
</project>

6
.idea/vcs.xml generated Normal file
View File

@@ -0,0 +1,6 @@
<?xml version="1.0" encoding="UTF-8"?>
<project version="4">
<component name="VcsDirectoryMappings">
<mapping directory="" vcs="Git" />
</component>
</project>

File diff suppressed because it is too large Load Diff

Binary file not shown.

View File

@@ -0,0 +1,23 @@
{
"Version": 1,
"WorkspaceRootPath": "C:\\Users\\busla\\source\\repos\\PIbd-22_BuslaevRoman_InternetProgramming\\",
"Documents": [],
"DocumentGroupContainers": [
{
"Orientation": 0,
"VerticalTabListWidth": 256,
"DocumentGroups": [
{
"DockedWidth": 212,
"SelectedChildIndex": -1,
"Children": [
{
"$type": "Bookmark",
"Name": "ST:0:0:{1c4feeaa-4718-4aa9-859d-94ce25d182ba}"
}
]
}
]
}
]
}

View File

@@ -0,0 +1,41 @@
{
"Version": 1,
"WorkspaceRootPath": "C:\\Users\\busla\\source\\repos\\PIbd-22_BuslaevRoman_InternetProgramming\\",
"Documents": [
{
"AbsoluteMoniker": "D:0:0:{A2FE74E1-B743-11D0-AE1A-00A0C90FFFC3}|\u003CMiscFiles\u003E|C:\\Users\\busla\\source\\repos\\PIbd-22_BuslaevRoman_InternetProgramming\\maket\\maket.html||{40D31677-CBC0-4297-A9EF-89D907823A98}",
"RelativeMoniker": "D:0:0:{A2FE74E1-B743-11D0-AE1A-00A0C90FFFC3}|\u003CMiscFiles\u003E|solutionrelative:maket\\maket.html||{40D31677-CBC0-4297-A9EF-89D907823A98}"
}
],
"DocumentGroupContainers": [
{
"Orientation": 0,
"VerticalTabListWidth": 256,
"DocumentGroups": [
{
"DockedWidth": 212,
"SelectedChildIndex": 1,
"Children": [
{
"$type": "Bookmark",
"Name": "ST:0:0:{1c4feeaa-4718-4aa9-859d-94ce25d182ba}"
},
{
"$type": "Document",
"DocumentIndex": 0,
"Title": "maket.html",
"DocumentMoniker": "C:\\Users\\busla\\source\\repos\\PIbd-22_BuslaevRoman_InternetProgramming\\maket\\maket.html",
"RelativeDocumentMoniker": "maket\\maket.html",
"ToolTip": "C:\\Users\\busla\\source\\repos\\PIbd-22_BuslaevRoman_InternetProgramming\\maket\\maket.html",
"RelativeToolTip": "maket\\maket.html",
"ViewState": "AgIAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA==",
"Icon": "ae27a6b0-e345-4288-96df-5eaf394ee369.001512|",
"WhenOpened": "2025-09-19T11:57:31.72Z",
"EditorCaption": ""
}
]
}
]
}
]
}

3
.vs/ProjectSettings.json Normal file
View File

@@ -0,0 +1,3 @@
{
"CurrentProjectSetting": null
}

View File

@@ -0,0 +1,6 @@
{
"ExpandedNodes": [
""
],
"PreviewInSolutionExplorer": false
}

BIN
.vs/slnx.sqlite Normal file

Binary file not shown.

3
backend/.gitattributes vendored Normal file
View File

@@ -0,0 +1,3 @@
/gradlew text eol=lf
*.bat text eol=crlf
*.jar binary

37
backend/.gitignore vendored Normal file
View 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/

35
backend/build.gradle Normal file
View File

@@ -0,0 +1,35 @@
plugins {
id 'java'
id 'org.springframework.boot' version '3.5.5'
id 'io.spring.dependency-management' version '1.1.7'
}
group = 'ru.ulstu.is'
version = '0.0.1-SNAPSHOT'
description = 'Movie API (Lab 1)'
def jdkVersion = '21'
defaultTasks 'bootRun'
java {
toolchain {
languageVersion = JavaLanguageVersion.of(jdkVersion)
}
}
repositories { mavenCentral() }
ext {
springdocVersion = '2.8.11'
}
dependencies {
implementation 'org.springframework.boot:spring-boot-starter-web'
implementation "org.springdoc:springdoc-openapi-starter-webmvc-ui:${springdocVersion}"
implementation 'org.springframework.boot:spring-boot-starter-validation'
implementation 'org.springframework.boot:spring-boot-starter-data-jpa'
runtimeOnly 'com.h2database:h2'
testImplementation 'org.springframework.boot:spring-boot-starter-test'
}
tasks.named('test') {
useJUnitPlatform()
}

BIN
backend/data/appdb.mv.db Normal file

Binary file not shown.

Binary file not shown.

View File

@@ -0,0 +1,7 @@
distributionBase=GRADLE_USER_HOME
distributionPath=wrapper/dists
distributionUrl=https\://services.gradle.org/distributions/gradle-8.14.3-bin.zip
networkTimeout=10000
validateDistributionUrl=true
zipStoreBase=GRADLE_USER_HOME
zipStorePath=wrapper/dists

251
backend/gradlew vendored Normal file
View File

@@ -0,0 +1,251 @@
#!/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.
#
# SPDX-License-Identifier: Apache-2.0
#
##############################################################################
#
# 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/platforms/jvm/plugins-application/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 -P "${APP_HOME:-./}" > /dev/null && printf '%s\n' "$PWD" ) || 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="\\\"\\\""
# 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, 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" \
-jar "$APP_HOME/gradle/wrapper/gradle-wrapper.jar" \
"$@"
# 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" "$@"

94
backend/gradlew.bat vendored Normal file
View File

@@ -0,0 +1,94 @@
@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
@rem SPDX-License-Identifier: Apache-2.0
@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. 1>&2
echo ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. 1>&2
echo. 1>&2
echo Please set the JAVA_HOME variable in your environment to match the 1>&2
echo location of your Java installation. 1>&2
goto fail
:findJavaFromJavaHome
set JAVA_HOME=%JAVA_HOME:"=%
set JAVA_EXE=%JAVA_HOME%/bin/java.exe
if exist "%JAVA_EXE%" goto execute
echo. 1>&2
echo ERROR: JAVA_HOME is set to an invalid directory: %JAVA_HOME% 1>&2
echo. 1>&2
echo Please set the JAVA_HOME variable in your environment to match the 1>&2
echo location of your Java installation. 1>&2
goto fail
:execute
@rem Setup the command line
set CLASSPATH=
@rem Execute Gradle
"%JAVA_EXE%" %DEFAULT_JVM_OPTS% %JAVA_OPTS% %GRADLE_OPTS% "-Dorg.gradle.appname=%APP_BASE_NAME%" -classpath "%CLASSPATH%" -jar "%APP_HOME%\gradle\wrapper\gradle-wrapper.jar" %*
: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
backend/settings.gradle Normal file
View File

@@ -0,0 +1 @@
rootProject.name = 'movie-api'

View File

@@ -0,0 +1,11 @@
package ru.ulstu.is.server;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
@SpringBootApplication
public class ServerApplication {
public static void main(String[] args) {
SpringApplication.run(ServerApplication.class, args);
}
}

View File

@@ -0,0 +1,21 @@
package ru.ulstu.is.server.api;
import jakarta.servlet.http.HttpServletRequest;
import org.springframework.http.*;
import org.springframework.web.bind.annotation.*;
@RestControllerAdvice
public class AdviceController {
@ExceptionHandler(NotFoundException.class)
public ResponseEntity<AdviceErrorBody> handleNotFound(NotFoundException ex) {
return ResponseEntity.status(HttpStatus.NOT_FOUND)
.body(new AdviceErrorBody(HttpStatus.NOT_FOUND.value(), ex.getMessage()));
}
@ExceptionHandler(Exception.class)
public ResponseEntity<AdviceErrorBody> handleAnyException(HttpServletRequest request, Throwable ex) {
HttpStatus status = HttpStatus.INTERNAL_SERVER_ERROR;
return new ResponseEntity<>(new AdviceErrorBody(status.value(), ex.getMessage()), status);
}
}

View File

@@ -0,0 +1,3 @@
package ru.ulstu.is.server.api;
public record AdviceErrorBody(int status, String message) { }

View File

@@ -0,0 +1,33 @@
package ru.ulstu.is.server.api;
import jakarta.validation.Valid;
import org.springframework.http.HttpStatus;
import org.springframework.web.bind.annotation.*;
import ru.ulstu.is.server.dto.DirectorRq;
import ru.ulstu.is.server.dto.DirectorRs;
import ru.ulstu.is.server.service.DirectorService;
import java.util.List;
@RestController
@RequestMapping("/api/1.0/directors")
public class DirectorController {
private final DirectorService service;
public DirectorController(DirectorService service) { this.service = service; }
@GetMapping public List<DirectorRs> all() { return service.getAll(); }
@GetMapping("/{id}") public DirectorRs one(@PathVariable Long id) { return service.get(id); }
@PostMapping
@ResponseStatus(HttpStatus.CREATED)
public DirectorRs create(@RequestBody @Valid DirectorRq rq) { return service.create(rq); }
@PutMapping("/{id}")
public DirectorRs update(@PathVariable Long id, @RequestBody @Valid DirectorRq rq) {
return service.update(id, rq);
}
@DeleteMapping("/{id}")
@ResponseStatus(HttpStatus.NO_CONTENT)
public void delete(@PathVariable Long id) { service.delete(id); }
}

View File

@@ -0,0 +1,33 @@
package ru.ulstu.is.server.api;
import jakarta.validation.Valid;
import org.springframework.http.HttpStatus;
import org.springframework.web.bind.annotation.*;
import ru.ulstu.is.server.dto.GenreRq;
import ru.ulstu.is.server.dto.GenreRs;
import ru.ulstu.is.server.service.GenreService;
import java.util.List;
@RestController
@RequestMapping("/api/1.0/genres")
public class GenreController {
private final GenreService service;
public GenreController(GenreService service) { this.service = service; }
@GetMapping public List<GenreRs> all() { return service.getAll(); }
@GetMapping("/{id}") public GenreRs one(@PathVariable Long id) { return service.get(id); }
@PostMapping
@ResponseStatus(HttpStatus.CREATED)
public GenreRs create(@RequestBody @Valid GenreRq rq) { return service.create(rq); }
@PutMapping("/{id}")
public GenreRs update(@PathVariable Long id, @RequestBody @Valid GenreRq rq) {
return service.update(id, rq);
}
@DeleteMapping("/{id}")
@ResponseStatus(HttpStatus.NO_CONTENT)
public void delete(@PathVariable Long id) { service.delete(id); }
}

View File

@@ -0,0 +1,42 @@
package ru.ulstu.is.server.api;
import jakarta.validation.Valid;
import org.springframework.http.HttpStatus;
import org.springframework.web.bind.annotation.*;
import ru.ulstu.is.server.dto.MovieRq;
import ru.ulstu.is.server.dto.MovieRs;
import ru.ulstu.is.server.service.MovieService;
import java.util.List;
@RestController
@RequestMapping("/api/1.0/movies")
public class MovieController {
private final MovieService service;
public MovieController(MovieService service) { this.service = service; }
@GetMapping
public List<MovieRs> all() { return service.getAll(); }
@GetMapping("/{id}")
public MovieRs one(@PathVariable Long id) { return service.get(id); }
@PostMapping
@ResponseStatus(HttpStatus.CREATED)
public MovieRs create(@RequestBody @Valid MovieRq rq) { return service.create(rq); }
@PutMapping("/{id}")
public MovieRs update(@PathVariable Long id, @RequestBody @Valid MovieRq rq) { return service.update(id, rq); }
@GetMapping("/page")
public List<MovieRs> getPage(
@RequestParam(defaultValue = "0") int page,
@RequestParam(defaultValue = "10") int size) {
return service.getPage(page, size);
}
@DeleteMapping("/{id}")
@ResponseStatus(HttpStatus.NO_CONTENT)
public void delete(@PathVariable Long id) { service.delete(id); }
}

View File

@@ -0,0 +1,7 @@
package ru.ulstu.is.server.api;
public class NotFoundException extends RuntimeException {
public <T> NotFoundException(Class<T> clazz, String id) {
super(String.format("%s with id %s is not found", clazz.getSimpleName(), id));
}
}

View File

@@ -0,0 +1,64 @@
package ru.ulstu.is.server.api;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import org.springframework.web.bind.annotation.*;
import ru.ulstu.is.server.repository.*;
import java.util.List;
@RestController
@RequestMapping("/api/1.0/reports")
@Tag(name = "Reports", description = "Отчёты и агрегированные выборки")
public class ReportController {
private final GenreRepository genreRepo;
private final DirectorRepository directorRepo;
private final UserRepository userRepo;
private final SubscriptionRepository subscriptionRepo;
private final MovieRepository movieRepo;
public ReportController(GenreRepository genreRepo,
DirectorRepository directorRepo,
UserRepository userRepo,
SubscriptionRepository subscriptionRepo,
MovieRepository movieRepo) {
this.genreRepo = genreRepo;
this.directorRepo = directorRepo;
this.userRepo = userRepo;
this.subscriptionRepo = subscriptionRepo;
this.movieRepo = movieRepo;
}
@GetMapping("/genres/stats")
@Operation(summary = "Количество фильмов по жанрам")
public List<GenreRepository.GenreStats> genreStats() {
return genreRepo.getGenreStats();
}
@GetMapping("/directors/top")
@Operation(summary = "Топ режиссёров по числу фильмов")
public List<MovieRepository.TopDirectors> topDirectors(
@RequestParam(defaultValue = "10") int limit) {
return movieRepo.findTopDirectors()
.stream().limit(Math.max(limit, 1)).toList();
}
@GetMapping("/subscriptions/usage")
@Operation(summary = "Использование подписок: тариф, цена, число пользователей")
public List<SubscriptionRepository.SubscriptionUsage> subscriptionUsage() {
return subscriptionRepo.usageStats();
}
@GetMapping("/users/by-subscription")
@Operation(summary = "Число пользователей по тарифам")
public List<UserRepository.UsersBySubscription> usersBySubscription() {
return userRepo.countUsersBySubscription();
}
@GetMapping("/users/avg-age-by-subscription")
@Operation(summary = "Средний возраст пользователей по тарифам")
public List<UserRepository.AvgAgeBySubscription> avgAgeBySubscription() {
return userRepo.avgAgeBySubscription();
}
}

View File

@@ -0,0 +1,33 @@
package ru.ulstu.is.server.api;
import jakarta.validation.Valid;
import org.springframework.http.HttpStatus;
import org.springframework.web.bind.annotation.*;
import ru.ulstu.is.server.dto.SubscriptionRq;
import ru.ulstu.is.server.dto.SubscriptionRs;
import ru.ulstu.is.server.service.SubscriptionService;
import java.util.List;
@RestController
@RequestMapping("/api/1.0/subscriptions")
public class SubscriptionController {
private final SubscriptionService service;
public SubscriptionController(SubscriptionService service) { this.service = service; }
@GetMapping public List<SubscriptionRs> all() { return service.getAll(); }
@GetMapping("/{id}") public SubscriptionRs one(@PathVariable Long id) { return service.get(id); }
@PostMapping
@ResponseStatus(HttpStatus.CREATED)
public SubscriptionRs create(@RequestBody @Valid SubscriptionRq rq) { return service.create(rq); }
@PutMapping("/{id}")
public SubscriptionRs update(@PathVariable Long id, @RequestBody @Valid SubscriptionRq rq) {
return service.update(id, rq);
}
@DeleteMapping("/{id}")
@ResponseStatus(HttpStatus.NO_CONTENT)
public void delete(@PathVariable Long id) { service.delete(id); }
}

View File

@@ -0,0 +1,33 @@
package ru.ulstu.is.server.api;
import jakarta.validation.Valid;
import org.springframework.http.HttpStatus;
import org.springframework.web.bind.annotation.*;
import ru.ulstu.is.server.dto.UserRq;
import ru.ulstu.is.server.dto.UserRs;
import ru.ulstu.is.server.service.UserService;
import java.util.List;
@RestController
@RequestMapping("/api/1.0/users")
public class UserController {
private final UserService service;
public UserController(UserService service) { this.service = service; }
@GetMapping public List<UserRs> all() { return service.getAll(); }
@GetMapping("/{id}") public UserRs one(@PathVariable Long id) { return service.get(id); }
@PostMapping
@ResponseStatus(HttpStatus.CREATED)
public UserRs create(@RequestBody @Valid UserRq rq) { return service.create(rq); }
@PutMapping("/{id}")
public UserRs update(@PathVariable Long id, @RequestBody @Valid UserRq rq) {
return service.update(id, rq);
}
@DeleteMapping("/{id}")
@ResponseStatus(HttpStatus.NO_CONTENT)
public void delete(@PathVariable Long id) { service.delete(id); }
}

View File

@@ -0,0 +1,8 @@
package ru.ulstu.is.server.configuration;
public final class Constants {
public static final String DEV_ORIGIN = "http://localhost:5173";
public static final String API_URL = "/api/1.0";
private Constants() { }
}

View File

@@ -0,0 +1,15 @@
package ru.ulstu.is.server.configuration;
import org.springframework.context.annotation.Configuration;
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(CorsRegistry registry) {
registry.addMapping(Constants.API_URL + "/**")
.allowedOrigins(Constants.DEV_ORIGIN)
.allowedMethods("GET", "POST", "PUT", "PATCH", "DELETE");
}
}

View File

@@ -0,0 +1,12 @@
package ru.ulstu.is.server.dto;
import jakarta.validation.constraints.NotBlank;
public class DirectorRefRq {
private String id;
private String name;
public String getId() { return id; }
public void setId(String id) { this.id = id; }
public String getName() { return name; }
public void setName(String name) { this.name = name; }
}

View File

@@ -0,0 +1,10 @@
package ru.ulstu.is.server.dto;
import jakarta.validation.constraints.NotBlank;
public class DirectorRq {
@NotBlank
private String name;
public String getName() { return name; }
public void setName(String name) { this.name = name; }
}

View File

@@ -0,0 +1,14 @@
package ru.ulstu.is.server.dto;
import jakarta.validation.constraints.NotBlank;
public class DirectorRs {
private Long id;
private String name;
public DirectorRs() { }
public DirectorRs(Long id, String name) { this.id = id; this.name = 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; }
}

View File

@@ -0,0 +1,12 @@
package ru.ulstu.is.server.dto;
import jakarta.validation.constraints.NotBlank;
public class GenreRefRq {
private String id;
private String name;
public String getId() { return id; }
public void setId(String id) { this.id = id; }
public String getName() { return name; }
public void setName(String name) { this.name = name; }
}

View File

@@ -0,0 +1,10 @@
package ru.ulstu.is.server.dto;
import jakarta.validation.constraints.NotBlank;
public class GenreRq {
@NotBlank
private String name;
public String getName() { return name; }
public void setName(String name) { this.name = name; }
}

View File

@@ -0,0 +1,14 @@
package ru.ulstu.is.server.dto;
import jakarta.validation.constraints.NotBlank;
public class GenreRs {
private Long id;
private String name;
public GenreRs() { }
public GenreRs(Long id, String name) { this.id = id; this.name = 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; }
}

View File

@@ -0,0 +1,26 @@
package ru.ulstu.is.server.dto;
import jakarta.validation.Valid;
import jakarta.validation.constraints.NotBlank;
import jakarta.validation.constraints.NotNull;
public class MovieRq {
@NotBlank
private String title;
private String image;
@NotNull @Valid
private GenreRefRq genre;
@NotNull @Valid
private DirectorRefRq director;
public String getTitle() { return title; }
public void setTitle(String title) { this.title = title; }
public String getImage() { return image; }
public void setImage(String image) { this.image = image; }
public GenreRefRq getGenre() { return genre; }
public void setGenre(GenreRefRq genre) { this.genre = genre; }
public DirectorRefRq getDirector() { return director; }
public void setDirector(DirectorRefRq director) { this.director = director; }
}

View File

@@ -0,0 +1,25 @@
package ru.ulstu.is.server.dto;
import jakarta.validation.Valid;
import jakarta.validation.constraints.NotBlank;
import jakarta.validation.constraints.NotNull;
public class MovieRs {
private Long id;
private String title;
private String image;
private GenreRs genre;
private DirectorRs director;
public Long getId() { return id; }
public void setId(Long id) { this.id = id; }
public String getTitle() { return title; }
public void setTitle(String title) { this.title = title; }
public String getImage() { return image; }
public void setImage(String image) { this.image = image; }
public GenreRs getGenre() { return genre; }
public void setGenre(GenreRs genre) { this.genre = genre; }
public DirectorRs getDirector() { return director; }
public void setDirector(DirectorRs director) { this.director = director; }
}

View File

@@ -0,0 +1,15 @@
package ru.ulstu.is.server.dto;
import jakarta.validation.constraints.NotBlank;
public class SubscriptionRefRq {
private String id;
private String level;
private Integer price;
public String getId() { return id; }
public void setId(String id) { this.id = id; }
public String getLevel() { return level; }
public void setLevel(String level) { this.level = level; }
public Integer getPrice() { return price; }
public void setPrice(Integer price) { this.price = price; }
}

View File

@@ -0,0 +1,16 @@
package ru.ulstu.is.server.dto;
import jakarta.validation.constraints.Min;
import jakarta.validation.constraints.NotBlank;
import jakarta.validation.constraints.NotNull;
public class SubscriptionRq {
@NotBlank
private String level;
@NotNull @Min(0)
private Integer price;
public String getLevel() { return level; }
public void setLevel(String level) { this.level = level; }
public Integer getPrice() { return price; }
public void setPrice(Integer price) { this.price = price; }
}

View File

@@ -0,0 +1,21 @@
package ru.ulstu.is.server.dto;
import jakarta.validation.constraints.Min;
import jakarta.validation.constraints.NotBlank;
import jakarta.validation.constraints.NotNull;
public class SubscriptionRs {
private Long id;
private String level;
private Integer price;
public SubscriptionRs() { }
public SubscriptionRs(Long id, String level, Integer price) {
this.id = id; this.level = level; this.price = price;
}
public Long getId() { return id; }
public void setId(Long id) { this.id = id; }
public String getLevel() { return level; }
public void setLevel(String level) { this.level = level; }
public Integer getPrice() { return price; }
public void setPrice(Integer price) { this.price = price; }
}

View File

@@ -0,0 +1,44 @@
package ru.ulstu.is.server.dto;
import jakarta.validation.Valid;
import jakarta.validation.constraints.Email;
import jakarta.validation.constraints.NotBlank;
import java.util.ArrayList;
import java.util.List;
public class UserRq {
@NotBlank private String name;
@NotBlank @Email private String login;
@NotBlank private String password;
private Boolean isAdmin = false;
private Integer age;
private String gender;
private String avatar;
private String subscriptionUntil;
@Valid private SubscriptionRefRq subscription;
private List<Long> watchlist = new ArrayList<>();
public String getName() { return name; }
public void setName(String name) { this.name = name; }
public String getLogin() { return login; }
public void setLogin(String login) { this.login = login; }
public String getPassword() { return password; }
public void setPassword(String password) { this.password = password; }
public Boolean getIsAdmin() { return isAdmin; }
public void setIsAdmin(Boolean isAdmin) { this.isAdmin = isAdmin; }
public Integer getAge() { return age; }
public void setAge(Integer age) { this.age = age; }
public String getGender() { return gender; }
public void setGender(String gender) { this.gender = gender; }
public String getAvatar() { return avatar; }
public void setAvatar(String avatar) { this.avatar = avatar; }
public String getSubscriptionUntil() { return subscriptionUntil; }
public void setSubscriptionUntil(String subscriptionUntil) { this.subscriptionUntil = subscriptionUntil; }
public SubscriptionRefRq getSubscription() { return subscription; }
public void setSubscription(SubscriptionRefRq subscription) { this.subscription = subscription; }
public List<Long> getWatchlist() { return watchlist; }
public void setWatchlist(List<Long> watchlist) { this.watchlist = watchlist; }
}

View File

@@ -0,0 +1,43 @@
package ru.ulstu.is.server.dto;
import jakarta.validation.Valid;
import jakarta.validation.constraints.Email;
import jakarta.validation.constraints.NotBlank;
import java.util.ArrayList;
import java.util.List;
public class UserRs {
private Long id;
private String name;
private String login;
private Boolean isAdmin;
private Integer age;
private String gender;
private String avatar;
private String subscriptionUntil;
private SubscriptionRs subscription;
private List<Long> watchlist;
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 String getLogin() { return login; }
public void setLogin(String login) { this.login = login; }
public Boolean getIsAdmin() { return isAdmin; }
public void setIsAdmin(Boolean isAdmin) { this.isAdmin = isAdmin; }
public Integer getAge() { return age; }
public void setAge(Integer age) { this.age = age; }
public String getGender() { return gender; }
public void setGender(String gender) { this.gender = gender; }
public String getAvatar() { return avatar; }
public void setAvatar(String avatar) { this.avatar = avatar; }
public String getSubscriptionUntil() { return subscriptionUntil; }
public void setSubscriptionUntil(String subscriptionUntil) { this.subscriptionUntil = subscriptionUntil; }
public SubscriptionRs getSubscription() { return subscription; }
public void setSubscription(SubscriptionRs subscription) { this.subscription = subscription; }
public List<Long> getWatchlist() { return watchlist; }
public void setWatchlist(List<Long> watchlist) { this.watchlist = watchlist; }
}

View File

@@ -0,0 +1,18 @@
package ru.ulstu.is.server.entity;
import jakarta.persistence.*;
@MappedSuperclass
public abstract class BaseEntity {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
public BaseEntity() { }
public BaseEntity(Long id) { this.id = id; }
public Long getId() { return id; }
public void setId(Long id) { this.id = id; }
}

View File

@@ -0,0 +1,33 @@
package ru.ulstu.is.server.entity;
import jakarta.persistence.*;
import java.util.ArrayList;
import java.util.List;
@Entity
@Table(name = "directors")
public class Director extends BaseEntity {
@Column(nullable = false, unique = true)
private String name;
@OneToMany(mappedBy = "director", cascade = CascadeType.ALL, orphanRemoval = false)
private List<Movie> movies = new ArrayList<>();
public Director() {}
public Director(Long id, String name) { setId(id); this.name = name; }
public void addMovie(Movie m) {
if (m == null) return;
movies.add(m);
m.setDirector(this);
}
public void removeMovie(Movie m) {
if (m == null) return;
movies.remove(m);
if (m.getDirector() == this) m.setDirector(null);
}
public String getName() { return name; }
public void setName(String name) { this.name = name; }
public List<Movie> getMovies() { return movies; }
}

View File

@@ -0,0 +1,33 @@
package ru.ulstu.is.server.entity;
import jakarta.persistence.*;
import java.util.ArrayList;
import java.util.List;
@Entity
@Table(name = "genres")
public class Genre extends BaseEntity {
@Column(nullable = false, unique = true)
private String name;
@OneToMany(mappedBy = "genre", cascade = CascadeType.ALL, orphanRemoval = false)
private List<Movie> movies = new ArrayList<>();
public Genre() {}
public Genre(Long id, String name) { setId(id); this.name = name; }
public void addMovie(Movie m) {
if (m == null) return;
movies.add(m);
m.setGenre(this);
}
public void removeMovie(Movie m) {
if (m == null) return;
movies.remove(m);
if (m.getGenre() == this) m.setGenre(null);
}
public String getName() { return name; }
public void setName(String name) { this.name = name; }
public List<Movie> getMovies() { return movies; }
}

View File

@@ -0,0 +1,42 @@
package ru.ulstu.is.server.entity;
import jakarta.persistence.*;
import ru.ulstu.is.server.entity.Genre;
import ru.ulstu.is.server.entity.Director;
@Entity
@Table(name = "movies")
public class Movie extends BaseEntity {
@Column(nullable = false)
private String title;
@Lob
@Column(columnDefinition = "CLOB")
private String image;
@ManyToOne(fetch = FetchType.LAZY)
@JoinColumn(name = "genre_id", nullable = false)
private Genre genre;
@ManyToOne(fetch = FetchType.LAZY)
@JoinColumn(name = "director_id", nullable = false)
private Director director;
public Movie() {}
public Movie(Long id, String title, String image, Genre genre, Director director) {
setId(id);
this.title = title;
this.image = image;
this.genre = genre;
this.director = director;
}
public String getTitle() { return title; }
public void setTitle(String title) { this.title = title; }
public String getImage() { return image; }
public void setImage(String image) { this.image = image; }
public Genre getGenre() { return genre; }
public void setGenre(Genre genre) { this.genre = genre; }
public Director getDirector() { return director; }
public void setDirector(Director director) { this.director = director; }
}

View File

@@ -0,0 +1,47 @@
package ru.ulstu.is.server.entity;
import jakarta.persistence.*;
import java.util.ArrayList;
import java.util.List;
@Entity
@Table(name = "subscriptions")
public class Subscription extends BaseEntity {
@Column(nullable = false, unique = true)
private String level;
@Column(nullable = false)
private Integer price;
@OneToMany(mappedBy = "subscription", orphanRemoval = false)
private List<User> users = new ArrayList<>();
public Subscription() { }
public Subscription(Long id, String level, Integer price) {
super(id);
this.level = level;
this.price = price;
}
public void addUser(User u) {
if (u == null) return;
users.add(u);
u.setSubscription(this);
}
public void removeUser(User u) {
if (u == null) return;
users.remove(u);
if (u.getSubscription() == this) {
u.setSubscription(null);
}
}
public String getLevel() { return level; }
public void setLevel(String level) { this.level = level; }
public Integer getPrice() { return price; }
public void setPrice(Integer price) { this.price = price; }
public List<User> getUsers() { return users; }
}

View File

@@ -0,0 +1,98 @@
package ru.ulstu.is.server.entity;
import jakarta.persistence.*;
import java.time.LocalDate;
import java.util.ArrayList;
import java.util.List;
@Entity
@Table(name = "users")
public class User extends BaseEntity {
@Column(nullable = false)
private String name;
@Column(nullable = false, unique = true)
private String login;
@Column(nullable = false)
private String password;
@Column(nullable = false)
private Boolean isAdmin = false;
@Column
private Integer age;
@Column
private String gender;
@Lob
@Column(columnDefinition = "CLOB")
private String avatar;
@ManyToOne(fetch = FetchType.LAZY)
@JoinColumn(name = "subscription_id")
private Subscription subscription;
@Column(name = "subscription_until")
private LocalDate subscriptionUntil;
@ManyToMany
@JoinTable(
name = "user_watchlist",
joinColumns = @JoinColumn(name = "user_id"),
inverseJoinColumns = @JoinColumn(name = "movie_id")
)
private List<Movie> watchlist = new ArrayList<>();
public User() { }
public User(Long id, String name, String login, String password, Boolean isAdmin) {
super(id);
this.name = name;
this.login = login;
this.password = password;
this.isAdmin = isAdmin;
}
public void addToWatchlist(Movie m) {
if (m == null) return;
if (!watchlist.contains(m)) watchlist.add(m);
}
public void removeFromWatchlist(Movie m) {
if (m == null) return;
watchlist.remove(m);
}
public String getName() { return name; }
public void setName(String name) { this.name = name; }
public String getLogin() { return login; }
public void setLogin(String login) { this.login = login; }
public String getPassword() { return password; }
public void setPassword(String password) { this.password = password; }
public Boolean getIsAdmin() { return isAdmin; }
public void setIsAdmin(Boolean isAdmin) { this.isAdmin = isAdmin; }
public Integer getAge() { return age; }
public void setAge(Integer age) { this.age = age; }
public String getGender() { return gender; }
public void setGender(String gender) { this.gender = gender; }
public String getAvatar() { return avatar; }
public void setAvatar(String avatar) { this.avatar = avatar; }
public Subscription getSubscription() { return subscription; }
public void setSubscription(Subscription subscription) { this.subscription = subscription; }
public LocalDate getSubscriptionUntil() { return subscriptionUntil; }
public void setSubscriptionUntil(LocalDate subscriptionUntil) { this.subscriptionUntil = subscriptionUntil; }
public List<Movie> getWatchlist() { return watchlist; }
public void setWatchlist(List<Movie> watchlist) { this.watchlist = watchlist != null ? watchlist : new ArrayList<>(); }
}

View File

@@ -0,0 +1,22 @@
package ru.ulstu.is.server.mapper;
import org.springframework.stereotype.Component;
import ru.ulstu.is.server.dto.DirectorRq;
import ru.ulstu.is.server.dto.DirectorRs;
import ru.ulstu.is.server.entity.Director;
import ru.ulstu.is.server.repository.SubscriptionRepository;
@Component
public class DirectorMapper {
public Director toEntity(DirectorRq rq) {
Director d = new Director();
d.setName(rq.getName());
return d;
}
public void updateEntity(Director d, DirectorRq rq) {
d.setName(rq.getName());
}
public DirectorRs toRs(Director d) {
return new DirectorRs(d.getId(), d.getName());
}
}

View File

@@ -0,0 +1,21 @@
package ru.ulstu.is.server.mapper;
import org.springframework.stereotype.Component;
import ru.ulstu.is.server.dto.GenreRq;
import ru.ulstu.is.server.dto.GenreRs;
import ru.ulstu.is.server.entity.Genre;
@Component
public class GenreMapper {
public Genre toEntity(GenreRq rq) {
Genre g = new Genre();
g.setName(rq.getName());
return g;
}
public void updateEntity(Genre g, GenreRq rq) {
g.setName(rq.getName());
}
public GenreRs toRs(Genre g) {
return new GenreRs(g.getId(), g.getName());
}
}

View File

@@ -0,0 +1,68 @@
package ru.ulstu.is.server.mapper;
import org.springframework.stereotype.Component;
import ru.ulstu.is.server.dto.*;
import ru.ulstu.is.server.entity.*;
import ru.ulstu.is.server.repository.DirectorRepository;
import ru.ulstu.is.server.repository.GenreRepository;
@Component
public class MovieMapper {
private final GenreRepository genreRepo;
private final DirectorRepository directorRepo;
public MovieMapper(GenreRepository genreRepo, DirectorRepository directorRepo) {
this.genreRepo = genreRepo;
this.directorRepo = directorRepo;
}
public Movie toEntity(MovieRq rq) {
Movie e = new Movie();
e.setTitle(rq.getTitle());
e.setImage(rq.getImage());
GenreRefRq gRef = rq.getGenre();
e.setGenre(resolveGenre(gRef));
DirectorRefRq dRef = rq.getDirector();
e.setDirector(resolveDirector(dRef));
return e;
}
public MovieRs toRs(Movie e) {
MovieRs rs = new MovieRs();
rs.setId(e.getId());
rs.setTitle(e.getTitle());
rs.setImage(e.getImage());
Genre g = e.getGenre();
if (g != null) rs.setGenre(new GenreRs(g.getId(), g.getName()));
Director d = e.getDirector();
if (d != null) rs.setDirector(new DirectorRs(d.getId(), d.getName()));
return rs;
}
private Genre resolveGenre(GenreRefRq ref) {
if (ref == null) return null;
Long id = parseId(ref.getId());
if (id != null) return genreRepo.findById(id).orElse(null);
if (ref.getName() != null) return new Genre(null, ref.getName());
return null;
}
private Director resolveDirector(DirectorRefRq ref) {
if (ref == null) return null;
Long id = parseId(ref.getId());
if (id != null) return directorRepo.findById(id).orElse(null);
if (ref.getName() != null) return new Director(null, ref.getName());
return null;
}
private Long parseId(String s) {
try { return s == null ? null : Long.parseLong(s); }
catch (NumberFormatException e) { return null; }
}
}

View File

@@ -0,0 +1,23 @@
package ru.ulstu.is.server.mapper;
import org.springframework.stereotype.Component;
import ru.ulstu.is.server.dto.SubscriptionRq;
import ru.ulstu.is.server.dto.SubscriptionRs;
import ru.ulstu.is.server.entity.Subscription;
@Component
public class SubscriptionMapper {
public Subscription toEntity(SubscriptionRq rq) {
Subscription s = new Subscription();
s.setLevel(rq.getLevel());
s.setPrice(rq.getPrice());
return s;
}
public void updateEntity(Subscription s, SubscriptionRq rq) {
s.setLevel(rq.getLevel());
s.setPrice(rq.getPrice());
}
public SubscriptionRs toRs(Subscription s) {
return new SubscriptionRs(s.getId(), s.getLevel(), s.getPrice());
}
}

View File

@@ -0,0 +1,120 @@
package ru.ulstu.is.server.mapper;
import org.springframework.stereotype.Component;
import ru.ulstu.is.server.dto.*;
import ru.ulstu.is.server.entity.Movie;
import ru.ulstu.is.server.entity.Subscription;
import ru.ulstu.is.server.entity.User;
import ru.ulstu.is.server.repository.MovieRepository;
import ru.ulstu.is.server.repository.SubscriptionRepository;
import java.time.LocalDate;
import java.time.format.DateTimeFormatter;
import java.util.ArrayList;
import java.util.List;
@Component
public class UserMapper {
private final SubscriptionRepository subscriptionRepository;
private final MovieRepository movieRepository;
private static final DateTimeFormatter DF = DateTimeFormatter.ISO_DATE;
public UserMapper(SubscriptionRepository subscriptionRepository,
MovieRepository movieRepository) {
this.subscriptionRepository = subscriptionRepository;
this.movieRepository = movieRepository;
}
public User toEntity(UserRq rq) {
User u = new User();
updateEntity(u, rq);
return u;
}
public void updateEntity(User u, UserRq rq) {
if (rq.getName() != null) u.setName(rq.getName());
if (rq.getLogin() != null) u.setLogin(rq.getLogin());
if (rq.getPassword() != null) u.setPassword(rq.getPassword());
if (rq.getIsAdmin() != null) u.setIsAdmin(rq.getIsAdmin());
if (rq.getAge() != null) u.setAge(rq.getAge());
if (rq.getGender() != null) u.setGender(rq.getGender());
if (rq.getAvatar() != null) u.setAvatar(rq.getAvatar());
if (rq.getSubscriptionUntil() != null) {
u.setSubscriptionUntil(parseDate(rq.getSubscriptionUntil()));
}
if (rq.getSubscription() != null) {
u.setSubscription(resolveSubscription(rq.getSubscription()));
}
if (rq.getWatchlist() != null) {
u.setWatchlist(resolveMovies(rq.getWatchlist()));
}
}
public UserRs toRs(User u) {
UserRs rs = new UserRs();
rs.setId(u.getId());
rs.setName(u.getName());
rs.setLogin(u.getLogin());
rs.setIsAdmin(u.getIsAdmin());
rs.setAge(u.getAge());
rs.setGender(u.getGender());
rs.setAvatar(u.getAvatar());
rs.setSubscriptionUntil(formatDate(u.getSubscriptionUntil()));
if (u.getSubscription() != null) {
Subscription s = u.getSubscription();
SubscriptionRs srs = new SubscriptionRs();
srs.setId(s.getId());
srs.setLevel(s.getLevel());
srs.setPrice(s.getPrice());
rs.setSubscription(srs);
}
if (u.getWatchlist() != null) {
rs.setWatchlist(u.getWatchlist().stream().map(Movie::getId).toList());
} else {
rs.setWatchlist(new ArrayList<>());
}
return rs;
}
private LocalDate parseDate(String s) {
try { return s == null ? null : LocalDate.parse(s, DF); }
catch (Exception ex) { return null; }
}
private String formatDate(LocalDate d) { return d == null ? null : DF.format(d); }
private Subscription resolveSubscription(SubscriptionRefRq ref) {
if (ref == null) return null;
Long id = tryParseLong(ref.getId());
if (id != null) {
return subscriptionRepository.findById(id).orElse(null);
}
if (ref.getLevel() != null) {
return subscriptionRepository.findByLevel(ref.getLevel())
.orElseGet(() -> subscriptionRepository.save(new Subscription(null, ref.getLevel(), ref.getPrice())));
}
return null;
}
private List<Movie> resolveMovies(List<Long> ids) {
List<Movie> list = new ArrayList<>();
if (ids == null) return list;
for (Long id : ids) {
movieRepository.findById(id).ifPresent(list::add);
}
return list;
}
private Long tryParseLong(String s) {
try { return s == null ? null : Long.parseLong(s); }
catch (NumberFormatException e) { return null; }
}
}

View File

@@ -0,0 +1,22 @@
package ru.ulstu.is.server.repository;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.jpa.repository.Query;
import ru.ulstu.is.server.entity.Director;
import java.util.List;
import java.util.Optional;
public interface DirectorRepository extends JpaRepository<Director, Long> {
Optional<Director> findByName(String name);
@Query("""
select d.name as director, count(m.id) as moviesCount
from Director d left join d.movies m
group by d.name
order by moviesCount desc
""")
List<DirectorStats> getDirectorStats();
interface DirectorStats { String getDirector(); long getMoviesCount(); }
}

View File

@@ -0,0 +1,22 @@
package ru.ulstu.is.server.repository;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.jpa.repository.Query;
import ru.ulstu.is.server.entity.Genre;
import java.util.List;
import java.util.Optional;
public interface GenreRepository extends JpaRepository<Genre, Long> {
Optional<Genre> findByName(String name);
@Query("""
select g.name as genre, count(m.id) as moviesCount
from Genre g left join g.movies m
group by g.name
order by moviesCount desc
""")
List<GenreStats> getGenreStats();
interface GenreStats { String getGenre(); long getMoviesCount(); }
}

View File

@@ -0,0 +1,24 @@
package ru.ulstu.is.server.repository;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.jpa.repository.Query;
import ru.ulstu.is.server.entity.Movie;
import java.util.List;
public interface MovieRepository extends JpaRepository<Movie, Long> {
Page<Movie> findAll(Pageable pageable);
List<Movie> findByGenre_Name(String name);
List<Movie> findByDirector_Name(String name);
@Query("""
select m.director.name as director, count(m.id) as moviesCount
from Movie m group by m.director.name order by moviesCount desc
""")
List<TopDirectors> findTopDirectors();
interface TopDirectors { String getDirector(); long getMoviesCount(); }
}

View File

@@ -0,0 +1,26 @@
package ru.ulstu.is.server.repository;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.jpa.repository.Query;
import ru.ulstu.is.server.entity.Subscription;
import java.util.List;
import java.util.Optional;
public interface SubscriptionRepository extends JpaRepository<Subscription, Long> {
Optional<Subscription> findByLevel(String level);
@Query("""
select s.level as level, s.price as price, count(u.id) as usersCount
from Subscription s left join s.users u
group by s.level, s.price
order by usersCount desc
""")
List<SubscriptionUsage> usageStats();
interface SubscriptionUsage {
String getLevel();
Integer getPrice();
long getUsersCount();
}
}

View File

@@ -0,0 +1,43 @@
package ru.ulstu.is.server.repository;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.jpa.repository.Query;
import ru.ulstu.is.server.entity.User;
import java.util.List;
import java.util.Optional;
public interface UserRepository extends JpaRepository<User, Long> {
Optional<User> findByLogin(String login);
List<User> findByIsAdmin(boolean isAdmin);
List<User> findBySubscription_Level(String level);
List<User> findByAgeGreaterThanEqual(Integer age);
@Query("""
select s.level as level, count(u.id) as usersCount
from User u join u.subscription s
group by s.level
order by usersCount desc
""")
List<UsersBySubscription> countUsersBySubscription();
interface UsersBySubscription {
String getLevel();
long getUsersCount();
}
@Query("""
select s.level as level, avg(u.age) as avgAge
from User u join u.subscription s
where u.age is not null
group by s.level
order by avgAge desc
""")
List<AvgAgeBySubscription> avgAgeBySubscription();
interface AvgAgeBySubscription {
String getLevel();
Double getAvgAge();
}
}

View File

@@ -0,0 +1,55 @@
package ru.ulstu.is.server.service;
import org.springframework.stereotype.Service;
import ru.ulstu.is.server.api.NotFoundException;
import ru.ulstu.is.server.dto.DirectorRq;
import ru.ulstu.is.server.dto.DirectorRs;
import ru.ulstu.is.server.entity.Director;
import ru.ulstu.is.server.mapper.DirectorMapper;
import ru.ulstu.is.server.repository.DirectorRepository;
import org.springframework.transaction.annotation.Transactional;
import java.util.List;
@Service
@Transactional
public class DirectorService {
private final DirectorRepository repo;
private final DirectorMapper mapper;
public DirectorService(DirectorRepository repo, DirectorMapper mapper) {
this.repo = repo; this.mapper = mapper;
}
@Transactional(readOnly = true)
public List<DirectorRs> getAll() {
return repo.findAll().stream().map(mapper::toRs).toList();
}
@Transactional(readOnly = true)
public DirectorRs get(Long id) {
return mapper.toRs(getEntity(id));
}
public DirectorRs create(DirectorRq rq) {
Director d = mapper.toEntity(rq);
d = repo.save(d);
return mapper.toRs(d);
}
public DirectorRs update(Long id, DirectorRq rq) {
Director d = getEntity(id);
mapper.updateEntity(d, rq);
d = repo.save(d);
return mapper.toRs(d);
}
public void delete(Long id) {
getEntity(id);
repo.deleteById(id);
}
Director getEntity(Long id) {
return repo.findById(id).orElseThrow(() -> new NotFoundException(Director.class, String.valueOf(id)));
}
}

View File

@@ -0,0 +1,55 @@
package ru.ulstu.is.server.service;
import org.springframework.stereotype.Service;
import ru.ulstu.is.server.api.NotFoundException;
import ru.ulstu.is.server.dto.GenreRq;
import ru.ulstu.is.server.dto.GenreRs;
import ru.ulstu.is.server.entity.Genre;
import ru.ulstu.is.server.mapper.GenreMapper;
import ru.ulstu.is.server.repository.GenreRepository;
import org.springframework.transaction.annotation.Transactional;
import java.util.List;
@Service
@Transactional
public class GenreService {
private final GenreRepository repo;
private final GenreMapper mapper;
public GenreService(GenreRepository repo, GenreMapper mapper) {
this.repo = repo; this.mapper = mapper;
}
@Transactional(readOnly = true)
public List<GenreRs> getAll() {
return repo.findAll().stream().map(mapper::toRs).toList();
}
@Transactional(readOnly = true)
public GenreRs get(Long id) {
return mapper.toRs(getEntity(id));
}
public GenreRs create(GenreRq rq) {
Genre g = mapper.toEntity(rq);
g = repo.save(g);
return mapper.toRs(g);
}
public GenreRs update(Long id, GenreRq rq) {
Genre g = getEntity(id);
mapper.updateEntity(g, rq);
g = repo.save(g);
return mapper.toRs(g);
}
public void delete(Long id) {
getEntity(id);
repo.deleteById(id);
}
Genre getEntity(Long id) {
return repo.findById(id).orElseThrow(() -> new NotFoundException(Genre.class, String.valueOf(id)));
}
}

View File

@@ -0,0 +1,107 @@
package ru.ulstu.is.server.service;
import org.springframework.data.domain.PageRequest;
import org.springframework.stereotype.Service;
import ru.ulstu.is.server.api.NotFoundException;
import ru.ulstu.is.server.dto.*;
import ru.ulstu.is.server.entity.Movie;
import ru.ulstu.is.server.entity.Genre;
import ru.ulstu.is.server.entity.Director;
import ru.ulstu.is.server.mapper.MovieMapper;
import ru.ulstu.is.server.repository.MovieRepository;
import ru.ulstu.is.server.repository.GenreRepository;
import ru.ulstu.is.server.repository.DirectorRepository;
import org.springframework.transaction.annotation.Transactional;
import java.util.List;
@Service
@Transactional
public class MovieService {
private final MovieRepository movies;
private final GenreRepository genres;
private final DirectorRepository directors;
private final MovieMapper mapper;
public MovieService(MovieRepository movies, GenreRepository genres,
DirectorRepository directors, MovieMapper mapper) {
this.movies = movies;
this.genres = genres;
this.directors = directors;
this.mapper = mapper;
}
@Transactional(readOnly = true)
public List<MovieRs> getAll() {
return movies.findAll().stream().map(mapper::toRs).toList();
}
@Transactional(readOnly = true)
public List<MovieRs> getPage(int page, int size) {
return movies.findAll(PageRequest.of(page, size))
.map(mapper::toRs)
.toList();
}
@Transactional(readOnly = true)
public MovieRs get(Long id) {
Movie m = movies.findById(id).orElseThrow(() -> new NotFoundException(ru.ulstu.is.server.entity.Movie.class, "movie " + id + " not found"));
return mapper.toRs(m);
}
public MovieRs create(MovieRq rq) {
Movie e = new Movie();
e.setTitle(rq.getTitle());
e.setImage(rq.getImage());
Genre g = resolveGenre(rq.getGenre());
Director d = resolveDirector(rq.getDirector());
e.setGenre(g);
e.setDirector(d);
Movie saved = movies.save(e);
return mapper.toRs(saved);
}
public MovieRs update(Long id, MovieRq rq) {
Movie e = movies.findById(id).orElseThrow(() -> new NotFoundException(ru.ulstu.is.server.entity.Movie.class, "movie " + id + " not found"));
e.setTitle(rq.getTitle());
e.setImage(rq.getImage());
if (rq.getGenre() != null) e.setGenre(resolveGenre(rq.getGenre()));
if (rq.getDirector() != null) e.setDirector(resolveDirector(rq.getDirector()));
return mapper.toRs(movies.save(e));
}
public void delete(Long id) {
movies.deleteById(id);
}
private Genre resolveGenre(GenreRefRq ref) {
if (ref == null) return null;
if (ref.getId() != null) {
Long id = tryParse(ref.getId());
if (id != null) return genres.findById(id).orElseThrow();
}
if (ref.getName() != null) return genres.findByName(ref.getName()).orElseGet(() ->
genres.save(new Genre(null, ref.getName())));
return null;
}
private Director resolveDirector(DirectorRefRq ref) {
if (ref == null) return null;
if (ref.getId() != null) {
Long id = tryParse(ref.getId());
if (id != null) return directors.findById(id).orElseThrow();
}
if (ref.getName() != null) return directors.findByName(ref.getName()).orElseGet(() ->
directors.save(new Director(null, ref.getName())));
return null;
}
private Long tryParse(String s) {
try { return s == null ? null : Long.parseLong(s); } catch (NumberFormatException e) { return null; }
}
}

View File

@@ -0,0 +1,55 @@
package ru.ulstu.is.server.service;
import org.springframework.stereotype.Service;
import ru.ulstu.is.server.api.NotFoundException;
import ru.ulstu.is.server.dto.SubscriptionRq;
import ru.ulstu.is.server.dto.SubscriptionRs;
import ru.ulstu.is.server.entity.Subscription;
import ru.ulstu.is.server.mapper.SubscriptionMapper;
import ru.ulstu.is.server.repository.SubscriptionRepository;
import org.springframework.transaction.annotation.Transactional;
import java.util.List;
@Service
@Transactional
public class SubscriptionService {
private final SubscriptionRepository repo;
private final SubscriptionMapper mapper;
public SubscriptionService(SubscriptionRepository repo, SubscriptionMapper mapper) {
this.repo = repo; this.mapper = mapper;
}
@Transactional(readOnly = true)
public List<SubscriptionRs> getAll() {
return repo.findAll().stream().map(mapper::toRs).toList();
}
@Transactional(readOnly = true)
public SubscriptionRs get(Long id) {
return mapper.toRs(getEntity(id));
}
public SubscriptionRs create(SubscriptionRq rq) {
Subscription s = mapper.toEntity(rq);
s = repo.save(s);
return mapper.toRs(s);
}
public SubscriptionRs update(Long id, SubscriptionRq rq) {
Subscription s = getEntity(id);
mapper.updateEntity(s, rq);
s = repo.save(s);
return mapper.toRs(s);
}
public void delete(Long id) {
getEntity(id);
repo.deleteById(id);
}
Subscription getEntity(Long id) {
return repo.findById(id).orElseThrow(() -> new NotFoundException(Subscription.class, String.valueOf(id)));
}
}

View File

@@ -0,0 +1,55 @@
package ru.ulstu.is.server.service;
import org.springframework.stereotype.Service;
import ru.ulstu.is.server.api.NotFoundException;
import ru.ulstu.is.server.dto.UserRq;
import ru.ulstu.is.server.dto.UserRs;
import ru.ulstu.is.server.entity.User;
import ru.ulstu.is.server.mapper.UserMapper;
import ru.ulstu.is.server.repository.UserRepository;
import org.springframework.transaction.annotation.Transactional;
import java.util.List;
@Service
@Transactional
public class UserService {
private final UserRepository repo;
private final UserMapper mapper;
public UserService(UserRepository repo, UserMapper mapper) {
this.repo = repo; this.mapper = mapper;
}
@Transactional(readOnly = true)
public List<UserRs> getAll() {
return repo.findAll().stream().map(mapper::toRs).toList();
}
@Transactional(readOnly = true)
public UserRs get(Long id) {
return mapper.toRs(getEntity(id));
}
public UserRs create(UserRq rq) {
User u = mapper.toEntity(rq);
u = repo.save(u);
return mapper.toRs(u);
}
public UserRs update(Long id, UserRq rq) {
User u = getEntity(id);
mapper.updateEntity(u, rq);
u = repo.save(u);
return mapper.toRs(u);
}
public void delete(Long id) {
getEntity(id);
repo.deleteById(id);
}
User getEntity(Long id) {
return repo.findById(id).orElseThrow(() -> new NotFoundException(User.class, String.valueOf(id)));
}
}

View File

@@ -0,0 +1,18 @@
spring.main.banner-mode=off
spring.application.name=server
server.port=8080
spring.datasource.url=jdbc:h2:file:./data/appdb
spring.datasource.driverClassName=org.h2.Driver
spring.datasource.username=sa
spring.datasource.password=
spring.jpa.hibernate.ddl-auto=update
spring.jpa.show-sql=true
spring.jpa.properties.hibernate.format_sql=true
spring.h2.console.enabled=true
spring.h2.console.path=/h2
# logging
logging.level.ru.ulstu.is.server=DEBUG

View File

@@ -0,0 +1,45 @@
package ru.ulstu.is.server;
import org.junit.jupiter.api.*;
import org.junit.jupiter.api.MethodOrderer.OrderAnnotation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import ru.ulstu.is.server.api.NotFoundException;
import ru.ulstu.is.server.dto.DirectorRq;
import ru.ulstu.is.server.dto.DirectorRs;
import ru.ulstu.is.server.service.DirectorService;
@SpringBootTest
@TestMethodOrder(OrderAnnotation.class)
class DirectorServiceTests {
@Autowired
private DirectorService service;
@Test
void getNotFound() {
Assertions.assertThrows(NotFoundException.class, () -> service.get(0L));
}
@Test @Order(1)
void createTest() {
service.create(new DirectorRq() {{ setName("Кристофер Нолан"); }});
service.create(new DirectorRq() {{ setName("Лана Вачовски"); }});
DirectorRs last = service.create(new DirectorRq() {{ setName("Дени Вильнёв"); }});
Assertions.assertEquals(3, service.getAll().size());
Assertions.assertEquals("Дени Вильнёв", service.get(last.getId()).getName());
}
@Test @Order(2)
void updateTest() {
DirectorRs upd = service.update(3L, new DirectorRq() {{ setName("Дени Вильнёв (FR)"); }});
Assertions.assertEquals("Дени Вильнёв (FR)", upd.getName());
}
@Test @Order(3)
void deleteTest() {
service.delete(3L);
Assertions.assertEquals(2, service.getAll().size());
}
}

View File

@@ -0,0 +1,50 @@
package ru.ulstu.is.server;
import org.junit.jupiter.api.*;
import org.junit.jupiter.api.MethodOrderer.OrderAnnotation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import ru.ulstu.is.server.api.NotFoundException;
import ru.ulstu.is.server.dto.GenreRq;
import ru.ulstu.is.server.dto.GenreRs;
import ru.ulstu.is.server.service.GenreService;
@SpringBootTest
@TestMethodOrder(OrderAnnotation.class)
class GenreServiceTests {
@Autowired
private GenreService service;
@Test
void getNotFound() {
Assertions.assertThrows(NotFoundException.class, () -> service.get(0L));
}
@Test @Order(1)
void createTest() {
service.create(new GenreRq() {{ setName("Фантастика"); }});
service.create(new GenreRq() {{ setName("Драма"); }});
GenreRs last = service.create(new GenreRq() {{ setName("Боевик"); }});
Assertions.assertEquals(3, service.getAll().size());
GenreRs cmp = service.get(last.getId());
Assertions.assertEquals(last.getId(), cmp.getId());
Assertions.assertEquals(last.getName(), cmp.getName());
}
@Test @Order(2)
void updateTest() {
GenreRs before = service.get(3L);
GenreRs after = service.update(3L, new GenreRq() {{ setName("Триллер"); }});
Assertions.assertEquals(3, service.getAll().size());
Assertions.assertEquals("Триллер", after.getName());
Assertions.assertNotEquals(before.getName(), after.getName());
}
@Test @Order(3)
void deleteTest() {
service.delete(3L);
Assertions.assertEquals(2, service.getAll().size());
}
}

View File

@@ -0,0 +1,65 @@
package ru.ulstu.is.server;
import org.junit.jupiter.api.*;
import org.junit.jupiter.api.MethodOrderer.OrderAnnotation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import ru.ulstu.is.server.api.NotFoundException;
import ru.ulstu.is.server.dto.*;
import ru.ulstu.is.server.service.*;
@SpringBootTest
@TestMethodOrder(OrderAnnotation.class)
class MovieServiceTests {
@Autowired private GenreService genreService;
@Autowired private DirectorService directorService;
@Autowired private MovieService movieService;
@Test
void getNotFound() {
Assertions.assertThrows(NotFoundException.class, () -> movieService.get(0L));
}
@Test @Order(1)
void createTest() {
// подготовим справочники
GenreRs g = genreService.create(new GenreRq() {{ setName("Фантастика"); }});
DirectorRs d = directorService.create(new DirectorRq() {{ setName("Кристофер Нолан"); }});
MovieRq rq1 = new MovieRq();
rq1.setTitle("Начало");
rq1.setGenre(new GenreRefRq() {{ setId(String.valueOf(g.getId())); }});
rq1.setDirector(new DirectorRefRq() {{ setId(String.valueOf(d.getId())); }});
movieService.create(rq1);
MovieRq rq2 = new MovieRq();
rq2.setTitle("Интерстеллар");
rq2.setGenre(new GenreRefRq() {{ setId(String.valueOf(g.getId())); }});
rq2.setDirector(new DirectorRefRq() {{ setId(String.valueOf(d.getId())); }});
MovieRs last = movieService.create(rq2);
Assertions.assertEquals(2, movieService.getAll().size());
Assertions.assertEquals("Интерстеллар", movieService.get(last.getId()).getTitle());
Assertions.assertEquals("Фантастика", movieService.get(last.getId()).getGenre().getName());
}
@Test @Order(2)
void updateTest() {
MovieRq upd = new MovieRq();
upd.setTitle("Интерстеллар (2014)");
upd.setGenre(new GenreRefRq() {{ setName("Научная фантастика"); }});
upd.setDirector(new DirectorRefRq() {{ setName("К. Нолан"); }});
MovieRs newEntity = movieService.update(2L, upd);
Assertions.assertEquals("Интерстеллар (2014)", newEntity.getTitle());
Assertions.assertEquals("Научная фантастика", newEntity.getGenre().getName());
Assertions.assertEquals("К. Нолан", newEntity.getDirector().getName());
}
@Test @Order(3)
void deleteTest() {
movieService.delete(2L);
Assertions.assertEquals(1, movieService.getAll().size());
}
}

View File

@@ -0,0 +1,46 @@
package ru.ulstu.is.server;
import org.junit.jupiter.api.*;
import org.junit.jupiter.api.MethodOrderer.OrderAnnotation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import ru.ulstu.is.server.api.NotFoundException;
import ru.ulstu.is.server.dto.SubscriptionRq;
import ru.ulstu.is.server.dto.SubscriptionRs;
import ru.ulstu.is.server.service.SubscriptionService;
@SpringBootTest
@TestMethodOrder(OrderAnnotation.class)
class SubscriptionServiceTests {
@Autowired
private SubscriptionService service;
@Test
void getNotFound() {
Assertions.assertThrows(NotFoundException.class, () -> service.get(0L));
}
@Test @Order(1)
void createTest() {
service.create(new SubscriptionRq() {{ setLevel("Базовая"); setPrice(299); }});
service.create(new SubscriptionRq() {{ setLevel("Стандарт"); setPrice(599); }});
SubscriptionRs last = service.create(new SubscriptionRq() {{ setLevel("Премиум"); setPrice(999); }});
Assertions.assertEquals(3, service.getAll().size());
Assertions.assertEquals(999, service.get(last.getId()).getPrice());
}
@Test @Order(2)
void updateTest() {
SubscriptionRs upd = service.update(3L, new SubscriptionRq() {{ setLevel("Премиум+"); setPrice(1299); }});
Assertions.assertEquals("Премиум+", upd.getLevel());
Assertions.assertEquals(1299, upd.getPrice());
}
@Test @Order(3)
void deleteTest() {
service.delete(3L);
Assertions.assertEquals(2, service.getAll().size());
}
}

View File

@@ -0,0 +1,68 @@
package ru.ulstu.is.server;
import org.junit.jupiter.api.*;
import org.junit.jupiter.api.MethodOrderer.OrderAnnotation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import ru.ulstu.is.server.api.NotFoundException;
import ru.ulstu.is.server.dto.*;
import ru.ulstu.is.server.entity.Subscription;
import ru.ulstu.is.server.repository.SubscriptionRepository;
import ru.ulstu.is.server.service.UserService;
import java.util.List;
@SpringBootTest
@TestMethodOrder(OrderAnnotation.class)
class UserServiceTests {
@Autowired private UserService userService;
@Autowired private SubscriptionRepository subscriptionRepository;
@Test
void getNotFound() {
Assertions.assertThrows(NotFoundException.class, () -> userService.get(0L));
}
@Test @Order(1)
void createTest() {
// подготовим подписку
Subscription sub = subscriptionRepository.save(new Subscription(null, "Базовая", 299));
UserRq rq = new UserRq();
rq.setName("Иван");
rq.setLogin("ivan@example.com");
rq.setPassword("1234");
var ref = new SubscriptionRefRq(); ref.setId(String.valueOf(sub.getId()));
rq.setSubscription(ref);
rq.setWatchlist(List.of());
UserRs created = userService.create(rq);
Assertions.assertNotNull(created.getId());
Assertions.assertEquals("Иван", created.getName());
Assertions.assertEquals("Базовая", created.getSubscription().getLevel());
}
@Test @Order(2)
void updateTest() {
UserRq upd = new UserRq();
upd.setName("Иван Петров");
upd.setLogin("ivan@example.com");
upd.setPassword("1234");
upd.setSubscriptionUntil("2026-01-01");
var newRef = new SubscriptionRefRq(); newRef.setLevel("Премиум"); newRef.setPrice(999);
upd.setSubscription(newRef);
UserRs after = userService.update(1L, upd);
Assertions.assertEquals("Иван Петров", after.getName());
Assertions.assertEquals("Премиум", after.getSubscription().getLevel());
Assertions.assertEquals(999, after.getSubscription().getPrice());
Assertions.assertEquals("2026-01-01", after.getSubscriptionUntil());
}
@Test @Order(3)
void deleteTest() {
userService.delete(1L);
Assertions.assertTrue(userService.getAll().isEmpty());
}
}

View File

@@ -0,0 +1,8 @@
logging.level.ru.ulstu.is.server=DEBUG
spring.datasource.url=jdbc:h2:mem:testdb
spring.datasource.driverClassName=org.h2.Driver
spring.datasource.username=sa
spring.datasource.password=
spring.jpa.hibernate.ddl-auto=create-drop
spring.jpa.show-sql=false

View File

@@ -1,323 +0,0 @@
* {
margin: 0;
padding: 0;
box-sizing: border-box;
}
html, body {
height: 100%;
margin: 0;
display: flex;
flex-direction: column;
}
body {
font-family: Arial, sans-serif;
background-color: #181818;
color: #fff;
text-align: center;
min-width: 70%;
}
nav a {
color: #fff;
margin: 10px;
text-decoration: none;
}
nav a:hover {
color: #FF0033;
}
.movie-list {
display: flex;
justify-content: space-around;
width: 500px;
flex-wrap: wrap;
margin: 0 auto;
}
.movie-list a {
color: #fff;
margin-bottom: 50px;
}
.movie-list img {
width: 150px;
height: auto;
}
table {
margin: auto;
background-color: #282828;
color: #fff;
}
.user_photo {
height: 130px;
width: 130px;
border-radius: 50px;
object-fit: cover;
}
#changeInfo {
font-size: 20px;
padding: 10px;
background-color: gray;
cursor: pointer;
margin-top: 20px;
}
#current_page {
color: red;
}
header {
display: flex;
justify-content: space-between;
align-items: center;
padding: 10px 20px;
background-color: #202020;
}
.logo {
display: flex;
align-items: center;
}
.logo img {
height: 40px;
margin-right: 10px;
}
nav ul {
display: flex;
list-style: none;
}
nav ul li {
position: relative;
margin: 15px 15px;
}
nav ul li a {
color: #fff;
text-decoration: none;
padding: 10px;
}
.dropdown-menu {
display: none;
position: absolute;
background-color: #333;
list-style: none;
top: 100%;
left: -40px;
min-width: 150px;
z-index: 1;
}
.dropdown-menu li {
padding: 5px 10px;
}
.dropdown-movies:hover .dropdown-menu {
display: block;
}
.user-actions a {
color: #fff;
text-decoration: none;
margin-left: 10px;
}
.content {
padding: 20px;
text-align: center;
}
main {
flex: 1;
}
footer {
display: flex;
justify-content: space-between;
align-items: center;
background-color: #202020;
padding: 10px 20px;
text-align: center;
}
.social-links img {
height: 30px;
margin: 0 5px;
}
.form-container {
width: 300px;
margin: 50px auto;
padding: 20px;
background-color: #282828;
border-radius: 10px;
text-align: center;
}
.form-container h2 {
margin-bottom: 20px;
}
.form-container input {
width: 100%;
padding: 10px;
margin: 10px 0;
border: none;
border-radius: 5px;
}
.form-container button {
width: 100%;
padding: 10px;
background-color: red;
border: none;
color: white;
font-size: 16px;
border-radius: 5px;
cursor: pointer;
margin-bottom: 17px;
}
.form-container button:hover {
background-color: darkred;
}
.form-container a {
color: red;
text-decoration: none;
}
.user-menu {
position: relative;
display: inline-block;
}
.account-btn {
color: #fff;
text-decoration: none;
padding: 10px;
}
.user-menu:hover .dropdown {
display: block;
}
.dropdown {
display: none;
position: absolute;
background-color: #333;
list-style: none;
padding: 5px;
left: -22px;
margin: 0;
border-radius: 5px;
width: 120px;
}
.dropdown li {
padding: 8px;
text-align: center;
}
.dropdown li a {
color: #fff;
text-decoration: none;
display: block;
}
.dropdown li a:hover {
background-color: red;
}
.footer-info {
margin: 0 auto;
}
@media (max-width: 1024px) {
header {
flex-direction: row;
justify-content: space-between;
padding: 10px;
}
nav ul {
flex-direction: row;
}
.movie-list {
max-width: 90%;
}
}
@media (max-width: 768px) {
header {
flex-direction: column;
text-align: center;
}
nav ul {
flex-direction: column;
padding: 10px;
}
.movie-list {
align-items: center;
}
footer {
flex-direction: column;
text-align: center;
}
.user-menu {
display: block;
position: static;
background-color: transparent;
text-align: center;
}
.user-menu li {
display: block;
}
.dropdown:hover .user-menu {
display: block;
}
.dropdown{
left: 310px;
}
}
@media (max-width: 480px) {
.side-menu {
width: 200px;
}
.movie-list img {
width: 120px;
}
footer {
padding: 5px;
}
.dropdown{
left: 135px;
}
span{
display:block;
}
table{
font-size: 25px;
}
}

3
front/.eslintignore Normal file
View File

@@ -0,0 +1,3 @@
node_modules
dist
backend

0
front/.eslintrc.json Normal file
View File

46
front/.gitignore vendored Normal file
View File

@@ -0,0 +1,46 @@
# See http://help.github.com/ignore-files/ for more about ignoring files.
# Compiled output
/dist
/tmp
/out-tsc
/bazel-out
# Node
/node_modules
npm-debug.log
yarn-error.log
# IDEs and editors
.idea/
.project
.classpath
.c9/
*.launch
.settings/
*.sublime-workspace
# Visual Studio Code
.vscode/*
!.vscode/settings.json
!.vscode/tasks.json
!.vscode/launch.json
!.vscode/extensions.json
.history/*
# Miscellaneous
/.angular/cache
.sass-cache/
/connect.lock
/coverage
/libpeerconnection.log
testem.log
/typings
# System files
.DS_Store
Thumbs.db
/.vs
/.vscode
/spa-react-movies

7
front/.prettierrc Normal file
View File

@@ -0,0 +1,7 @@
{
"tabWidth": 4,
"singleQuote": false,
"printWidth": 120,
"trailingComma": "es5",
"useTabs": false
}

137
front/db.json Normal file

File diff suppressed because one or more lines are too long

12
front/index.html Normal file
View File

@@ -0,0 +1,12 @@
<!DOCTYPE html>
<html lang="ru">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>React Кинотеатр</title>
</head>
<body class="bg-dark text-white">
<div id="root"></div>
<script type="module" src="/src/index.jsx"></script>
</body>
</html>

12
front/jsconfig.json Normal file
View File

@@ -0,0 +1,12 @@
{
"compilerOptions": {
"jsx": "react-jsx",
"target": "ES2020",
"module": "ESNext",
"moduleResolution": "node",
"allowSyntheticDefaultImports": true,
"baseUrl": "./src/**",
"checkJs": true
},
"exclude": ["node_modules", "**/node_modules/*"]
}

6317
front/package-lock.json generated Normal file

File diff suppressed because it is too large Load Diff

44
front/package.json Normal file
View File

@@ -0,0 +1,44 @@
{
"name": "int-prog",
"private": true,
"version": "1.0.0",
"type": "module",
"scripts": {
"start": "vite",
"vite": "vite",
"build": "vite build",
"serve": "http-server -p 3000 ./dist/",
"prod": "npm-run-all build serve",
"start:server": "json-server --watch db.json --port 3000",
"lint": "eslint ."
},
"dependencies": {
"axios": "^1.9.0",
"bootstrap": "^5.3.5",
"bootstrap-icons": "^1.12.1",
"prop-types": "^15.8.1",
"react": "^19.0.0",
"react-bootstrap": "^2.10.9",
"react-dom": "^19.0.0",
"react-easy-crop": "^5.4.1",
"react-router-dom": "^6.30.0"
},
"devDependencies": {
"@eslint/js": "^9.21.0",
"@types/react": "^19.0.10",
"@types/react-dom": "^19.0.4",
"@vitejs/plugin-react": "^4.3.4",
"eslint": "^9.21.0",
"eslint-config-prettier": "^10.1.1",
"eslint-import-resolver-vite": "^2.1.0",
"eslint-plugin-import": "^2.31.0",
"eslint-plugin-prettier": "^5.2.5",
"eslint-plugin-react": "^7.37.4",
"eslint-plugin-react-hooks": "^5.1.0",
"eslint-plugin-react-refresh": "^0.4.19",
"globals": "^15.15.0",
"http-server": "^14.1.1",
"json-server": "^1.0.0-beta.3",
"vite": "^6.2.0"
}
}

6
front/src/App.jsx Normal file
View File

@@ -0,0 +1,6 @@
import { RouterProvider } from "react-router-dom";
import { router } from "./router";
export default function App() {
return <RouterProvider router={router} />;
}

21
front/src/api/authApi.js Normal file
View File

@@ -0,0 +1,21 @@
import api from "./instance";
export const loginRequest = async (email, password) => {
const res = await api.get("/users");
return res.data.find(u => u.login === email && u.password === password);
};
export const registerUser = async ({ name, email, password }) => {
const { data } = await api.get("/users", { params: { login: email } });
if (data.length > 0) return false;
const newUser = {
name,
login: email,
password,
watchlist: [],
isAdmin: false,
};
await api.post("/users", newUser);
return true;
};

View File

@@ -0,0 +1,3 @@
import api from "./instance";
export const getAll = () => api.get("/directors").then(r => r.data);

View File

@@ -0,0 +1,3 @@
import api from "./instance";
export const getAll = () => api.get("/genres").then(r => r.data);

View File

@@ -0,0 +1,4 @@
import axios from "axios";
const api = axios.create({ baseURL: "http://localhost:8080/api/1.0" });
export default api;

View File

@@ -0,0 +1,10 @@
import api from "./instance";
export const getAll = () =>
api.get("/movies").then(r => r.data);
export const getMovieById = id =>
api.get(`/movies/${id}`).then(r => r.data);
export const removeOne = (id) => api.delete(`/movies/${id}`);
export const createOne = (movie) => api.post("/movies", movie).then(r => r.data);
export const updateOne = (id, movie) => api.put(`/movies/${id}`, movie).then(r => r.data);

View File

@@ -0,0 +1,8 @@
import api from "./instance";
export const getSubscriptions = () => api.get("/subscriptions").then(res => res.data);
export const getUserById = (id) => api.get(`/users/${id}`).then(res => res.data);
export const updateUserSubscription = (id, data) =>
api.patch(`/users/${id}`, data).then(res => res.data);

View File

@@ -0,0 +1,9 @@
import api from "./instance";
export const getUserById = id => api.get(`/users/${id}`).then(r => r.data);
export const updateUser = (id, data) =>
api.patch(`/users/${id}`, data).then(r => r.data);
export const getAllMovies = () => api.get("/movies").then(r => r.data);
export const getSubscriptionById = id =>
api.get(`/subscriptions/${id}`).then(r => r.data);

View File

@@ -0,0 +1,69 @@
import { useState, useCallback, useRef } from "react";
import Cropper from "react-easy-crop";
import getCroppedImg from "../utils/cropToBase64";
export default function ImageCropper({ value, onChange }) {
const inputRef = useRef();
const [src, setSrc] = useState(null);
const [crop, setCrop] = useState({ x: 0, y: 0 });
const [zoom, setZoom] = useState(1);
const [croppedArea, setCroppedArea] = useState(null);
const openFile = e => {
const file = e.target.files[0];
if (!file) return;
const reader = new FileReader();
reader.onload = ev => setSrc(ev.target.result);
reader.readAsDataURL(file);
};
const onCropComplete = useCallback((_, areaPixels) => {
setCroppedArea(areaPixels);
}, []);
const handleDone = async () => {
const base64 = await getCroppedImg(src, croppedArea);
onChange(base64);
setSrc(null);
inputRef.current.value = "";
};
return (
<>
<input type="file" accept="image/*" className="form-control"
ref={inputRef} onChange={openFile} />
{value && !src && (
<img src={value} alt="poster" className="img-fluid mt-3" style={{maxWidth:300}}/>
)}
{src && (
<div className="position-relative mt-3" style={{ width: 300, height: 300 }}>
<Cropper
image={src}
crop={crop}
zoom={zoom}
aspect={3/2}
onCropChange={setCrop}
onZoomChange={setZoom}
onCropComplete={onCropComplete}
/>
<input
type="range"
min="1" max="3" step="0.1"
value={zoom}
onChange={e => setZoom(parseFloat(e.target.value))}
className="form-range mt-2"
style={{ width: 300 }}
/>
</div>
)}
<button className="btn btn-secondary btn-sm mt-10" onClick={handleDone}>
Обрезать
</button>
</>
);
}

Some files were not shown because too many files have changed in this diff Show More