Compare commits

..

No commits in common. "main" and "master" have entirely different histories.
main ... master

522 changed files with 27097 additions and 56 deletions

63
.gitattributes vendored Normal file
View File

@ -0,0 +1,63 @@
###############################################################################
# Set default behavior to automatically normalize line endings.
###############################################################################
* text=auto
###############################################################################
# Set default behavior for command prompt diff.
#
# This is need for earlier builds of msysgit that does not have it on by
# default for csharp files.
# Note: This is only used by command line
###############################################################################
#*.cs diff=csharp
###############################################################################
# Set the merge driver for project and solution files
#
# Merging from the command prompt will add diff markers to the files if there
# are conflicts (Merging from VS is not affected by the settings below, in VS
# the diff markers are never inserted). Diff markers may cause the following
# file extensions to fail to load in VS. An alternative would be to treat
# these files as binary and thus will always conflict and require user
# intervention with every merge. To do so, just uncomment the entries below
###############################################################################
#*.sln merge=binary
#*.csproj merge=binary
#*.vbproj merge=binary
#*.vcxproj merge=binary
#*.vcproj merge=binary
#*.dbproj merge=binary
#*.fsproj merge=binary
#*.lsproj merge=binary
#*.wixproj merge=binary
#*.modelproj merge=binary
#*.sqlproj merge=binary
#*.wwaproj merge=binary
###############################################################################
# behavior for image files
#
# image files are treated as binary by default.
###############################################################################
#*.jpg binary
#*.png binary
#*.gif binary
###############################################################################
# diff behavior for common document formats
#
# Convert binary document formats to text before diffing them. This feature
# is only available from the command line. Turn it on by uncommenting the
# entries below.
###############################################################################
#*.doc diff=astextplain
#*.DOC diff=astextplain
#*.docx diff=astextplain
#*.DOCX diff=astextplain
#*.dot diff=astextplain
#*.DOT diff=astextplain
#*.pdf diff=astextplain
#*.PDF diff=astextplain
#*.rtf diff=astextplain
#*.RTF diff=astextplain

57
.gitignore vendored
View File

@ -1,22 +1,7 @@
# ---> VisualStudioCode
.vscode/*
!.vscode/settings.json
!.vscode/tasks.json
!.vscode/launch.json
!.vscode/extensions.json
!.vscode/*.code-snippets
# Local History for Visual Studio Code
.history/
# Built Visual Studio Code Extensions
*.vsix
# ---> VisualStudio
## Ignore Visual Studio temporary files, build results, and
## files generated by popular Visual Studio add-ons.
##
## Get latest from https://github.com/github/gitignore/blob/main/VisualStudio.gitignore
## Get latest from https://github.com/github/gitignore/blob/master/VisualStudio.gitignore
# User-specific files
*.rsuser
@ -44,6 +29,7 @@ x86/
bld/
[Bb]in/
[Oo]bj/
[Oo]ut/
[Ll]og/
[Ll]ogs/
@ -105,7 +91,6 @@ StyleCopReport.xml
*.tmp_proj
*_wpftmp.csproj
*.log
*.tlog
*.vspscc
*.vssscc
.builds
@ -309,17 +294,6 @@ node_modules/
# Visual Studio 6 auto-generated workspace file (contains which files were open etc.)
*.vbw
# Visual Studio 6 auto-generated project file (contains which files were open etc.)
*.vbp
# Visual Studio 6 workspace and project file (working project files containing files to include in project)
*.dsw
*.dsp
# Visual Studio 6 technical files
*.ncb
*.aps
# Visual Studio LightSwitch build output
**/*.HTMLClient/GeneratedArtifacts
**/*.DesktopClient/GeneratedArtifacts
@ -376,9 +350,6 @@ ASALocalRun/
# Local History for Visual Studio
.localhistory/
# Visual Studio History (VSHistory) files
.vshistory/
# BeatPulse healthcheck temp database
healthchecksdb
@ -389,26 +360,4 @@ MigrationBackup/
.ionide/
# Fody - auto-generated XML schema
FodyWeavers.xsd
# VS Code files for those working on multiple tools
.vscode/*
!.vscode/settings.json
!.vscode/tasks.json
!.vscode/launch.json
!.vscode/extensions.json
*.code-workspace
# Local History for Visual Studio Code
.history/
# Windows Installer files from build outputs
*.cab
*.msi
*.msix
*.msm
*.msp
# JetBrains Rider
*.sln.iml
FodyWeavers.xsd

14
Laba1/.vscode/launch.json vendored Normal file
View File

@ -0,0 +1,14 @@
{
"configurations": [
{
"type": "java",
"name": "Spring Boot-DemoApplication<demo>",
"request": "launch",
"cwd": "${workspaceFolder}",
"mainClass": "com.example.demo.DemoApplication",
"projectName": "demo",
"args": "",
"envFile": "${workspaceFolder}/.env"
}
]
}

37
Laba1/demo/.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/

27
Laba1/demo/build.gradle Normal file
View File

@ -0,0 +1,27 @@
plugins {
id 'java'
id 'org.springframework.boot' version '3.2.2'
id 'io.spring.dependency-management' version '1.1.4'
}
group = 'com.example'
version = '0.0.1-SNAPSHOT'
java {
sourceCompatibility = '17'
}
repositories {
mavenCentral()
}
dependencies {
implementation 'org.springframework.boot:spring-boot-starter-web'
implementation 'org.springdoc:springdoc-openapi-starter-webmvc-ui:2.3.0'
testImplementation 'org.springframework.boot:spring-boot-starter-test'
}
tasks.named('test') {
useJUnitPlatform()
}

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.5-bin.zip
networkTimeout=10000
validateDistributionUrl=true
zipStoreBase=GRADLE_USER_HOME
zipStorePath=wrapper/dists

249
Laba1/demo/gradlew vendored Normal file
View 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
Laba1/demo/gradlew.bat vendored Normal file
View 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

61
Laba1/demo/index.html Normal file
View File

@ -0,0 +1,61 @@
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
</head>
<body>
<p id="out">Push the button</p>
<input id="name"/>
<br/>
<button onclick="get()">Get</button>
<br/>
<button onclick="getTest()">Get Test</button>
<br/>
<button onclick="post()">Post</button>
<br/>
<button onclick="put()">Put</button>
</body>
<script>
const url = "http://localhost:8080/api";
const out = document.getElementById("out");
const name = document.getElementById("name");
const get = async () => {
const res = await fetch(`${url}?name=${name.value}`);
const text = await res.text();
out.innerText = text;
}
const getTest = async () => {
const res = await fetch(`${url}/test`);
const text = await res.text();
out.innerText = text;
}
const post = async () => {
if (!name.value) {
alert("Name is required");
return;
}
const res = await fetch(url, {
method: 'post',
headers: {'Content-Type': 'application/json'},
body: name.value
});
const text = await res.text();
out.innerText = text;
}
const put = async () => {
if (!name.value) {
alert("Name is required");
return;
}
const res = await fetch(`${url}/${name.value}`, {
method: 'put',
headers: {'Content-Type': 'application/json'},
body: name.value
});
const text = await res.text();
out.innerText = text;
}
</script>
</html>

View File

@ -0,0 +1 @@
rootProject.name = 'demo'

View File

@ -0,0 +1,56 @@
package com.example.demo;
import java.util.Date;
import java.util.List;
import java.util.ArrayList;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
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;
@RestController
@RequestMapping("/user")
public class ApiController {
private List<User> Users = new ArrayList<User>();
@PostMapping
public User CreateUser(@RequestBody User user) {
Users.add(user);
return user;
}
@GetMapping
public List<User> readAllUsers() {
return Users;
}
@GetMapping("/{id}")
public User readUser(@PathVariable int id) {
return Users.get(id);
}
@PutMapping("/{id}")
public User updateUser(@RequestBody User user, @PathVariable int id) {
Users.remove(id);
Users.add(id, user);
return user;
}
@DeleteMapping("/{id}")
public User deleteUser(@PathVariable int id) {
User tmp = Users.get(id);
Users.remove(id);
return tmp;
}
}

View File

@ -0,0 +1,13 @@
package com.example.demo;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
@SpringBootApplication
public class DemoApplication {
public static void main(String[] args) {
SpringApplication.run(DemoApplication.class, args);
}
}

View File

@ -0,0 +1,42 @@
package com.example.demo;
import com.fasterxml.jackson.annotation.JsonCreator;
import com.fasterxml.jackson.annotation.JsonProperty;
public class User {
private String name;
private String phoneNumber;
private String mail;
private String year;
public User() {
}
@JsonCreator
public User(
@JsonProperty(value = "name") String name,
@JsonProperty(value = "phoneNumber") String phoneNumber,
@JsonProperty(value = "mail") String mail,
@JsonProperty(value = "year") String year) {
this.name = name;
this.phoneNumber = phoneNumber;
this.mail = mail;
this.year = year;
}
public String getName() {
return name;
}
public String getPhoneNumber() {
return phoneNumber;
}
public String getMail() {
return mail;
}
public String getYear() {
return year;
}
}

View File

@ -0,0 +1,15 @@
package com.example.demo;
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 WebConfig implements WebMvcConfigurer {
@Override
public void addCorsMappings(@NonNull CorsRegistry registry) {
registry.addMapping("/**")
.allowedMethods("GET", "POST", "PUT", "DELETE");
}
}

View File

@ -0,0 +1 @@

View File

@ -0,0 +1,13 @@
package com.example.demo;
import org.junit.jupiter.api.Test;
import org.springframework.boot.test.context.SpringBootTest;
@SpringBootTest
class DemoApplicationTests {
@Test
void contextLoads() {
}
}

BIN
Laba2/2.zip Normal file

Binary file not shown.

37
Laba2/Лекция2-src/.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/

View File

@ -0,0 +1,28 @@
plugins {
id 'java'
id 'org.springframework.boot' version '3.2.3'
id 'io.spring.dependency-management' version '1.1.4'
}
group = 'com.example'
version = '0.0.1-SNAPSHOT'
java {
sourceCompatibility = '17'
}
repositories {
mavenCentral()
}
dependencies {
implementation 'org.springframework.boot:spring-boot-starter-web'
implementation 'org.springdoc:springdoc-openapi-starter-webmvc-ui:2.3.0'
implementation 'org.modelmapper:modelmapper:3.2.0'
testImplementation 'org.springframework.boot:spring-boot-starter-test'
}
tasks.named('test') {
useJUnitPlatform()
}

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.5-bin.zip
networkTimeout=10000
validateDistributionUrl=true
zipStoreBase=GRADLE_USER_HOME
zipStorePath=wrapper/dists

249
Laba2/Лекция2-src/gradlew vendored Normal file
View 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
Laba2/Лекция2-src/gradlew.bat vendored Normal file
View 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

View File

@ -0,0 +1,6 @@
{
"name": екция2-src",
"lockfileVersion": 3,
"requires": true,
"packages": {}
}

View File

@ -0,0 +1 @@
rootProject.name = 'demo'

View File

@ -0,0 +1,78 @@
package com.example.demo;
import java.util.Objects;
import java.util.ArrayList;
import java.util.List;
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.films.model.FilmEntity;
import com.example.demo.films.service.FilmService;
import com.example.demo.genres.model.GenreEntity;
import com.example.demo.genres.service.GenreService;
import com.example.demo.subscribes.model.SubscribeEntity;
import com.example.demo.subscribes.service.SubscribeService;
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 FilmService filmService;
private final GenreService genreService;
private final SubscribeService subscribeService;
private final UserService userService;
public DemoApplication(GenreService genreService, FilmService filmService, SubscribeService subscribeService,
UserService userService) {
this.genreService = genreService;
this.filmService = filmService;
this.subscribeService = subscribeService;
this.userService = userService;
}
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])) {
final List<FilmEntity> emptyList = new ArrayList<>();
log.info("Create default genres values");
final var genre1 = genreService.create(new GenreEntity(null, "Drama"));
final var genre2 = genreService.create(new GenreEntity(null, "Comedy"));
final var genre3 = genreService.create(new GenreEntity(null, "Sport"));
final var genre4 = genreService.create(new GenreEntity(null, "Triller"));
log.info("Create default subscribes values");
final var subscribe1 = subscribeService.create(new SubscribeEntity(null, "Standart", 200d));
final var subscribe2 = subscribeService.create(new SubscribeEntity(null, "Premium", 300d));
log.info("Create default films values");
final var film1 = filmService.create(new FilmEntity(null, "film1", genre1, 200d, 20));
final var film2 = filmService.create(new FilmEntity(null, "film2", genre2, 2000d, 40));
final var film3 = filmService.create(new FilmEntity(null, "film3", genre3, 4800d, 30));
final var film4 = filmService.create(new FilmEntity(null, "film4", genre4, 8800d, 21));
final var film5 = filmService.create(new FilmEntity(null, "film5", genre1, 2700d, 10));
log.info("Create default users values");
final var user1 = userService.create(new UserEntity(null, subscribe1, "user1", "mail", "phone", emptyList));
final var user2 = userService.create(new UserEntity(null, subscribe2, "user1", "mail", "phone", emptyList));
user1.addFilm(film1);
user1.addFilm(film2);
user1.addFilm(film3);
user1.addFilm(film4);
user1.addFilm(film5);
user2.addFilm(film2);
user2.addFilm(film5);
}
}
}

View File

@ -0,0 +1,8 @@
package com.example.demo.core.configuration;
public class Constants {
public static final String API_URL = "/api/1.0";
private Constants() {
}
}

View File

@ -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();
}
}

View File

@ -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");
}
}

View File

@ -0,0 +1,7 @@
package com.example.demo.core.error;
public class NotFoundException extends RuntimeException {
public NotFoundException(Long id) {
super(String.format("Entity with id [%s] is not found or not exists", id));
}
}

View File

@ -0,0 +1,20 @@
package com.example.demo.core.model;
public abstract class BaseEntity {
protected Long id;
protected BaseEntity() {
}
protected BaseEntity(Long id) {
this.id = id;
}
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
}

View File

@ -0,0 +1,17 @@
package com.example.demo.core.repository;
import java.util.List;
public interface CommonRepository<E, T> {
List<E> getAll();
E get(T id);
E create(E entity);
E update(E entity);
E delete(E entity);
void deleteAll();
}

View File

@ -0,0 +1,57 @@
package com.example.demo.core.repository;
import java.util.List;
import java.util.Map;
import java.util.TreeMap;
import com.example.demo.core.model.BaseEntity;
public abstract class MapRepository<E extends BaseEntity> implements CommonRepository<E, Long> {
private final Map<Long, E> entities = new TreeMap<>();
private Long lastId = 0L;
protected MapRepository() {
}
@Override
public List<E> getAll() {
return entities.values().stream().toList();
}
@Override
public E get(Long id) {
return entities.get(id);
}
@Override
public E create(E entity) {
lastId++;
entity.setId(lastId);
entities.put(lastId, entity);
return entity;
}
@Override
public E update(E entity) {
if (get(entity.getId()) == null) {
return null;
}
entities.put(entity.getId(), entity);
return entity;
}
@Override
public E delete(E entity) {
if (get(entity.getId()) == null) {
return null;
}
entities.remove(entity.getId());
return entity;
}
@Override
public void deleteAll() {
lastId = 0L;
entities.clear();
}
}

View File

@ -0,0 +1,70 @@
package com.example.demo.films.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.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import com.example.demo.core.configuration.Constants;
import com.example.demo.films.model.FilmEntity;
import com.example.demo.films.service.FilmService;
import com.example.demo.genres.service.GenreService;
import jakarta.validation.Valid;
@RestController
@RequestMapping(Constants.API_URL + "/film")
public class FilmController {
private final FilmService filmService;
private final GenreService genreService;
private final ModelMapper modelMapper;
public FilmController(FilmService filmService, GenreService genreService, ModelMapper modelMapper) {
this.filmService = filmService;
this.genreService = genreService;
this.modelMapper = modelMapper;
}
private FilmDto toDto(FilmEntity entity) {
return modelMapper.map(entity, FilmDto.class);
}
private FilmEntity toEntity(FilmDto dto) {
final FilmEntity entity = modelMapper.map(dto, FilmEntity.class);
entity.setGenre(genreService.get(dto.getGenreId()));
return entity;
}
@GetMapping
public List<FilmDto> getAll(@RequestParam(name = "genreId", defaultValue = "0") Long typeId) {
return filmService.getAll(typeId).stream().map(this::toDto).toList();
}
@GetMapping("/{id}")
public FilmDto get(@PathVariable(name = "id") Long id) {
return toDto(filmService.get(id));
}
@PostMapping
public FilmDto create(@RequestBody @Valid FilmDto dto) {
return toDto(filmService.create(toEntity(dto)));
}
@PutMapping("/{id}")
public FilmDto update(@PathVariable(name = "id") Long id, @RequestBody FilmDto dto) {
return toDto(filmService.update(id, toEntity(dto)));
}
@DeleteMapping("/{id}")
public FilmDto delete(@PathVariable(name = "id") Long id) {
return toDto(filmService.delete(id));
}
}

View File

@ -0,0 +1,59 @@
package com.example.demo.films.api;
import com.fasterxml.jackson.annotation.JsonProperty;
import jakarta.validation.constraints.Min;
import jakarta.validation.constraints.NotNull;
public class FilmDto {
private Long id;
@NotNull
private String name;
@NotNull
@Min(1)
private Long genreId;
@NotNull
@Min(1)
private Double price;
@NotNull
@Min(1)
private Integer discount;
@JsonProperty(access = JsonProperty.Access.READ_ONLY)
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public Long getGenreId() {
return genreId;
}
public void setGenreId(Long genreId) {
this.genreId = genreId;
}
public Double getPrice() {
return price;
}
public void setPrice(Double price) {
this.price = price;
}
public Integer getDiscount() {
return discount;
}
public void setDiscount(Integer discount) {
this.discount = discount;
}
@JsonProperty(access = JsonProperty.Access.READ_ONLY)
public Double getSum() {
return price - ((price * discount) * 0.01);
}
}

View File

@ -0,0 +1,76 @@
package com.example.demo.films.model;
import java.util.Objects;
import com.example.demo.core.model.BaseEntity;
import com.example.demo.genres.model.GenreEntity;
public class FilmEntity extends BaseEntity {
private String name;
private GenreEntity genre;
private Double price;
private Integer discount;
public FilmEntity() {
super();
}
public FilmEntity(Long id, String name, GenreEntity genre, Double price, Integer discount) {
super(id);
this.name = name;
this.genre = genre;
this.price = price;
this.discount = discount;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public GenreEntity getGenre() {
return genre;
}
public void setGenre(GenreEntity genre) {
this.genre = genre;
}
public Double getPrice() {
return price;
}
public void setPrice(Double price) {
this.price = price;
}
public Integer getDiscount() {
return discount;
}
public void setDiscount(Integer discount) {
this.discount = discount;
}
@Override
public int hashCode() {
return Objects.hash(id, name, genre, price, discount);
}
@Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null || getClass() != obj.getClass())
return false;
final FilmEntity other = (FilmEntity) obj;
return Objects.equals(other.getId(), id)
&& Objects.equals(other.getName(), name)
&& Objects.equals(other.getGenre(), genre)
&& Objects.equals(other.getPrice(), price)
&& Objects.equals(other.getDiscount(), discount);
}
}

View File

@ -0,0 +1,10 @@
package com.example.demo.films.repository;
import org.springframework.stereotype.Repository;
import com.example.demo.core.repository.MapRepository;
import com.example.demo.films.model.FilmEntity;
@Repository
public class FilmRepository extends MapRepository<FilmEntity> {
}

View File

@ -0,0 +1,56 @@
package com.example.demo.films.service;
import java.util.List;
import java.util.Objects;
import java.util.Optional;
import org.springframework.stereotype.Service;
import com.example.demo.core.error.NotFoundException;
import com.example.demo.films.model.FilmEntity;
import com.example.demo.films.repository.FilmRepository;
@Service
public class FilmService {
private final FilmRepository repository;
public FilmService(FilmRepository repository) {
this.repository = repository;
}
public List<FilmEntity> getAll() {
return repository.getAll();
}
public List<FilmEntity> getAll(Long typeId) {
if (Objects.equals(typeId, 0L)) {
return repository.getAll();
}
return repository.getAll().stream()
.filter(film -> film.getGenre().getId().equals(typeId))
.toList();
}
public FilmEntity get(Long id) {
return Optional.ofNullable(repository.get(id))
.orElseThrow(() -> new NotFoundException(id));
}
public FilmEntity create(FilmEntity entity) {
return repository.create(entity);
}
public FilmEntity update(Long id, FilmEntity entity) {
final FilmEntity existsEntity = get(id);
existsEntity.setName(entity.getName());
existsEntity.setGenre(entity.getGenre());
existsEntity.setPrice(entity.getPrice());
existsEntity.setDiscount(entity.getDiscount());
return repository.update(existsEntity);
}
public FilmEntity delete(Long id) {
final FilmEntity existsEntity = get(id);
return repository.delete(existsEntity);
}
}

View File

@ -0,0 +1,65 @@
package com.example.demo.genres.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.genres.model.GenreEntity;
import com.example.demo.genres.service.GenreService;
import jakarta.validation.Valid;
@RestController
@RequestMapping(Constants.API_URL + "/genre")
public class GenreController {
private final GenreService genreService;
private final ModelMapper modelMapper;
public GenreController(GenreService genreService, ModelMapper modelMapper) {
this.genreService = genreService;
this.modelMapper = modelMapper;
}
private GenreDto toDto(GenreEntity entity) {
return modelMapper.map(entity, GenreDto.class);
}
private GenreEntity toEntity(GenreDto dto) {
final GenreEntity entity = modelMapper.map(dto, GenreEntity.class);
return entity;
}
@GetMapping
public List<GenreDto> getAll() {
return genreService.getAll().stream().map(this::toDto).toList();
}
@GetMapping("/{id}")
public GenreDto get(@PathVariable(name = "id") Long id) {
return toDto(genreService.get(id));
}
@PostMapping
public GenreDto create(@RequestBody @Valid GenreDto dto) {
return toDto(genreService.create(toEntity(dto)));
}
@PutMapping("/{id}")
public GenreDto update(@PathVariable(name = "id") Long id, @RequestBody GenreDto dto) {
return toDto(genreService.update(id, toEntity(dto)));
}
@DeleteMapping("/{id}")
public GenreDto delete(@PathVariable(name = "id") Long id) {
return toDto(genreService.delete(id));
}
}

View File

@ -0,0 +1,28 @@
package com.example.demo.genres.api;
import com.fasterxml.jackson.annotation.JsonProperty;
import jakarta.validation.constraints.NotNull;
public class GenreDto {
private Long id;
@NotNull
private String name;
@JsonProperty(access = JsonProperty.Access.READ_ONLY)
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,42 @@
package com.example.demo.genres.model;
import java.util.Objects;
import com.example.demo.core.model.BaseEntity;
public class GenreEntity extends BaseEntity {
private String name;
public GenreEntity() {
super();
}
public GenreEntity(Long id, String name) {
super(id);
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 GenreEntity other = (GenreEntity) obj;
return Objects.equals(other.getId(), id)
&& Objects.equals(other.getName(), name);
}
}

View File

@ -0,0 +1,10 @@
package com.example.demo.genres.repository;
import org.springframework.stereotype.Repository;
import com.example.demo.core.repository.MapRepository;
import com.example.demo.genres.model.GenreEntity;
@Repository
public class GenreRepository extends MapRepository<GenreEntity> {
}

View File

@ -0,0 +1,42 @@
package com.example.demo.genres.service;
import java.util.List;
import java.util.Optional;
import org.springframework.stereotype.Service;
import com.example.demo.core.error.NotFoundException;
import com.example.demo.genres.model.GenreEntity;
import com.example.demo.genres.repository.GenreRepository;
@Service
public class GenreService {
private final GenreRepository repository;
public GenreService(GenreRepository repository) {
this.repository = repository;
}
public List<GenreEntity> getAll() {
return repository.getAll();
}
public GenreEntity get(Long id) {
return Optional.ofNullable(repository.get(id)).orElseThrow(() -> new NotFoundException(id));
}
public GenreEntity create(GenreEntity entity) {
return repository.create(entity);
}
public GenreEntity update(Long id, GenreEntity entity) {
final GenreEntity existsEntity = get(id);
existsEntity.setName(entity.getName());
return repository.update(existsEntity);
}
public GenreEntity delete(Long id) {
final GenreEntity existsEntity = get(id);
return repository.delete(existsEntity);
}
}

View File

@ -0,0 +1,5 @@
package com.example.demo.speaker.configuration;
public class SpeakerConfiguration {
}

View File

@ -0,0 +1,64 @@
package com.example.demo.subscribes.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.subscribes.model.SubscribeEntity;
import com.example.demo.subscribes.service.SubscribeService;
import jakarta.validation.Valid;
@RestController
@RequestMapping(Constants.API_URL + "/subscribe")
public class SubscribeController {
private final SubscribeService subscribeService;
private final ModelMapper modelMapper;
public SubscribeController(SubscribeService subscribeService, ModelMapper modelMapper) {
this.subscribeService = subscribeService;
this.modelMapper = modelMapper;
}
private SubscribeDto toDto(SubscribeEntity entity) {
return modelMapper.map(entity, SubscribeDto.class);
}
private SubscribeEntity toEntity(SubscribeDto dto) {
return modelMapper.map(dto, SubscribeEntity.class);
}
@GetMapping
public List<SubscribeDto> getAll() {
return subscribeService.getAll().stream().map(this::toDto).toList();
}
@GetMapping("/{id}")
public SubscribeDto get(@PathVariable(name = "id") Long id) {
return toDto(subscribeService.get(id));
}
@PostMapping
public SubscribeDto create(@RequestBody @Valid SubscribeDto dto) {
return toDto(subscribeService.create(toEntity(dto)));
}
@PutMapping("/{id}")
public SubscribeDto update(@PathVariable(name = "id") Long id, @RequestBody SubscribeDto dto) {
return toDto(subscribeService.update(id, toEntity(dto)));
}
@DeleteMapping("/{id}")
public SubscribeDto delete(@PathVariable(name = "id") Long id) {
return toDto(subscribeService.delete(id));
}
}

View File

@ -0,0 +1,41 @@
package com.example.demo.subscribes.api;
import com.fasterxml.jackson.annotation.JsonProperty;
import jakarta.validation.constraints.NotBlank;
import jakarta.validation.constraints.NotNull;
import jakarta.validation.constraints.Min;
public class SubscribeDto {
private Long id;
@NotBlank
private String name;
@NotNull
@Min(1)
private Double cost;
@JsonProperty(access = JsonProperty.Access.READ_ONLY)
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 Double getCost() {
return cost;
}
public void setCost(Double cost) {
this.cost = cost;
}
}

View File

@ -0,0 +1,54 @@
package com.example.demo.subscribes.model;
import java.util.Objects;
import com.example.demo.core.model.BaseEntity;
public class SubscribeEntity extends BaseEntity {
private String name;
private Double cost;
public SubscribeEntity() {
super();
}
public SubscribeEntity(Long id, String name, Double cost) {
super(id);
this.name = name;
this.cost = cost;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public Double getCost() {
return cost;
}
public void setCost(Double cost) {
this.cost = cost;
}
@Override
public int hashCode() {
return Objects.hash(id, name, cost);
}
@Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null || getClass() != obj.getClass())
return false;
final SubscribeEntity other = (SubscribeEntity) obj;
return Objects.equals(other.getId(), id)
&& Objects.equals(other.getName(), name)
&& Objects.equals(other.getCost(), cost);
}
}

View File

@ -0,0 +1,10 @@
package com.example.demo.subscribes.repository;
import org.springframework.stereotype.Repository;
import com.example.demo.core.repository.MapRepository;
import com.example.demo.subscribes.model.SubscribeEntity;
@Repository
public class SubscribeRepository extends MapRepository<SubscribeEntity> {
}

View File

@ -0,0 +1,44 @@
package com.example.demo.subscribes.service;
import java.util.List;
import java.util.Optional;
import org.springframework.stereotype.Service;
import com.example.demo.core.error.NotFoundException;
import com.example.demo.subscribes.model.SubscribeEntity;
import com.example.demo.subscribes.repository.SubscribeRepository;
@Service
public class SubscribeService {
private final SubscribeRepository repository;
public SubscribeService(SubscribeRepository repository) {
this.repository = repository;
}
public List<SubscribeEntity> getAll() {
return repository.getAll();
}
public SubscribeEntity get(Long id) {
return Optional.ofNullable(repository.get(id))
.orElseThrow(() -> new NotFoundException(id));
}
public SubscribeEntity create(SubscribeEntity entity) {
return repository.create(entity);
}
public SubscribeEntity update(Long id, SubscribeEntity entity) {
final SubscribeEntity existsEntity = get(id);
existsEntity.setName(entity.getName());
existsEntity.setCost(entity.getCost());
return repository.update(existsEntity);
}
public SubscribeEntity delete(Long id) {
final SubscribeEntity existsEntity = get(id);
return repository.delete(existsEntity);
}
}

View File

@ -0,0 +1,85 @@
package com.example.demo.users.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.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import com.example.demo.core.configuration.Constants;
import com.example.demo.users.model.UserEntity;
import com.example.demo.users.service.UserService;
import com.example.demo.subscribes.service.SubscribeService;
import com.example.demo.films.service.FilmService;
import jakarta.validation.Valid;
@RestController
@RequestMapping(Constants.API_URL + "/user")
public class UserController {
private final UserService userService;
private final SubscribeService subscribeService;
private final ModelMapper modelMapper;
private final FilmService filmService;
public UserController(UserService userService, SubscribeService subscribeService, ModelMapper modelMapper,
FilmService filmService) {
this.userService = userService;
this.subscribeService = subscribeService;
this.modelMapper = modelMapper;
this.filmService = filmService;
}
private UserDto toDto(UserEntity entity) {
return modelMapper.map(entity, UserDto.class);
}
private UserEntity toEntity(UserDto dto) {
final UserEntity entity = modelMapper.map(dto, UserEntity.class);
entity.setSubscribe(subscribeService.get(dto.getSubscribeId()));
return entity;
}
@GetMapping
public List<UserDto> getAll(@RequestParam(name = "subscribeId", defaultValue = "0") Long subscribeId) {
return userService.getAll(subscribeId).stream().map(this::toDto).toList();
}
@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)));
}
@PutMapping("/addFilm/{id}")
public UserDto addFilm(@PathVariable(name = "id") Long id, @RequestBody Long filmId) {
return toDto(userService.addFilm(id, filmService.get(filmId)));
}
@PutMapping("/deleteFilm/{id}")
public UserDto deleteFilm(@PathVariable(name = "id") Long id, @RequestBody Long filmId) {
return toDto(userService.deleteFilm(id, filmService.get(filmId)));
}
@DeleteMapping("/{id}")
public UserDto delete(@PathVariable(name = "id") Long id) {
return toDto(userService.delete(id));
}
}

View File

@ -0,0 +1,84 @@
package com.example.demo.users.api;
import com.fasterxml.jackson.annotation.JsonProperty;
import java.util.ArrayList;
import java.util.List;
import jakarta.validation.constraints.Min;
import jakarta.validation.constraints.NotNull;
import jakarta.validation.constraints.NotBlank;
import com.example.demo.films.model.FilmEntity;
public class UserDto {
private Long id;
@NotNull
@Min(1)
private Long subscribeId;
@NotBlank
private String name;
@NotBlank
private String mail;
@NotBlank
private String phone;
private final List<FilmEntity> listFilms = new ArrayList<FilmEntity>();
@JsonProperty(access = JsonProperty.Access.READ_ONLY)
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public Long getSubscribeId() {
return subscribeId;
}
public void setSubscribeId(Long subscribeId) {
this.subscribeId = subscribeId;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getMail() {
return mail;
}
public void setMail(String mail) {
this.mail = mail;
}
public String getPhone() {
return phone;
}
public void setPhone(String phone) {
this.phone = phone;
}
public List<FilmEntity> getListFilms() {
return listFilms;
}
public void setListFilms(List<FilmEntity> listFilms) {
this.listFilms.clear();
this.listFilms.addAll(listFilms);
}
public void addFilm(FilmEntity film) {
this.listFilms.add(film);
}
public void deletefilm(FilmEntity film) {
this.listFilms.remove(film);
}
}

View File

@ -0,0 +1,102 @@
package com.example.demo.users.model;
import java.util.Objects;
import java.util.ArrayList;
import java.util.List;
import com.example.demo.core.model.BaseEntity;
import com.example.demo.subscribes.model.SubscribeEntity;
import com.example.demo.films.model.FilmEntity;
public class UserEntity extends BaseEntity {
private SubscribeEntity subscribe;
private String name;
private String mail;
private String phone;
private final List<FilmEntity> listFilms = new ArrayList<FilmEntity>();
public UserEntity() {
super();
}
public UserEntity(Long id, SubscribeEntity subscribe, String name, String mail, String phone,
List<FilmEntity> listFims) {
super(id);
this.subscribe = subscribe;
this.name = name;
this.mail = mail;
this.phone = phone;
if (!listFims.isEmpty()) {
this.listFilms.clear();
this.listFilms.addAll(listFims);
}
}
public SubscribeEntity getSubscribe() {
return subscribe;
}
public void setSubscribe(SubscribeEntity subscribe) {
this.subscribe = subscribe;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getMail() {
return mail;
}
public void setMail(String mail) {
this.mail = mail;
}
public String getPhone() {
return phone;
}
public void setPhone(String phone) {
this.phone = phone;
}
public List<FilmEntity> getListFilms() {
return listFilms;
}
public void setListFilms(List<FilmEntity> listFilms) {
this.listFilms.addAll(listFilms);
}
public void addFilm(FilmEntity film) {
this.listFilms.add(film);
}
public void deleteFilm(FilmEntity film) {
this.listFilms.remove(film);
}
@Override
public int hashCode() {
return Objects.hash(id, subscribe, name, mail, phone, listFilms);
}
@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.getSubscribe(), subscribe)
&& Objects.equals(other.getName(), name)
&& Objects.equals(other.getMail(), mail)
&& Objects.equals(other.getPhone(), phone)
&& Objects.equals(other.getListFilms(), listFilms);
}
}

View File

@ -0,0 +1,10 @@
package com.example.demo.users.repository;
import org.springframework.stereotype.Repository;
import com.example.demo.core.repository.MapRepository;
import com.example.demo.users.model.UserEntity;
@Repository
public class UserRepository extends MapRepository<UserEntity> {
}

View File

@ -0,0 +1,71 @@
package com.example.demo.users.service;
import java.util.List;
import java.util.Objects;
import java.util.Optional;
import org.springframework.stereotype.Service;
import com.example.demo.core.error.NotFoundException;
import com.example.demo.users.model.UserEntity;
import com.example.demo.films.model.FilmEntity;
import com.example.demo.users.repository.UserRepository;
@Service
public class UserService {
private final UserRepository repository;
public UserService(UserRepository repository) {
this.repository = repository;
}
public List<UserEntity> getAll(Long subscribeId) {
if (Objects.equals(subscribeId, 0L)) {
return repository.getAll();
}
return repository.getAll().stream()
.filter(user -> user.getSubscribe().getId().equals(subscribeId))
.toList();
}
public List<UserEntity> getAll() {
return repository.getAll();
}
public UserEntity get(Long id) {
return Optional.ofNullable(repository.get(id))
.orElseThrow(() -> new NotFoundException(id));
}
public UserEntity create(UserEntity entity) {
return repository.create(entity);
}
public UserEntity update(Long id, UserEntity entity) {
final UserEntity existsEntity = get(id);
existsEntity.setSubscribe(entity.getSubscribe());
existsEntity.setName(entity.getName());
existsEntity.setMail(entity.getMail());
existsEntity.setPhone(entity.getPhone());
return repository.update(existsEntity);
}
public UserEntity delete(Long id) {
final UserEntity existsEntity = get(id);
return repository.delete(existsEntity);
}
public UserEntity addFilm(Long id, FilmEntity film) {
final UserEntity existsEntity = get(id);
if (!existsEntity.getListFilms().contains(film))
existsEntity.addFilm(film);
return repository.update(existsEntity);
}
public UserEntity deleteFilm(Long id, FilmEntity film) {
final UserEntity existsEntity = get(id);
if (existsEntity.getListFilms().contains(film))
existsEntity.deleteFilm(film);
return repository.update(existsEntity);
}
}

View File

@ -0,0 +1,79 @@
package com.example.demo;
import org.junit.jupiter.api.Assertions;
import org.junit.jupiter.api.MethodOrderer.OrderAnnotation;
import org.junit.jupiter.api.Order;
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.core.error.NotFoundException;
import com.example.demo.films.service.FilmService;
import com.example.demo.films.model.FilmEntity;
import com.example.demo.genres.model.GenreEntity;
@SpringBootTest
@TestMethodOrder(OrderAnnotation.class)
public class FilmsServiceTests {
@Autowired
private FilmService filmService;
@Test
void getFilmTest() {
Assertions.assertThrows(NotFoundException.class, () -> filmService.get(0L));
}
@Test
@Order(1)
void createFilmTest() {
final GenreEntity genre = new GenreEntity(null, "genre");
filmService.create(new FilmEntity(null, "name", genre, 100d, 20));
filmService.create(new FilmEntity(null, "name", genre, 100d, 20));
final FilmEntity last = filmService.create(new FilmEntity(null, "name", genre, 100d, 20));
Assertions.assertEquals(3, filmService.getAll().size());
Assertions.assertEquals(last, filmService.get(3L));
}
@Test
@Order(2)
void updateFilmTest() {
final String testName = "TEST";
final GenreEntity testGenre = new GenreEntity(null, "test");
final Double testPrice = 123d;
final int testDiscount = 12;
final FilmEntity entity = filmService.get(3L);
final String oldName = entity.getName();
final GenreEntity oldGenre = entity.getGenre();
final Double oldPrice = entity.getPrice();
final int oldDiscount = entity.getDiscount();
final FilmEntity newEntity = filmService.update(3L,
new FilmEntity(3L, testName, testGenre, testPrice, testDiscount));
Assertions.assertEquals(3, filmService.getAll().size());
Assertions.assertEquals(newEntity, filmService.get(3L));
Assertions.assertEquals(testName, newEntity.getName());
Assertions.assertNotEquals(oldName, newEntity.getName());
Assertions.assertEquals(testGenre, newEntity.getGenre());
Assertions.assertNotEquals(oldGenre, newEntity.getGenre());
Assertions.assertEquals(testPrice, newEntity.getPrice());
Assertions.assertNotEquals(oldPrice, newEntity.getPrice());
Assertions.assertEquals(testDiscount, newEntity.getDiscount());
Assertions.assertNotEquals(oldDiscount, newEntity.getDiscount());
}
@Test
@Order(3)
void deleteFilmTest() {
final GenreEntity genre = new GenreEntity(null, "genre");
filmService.delete(3L);
Assertions.assertEquals(2, filmService.getAll().size());
final FilmEntity last = filmService.get(2L);
Assertions.assertEquals(2L, last.getId());
final FilmEntity newEntity = filmService.create(new FilmEntity(null, "film", genre, 500d, 10));
Assertions.assertEquals(3, filmService.getAll().size());
Assertions.assertEquals(4L, newEntity.getId());
}
}

View File

@ -0,0 +1,61 @@
package com.example.demo;
import org.junit.jupiter.api.Assertions;
import org.junit.jupiter.api.MethodOrderer.OrderAnnotation;
import org.junit.jupiter.api.Order;
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.core.error.NotFoundException;
import com.example.demo.genres.model.GenreEntity;
import com.example.demo.genres.service.GenreService;
@SpringBootTest
@TestMethodOrder(OrderAnnotation.class)
class GenreServiceTests {
@Autowired
private GenreService genreService;
@Test
void getGenreTest() {
Assertions.assertThrows(NotFoundException.class, () -> genreService.get(0L));
}
@Test
@Order(1)
void createGenreTest() {
genreService.create(new GenreEntity(null, "Drama"));
genreService.create(new GenreEntity(null, "Comedy"));
final GenreEntity last = genreService.create(new GenreEntity(null, "Triller"));
Assertions.assertEquals(3, genreService.getAll().size());
Assertions.assertEquals(last, genreService.get(3L));
}
@Test
@Order(2)
void updateGenreTest() {
final String test = "TEST";
final GenreEntity entity = genreService.get(3L);
final String oldName = entity.getName();
final GenreEntity newEntity = genreService.update(3L, new GenreEntity(1L, test));
Assertions.assertEquals(3, genreService.getAll().size());
Assertions.assertEquals(newEntity, genreService.get(3L));
Assertions.assertEquals(test, newEntity.getName());
Assertions.assertNotEquals(oldName, newEntity.getName());
}
@Test
@Order(3)
void deleteGenreTest() {
genreService.delete(3L);
Assertions.assertEquals(2, genreService.getAll().size());
final GenreEntity last = genreService.get(2L);
Assertions.assertEquals(2L, last.getId());
final GenreEntity newEntity = genreService.create(new GenreEntity(null, "Drama"));
Assertions.assertEquals(3, genreService.getAll().size());
Assertions.assertEquals(4L, newEntity.getId());
}
}

View File

@ -0,0 +1,65 @@
package com.example.demo;
import org.junit.jupiter.api.Assertions;
import org.junit.jupiter.api.MethodOrderer.OrderAnnotation;
import org.junit.jupiter.api.Order;
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.core.error.NotFoundException;
import com.example.demo.subscribes.service.SubscribeService;
import com.example.demo.subscribes.model.SubscribeEntity;
@SpringBootTest
@TestMethodOrder(OrderAnnotation.class)
public class SubscribeServiceTests {
@Autowired
private SubscribeService subscribeService;
@Test
void getSubscribeTest() {
Assertions.assertThrows(NotFoundException.class, () -> subscribeService.get(0L));
}
@Test
@Order(1)
void createSubscribeTest() {
subscribeService.create(new SubscribeEntity(null, "sub1", 100d));
subscribeService.create(new SubscribeEntity(null, "sub2", 200d));
final SubscribeEntity last = subscribeService.create(new SubscribeEntity(null, "sub3", 300d));
Assertions.assertEquals(3, subscribeService.getAll().size());
Assertions.assertEquals(last, subscribeService.get(3L));
}
@Test
@Order(2)
void updateSubscribeTest() {
final String testName = "TEST";
final Double testPrice = 123d;
final SubscribeEntity entity = subscribeService.get(3L);
final String oldName = entity.getName();
final Double oldPrice = entity.getCost();
final SubscribeEntity newEntity = subscribeService.update(3L, new SubscribeEntity(3L, testName, testPrice));
Assertions.assertEquals(3, subscribeService.getAll().size());
Assertions.assertEquals(newEntity, subscribeService.get(3L));
Assertions.assertEquals(testName, newEntity.getName());
Assertions.assertNotEquals(oldName, newEntity.getName());
Assertions.assertEquals(testPrice, newEntity.getCost());
Assertions.assertNotEquals(oldPrice, newEntity.getCost());
}
@Test
@Order(3)
void deleteSubscribeTest() {
subscribeService.delete(3L);
Assertions.assertEquals(2, subscribeService.getAll().size());
final SubscribeEntity last = subscribeService.get(2L);
Assertions.assertEquals(2L, last.getId());
final SubscribeEntity newEntity = subscribeService.create(new SubscribeEntity(null, "sub8", 500d));
Assertions.assertEquals(3, subscribeService.getAll().size());
Assertions.assertEquals(4L, newEntity.getId());
}
}

View File

@ -0,0 +1,110 @@
package com.example.demo;
import org.junit.jupiter.api.Assertions;
import org.junit.jupiter.api.MethodOrderer.OrderAnnotation;
import org.junit.jupiter.api.Order;
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 java.util.ArrayList;
import java.util.List;
import com.example.demo.core.error.NotFoundException;
import com.example.demo.films.model.FilmEntity;
import com.example.demo.users.model.UserEntity;
import com.example.demo.users.service.UserService;
import com.example.demo.genres.model.GenreEntity;
import com.example.demo.subscribes.model.SubscribeEntity;
@SpringBootTest
@TestMethodOrder(OrderAnnotation.class)
class UsersServiceTests {
@Autowired
private UserService userService;
final List<FilmEntity> emptyList = new ArrayList<FilmEntity>();
final GenreEntity genre = new GenreEntity(null, "genre");
final FilmEntity film = new FilmEntity(null, "name", genre, 100d, 10);
@Test
void getUserTest() {
Assertions.assertThrows(NotFoundException.class, () -> userService.get(0L));
}
@Test
@Order(1)
void createUserTest() {
final SubscribeEntity sub = new SubscribeEntity(null, "sub", 100d);
userService.create(new UserEntity(null, sub, "name", "mail", "phone", emptyList));
userService.create(new UserEntity(null, sub, "name", "mail", "phone", emptyList));
final UserEntity last = userService.create(new UserEntity(null, sub, "name", "mail", "phone", emptyList));
Assertions.assertEquals(3, userService.getAll().size());
Assertions.assertEquals(last, userService.get(3L));
}
@Test
@Order(2)
void updateUserTest() {
final SubscribeEntity testSub = new SubscribeEntity(null, "test", 100d);
final String testName = "TEST";
final String testMail = "TEST";
final String testPhone = "TEST";
final UserEntity entity = userService.get(3L);
final SubscribeEntity oldSub = entity.getSubscribe();
final String oldName = entity.getName();
final String oldMail = entity.getMail();
final String oldPhone = entity.getPhone();
final UserEntity newEntity = userService.update(3L,
new UserEntity(3L, testSub, testName, testMail, testPhone, emptyList));
Assertions.assertEquals(3, userService.getAll().size());
Assertions.assertEquals(newEntity, userService.get(3L));
Assertions.assertEquals(testSub, newEntity.getSubscribe());
Assertions.assertNotEquals(oldSub, newEntity.getSubscribe());
Assertions.assertEquals(testName, newEntity.getName());
Assertions.assertNotEquals(oldName, newEntity.getName());
Assertions.assertEquals(testMail, newEntity.getMail());
Assertions.assertNotEquals(oldMail, newEntity.getMail());
Assertions.assertEquals(testPhone, newEntity.getPhone());
Assertions.assertNotEquals(oldPhone, newEntity.getPhone());
}
@Test
@Order(3)
void deleteUserTest() {
final SubscribeEntity sub = new SubscribeEntity(null, "sub", 100d);
userService.delete(3L);
Assertions.assertEquals(2, userService.getAll().size());
final UserEntity last = userService.get(2L);
Assertions.assertEquals(2L, last.getId());
final UserEntity newEntity = userService.create(new UserEntity(null, sub, "name", "mail", "phone", emptyList));
Assertions.assertEquals(3, userService.getAll().size());
Assertions.assertEquals(4L, newEntity.getId());
}
@Test
@Order(4)
void addFilmTest() {
userService.addFilm(4L, film);
userService.addFilm(4L, film);
Assertions.assertEquals(true, userService.get(4L).getListFilms().contains(film));
Assertions.assertEquals(1, userService.get(4L).getListFilms().size());
}
@Test
@Order(5)
void deleteFilmTest() {
Assertions.assertEquals(true, userService.get(4L).getListFilms().contains(film));
Assertions.assertEquals(1, userService.get(4L).getListFilms().size());
userService.deleteFilm(4L, film);
Assertions.assertEquals(false, userService.get(4L).getListFilms().contains(film));
Assertions.assertEquals(0, userService.get(4L).getListFilms().size());
}
}

36
Laba3/Лекция3-src/.gitignore vendored Normal file
View File

@ -0,0 +1,36 @@
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/
data.*.db

View File

@ -0,0 +1,12 @@
{
"recommendations": [
// fronted
"AndersEAndersen.html-class-suggestions",
"dbaeumer.vscode-eslint",
// backend
"vscjava.vscode-java-pack",
"vmware.vscode-boot-dev-pack",
"vscjava.vscode-gradle",
"redhat.vscode-xml"
]
}

View File

@ -0,0 +1,24 @@
{
"configurations": [
{
"type": "java",
"name": "Demo",
"request": "launch",
"cwd": "${workspaceFolder}",
"mainClass": "com.example.demo.DemoApplication",
"projectName": "lec3",
"args": "--populate",
"envFile": "${workspaceFolder}/.env"
},
{
"type": "java",
"name": "Spring Boot-DemoApplication<Лекция3-src>",
"request": "launch",
"cwd": "${workspaceFolder}",
"mainClass": "com.example.demo.DemoApplication",
"projectName": екция3-src",
"args": "",
"envFile": "${workspaceFolder}/.env"
}
]
}

View File

@ -0,0 +1,21 @@
{
"editor.tabSize": 4,
"editor.detectIndentation": false,
"editor.insertSpaces": true,
"editor.formatOnPaste": true,
"editor.formatOnSave": true,
"editor.formatOnType": false,
"java.compile.nullAnalysis.mode": "disabled",
"java.configuration.updateBuildConfiguration": "automatic",
"[java]": {
"editor.pasteAs.enabled": false,
},
"gradle.nestedProjects": true,
"java.saveActions.organizeImports": true,
"java.dependency.packagePresentation": "hierarchical",
"spring-boot.ls.problem.boot2.JAVA_CONSTRUCTOR_PARAMETER_INJECTION": "WARNING",
"spring.initializr.defaultLanguage": "Java",
"java.format.settings.url": ".vscode/eclipse-formatter.xml",
"java.project.explorer.showNonJavaResources": true,
"java.codeGeneration.hashCodeEquals.useJava7Objects": true,
}

View File

@ -0,0 +1,43 @@
plugins {
id 'java'
id 'org.springframework.boot' version '3.2.4'
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()
}

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.5-bin.zip
networkTimeout=10000
validateDistributionUrl=true
zipStoreBase=GRADLE_USER_HOME
zipStorePath=wrapper/dists

249
Laba3/Лекция3-src/gradlew vendored Normal file
View 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
Laba3/Лекция3-src/gradlew.bat vendored Normal file
View 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

View File

@ -0,0 +1,18 @@
Swagger UI: \
http://localhost:8080/swagger-ui/index.html
H2 Console: \
http://localhost:8080/h2-console
JDBC URL: jdbc:h2:file:./data \
User Name: sa \
Password: password
Почитать:
- Односторонние и двусторонние связи https://www.baeldung.com/jpa-hibernate-associations
- Getters и Setters для двусторонних связей https://en.wikibooks.org/wiki/Java_Persistence/OneToMany#Getters_and_Setters
- Многие-ко-многим с доп. атрибутами https://thorben-janssen.com/hibernate-tip-many-to-many-association-with-additional-attributes/
- Многие-ко-многим с доп. атрибутами https://www.baeldung.com/jpa-many-to-many
- Каскадное удаление сущностей со связями многие-ко-многим https://www.baeldung.com/jpa-remove-entity-many-to-many
- Выбор типа коллекции для отношений вида ко-многим в JPA https://thorben-janssen.com/association-mappings-bag-list-set/

View File

@ -0,0 +1 @@
rootProject.name = 'demo'

View File

@ -0,0 +1,74 @@
package com.example.demo;
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.users.model.UserEntity;
import com.example.demo.users.service.UserService;
import com.example.demo.films.model.FilmEntity;
import com.example.demo.films.service.FilmService;
import com.example.demo.genres.model.GenreEntity;
import com.example.demo.genres.service.GenreService;
import com.example.demo.subscribes.model.SubscribeEntity;
import com.example.demo.subscribes.service.SubscribeService;
@SpringBootApplication
public class DemoApplication implements CommandLineRunner {
private final Logger log = LoggerFactory.getLogger(DemoApplication.class);
private final UserService userService;
private final FilmService filmService;
private final GenreService genreService;
private final SubscribeService subscribeService;
public DemoApplication(
UserService userService,
FilmService filmService,
GenreService genreService,
SubscribeService subscribeService) {
this.userService = userService;
this.filmService = filmService;
this.genreService = genreService;
this.subscribeService = subscribeService;
}
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 genre values");
// final var genre1 = genreService.create(new GenreEntity("жанр1"));
// final var genre2 = genreService.create(new GenreEntity("жанр2"));
// final var genre3 = genreService.create(new GenreEntity("жанр3"));
// log.info("Create default film values");
// final var film1 = filmService.create(new FilmEntity("film1", genre1, 100d,
// 20));
// final var film2 = filmService.create(new FilmEntity("film2", genre1, 100d,
// 20));
// final var film3 = filmService.create(new FilmEntity("film3", genre2, 100d,
// 20));
// final var film4 = filmService.create(new FilmEntity("film4", genre3, 100d,
// 20));
// final var film5 = filmService.create(new FilmEntity("film5", genre1, 100d,
// 20));
log.info("Create default subscribe values");
final var subscribe1 = subscribeService.create(new SubscribeEntity("Подписка 1", 100d));
final var subscribe2 = subscribeService.create(new SubscribeEntity("Подписка 2", 200d));
log.info("Create default user values");
final var user1 = userService.create(new UserEntity(subscribe1, "user1", "mail", "phone"));
userService.create(new UserEntity(subscribe2, "user2", "mail", "phone"));
}
}
}

View File

@ -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";
private Constants() {
}
}

View File

@ -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();
}
}

View File

@ -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");
}
}

View File

@ -0,0 +1,7 @@
package com.example.demo.core.error;
public class NotFoundException extends RuntimeException {
public <T> NotFoundException(Class<T> clazz, Long id) {
super(String.format("%s with id [%s] is not found or not exists", clazz.getSimpleName(), id));
}
}

View 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;
}
}

View File

@ -0,0 +1,73 @@
package com.example.demo.films.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.films.model.FilmEntity;
import com.example.demo.films.service.FilmService;
import com.example.demo.genres.service.GenreService;
import jakarta.validation.Valid;
@RestController
@RequestMapping(Constants.API_URL + "/film")
public class FilmController {
private final FilmService filmService;
private final GenreService genreService;
private final ModelMapper modelMapper;
public FilmController(FilmService filmService, GenreService genreService, ModelMapper modelMapper) {
this.filmService = filmService;
this.genreService = genreService;
this.modelMapper = modelMapper;
}
private FilmDto toDto(FilmEntity entity) {
return modelMapper.map(entity, FilmDto.class);
}
private FilmEntity toEntity(FilmDto dto) {
final FilmEntity entity = modelMapper.map(dto, FilmEntity.class);
entity.setGenre(genreService.get(dto.getGenreId()));
return entity;
}
@GetMapping
public List<FilmDto> getAll() {
return filmService.getAll().stream()
.map(this::toDto)
.toList();
}
@GetMapping("/{id}")
public FilmDto get(@PathVariable(name = "id") Long id) {
return toDto(filmService.get(id));
}
@PostMapping
public FilmDto create(@RequestBody @Valid FilmDto dto) {
return toDto(filmService.create(toEntity(dto)));
}
@PutMapping("/{id}")
public FilmDto update(
@PathVariable(name = "id") Long id,
@RequestBody @Valid FilmDto dto) {
return toDto(filmService.update(id, toEntity(dto)));
}
@DeleteMapping("/{id}")
public FilmDto delete(@PathVariable(name = "id") Long id) {
return toDto(filmService.delete(id));
}
}

View File

@ -0,0 +1,59 @@
package com.example.demo.films.api;
import com.fasterxml.jackson.annotation.JsonProperty;
import jakarta.validation.constraints.Min;
import jakarta.validation.constraints.NotNull;
public class FilmDto {
private Long id;
@NotNull
private String name;
@NotNull
@Min(1)
private Long genreId;
@NotNull
@Min(1)
private Double price;
@NotNull
@Min(1)
private Integer discount;
@JsonProperty(access = JsonProperty.Access.READ_ONLY)
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public Long getGenreId() {
return genreId;
}
public void setGenreId(Long genreId) {
this.genreId = genreId;
}
public Double getPrice() {
return price;
}
public void setPrice(Double price) {
this.price = price;
}
public Integer getDiscount() {
return discount;
}
public void setDiscount(Integer discount) {
this.discount = discount;
}
@JsonProperty(access = JsonProperty.Access.READ_ONLY)
public Double getSum() {
return price - ((price * discount) * 0.01);
}
}

View File

@ -0,0 +1,106 @@
package com.example.demo.films.model;
import java.util.HashSet;
import java.util.Objects;
import java.util.Set;
import com.example.demo.core.model.BaseEntity;
import com.example.demo.genres.model.GenreEntity;
import com.example.demo.userFilm.model.UserFilmEntity;
import jakarta.persistence.Column;
import jakarta.persistence.Entity;
import jakarta.persistence.JoinColumn;
import jakarta.persistence.ManyToOne;
import jakarta.persistence.OneToMany;
import jakarta.persistence.OrderBy;
import jakarta.persistence.Table;
@Entity
@Table(name = "films")
public class FilmEntity extends BaseEntity {
@Column(nullable = false, unique = true, length = 100)
private String name;
@ManyToOne
@JoinColumn(name = "genreId", nullable = false)
private GenreEntity genre;
@Column(nullable = false)
private Double price;
@Column(nullable = false)
private Integer discount;
@OneToMany(mappedBy = "film")
@OrderBy("id ASC")
private Set<UserFilmEntity> userFilms = new HashSet<>();
public FilmEntity() {
}
public FilmEntity(String name, GenreEntity genre, Double price, Integer discount) {
this.name = name;
this.genre = genre;
this.price = price;
this.discount = discount;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public GenreEntity getGenre() {
return genre;
}
public void setGenre(GenreEntity genre) {
this.genre = genre;
}
public Double getPrice() {
return price;
}
public void setPrice(Double price) {
this.price = price;
}
public Integer getDiscount() {
return discount;
}
public void setDiscount(Integer discount) {
this.discount = discount;
}
public Set<UserFilmEntity> getUserFilms() {
return userFilms;
}
public void addUser(UserFilmEntity userFilm) {
if (userFilm.getFilm() != this) {
userFilm.setFilm(this);
}
userFilms.add(userFilm);
}
@Override
public int hashCode() {
return Objects.hash(id, name, genre, price, discount);
}
@Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null || getClass() != obj.getClass())
return false;
final FilmEntity other = (FilmEntity) obj;
return Objects.equals(other.getId(), id)
&& Objects.equals(other.getName(), name)
&& Objects.equals(other.getGenre(), genre)
&& Objects.equals(other.getPrice(), price)
&& Objects.equals(other.getDiscount(), discount);
}
}

View File

@ -0,0 +1,15 @@
package com.example.demo.films.model;
public class UserFilmEntity {
public FilmEntity getFilm() {
// TODO Auto-generated method stub
throw new UnsupportedOperationException("Unimplemented method 'getFilm'");
}
public void setFilm(FilmEntity filmEntity) {
// TODO Auto-generated method stub
throw new UnsupportedOperationException("Unimplemented method 'setFilm'");
}
}

View File

@ -0,0 +1,11 @@
package com.example.demo.films.repository;
import java.util.Optional;
import org.springframework.data.repository.CrudRepository;
import com.example.demo.films.model.FilmEntity;
public interface FilmRepository extends CrudRepository<FilmEntity, Long> {
Optional<FilmEntity> findByNameIgnoreCase(String name);
}

View File

@ -0,0 +1,64 @@
package com.example.demo.films.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.films.model.FilmEntity;
import com.example.demo.films.repository.FilmRepository;
@Service
public class FilmService {
private final FilmRepository repository;
public FilmService(FilmRepository repository) {
this.repository = repository;
}
private void checkName(String name) {
if (repository.findByNameIgnoreCase(name).isPresent()) {
throw new IllegalArgumentException(
String.format("Type with name %s is already exists", name));
}
}
@Transactional(readOnly = true)
public List<FilmEntity> getAll() {
return StreamSupport.stream(repository.findAll().spliterator(), false).toList();
}
@Transactional(readOnly = true)
public FilmEntity get(long id) {
return repository.findById(id)
.orElseThrow(() -> new NotFoundException(FilmEntity.class, id));
}
@Transactional
public FilmEntity create(FilmEntity entity) {
if (entity == null) {
throw new IllegalArgumentException("Entity is null");
}
checkName(entity.getName());
return repository.save(entity);
}
@Transactional
public FilmEntity update(Long id, FilmEntity entity) {
final FilmEntity existsEntity = get(id);
existsEntity.setName(entity.getName());
existsEntity.setGenre(entity.getGenre());
existsEntity.setPrice(entity.getPrice());
existsEntity.setDiscount(entity.getDiscount());
return repository.save(existsEntity);
}
@Transactional
public FilmEntity delete(Long id) {
final FilmEntity existsEntity = get(id);
repository.delete(existsEntity);
return existsEntity;
}
}

View File

@ -0,0 +1,68 @@
package com.example.demo.genres.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.genres.model.GenreEntity;
import com.example.demo.genres.service.GenreService;
import jakarta.validation.Valid;
@RestController
@RequestMapping(Constants.API_URL + "/genre")
public class GenreController {
private final GenreService genreService;
private final ModelMapper modelMapper;
public GenreController(GenreService genreService, ModelMapper modelMapper) {
this.genreService = genreService;
this.modelMapper = modelMapper;
}
private GenreDto toDto(GenreEntity entity) {
return modelMapper.map(entity, GenreDto.class);
}
private GenreEntity toEntity(GenreDto dto) {
return modelMapper.map(dto, GenreEntity.class);
}
@GetMapping
public List<GenreDto> getAll() {
return genreService.getAll().stream()
.map(this::toDto)
.toList();
}
@GetMapping("/{id}")
public GenreDto get(@PathVariable(name = "id") Long id) {
return toDto(genreService.get(id));
}
@PostMapping
public GenreDto create(@RequestBody @Valid GenreDto dto) {
return toDto(genreService.create(toEntity(dto)));
}
@PutMapping("/{id}")
public GenreDto update(
@PathVariable(name = "id") Long id,
@RequestBody @Valid GenreDto dto) {
return toDto(genreService.update(id, toEntity(dto)));
}
@DeleteMapping("/{id}")
public GenreDto delete(@PathVariable(name = "id") Long id) {
return toDto(genreService.delete(id));
}
}

View File

@ -0,0 +1,30 @@
package com.example.demo.genres.api;
import com.fasterxml.jackson.annotation.JsonProperty;
import jakarta.validation.constraints.NotNull;
import jakarta.validation.constraints.Size;
public class GenreDto {
private Long id;
@NotNull
@Size(min = 5, max = 50)
private String name;
@JsonProperty(access = JsonProperty.Access.READ_ONLY)
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,47 @@
package com.example.demo.genres.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 = "genres")
public class GenreEntity extends BaseEntity {
@Column(nullable = false, unique = true, length = 50)
private String name;
public GenreEntity() {
}
public GenreEntity(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 GenreEntity other = (GenreEntity) obj;
return Objects.equals(other.getId(), id)
&& Objects.equals(other.getName(), name);
}
}

View File

@ -0,0 +1,11 @@
package com.example.demo.genres.repository;
import java.util.Optional;
import org.springframework.data.repository.CrudRepository;
import com.example.demo.genres.model.GenreEntity;
public interface GenreRepository extends CrudRepository<GenreEntity, Long> {
Optional<GenreEntity> findByNameIgnoreCase(String name);
}

View File

@ -0,0 +1,62 @@
package com.example.demo.genres.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.genres.model.GenreEntity;
import com.example.demo.genres.repository.GenreRepository;
@Service
public class GenreService {
private final GenreRepository repository;
public GenreService(GenreRepository repository) {
this.repository = repository;
}
private void checkName(String name) {
if (repository.findByNameIgnoreCase(name).isPresent()) {
throw new IllegalArgumentException(
String.format("Type with name %s is already exists", name));
}
}
@Transactional(readOnly = true)
public List<GenreEntity> getAll() {
return StreamSupport.stream(repository.findAll().spliterator(), false).toList();
}
@Transactional(readOnly = true)
public GenreEntity get(long id) {
return repository.findById(id)
.orElseThrow(() -> new NotFoundException(GenreEntity.class, id));
}
@Transactional
public GenreEntity create(GenreEntity entity) {
if (entity == null) {
throw new IllegalArgumentException("Entity is null");
}
checkName(entity.getName());
return repository.save(entity);
}
@Transactional
public GenreEntity update(Long id, GenreEntity entity) {
final GenreEntity existsEntity = get(id);
checkName(entity.getName());
existsEntity.setName(entity.getName());
return repository.save(existsEntity);
}
@Transactional
public GenreEntity delete(Long id) {
final GenreEntity existsEntity = get(id);
repository.delete(existsEntity);
return existsEntity;
}
}

View File

@ -0,0 +1,68 @@
package com.example.demo.subscribes.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.subscribes.model.SubscribeEntity;
import com.example.demo.subscribes.service.SubscribeService;
import jakarta.validation.Valid;
@RestController
@RequestMapping(Constants.API_URL + "/subscribe")
public class SubscribeController {
private final SubscribeService subscribeService;
private final ModelMapper modelMapper;
public SubscribeController(SubscribeService subscribeService, ModelMapper modelMapper) {
this.subscribeService = subscribeService;
this.modelMapper = modelMapper;
}
private SubscribeDto toDto(SubscribeEntity entity) {
return modelMapper.map(entity, SubscribeDto.class);
}
private SubscribeEntity toEntity(SubscribeDto dto) {
return modelMapper.map(dto, SubscribeEntity.class);
}
@GetMapping
public List<SubscribeDto> getAll() {
return subscribeService.getAll().stream()
.map(this::toDto)
.toList();
}
@GetMapping("/{id}")
public SubscribeDto get(@PathVariable(name = "id") Long id) {
return toDto(subscribeService.get(id));
}
@PostMapping
public SubscribeDto create(@RequestBody @Valid SubscribeDto dto) {
return toDto(subscribeService.create(toEntity(dto)));
}
@PutMapping("/{id}")
public SubscribeDto update(
@PathVariable(name = "id") Long id,
@RequestBody @Valid SubscribeDto dto) {
return toDto(subscribeService.update(id, toEntity(dto)));
}
@DeleteMapping("/{id}")
public SubscribeDto delete(@PathVariable(name = "id") Long id) {
return toDto(subscribeService.delete(id));
}
}

View File

@ -0,0 +1,42 @@
package com.example.demo.subscribes.api;
import com.fasterxml.jackson.annotation.JsonProperty;
import jakarta.validation.constraints.NotNull;
import jakarta.validation.constraints.Min;
import jakarta.validation.constraints.Size;
public class SubscribeDto {
private Long id;
@NotNull
@Size(min = 3, max = 50)
private String name;
@NotNull
@Min(1)
private Double cost;
@JsonProperty(access = JsonProperty.Access.READ_ONLY)
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 Double getCost() {
return cost;
}
public void setCost(Double cost) {
this.cost = cost;
}
}

View File

@ -0,0 +1,60 @@
package com.example.demo.subscribes.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 = "subscribes")
public class SubscribeEntity extends BaseEntity {
@Column(nullable = false, unique = true, length = 50)
private String name;
@Column(nullable = false)
private Double cost;
public SubscribeEntity() {
}
public SubscribeEntity(String name, Double cost) {
this.name = name;
this.cost = cost;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public Double getCost() {
return cost;
}
public void setCost(Double cost) {
this.cost = cost;
}
@Override
public int hashCode() {
return Objects.hash(id, name, cost);
}
@Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null || getClass() != obj.getClass())
return false;
final SubscribeEntity other = (SubscribeEntity) obj;
return Objects.equals(other.getId(), id)
&& Objects.equals(other.getName(), name)
&& Objects.equals(other.getCost(), cost);
}
}

View File

@ -0,0 +1,11 @@
package com.example.demo.subscribes.repository;
import java.util.Optional;
import org.springframework.data.repository.CrudRepository;
import com.example.demo.subscribes.model.SubscribeEntity;
public interface SubscribeRepository extends CrudRepository<SubscribeEntity, Long> {
Optional<SubscribeEntity> findByNameIgnoreCase(String name);
}

View File

@ -0,0 +1,62 @@
package com.example.demo.subscribes.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.subscribes.model.SubscribeEntity;
import com.example.demo.subscribes.repository.SubscribeRepository;
@Service
public class SubscribeService {
private final SubscribeRepository repository;
public SubscribeService(SubscribeRepository repository) {
this.repository = repository;
}
private void checkName(String name) {
if (repository.findByNameIgnoreCase(name).isPresent()) {
throw new IllegalArgumentException(
String.format("Type with name %s is already exists", name));
}
}
@Transactional(readOnly = true)
public List<SubscribeEntity> getAll() {
return StreamSupport.stream(repository.findAll().spliterator(), false).toList();
}
@Transactional(readOnly = true)
public SubscribeEntity get(long id) {
return repository.findById(id)
.orElseThrow(() -> new NotFoundException(SubscribeEntity.class, id));
}
@Transactional
public SubscribeEntity create(SubscribeEntity entity) {
if (entity == null) {
throw new IllegalArgumentException("Entity is null");
}
checkName(entity.getName());
return repository.save(entity);
}
@Transactional
public SubscribeEntity update(Long id, SubscribeEntity entity) {
final SubscribeEntity existsEntity = get(id);
checkName(entity.getName());
existsEntity.setName(entity.getName());
return repository.save(existsEntity);
}
@Transactional
public SubscribeEntity delete(Long id) {
final SubscribeEntity existsEntity = get(id);
repository.delete(existsEntity);
return existsEntity;
}
}

View File

@ -0,0 +1,95 @@
package com.example.demo.userFilm.model;
import com.example.demo.films.model.FilmEntity;
import com.example.demo.users.model.UserEntity;
import java.util.Objects;
import jakarta.persistence.EmbeddedId;
import jakarta.persistence.Entity;
import jakarta.persistence.JoinColumn;
import jakarta.persistence.ManyToOne;
import jakarta.persistence.MapsId;
import jakarta.persistence.Table;
@Entity
@Table(name = "users_films")
public class UserFilmEntity {
@EmbeddedId
private UserFilmId id = new UserFilmId();
@ManyToOne
@MapsId("userId")
@JoinColumn(name = "user_id")
private UserEntity user;
@ManyToOne
@MapsId("filmId")
@JoinColumn(name = "film_id")
private FilmEntity film;
private boolean viewed;
public UserFilmEntity() {
}
public UserFilmEntity(UserEntity user, FilmEntity film, boolean viewed) {
this.user = user;
this.film = film;
this.viewed = viewed;
}
public UserFilmId getId() {
return id;
}
public void setId(UserFilmId id) {
this.id = id;
}
public UserEntity getUser() {
return user;
}
public void setUser(UserEntity user) {
this.user = user;
if (!user.getUserFilms().contains(this)) {
user.getUserFilms().add(this);
}
}
public FilmEntity getFilm() {
return film;
}
public void setFilm(FilmEntity film) {
this.film = film;
if (!film.getUserFilms().contains(this)) {
film.getUserFilms().add(this);
}
}
public boolean isViewed() {
return viewed;
}
public void setActive(boolean viewed) {
this.viewed = viewed;
}
@Override
public int hashCode() {
return Objects.hash(id, user.getId(), film.getId(), viewed);
}
@Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null || getClass() != obj.getClass())
return false;
UserFilmEntity other = (UserFilmEntity) obj;
return Objects.equals(id, other.id)
&& Objects.equals(user.getId(), other.user.getId())
&& Objects.equals(film.getId(), other.film.getId())
&& viewed == other.viewed;
}
}

View File

@ -0,0 +1,55 @@
package com.example.demo.userFilm.model;
import java.util.Objects;
import java.util.Optional;
import jakarta.persistence.Embeddable;
@Embeddable
public class UserFilmId {
private Long userId;
private Long filmId;
public UserFilmId() {
}
public UserFilmId(Long userId, Long filmId) {
this.userId = userId;
this.filmId = filmId;
}
public Long getUserId() {
return userId;
}
public void setUserId(Long userId) {
this.userId = userId;
}
public Long getFilmId() {
return filmId;
}
public void setFilmId(Long filmId) {
this.filmId = filmId;
}
@Override
public int hashCode() {
return Objects.hash(
Optional.ofNullable(userId).orElse(0L),
Optional.ofNullable(filmId).orElse(0L));
}
@Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null || getClass() != obj.getClass())
return false;
UserFilmId other = (UserFilmId) obj;
return Objects.equals(userId, other.userId)
&& Objects.equals(filmId, other.filmId);
}
}

View File

@ -0,0 +1,80 @@
package com.example.demo.users.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.users.model.UserEntity;
import com.example.demo.users.service.UserService;
import com.example.demo.films.service.FilmService;
import jakarta.validation.Valid;
@RestController
@RequestMapping(Constants.API_URL + "/user")
public class UserController {
private final UserService userService;
private final FilmService filmService;
private final ModelMapper modelMapper;
public UserController(UserService userService, FilmService filmService, ModelMapper modelMapper) {
this.userService = userService;
this.filmService = filmService;
this.modelMapper = modelMapper;
}
private UserDto toDto(UserEntity entity) {
return modelMapper.map(entity, UserDto.class);
}
private UserEntity toEntity(UserDto dto) {
return modelMapper.map(dto, UserEntity.class);
}
@GetMapping
public List<UserDto> getAll() {
return userService.getAll().stream()
.map(this::toDto)
.toList();
}
@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));
}
@PutMapping("/addFilm/{id}")
public UserDto addFilm(@PathVariable(name = "id") Long id, @RequestBody Long filmId) {
return toDto(userService.addFilm(id, filmService.get(filmId)));
}
@PutMapping("/deleteFilm/{id}")
public UserDto deleteFilm(@PathVariable(name = "id") Long id, @RequestBody Long filmId) {
return toDto(userService.deleteFilm(id, filmService.get(filmId)));
}
}

View File

@ -0,0 +1,89 @@
package com.example.demo.users.api;
import com.fasterxml.jackson.annotation.JsonProperty;
import com.fasterxml.jackson.annotation.JsonProperty.Access;
import java.util.ArrayList;
import java.util.List;
import jakarta.validation.constraints.NotBlank;
import jakarta.validation.constraints.Size;
import jakarta.validation.constraints.NotNull;
import jakarta.validation.constraints.Min;
import com.example.demo.films.model.FilmEntity;
public class UserDto {
@JsonProperty(access = Access.READ_ONLY)
private Long id;
@NotBlank
@Size(min = 3, max = 50)
private String name;
@NotBlank
@Size(min = 3, max = 50)
private String mail;
@NotBlank
@Size(min = 8, max = 30)
private String phone;
@NotNull
@Min(1)
private Long suscribeId;
private final List<FilmEntity> listFilms = new ArrayList<FilmEntity>();
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 getMail() {
return mail;
}
public void setMail(String mail) {
this.mail = mail;
}
public String getPhone() {
return phone;
}
public void setPhone(String phone) {
this.phone = phone;
}
public Long getSubscribeId() {
return suscribeId;
}
public void setSubscribe(Long subscribeId) {
this.suscribeId = subscribeId;
}
public List<FilmEntity> getListFilms() {
return listFilms;
}
public void setListFilms(List<FilmEntity> listFilms) {
this.listFilms.clear();
this.listFilms.addAll(listFilms);
}
public void addFilm(FilmEntity film) {
this.listFilms.add(film);
}
public void deletefilm(FilmEntity film) {
this.listFilms.remove(film);
}
}

View File

@ -0,0 +1,116 @@
package com.example.demo.users.model;
import java.util.HashSet;
import java.util.Objects;
import java.util.Set;
import com.example.demo.core.model.BaseEntity;
import com.example.demo.subscribes.model.SubscribeEntity;
import com.example.demo.userFilm.model.UserFilmEntity;
import jakarta.persistence.CascadeType;
import jakarta.persistence.Column;
import jakarta.persistence.Entity;
import jakarta.persistence.OneToMany;
import jakarta.persistence.OrderBy;
import jakarta.persistence.ManyToOne;
import jakarta.persistence.JoinColumn;
import jakarta.persistence.Table;
@Entity
@Table(name = "users")
public class UserEntity extends BaseEntity {
@Column(nullable = false, unique = true, length = 50)
private String name;
@Column(nullable = false, unique = true, length = 50)
private String mail;
@Column(nullable = false, unique = true, length = 20)
private String phone;
@ManyToOne
@JoinColumn(name = "subscribeId", nullable = false)
private SubscribeEntity subscribe;
@OneToMany(mappedBy = "user", cascade = CascadeType.ALL, orphanRemoval = true)
@OrderBy("id ASC")
private Set<UserFilmEntity> userFilms = new HashSet<>();
public UserEntity() {
}
public UserEntity(SubscribeEntity subscribe, String name, String mail, String phone) {
this.subscribe = subscribe;
this.name = name;
this.mail = mail;
this.phone = phone;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getMail() {
return mail;
}
public void setMail(String mail) {
this.mail = mail;
}
public String getPhone() {
return phone;
}
public void setPhone(String phone) {
this.phone = phone;
}
public Set<UserFilmEntity> getUserFilms() {
return userFilms;
}
public void addFilm(UserFilmEntity userFilm) {
if (userFilm.getUser() != this) {
userFilm.setUser(this);
}
userFilms.add(userFilm);
}
public void deleteFilm(UserFilmEntity userFilm) {
if (userFilm.getUser() != this) {
return;
}
userFilms.remove(userFilm);
}
public SubscribeEntity getSubscribe() {
return subscribe;
}
public void setSubscribe(SubscribeEntity subscribe) {
this.subscribe = subscribe;
}
@Override
public int hashCode() {
return Objects.hash(id, name, mail, phone, userFilms, subscribe);
}
@Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null || getClass() != obj.getClass())
return false;
UserEntity other = (UserEntity) obj;
return Objects.equals(other.getId(), id)
&& Objects.equals(other.getName(), name)
&& Objects.equals(other.getMail(), mail)
&& Objects.equals(other.getPhone(), phone)
&& Objects.equals(other.getSubscribe(), subscribe)
&& Objects.equals(other.getUserFilms(), userFilms);
}
}

View File

@ -0,0 +1,11 @@
package com.example.demo.users.repository;
import java.util.Optional;
import org.springframework.data.repository.CrudRepository;
import com.example.demo.users.model.UserEntity;
public interface UserRepository extends CrudRepository<UserEntity, Long> {
Optional<UserEntity> findByNameIgnoreCase(String name);
}

View File

@ -0,0 +1,218 @@
package com.example.demo.users.service;
import java.util.List;
import java.util.stream.StreamSupport;
import org.modelmapper.internal.util.Objects;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import com.example.demo.core.error.NotFoundException;
import com.example.demo.films.model.FilmEntity;
import com.example.demo.films.service.FilmService;
import com.example.demo.users.model.UserEntity;
import com.example.demo.users.repository.UserRepository;
import com.example.demo.userFilm.model.UserFilmEntity;
@Service
public class UserService {
// private final UserRepository repository;
// public UserService(UserRepository repository) {
// this.repository = repository;
// }
// private void checkName(String name) {
// if (repository.findByNameIgnoreCase(name).isPresent()) {
// throw new IllegalArgumentException(
// String.format("Type with name %s is already exists", name));
// }
// }
// @Transactional(readOnly = true)
// public List<UserEntity> getAll() {
// return StreamSupport.stream(repository.findAll().spliterator(), false).toList();
// }
// @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");
// }
// checkName(entity.getName());
// return repository.save(entity);
// }
// @Transactional
// public UserEntity update(long id, UserEntity entity) {
// final UserEntity existsEntity = get(id);
// checkName(entity.getName());
// existsEntity.setName(entity.getName());
// existsEntity.setMail(entity.getMail());
// existsEntity.setPhone(entity.getPhone());
// existsEntity.setSubscribe(entity.getSubscribe());
// repository.save(existsEntity);
// return existsEntity;
// }
// @Transactional
// public UserEntity delete(long id) {
// final UserEntity existsEntity = get(id);
// repository.delete(existsEntity);
// return existsEntity;
// }
// @Transactional(readOnly = true)
// public List<UserFilmEntity> getUserFilms(long id) {
// return get(id).getUserFilms().stream().toList();
// }
// @Transactional
// public UserEntity addFilm(Long id, UserFilmEntity film1) {
// final UserEntity existsEntity = get(id);
// if (!existsEntity.getUserFilms().contains(film1))
// existsEntity.addFilm(film1);
// return repository.save(existsEntity);
// }
// @Transactional
// public UserEntity deleteFilm(Long id, UserFilmEntity film) {
// final UserEntity existsEntity = get(id);
// if (existsEntity.getUserFilms().contains(film))
// existsEntity.deleteFilm(film);
// return repository.save(existsEntity);
// }
private final UserRepository repository;
private final FilmService filmService;
public UserService(
UserRepository repository,
FilmService filmService) {
this.repository = repository;
this.filmService = filmService;
}
private void checkLogin(String login) {
if (repository.findByNameIgnoreCase(login).isPresent()) {
throw new IllegalArgumentException(
String.format("User with login %s is already exists", login));
}
}
@Transactional(readOnly = true)
public List<UserEntity> getAll() {
return StreamSupport.stream(repository.findAll().spliterator(), false).toList();
}
@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");
}
checkLogin(entity.getName());
repository.save(entity);
filmService.getAll().forEach(film -> {
final UserFilmEntity userFilm = new UserFilmEntity(entity, film, true);
userFilm.setUser(entity);
userFilm.setFilm(film);
});
return repository.save(entity);
}
@Transactional
public UserEntity update(long id, UserEntity entity) {
final UserEntity existsEntity = get(id);
checkLogin(entity.getName());
existsEntity.setName(entity.getName());
repository.save(existsEntity);
return existsEntity;
}
@Transactional
public UserEntity delete(long id) {
final UserEntity existsEntity = get(id);
repository.delete(existsEntity);
return existsEntity;
}
@Transactional(readOnly = true)
public List<FilmEntity> getUserFilms(long id) {
return get(id).getUserFilms().stream()
.filter(UserFilmEntity::isViewed)
.map(UserFilmEntity::getFilm)
.toList();
}
private List<FilmEntity> changeUserFilmsState(
UserEntity existsUser,
List<Long> filmsIds,
boolean state) {
return existsUser.getUserFilms().stream()
.filter(film -> Objects.nonNull(film.getFilm()))
.filter(film -> filmsIds.contains(film.getFilm().getId()))
.filter(film -> film.isViewed() == !state)
.map(film -> {
film.setActive(state);
return film.getFilm();
})
.toList();
}
@Transactional
public List<FilmEntity> enableUserFilms(long id, List<Long> filmsIds) {
final UserEntity existsUser = get(id);
final List<FilmEntity> changedFilms = changeUserFilmsState(
existsUser, filmsIds, true);
repository.save(existsUser);
return changedFilms;
}
@Transactional
public List<FilmEntity> disableUserFilms(long id, List<Long> filmsIds) {
final UserEntity existsUser = get(id);
final List<FilmEntity> changedFilms = changeUserFilmsState(
existsUser, filmsIds, false);
repository.save(existsUser);
return changedFilms;
}
@Transactional
public List<FilmEntity> deleteAllUserFilms(long id) {
final UserEntity existsUser = get(id);
final List<UserFilmEntity> films = existsUser.getUserFilms().stream()
.filter(film -> Objects.nonNull(film.getFilm()))
.toList();
films.forEach(existsUser::deleteFilm);
repository.save(existsUser);
return films.stream()
.map(UserFilmEntity::getFilm)
.toList();
}
}

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