lab45
This commit is contained in:
parent
9d6a80ec13
commit
fb785b0dc9
36
lab3/.gitignore
vendored
Normal file
36
lab3/.gitignore
vendored
Normal 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
|
12
lab3/.vscode/extensions.json
vendored
Normal file
12
lab3/.vscode/extensions.json
vendored
Normal 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"
|
||||
]
|
||||
}
|
24
lab3/.vscode/launch.json
vendored
Normal file
24
lab3/.vscode/launch.json
vendored
Normal file
@ -0,0 +1,24 @@
|
||||
{
|
||||
"configurations": [
|
||||
{
|
||||
"type": "java",
|
||||
"name": "Demo",
|
||||
"request": "launch",
|
||||
"cwd": "${workspaceFolder}",
|
||||
"mainClass": "com.example.demo.DemoApplication",
|
||||
"projectName": "lec4",
|
||||
"args": "",
|
||||
"envFile": "${workspaceFolder}/.env"
|
||||
},
|
||||
{
|
||||
"type": "java",
|
||||
"name": "Demo (populate)",
|
||||
"request": "launch",
|
||||
"cwd": "${workspaceFolder}",
|
||||
"mainClass": "com.example.demo.DemoApplication",
|
||||
"projectName": "lec4",
|
||||
"args": "--populate",
|
||||
"envFile": "${workspaceFolder}/.env"
|
||||
}
|
||||
]
|
||||
}
|
21
lab3/.vscode/settings.json
vendored
Normal file
21
lab3/.vscode/settings.json
vendored
Normal 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,
|
||||
}
|
62
lab3/build.gradle
Normal file
62
lab3/build.gradle
Normal file
@ -0,0 +1,62 @@
|
||||
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'
|
||||
|
||||
ext {
|
||||
springProfiles = []
|
||||
if (project.hasProperty('prod')) {
|
||||
springProfiles.add('prod')
|
||||
} else {
|
||||
springProfiles.add('dev')
|
||||
}
|
||||
}
|
||||
|
||||
bootRun {
|
||||
def currentProfiles = springProfiles.join(',')
|
||||
println('Current profiles are: ' + currentProfiles)
|
||||
def currentArgs = ['--spring.profiles.active=' + currentProfiles]
|
||||
if (project.hasProperty('args')) {
|
||||
currentArgs.addAll(project.args.split(','))
|
||||
}
|
||||
args currentArgs
|
||||
}
|
||||
|
||||
jar {
|
||||
enabled = false
|
||||
}
|
||||
|
||||
bootJar {
|
||||
archiveFileName = String.format('%s-%s.jar', rootProject.name, version)
|
||||
}
|
||||
|
||||
assert System.properties['java.specification.version'] == '17' || '21'
|
||||
java {
|
||||
sourceCompatibility = '17'
|
||||
}
|
||||
|
||||
repositories {
|
||||
mavenCentral()
|
||||
}
|
||||
|
||||
dependencies {
|
||||
implementation 'org.springframework.boot:spring-boot-starter-web'
|
||||
implementation 'org.springframework.boot:spring-boot-starter-validation'
|
||||
implementation 'org.springdoc:springdoc-openapi-starter-webmvc-ui:2.3.0'
|
||||
implementation 'org.modelmapper:modelmapper:3.2.0'
|
||||
|
||||
implementation 'org.springframework.boot:spring-boot-starter-data-jpa'
|
||||
implementation 'com.h2database:h2:2.2.224'
|
||||
|
||||
testImplementation 'org.springframework.boot:spring-boot-starter-test'
|
||||
}
|
||||
|
||||
tasks.named('test') {
|
||||
useJUnitPlatform()
|
||||
}
|
BIN
lab3/gradle/wrapper/gradle-wrapper.jar
vendored
Normal file
BIN
lab3/gradle/wrapper/gradle-wrapper.jar
vendored
Normal file
Binary file not shown.
7
lab3/gradle/wrapper/gradle-wrapper.properties
vendored
Normal file
7
lab3/gradle/wrapper/gradle-wrapper.properties
vendored
Normal file
@ -0,0 +1,7 @@
|
||||
distributionBase=GRADLE_USER_HOME
|
||||
distributionPath=wrapper/dists
|
||||
distributionUrl=https\://services.gradle.org/distributions/gradle-8.5-bin.zip
|
||||
networkTimeout=10000
|
||||
validateDistributionUrl=true
|
||||
zipStoreBase=GRADLE_USER_HOME
|
||||
zipStorePath=wrapper/dists
|
249
lab3/gradlew
vendored
Normal file
249
lab3/gradlew
vendored
Normal file
@ -0,0 +1,249 @@
|
||||
#!/bin/sh
|
||||
|
||||
#
|
||||
# Copyright © 2015-2021 the original authors.
|
||||
#
|
||||
# Licensed under the Apache License, Version 2.0 (the "License");
|
||||
# you may not use this file except in compliance with the License.
|
||||
# You may obtain a copy of the License at
|
||||
#
|
||||
# https://www.apache.org/licenses/LICENSE-2.0
|
||||
#
|
||||
# Unless required by applicable law or agreed to in writing, software
|
||||
# distributed under the License is distributed on an "AS IS" BASIS,
|
||||
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
# See the License for the specific language governing permissions and
|
||||
# limitations under the License.
|
||||
#
|
||||
|
||||
##############################################################################
|
||||
#
|
||||
# Gradle start up script for POSIX generated by Gradle.
|
||||
#
|
||||
# Important for running:
|
||||
#
|
||||
# (1) You need a POSIX-compliant shell to run this script. If your /bin/sh is
|
||||
# noncompliant, but you have some other compliant shell such as ksh or
|
||||
# bash, then to run this script, type that shell name before the whole
|
||||
# command line, like:
|
||||
#
|
||||
# ksh Gradle
|
||||
#
|
||||
# Busybox and similar reduced shells will NOT work, because this script
|
||||
# requires all of these POSIX shell features:
|
||||
# * functions;
|
||||
# * expansions «$var», «${var}», «${var:-default}», «${var+SET}»,
|
||||
# «${var#prefix}», «${var%suffix}», and «$( cmd )»;
|
||||
# * compound commands having a testable exit status, especially «case»;
|
||||
# * various built-in commands including «command», «set», and «ulimit».
|
||||
#
|
||||
# Important for patching:
|
||||
#
|
||||
# (2) This script targets any POSIX shell, so it avoids extensions provided
|
||||
# by Bash, Ksh, etc; in particular arrays are avoided.
|
||||
#
|
||||
# The "traditional" practice of packing multiple parameters into a
|
||||
# space-separated string is a well documented source of bugs and security
|
||||
# problems, so this is (mostly) avoided, by progressively accumulating
|
||||
# options in "$@", and eventually passing that to Java.
|
||||
#
|
||||
# Where the inherited environment variables (DEFAULT_JVM_OPTS, JAVA_OPTS,
|
||||
# and GRADLE_OPTS) rely on word-splitting, this is performed explicitly;
|
||||
# see the in-line comments for details.
|
||||
#
|
||||
# There are tweaks for specific operating systems such as AIX, CygWin,
|
||||
# Darwin, MinGW, and NonStop.
|
||||
#
|
||||
# (3) This script is generated from the Groovy template
|
||||
# https://github.com/gradle/gradle/blob/HEAD/subprojects/plugins/src/main/resources/org/gradle/api/internal/plugins/unixStartScript.txt
|
||||
# within the Gradle project.
|
||||
#
|
||||
# You can find Gradle at https://github.com/gradle/gradle/.
|
||||
#
|
||||
##############################################################################
|
||||
|
||||
# Attempt to set APP_HOME
|
||||
|
||||
# Resolve links: $0 may be a link
|
||||
app_path=$0
|
||||
|
||||
# Need this for daisy-chained symlinks.
|
||||
while
|
||||
APP_HOME=${app_path%"${app_path##*/}"} # leaves a trailing /; empty if no leading path
|
||||
[ -h "$app_path" ]
|
||||
do
|
||||
ls=$( ls -ld "$app_path" )
|
||||
link=${ls#*' -> '}
|
||||
case $link in #(
|
||||
/*) app_path=$link ;; #(
|
||||
*) app_path=$APP_HOME$link ;;
|
||||
esac
|
||||
done
|
||||
|
||||
# This is normally unused
|
||||
# shellcheck disable=SC2034
|
||||
APP_BASE_NAME=${0##*/}
|
||||
# Discard cd standard output in case $CDPATH is set (https://github.com/gradle/gradle/issues/25036)
|
||||
APP_HOME=$( cd "${APP_HOME:-./}" > /dev/null && pwd -P ) || exit
|
||||
|
||||
# Use the maximum available, or set MAX_FD != -1 to use that value.
|
||||
MAX_FD=maximum
|
||||
|
||||
warn () {
|
||||
echo "$*"
|
||||
} >&2
|
||||
|
||||
die () {
|
||||
echo
|
||||
echo "$*"
|
||||
echo
|
||||
exit 1
|
||||
} >&2
|
||||
|
||||
# OS specific support (must be 'true' or 'false').
|
||||
cygwin=false
|
||||
msys=false
|
||||
darwin=false
|
||||
nonstop=false
|
||||
case "$( uname )" in #(
|
||||
CYGWIN* ) cygwin=true ;; #(
|
||||
Darwin* ) darwin=true ;; #(
|
||||
MSYS* | MINGW* ) msys=true ;; #(
|
||||
NONSTOP* ) nonstop=true ;;
|
||||
esac
|
||||
|
||||
CLASSPATH=$APP_HOME/gradle/wrapper/gradle-wrapper.jar
|
||||
|
||||
|
||||
# Determine the Java command to use to start the JVM.
|
||||
if [ -n "$JAVA_HOME" ] ; then
|
||||
if [ -x "$JAVA_HOME/jre/sh/java" ] ; then
|
||||
# IBM's JDK on AIX uses strange locations for the executables
|
||||
JAVACMD=$JAVA_HOME/jre/sh/java
|
||||
else
|
||||
JAVACMD=$JAVA_HOME/bin/java
|
||||
fi
|
||||
if [ ! -x "$JAVACMD" ] ; then
|
||||
die "ERROR: JAVA_HOME is set to an invalid directory: $JAVA_HOME
|
||||
|
||||
Please set the JAVA_HOME variable in your environment to match the
|
||||
location of your Java installation."
|
||||
fi
|
||||
else
|
||||
JAVACMD=java
|
||||
if ! command -v java >/dev/null 2>&1
|
||||
then
|
||||
die "ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH.
|
||||
|
||||
Please set the JAVA_HOME variable in your environment to match the
|
||||
location of your Java installation."
|
||||
fi
|
||||
fi
|
||||
|
||||
# Increase the maximum file descriptors if we can.
|
||||
if ! "$cygwin" && ! "$darwin" && ! "$nonstop" ; then
|
||||
case $MAX_FD in #(
|
||||
max*)
|
||||
# In POSIX sh, ulimit -H is undefined. That's why the result is checked to see if it worked.
|
||||
# shellcheck disable=SC2039,SC3045
|
||||
MAX_FD=$( ulimit -H -n ) ||
|
||||
warn "Could not query maximum file descriptor limit"
|
||||
esac
|
||||
case $MAX_FD in #(
|
||||
'' | soft) :;; #(
|
||||
*)
|
||||
# In POSIX sh, ulimit -n is undefined. That's why the result is checked to see if it worked.
|
||||
# shellcheck disable=SC2039,SC3045
|
||||
ulimit -n "$MAX_FD" ||
|
||||
warn "Could not set maximum file descriptor limit to $MAX_FD"
|
||||
esac
|
||||
fi
|
||||
|
||||
# Collect all arguments for the java command, stacking in reverse order:
|
||||
# * args from the command line
|
||||
# * the main class name
|
||||
# * -classpath
|
||||
# * -D...appname settings
|
||||
# * --module-path (only if needed)
|
||||
# * DEFAULT_JVM_OPTS, JAVA_OPTS, and GRADLE_OPTS environment variables.
|
||||
|
||||
# For Cygwin or MSYS, switch paths to Windows format before running java
|
||||
if "$cygwin" || "$msys" ; then
|
||||
APP_HOME=$( cygpath --path --mixed "$APP_HOME" )
|
||||
CLASSPATH=$( cygpath --path --mixed "$CLASSPATH" )
|
||||
|
||||
JAVACMD=$( cygpath --unix "$JAVACMD" )
|
||||
|
||||
# Now convert the arguments - kludge to limit ourselves to /bin/sh
|
||||
for arg do
|
||||
if
|
||||
case $arg in #(
|
||||
-*) false ;; # don't mess with options #(
|
||||
/?*) t=${arg#/} t=/${t%%/*} # looks like a POSIX filepath
|
||||
[ -e "$t" ] ;; #(
|
||||
*) false ;;
|
||||
esac
|
||||
then
|
||||
arg=$( cygpath --path --ignore --mixed "$arg" )
|
||||
fi
|
||||
# Roll the args list around exactly as many times as the number of
|
||||
# args, so each arg winds up back in the position where it started, but
|
||||
# possibly modified.
|
||||
#
|
||||
# NB: a `for` loop captures its iteration list before it begins, so
|
||||
# changing the positional parameters here affects neither the number of
|
||||
# iterations, nor the values presented in `arg`.
|
||||
shift # remove old arg
|
||||
set -- "$@" "$arg" # push replacement arg
|
||||
done
|
||||
fi
|
||||
|
||||
|
||||
# Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script.
|
||||
DEFAULT_JVM_OPTS='"-Xmx64m" "-Xms64m"'
|
||||
|
||||
# Collect all arguments for the java command:
|
||||
# * DEFAULT_JVM_OPTS, JAVA_OPTS, JAVA_OPTS, and optsEnvironmentVar are not allowed to contain shell fragments,
|
||||
# and any embedded shellness will be escaped.
|
||||
# * For example: A user cannot expect ${Hostname} to be expanded, as it is an environment variable and will be
|
||||
# treated as '${Hostname}' itself on the command line.
|
||||
|
||||
set -- \
|
||||
"-Dorg.gradle.appname=$APP_BASE_NAME" \
|
||||
-classpath "$CLASSPATH" \
|
||||
org.gradle.wrapper.GradleWrapperMain \
|
||||
"$@"
|
||||
|
||||
# Stop when "xargs" is not available.
|
||||
if ! command -v xargs >/dev/null 2>&1
|
||||
then
|
||||
die "xargs is not available"
|
||||
fi
|
||||
|
||||
# Use "xargs" to parse quoted args.
|
||||
#
|
||||
# With -n1 it outputs one arg per line, with the quotes and backslashes removed.
|
||||
#
|
||||
# In Bash we could simply go:
|
||||
#
|
||||
# readarray ARGS < <( xargs -n1 <<<"$var" ) &&
|
||||
# set -- "${ARGS[@]}" "$@"
|
||||
#
|
||||
# but POSIX shell has neither arrays nor command substitution, so instead we
|
||||
# post-process each arg (as a line of input to sed) to backslash-escape any
|
||||
# character that might be a shell metacharacter, then use eval to reverse
|
||||
# that process (while maintaining the separation between arguments), and wrap
|
||||
# the whole thing up as a single "set" statement.
|
||||
#
|
||||
# This will of course break if any of these variables contains a newline or
|
||||
# an unmatched quote.
|
||||
#
|
||||
|
||||
eval "set -- $(
|
||||
printf '%s\n' "$DEFAULT_JVM_OPTS $JAVA_OPTS $GRADLE_OPTS" |
|
||||
xargs -n1 |
|
||||
sed ' s~[^-[:alnum:]+,./:=@_]~\\&~g; ' |
|
||||
tr '\n' ' '
|
||||
)" '"$@"'
|
||||
|
||||
exec "$JAVACMD" "$@"
|
92
lab3/gradlew.bat
vendored
Normal file
92
lab3/gradlew.bat
vendored
Normal file
@ -0,0 +1,92 @@
|
||||
@rem
|
||||
@rem Copyright 2015 the original author or authors.
|
||||
@rem
|
||||
@rem Licensed under the Apache License, Version 2.0 (the "License");
|
||||
@rem you may not use this file except in compliance with the License.
|
||||
@rem You may obtain a copy of the License at
|
||||
@rem
|
||||
@rem https://www.apache.org/licenses/LICENSE-2.0
|
||||
@rem
|
||||
@rem Unless required by applicable law or agreed to in writing, software
|
||||
@rem distributed under the License is distributed on an "AS IS" BASIS,
|
||||
@rem WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
@rem See the License for the specific language governing permissions and
|
||||
@rem limitations under the License.
|
||||
@rem
|
||||
|
||||
@if "%DEBUG%"=="" @echo off
|
||||
@rem ##########################################################################
|
||||
@rem
|
||||
@rem Gradle startup script for Windows
|
||||
@rem
|
||||
@rem ##########################################################################
|
||||
|
||||
@rem Set local scope for the variables with windows NT shell
|
||||
if "%OS%"=="Windows_NT" setlocal
|
||||
|
||||
set DIRNAME=%~dp0
|
||||
if "%DIRNAME%"=="" set DIRNAME=.
|
||||
@rem This is normally unused
|
||||
set APP_BASE_NAME=%~n0
|
||||
set APP_HOME=%DIRNAME%
|
||||
|
||||
@rem Resolve any "." and ".." in APP_HOME to make it shorter.
|
||||
for %%i in ("%APP_HOME%") do set APP_HOME=%%~fi
|
||||
|
||||
@rem Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script.
|
||||
set DEFAULT_JVM_OPTS="-Xmx64m" "-Xms64m"
|
||||
|
||||
@rem Find java.exe
|
||||
if defined JAVA_HOME goto findJavaFromJavaHome
|
||||
|
||||
set JAVA_EXE=java.exe
|
||||
%JAVA_EXE% -version >NUL 2>&1
|
||||
if %ERRORLEVEL% equ 0 goto execute
|
||||
|
||||
echo.
|
||||
echo ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH.
|
||||
echo.
|
||||
echo Please set the JAVA_HOME variable in your environment to match the
|
||||
echo location of your Java installation.
|
||||
|
||||
goto fail
|
||||
|
||||
:findJavaFromJavaHome
|
||||
set JAVA_HOME=%JAVA_HOME:"=%
|
||||
set JAVA_EXE=%JAVA_HOME%/bin/java.exe
|
||||
|
||||
if exist "%JAVA_EXE%" goto execute
|
||||
|
||||
echo.
|
||||
echo ERROR: JAVA_HOME is set to an invalid directory: %JAVA_HOME%
|
||||
echo.
|
||||
echo Please set the JAVA_HOME variable in your environment to match the
|
||||
echo location of your Java installation.
|
||||
|
||||
goto fail
|
||||
|
||||
:execute
|
||||
@rem Setup the command line
|
||||
|
||||
set CLASSPATH=%APP_HOME%\gradle\wrapper\gradle-wrapper.jar
|
||||
|
||||
|
||||
@rem Execute Gradle
|
||||
"%JAVA_EXE%" %DEFAULT_JVM_OPTS% %JAVA_OPTS% %GRADLE_OPTS% "-Dorg.gradle.appname=%APP_BASE_NAME%" -classpath "%CLASSPATH%" org.gradle.wrapper.GradleWrapperMain %*
|
||||
|
||||
:end
|
||||
@rem End local scope for the variables with windows NT shell
|
||||
if %ERRORLEVEL% equ 0 goto mainEnd
|
||||
|
||||
:fail
|
||||
rem Set variable GRADLE_EXIT_CONSOLE if you need the _script_ return code instead of
|
||||
rem the _cmd.exe /c_ return code!
|
||||
set EXIT_CODE=%ERRORLEVEL%
|
||||
if %EXIT_CODE% equ 0 set EXIT_CODE=1
|
||||
if not ""=="%GRADLE_EXIT_CONSOLE%" exit %EXIT_CODE%
|
||||
exit /b %EXIT_CODE%
|
||||
|
||||
:mainEnd
|
||||
if "%OS%"=="Windows_NT" endlocal
|
||||
|
||||
:omega
|
28
lab3/readme.md
Normal file
28
lab3/readme.md
Normal file
@ -0,0 +1,28 @@
|
||||
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
|
||||
|
||||
Для профиля prod необходимо наличие СУБД PostgreSQL и БД demo-app.
|
||||
|
||||
Создать БД можно так: \
|
||||
createdb -h localhost -U postgres demo-app
|
||||
|
||||
Пример запуска приложения с профилем prod и заполнением БД с помощью аргумента --populate:
|
||||
|
||||
- nix => bash ./gradlew.bat -Pprod -Pargs='--populate'
|
||||
- windows =>.\gradlew.bat -Pprod -Pargs='--populate'
|
||||
|
||||
Почитать:
|
||||
|
||||
- Односторонние и двусторонние связи 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/
|
1
lab3/settings.gradle
Normal file
1
lab3/settings.gradle
Normal file
@ -0,0 +1 @@
|
||||
rootProject.name = 'demo'
|
61
lab3/src/main/java/com/example/demo/DemoApplication.java
Normal file
61
lab3/src/main/java/com/example/demo/DemoApplication.java
Normal file
@ -0,0 +1,61 @@
|
||||
package com.example.demo;
|
||||
|
||||
import java.util.Arrays;
|
||||
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.authors.model.AuthorEntity;
|
||||
import com.example.demo.authors.service.AuthorService;
|
||||
import com.example.demo.books.model.BookEntity;
|
||||
import com.example.demo.books.service.BookService;
|
||||
import com.example.demo.genres.model.GenreEntity;
|
||||
import com.example.demo.genres.service.GenreService;
|
||||
|
||||
@SpringBootApplication
|
||||
public class DemoApplication implements CommandLineRunner {
|
||||
private final Logger log = LoggerFactory.getLogger(DemoApplication.class);
|
||||
|
||||
private final GenreService genreService;
|
||||
private final AuthorService authorService;
|
||||
private final BookService bookService;
|
||||
|
||||
public DemoApplication(GenreService genreService, AuthorService authorService, BookService bookService) {
|
||||
this.genreService = genreService;
|
||||
this.authorService = authorService;
|
||||
this.bookService = bookService;
|
||||
}
|
||||
|
||||
public static void main(String[] args) {
|
||||
SpringApplication.run(DemoApplication.class, args);
|
||||
}
|
||||
|
||||
@Override
|
||||
public void run(String... args) throws Exception {
|
||||
if (args.length > 0 && Arrays.asList(args).contains("--populate")) {
|
||||
log.info("Create default genre values");
|
||||
final var genre1 = genreService.create(new GenreEntity("Роман"));
|
||||
final var genre2 = genreService.create(new GenreEntity("Комедия"));
|
||||
final var genre3 = genreService.create(new GenreEntity("Трагедия"));
|
||||
|
||||
log.info("Create default author values");
|
||||
final var author1 = authorService.create(new AuthorEntity("Л.Н. Толстой"));
|
||||
final var author2 = authorService.create(new AuthorEntity("Илья Ильф"));
|
||||
final var author3 = authorService.create(new AuthorEntity("Ф.М. Достоевский"));
|
||||
|
||||
log.info("Create default book values");
|
||||
final var books = List.of(
|
||||
new BookEntity(genre1, author1, "", "", ""),
|
||||
new BookEntity(genre1, author2, "", "", ""),
|
||||
new BookEntity(genre2, author3, "", "", ""),
|
||||
new BookEntity(genre2, author1, "", "", ""),
|
||||
new BookEntity(genre3, author2, "", "", ""),
|
||||
new BookEntity(genre3, author3, "", "", ""));
|
||||
books.forEach(book -> bookService.create(book));
|
||||
}
|
||||
}
|
||||
}
|
@ -0,0 +1,68 @@
|
||||
package com.example.demo.authors.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.authors.model.AuthorEntity;
|
||||
import com.example.demo.authors.service.AuthorService;
|
||||
|
||||
import jakarta.validation.Valid;
|
||||
|
||||
@RestController
|
||||
@RequestMapping(Constants.API_URL + "/author")
|
||||
public class AuthorController {
|
||||
private final AuthorService authorService;
|
||||
private final ModelMapper modelMapper;
|
||||
|
||||
public AuthorController(AuthorService authorService, ModelMapper modelMapper) {
|
||||
this.authorService = authorService;
|
||||
this.modelMapper = modelMapper;
|
||||
}
|
||||
|
||||
private AuthorDto toDto(AuthorEntity entity) {
|
||||
return modelMapper.map(entity, AuthorDto.class);
|
||||
}
|
||||
|
||||
private AuthorEntity toEntity(AuthorDto dto) {
|
||||
return modelMapper.map(dto, AuthorEntity.class);
|
||||
}
|
||||
|
||||
@GetMapping
|
||||
public List<AuthorDto> getAll() {
|
||||
return authorService.getAll().stream()
|
||||
.map(this::toDto)
|
||||
.toList();
|
||||
}
|
||||
|
||||
@GetMapping("/{id}")
|
||||
public AuthorDto get(@PathVariable(name = "id") Long id) {
|
||||
return toDto(authorService.get(id));
|
||||
}
|
||||
|
||||
@PostMapping
|
||||
public AuthorDto create(@RequestBody @Valid AuthorDto dto) {
|
||||
return toDto(authorService.create(toEntity(dto)));
|
||||
}
|
||||
|
||||
@PutMapping("/{id}")
|
||||
public AuthorDto update(
|
||||
@PathVariable(name = "id") Long id,
|
||||
@RequestBody @Valid AuthorDto dto) {
|
||||
return toDto(authorService.update(id, toEntity(dto)));
|
||||
}
|
||||
|
||||
@DeleteMapping("/{id}")
|
||||
public AuthorDto delete(@PathVariable(name = "id") Long id) {
|
||||
return toDto(authorService.delete(id));
|
||||
}
|
||||
}
|
@ -0,0 +1,30 @@
|
||||
package com.example.demo.authors.api;
|
||||
|
||||
import com.fasterxml.jackson.annotation.JsonProperty;
|
||||
|
||||
import jakarta.validation.constraints.NotBlank;
|
||||
import jakarta.validation.constraints.Size;
|
||||
|
||||
public class AuthorDto {
|
||||
@JsonProperty(access = JsonProperty.Access.READ_ONLY)
|
||||
private Long id;
|
||||
@NotBlank
|
||||
@Size(min = 5, max = 50)
|
||||
private String name;
|
||||
|
||||
public Long getId() {
|
||||
return id;
|
||||
}
|
||||
|
||||
public void setId(Long id) {
|
||||
this.id = id;
|
||||
}
|
||||
|
||||
public String getName() {
|
||||
return name;
|
||||
}
|
||||
|
||||
public void setName(String name) {
|
||||
this.name = name;
|
||||
}
|
||||
}
|
@ -0,0 +1,53 @@
|
||||
package com.example.demo.authors.model;
|
||||
|
||||
import java.util.HashSet;
|
||||
import java.util.Objects;
|
||||
import java.util.Set;
|
||||
|
||||
import com.example.demo.books.model.BookEntity;
|
||||
import com.example.demo.core.model.BaseEntity;
|
||||
|
||||
import jakarta.persistence.CascadeType;
|
||||
import jakarta.persistence.Column;
|
||||
import jakarta.persistence.Entity;
|
||||
import jakarta.persistence.OneToMany;
|
||||
import jakarta.persistence.Table;
|
||||
|
||||
@Entity
|
||||
@Table(name = "authors")
|
||||
public class AuthorEntity extends BaseEntity {
|
||||
@Column(nullable = false, unique = true, length = 50)
|
||||
private String name;
|
||||
@OneToMany(mappedBy = "author", cascade = CascadeType.ALL)
|
||||
private Set<BookEntity> books = new HashSet<>();
|
||||
|
||||
public AuthorEntity() {
|
||||
}
|
||||
|
||||
public AuthorEntity(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 AuthorEntity other = (AuthorEntity) obj;
|
||||
return Objects.equals(other.getId(), id) && Objects.equals(other.getName(), name);
|
||||
}
|
||||
}
|
@ -0,0 +1,11 @@
|
||||
package com.example.demo.authors.repository;
|
||||
|
||||
import java.util.Optional;
|
||||
|
||||
import org.springframework.data.repository.CrudRepository;
|
||||
|
||||
import com.example.demo.authors.model.AuthorEntity;
|
||||
|
||||
public interface AuthorRepository extends CrudRepository<AuthorEntity, Long> {
|
||||
Optional<AuthorEntity> findByNameIgnoreCase(String name);
|
||||
}
|
@ -0,0 +1,68 @@
|
||||
package com.example.demo.authors.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.authors.model.AuthorEntity;
|
||||
import com.example.demo.authors.repository.AuthorRepository;
|
||||
|
||||
@Service
|
||||
public class AuthorService {
|
||||
private final AuthorRepository repository;
|
||||
|
||||
public AuthorService(AuthorRepository repository) {
|
||||
this.repository = repository;
|
||||
}
|
||||
|
||||
private void checkName(String name) {
|
||||
if (repository.findByNameIgnoreCase(name).isPresent()) {
|
||||
throw new IllegalArgumentException(
|
||||
String.format("Author with name %s is already exists", name));
|
||||
}
|
||||
}
|
||||
|
||||
public AuthorEntity findByName(String name) {
|
||||
return repository.findByNameIgnoreCase(name).orElse(null);
|
||||
}
|
||||
|
||||
@Transactional(readOnly = true)
|
||||
public List<AuthorEntity> getAll() {
|
||||
return StreamSupport.stream(repository.findAll().spliterator(), false).toList();
|
||||
}
|
||||
|
||||
@Transactional(readOnly = true)
|
||||
public AuthorEntity get(long id) {
|
||||
return repository.findById(id)
|
||||
.orElseThrow(() -> new NotFoundException(AuthorEntity.class, id));
|
||||
}
|
||||
|
||||
@Transactional
|
||||
public AuthorEntity create(AuthorEntity entity) {
|
||||
if (entity == null) {
|
||||
throw new IllegalArgumentException("Entity is null");
|
||||
}
|
||||
checkName(entity.getName());
|
||||
return repository.save(entity);
|
||||
}
|
||||
|
||||
@Transactional
|
||||
public AuthorEntity update(Long id, AuthorEntity entity) {
|
||||
final AuthorEntity existsEntity = get(id);
|
||||
if (!existsEntity.getName().equalsIgnoreCase(entity.getName())) {
|
||||
checkName(entity.getName());
|
||||
}
|
||||
existsEntity.setName(entity.getName());
|
||||
return repository.save(existsEntity);
|
||||
}
|
||||
|
||||
@Transactional
|
||||
public AuthorEntity delete(Long id) {
|
||||
final AuthorEntity existsEntity = get(id);
|
||||
repository.delete(existsEntity);
|
||||
return existsEntity;
|
||||
}
|
||||
}
|
@ -0,0 +1,83 @@
|
||||
package com.example.demo.books.api;
|
||||
|
||||
import org.modelmapper.ModelMapper;
|
||||
import org.springframework.web.bind.annotation.RequestMapping;
|
||||
import org.springframework.web.bind.annotation.RestController;
|
||||
|
||||
import com.example.demo.genres.service.GenreService;
|
||||
import com.example.demo.core.api.PageDto;
|
||||
import com.example.demo.core.api.PageDtoMapper;
|
||||
import com.example.demo.core.configuration.Constants;
|
||||
import com.example.demo.books.model.BookEntity;
|
||||
import com.example.demo.books.service.BookService;
|
||||
|
||||
import jakarta.validation.Valid;
|
||||
|
||||
import org.springframework.data.domain.PageRequest;
|
||||
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.RequestParam;
|
||||
import org.springframework.web.bind.annotation.PostMapping;
|
||||
import org.springframework.web.bind.annotation.RequestBody;
|
||||
import org.springframework.web.bind.annotation.PutMapping;
|
||||
|
||||
@RestController
|
||||
@RequestMapping(Constants.API_URL + "/book")
|
||||
public class BookController {
|
||||
private final BookService bookService;
|
||||
private final GenreService genreService;
|
||||
private final ModelMapper modelMapper;
|
||||
|
||||
public BookController(BookService bookService, GenreService genreService, ModelMapper modelMapper) {
|
||||
this.modelMapper = modelMapper;
|
||||
this.genreService = genreService;
|
||||
this.bookService = bookService;
|
||||
}
|
||||
|
||||
private BookDto toDto(BookEntity entity) {
|
||||
return modelMapper.map(entity, BookDto.class);
|
||||
}
|
||||
|
||||
private BookEntity toEntity(BookDto dto) {
|
||||
final BookEntity entity = modelMapper.map(dto, BookEntity.class);
|
||||
entity.setGenre(genreService.get(dto.getGenreId()));
|
||||
return entity;
|
||||
}
|
||||
|
||||
// @GetMapping
|
||||
// public List<BookDto> getAll(@RequestParam(name = "genreId", defaultValue =
|
||||
// "0") Long genreId) {
|
||||
// return bookService.getAll(genreId).stream().map(this::toDto).toList();
|
||||
// }
|
||||
|
||||
@GetMapping
|
||||
public PageDto<BookDto> getAll(
|
||||
@RequestParam(name = "genreId", defaultValue = "0") Long genreId,
|
||||
@RequestParam(name = "authorId", defaultValue = "0") Long authorId,
|
||||
@RequestParam(name = "pageNumber", defaultValue = "0") Integer pageNumber,
|
||||
@RequestParam(name = "pageSize", defaultValue = "5") Integer pageSize) {
|
||||
PageRequest pageRequest = PageRequest.of(pageNumber, pageSize);
|
||||
return PageDtoMapper.toDto(bookService.getAll(genreId, authorId, pageRequest), this::toDto);
|
||||
}
|
||||
|
||||
@GetMapping("/{id}")
|
||||
public BookDto get(@PathVariable(name = "id") Long id) {
|
||||
return toDto(bookService.get(id));
|
||||
}
|
||||
|
||||
@PostMapping
|
||||
public BookDto create(@RequestBody @Valid BookDto dto) {
|
||||
return toDto(bookService.create(toEntity(dto)));
|
||||
}
|
||||
|
||||
@PutMapping("/{id}")
|
||||
public BookDto update(@PathVariable(name = "id") Long id, @RequestBody BookDto dto) {
|
||||
return toDto(bookService.update(id, toEntity(dto)));
|
||||
}
|
||||
|
||||
@DeleteMapping("/{id}")
|
||||
public BookDto delete(@PathVariable(name = "id") Long id) {
|
||||
return toDto(bookService.delete(id));
|
||||
}
|
||||
}
|
77
lab3/src/main/java/com/example/demo/books/api/BookDto.java
Normal file
77
lab3/src/main/java/com/example/demo/books/api/BookDto.java
Normal file
@ -0,0 +1,77 @@
|
||||
package com.example.demo.books.api;
|
||||
|
||||
import com.fasterxml.jackson.annotation.JsonProperty;
|
||||
|
||||
import jakarta.validation.constraints.Min;
|
||||
import jakarta.validation.constraints.NotBlank;
|
||||
import jakarta.validation.constraints.NotNull;
|
||||
|
||||
public class BookDto {
|
||||
private Integer id;
|
||||
|
||||
@NotNull
|
||||
@Min(1)
|
||||
private Integer genreId;
|
||||
|
||||
@NotNull
|
||||
@Min(1)
|
||||
private Integer authorId;
|
||||
|
||||
@NotBlank
|
||||
private String name;
|
||||
|
||||
@NotBlank
|
||||
private String year;
|
||||
|
||||
@NotBlank
|
||||
private String description;
|
||||
|
||||
@JsonProperty(access = JsonProperty.Access.READ_ONLY)
|
||||
public Integer getId() {
|
||||
return id;
|
||||
}
|
||||
|
||||
public void setId(Integer id) {
|
||||
this.id = id;
|
||||
}
|
||||
|
||||
public Integer getGenreId() {
|
||||
return genreId;
|
||||
}
|
||||
|
||||
public void setGenreId(Integer genreId) {
|
||||
this.genreId = genreId;
|
||||
}
|
||||
|
||||
public String getName() {
|
||||
return name;
|
||||
}
|
||||
|
||||
public void setName(String name) {
|
||||
this.name = name;
|
||||
}
|
||||
|
||||
public Integer getAuthorId() {
|
||||
return authorId;
|
||||
}
|
||||
|
||||
public void setAuthorId(Integer authorId) {
|
||||
this.authorId = authorId;
|
||||
}
|
||||
|
||||
public String getYear() {
|
||||
return year;
|
||||
}
|
||||
|
||||
public void setYear(String year) {
|
||||
this.year = year;
|
||||
}
|
||||
|
||||
public String getDescription() {
|
||||
return description;
|
||||
}
|
||||
|
||||
public void setDescription(String description) {
|
||||
this.description = description;
|
||||
}
|
||||
}
|
101
lab3/src/main/java/com/example/demo/books/model/BookEntity.java
Normal file
101
lab3/src/main/java/com/example/demo/books/model/BookEntity.java
Normal file
@ -0,0 +1,101 @@
|
||||
package com.example.demo.books.model;
|
||||
|
||||
import java.util.Objects;
|
||||
|
||||
import com.example.demo.authors.model.AuthorEntity;
|
||||
import com.example.demo.core.model.BaseEntity;
|
||||
import com.example.demo.genres.model.GenreEntity;
|
||||
|
||||
import jakarta.persistence.Column;
|
||||
import jakarta.persistence.Entity;
|
||||
import jakarta.persistence.JoinColumn;
|
||||
import jakarta.persistence.ManyToOne;
|
||||
import jakarta.persistence.Table;
|
||||
|
||||
@Entity
|
||||
@Table(name = "books")
|
||||
public class BookEntity extends BaseEntity {
|
||||
@ManyToOne
|
||||
@JoinColumn(name = "genreId", nullable = false)
|
||||
private GenreEntity genre;
|
||||
@ManyToOne
|
||||
@JoinColumn(name = "authorId", nullable = false)
|
||||
private AuthorEntity author;
|
||||
@Column(nullable = false, length = 50)
|
||||
private String name;
|
||||
@Column(name = "years", nullable = false, length = 4)
|
||||
private String year;
|
||||
@Column(nullable = false, length = 250)
|
||||
private String description;
|
||||
|
||||
public BookEntity() {
|
||||
}
|
||||
|
||||
public BookEntity(GenreEntity genre, AuthorEntity author, String name, String year, String description) {
|
||||
this.genre = genre;
|
||||
this.name = name;
|
||||
this.author = author;
|
||||
this.year = year;
|
||||
this.description = description;
|
||||
}
|
||||
|
||||
public GenreEntity getGenre() {
|
||||
return genre;
|
||||
}
|
||||
|
||||
public void setGenre(GenreEntity genre) {
|
||||
this.genre = genre;
|
||||
}
|
||||
|
||||
public AuthorEntity getAuthor() {
|
||||
return author;
|
||||
}
|
||||
|
||||
public void setAuthor(AuthorEntity author) {
|
||||
this.author = author;
|
||||
}
|
||||
|
||||
public String getName() {
|
||||
return name;
|
||||
}
|
||||
|
||||
public void setName(String name) {
|
||||
this.name = name;
|
||||
}
|
||||
|
||||
public String getYear() {
|
||||
return year;
|
||||
}
|
||||
|
||||
public void setYear(String year) {
|
||||
this.year = year;
|
||||
}
|
||||
|
||||
public String getDescription() {
|
||||
return description;
|
||||
}
|
||||
|
||||
public void setDescription(String description) {
|
||||
this.description = description;
|
||||
}
|
||||
|
||||
@Override
|
||||
public int hashCode() {
|
||||
return Objects.hash(id, genre, name, author, year, description);
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean equals(Object obj) {
|
||||
if (this == obj)
|
||||
return true;
|
||||
if (obj == null || getClass() != obj.getClass())
|
||||
return false;
|
||||
final BookEntity other = (BookEntity) obj;
|
||||
return Objects.equals(other.getId(), id)
|
||||
&& Objects.equals(other.getGenre(), genre)
|
||||
&& Objects.equals(other.getName(), name)
|
||||
&& Objects.equals(other.getAuthor(), author)
|
||||
&& Objects.equals(other.getYear(), year)
|
||||
&& Objects.equals(other.getDescription(), description);
|
||||
}
|
||||
}
|
@ -0,0 +1,28 @@
|
||||
package com.example.demo.books.repository;
|
||||
|
||||
import java.util.Optional;
|
||||
import java.util.List;
|
||||
|
||||
import org.springframework.data.domain.Page;
|
||||
import org.springframework.data.domain.PageRequest;
|
||||
import org.springframework.data.repository.CrudRepository;
|
||||
import org.springframework.data.repository.PagingAndSortingRepository;
|
||||
|
||||
import com.example.demo.books.model.BookEntity;
|
||||
|
||||
public interface BookRepository
|
||||
extends CrudRepository<BookEntity, Long>, PagingAndSortingRepository<BookEntity, Long> {
|
||||
Optional<BookEntity> findByNameIgnoreCase(String name);
|
||||
|
||||
List<BookEntity> findByGenreId(Long genreId);
|
||||
|
||||
Page<BookEntity> findByGenreId(Long genreId, PageRequest pageable);
|
||||
|
||||
List<BookEntity> findByAuthorId(Long authorId);
|
||||
|
||||
Page<BookEntity> findByAuthorId(Long authorId, PageRequest pageable);
|
||||
|
||||
List<BookEntity> findByGenreIdAndAuthorId(Long genreId, Long authorId);
|
||||
|
||||
Page<BookEntity> findByGenreIdAndAuthorId(Long genreId, Long authorId, PageRequest pageable);
|
||||
}
|
@ -0,0 +1,76 @@
|
||||
package com.example.demo.books.service;
|
||||
|
||||
import java.util.List;
|
||||
import java.util.stream.StreamSupport;
|
||||
|
||||
import org.springframework.data.domain.Page;
|
||||
import org.springframework.data.domain.PageRequest;
|
||||
import org.springframework.stereotype.Service;
|
||||
import org.springframework.transaction.annotation.Transactional;
|
||||
|
||||
import com.example.demo.core.error.NotFoundException;
|
||||
import com.example.demo.books.model.BookEntity;
|
||||
import com.example.demo.books.repository.BookRepository;
|
||||
|
||||
@Service
|
||||
public class BookService {
|
||||
private final BookRepository repository;
|
||||
|
||||
public BookService(BookRepository repository) {
|
||||
this.repository = repository;
|
||||
}
|
||||
|
||||
@Transactional(readOnly = true)
|
||||
public List<BookEntity> getAll(long genreId, long authorId) {
|
||||
if (genreId == 0L && authorId == 0L) {
|
||||
return StreamSupport.stream(repository.findAll().spliterator(), false).toList();
|
||||
} else if (genreId == 0L) {
|
||||
return repository.findByAuthorId(authorId);
|
||||
} else if (authorId == 0L) {
|
||||
return repository.findByGenreId(genreId);
|
||||
} else {
|
||||
return repository.findByGenreIdAndAuthorId(genreId, authorId);
|
||||
}
|
||||
}
|
||||
|
||||
@Transactional(readOnly = true)
|
||||
public Page<BookEntity> getAll(long genreId, long authorId, PageRequest pageRequest) {
|
||||
if (genreId == 0L && authorId == 0L) {
|
||||
return repository.findAll(pageRequest);
|
||||
} else if (genreId == 0L) {
|
||||
return repository.findByAuthorId(authorId, pageRequest);
|
||||
} else if (authorId == 0L) {
|
||||
return repository.findByGenreId(genreId, pageRequest);
|
||||
} else {
|
||||
return repository.findByGenreIdAndAuthorId(genreId, authorId, pageRequest);
|
||||
}
|
||||
}
|
||||
|
||||
@Transactional(readOnly = true)
|
||||
public BookEntity get(long id) {
|
||||
return repository.findById(id)
|
||||
.orElseThrow(() -> new NotFoundException(BookEntity.class, id));
|
||||
}
|
||||
|
||||
@Transactional
|
||||
public BookEntity create(BookEntity entity) {
|
||||
if (entity == null) {
|
||||
throw new IllegalArgumentException("Entity is null");
|
||||
}
|
||||
return repository.save(entity);
|
||||
}
|
||||
|
||||
@Transactional
|
||||
public BookEntity update(Long id, BookEntity entity) {
|
||||
final BookEntity existsEntity = get(id);
|
||||
existsEntity.setName(entity.getName());
|
||||
return repository.save(existsEntity);
|
||||
}
|
||||
|
||||
@Transactional
|
||||
public BookEntity delete(Long id) {
|
||||
final BookEntity existsEntity = get(id);
|
||||
repository.delete(existsEntity);
|
||||
return existsEntity;
|
||||
}
|
||||
}
|
97
lab3/src/main/java/com/example/demo/core/api/PageDto.java
Normal file
97
lab3/src/main/java/com/example/demo/core/api/PageDto.java
Normal file
@ -0,0 +1,97 @@
|
||||
package com.example.demo.core.api;
|
||||
|
||||
import java.util.ArrayList;
|
||||
import java.util.List;
|
||||
|
||||
public class PageDto<D> {
|
||||
private List<D> items = new ArrayList<>();
|
||||
private int itemsCount;
|
||||
private int currentPage;
|
||||
private int currentSize;
|
||||
private int totalPages;
|
||||
private long totalItems;
|
||||
private boolean isFirst;
|
||||
private boolean isLast;
|
||||
private boolean hasNext;
|
||||
private boolean hasPrevious;
|
||||
|
||||
public List<D> getItems() {
|
||||
return items;
|
||||
}
|
||||
|
||||
public void setItems(List<D> items) {
|
||||
this.items = items;
|
||||
}
|
||||
|
||||
public int getItemsCount() {
|
||||
return itemsCount;
|
||||
}
|
||||
|
||||
public void setItemsCount(int itemsCount) {
|
||||
this.itemsCount = itemsCount;
|
||||
}
|
||||
|
||||
public int getCurrentPage() {
|
||||
return currentPage;
|
||||
}
|
||||
|
||||
public void setCurrentPage(int currentPage) {
|
||||
this.currentPage = currentPage;
|
||||
}
|
||||
|
||||
public int getCurrentSize() {
|
||||
return currentSize;
|
||||
}
|
||||
|
||||
public void setCurrentSize(int currentSize) {
|
||||
this.currentSize = currentSize;
|
||||
}
|
||||
|
||||
public int getTotalPages() {
|
||||
return totalPages;
|
||||
}
|
||||
|
||||
public void setTotalPages(int totalPages) {
|
||||
this.totalPages = totalPages;
|
||||
}
|
||||
|
||||
public long getTotalItems() {
|
||||
return totalItems;
|
||||
}
|
||||
|
||||
public void setTotalItems(long totalItems) {
|
||||
this.totalItems = totalItems;
|
||||
}
|
||||
|
||||
public boolean isFirst() {
|
||||
return isFirst;
|
||||
}
|
||||
|
||||
public void setFirst(boolean isFirst) {
|
||||
this.isFirst = isFirst;
|
||||
}
|
||||
|
||||
public boolean isLast() {
|
||||
return isLast;
|
||||
}
|
||||
|
||||
public void setLast(boolean isLast) {
|
||||
this.isLast = isLast;
|
||||
}
|
||||
|
||||
public boolean isHasNext() {
|
||||
return hasNext;
|
||||
}
|
||||
|
||||
public void setHasNext(boolean hasNext) {
|
||||
this.hasNext = hasNext;
|
||||
}
|
||||
|
||||
public boolean isHasPrevious() {
|
||||
return hasPrevious;
|
||||
}
|
||||
|
||||
public void setHasPrevious(boolean hasPrevious) {
|
||||
this.hasPrevious = hasPrevious;
|
||||
}
|
||||
}
|
@ -0,0 +1,25 @@
|
||||
package com.example.demo.core.api;
|
||||
|
||||
import java.util.function.Function;
|
||||
|
||||
import org.springframework.data.domain.Page;
|
||||
|
||||
public class PageDtoMapper {
|
||||
private PageDtoMapper() {
|
||||
}
|
||||
|
||||
public static <D, E> PageDto<D> toDto(Page<E> page, Function<E, D> mapper) {
|
||||
final PageDto<D> dto = new PageDto<>();
|
||||
dto.setItems(page.getContent().stream().map(mapper::apply).toList());
|
||||
dto.setItemsCount(page.getNumberOfElements());
|
||||
dto.setCurrentPage(page.getNumber());
|
||||
dto.setCurrentSize(page.getSize());
|
||||
dto.setTotalPages(page.getTotalPages());
|
||||
dto.setTotalItems(page.getTotalElements());
|
||||
dto.setFirst(page.isFirst());
|
||||
dto.setLast(page.isLast());
|
||||
dto.setHasNext(page.hasNext());
|
||||
dto.setHasPrevious(page.hasPrevious());
|
||||
return dto;
|
||||
}
|
||||
}
|
@ -0,0 +1,12 @@
|
||||
package com.example.demo.core.configuration;
|
||||
|
||||
public class Constants {
|
||||
public static final String SEQUENCE_NAME = "hibernate_sequence";
|
||||
|
||||
public static final String API_URL = "/api/1.0";
|
||||
|
||||
public static final String DEFAULT_PAGE_SIZE = "5";
|
||||
|
||||
private Constants() {
|
||||
}
|
||||
}
|
@ -0,0 +1,13 @@
|
||||
package com.example.demo.core.configuration;
|
||||
|
||||
import org.modelmapper.ModelMapper;
|
||||
import org.springframework.context.annotation.Bean;
|
||||
import org.springframework.context.annotation.Configuration;
|
||||
|
||||
@Configuration
|
||||
public class MapperConfiguration {
|
||||
@Bean
|
||||
ModelMapper modelMapper() {
|
||||
return new ModelMapper();
|
||||
}
|
||||
}
|
@ -0,0 +1,15 @@
|
||||
package com.example.demo.core.configuration;
|
||||
|
||||
import org.springframework.context.annotation.Configuration;
|
||||
import org.springframework.lang.NonNull;
|
||||
import org.springframework.web.servlet.config.annotation.CorsRegistry;
|
||||
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
|
||||
|
||||
@Configuration
|
||||
public class WebConfiguration implements WebMvcConfigurer {
|
||||
@Override
|
||||
public void addCorsMappings(@NonNull CorsRegistry registry) {
|
||||
registry.addMapping("/**")
|
||||
.allowedMethods("GET", "POST", "PUT", "DELETE");
|
||||
}
|
||||
}
|
@ -0,0 +1,54 @@
|
||||
package com.example.demo.core.error;
|
||||
|
||||
import org.slf4j.Logger;
|
||||
import org.slf4j.LoggerFactory;
|
||||
import org.springframework.http.HttpStatus;
|
||||
import org.springframework.http.HttpStatusCode;
|
||||
import org.springframework.http.ResponseEntity;
|
||||
import org.springframework.web.bind.MethodArgumentNotValidException;
|
||||
import org.springframework.web.bind.annotation.ExceptionHandler;
|
||||
import org.springframework.web.bind.annotation.ResponseStatus;
|
||||
import org.springframework.web.bind.annotation.RestControllerAdvice;
|
||||
|
||||
@RestControllerAdvice
|
||||
public class AdviceController {
|
||||
private final Logger log = LoggerFactory.getLogger(AdviceController.class);
|
||||
|
||||
public static ErrorCauseDto getRootCause(Throwable throwable) {
|
||||
Throwable rootCause = throwable;
|
||||
while (rootCause.getCause() != null && rootCause.getCause() != rootCause) {
|
||||
rootCause = rootCause.getCause();
|
||||
}
|
||||
final StackTraceElement firstError = rootCause.getStackTrace()[0];
|
||||
return new ErrorCauseDto(
|
||||
rootCause.getClass().getName(),
|
||||
firstError.getMethodName(),
|
||||
firstError.getFileName(),
|
||||
firstError.getLineNumber());
|
||||
}
|
||||
|
||||
private ResponseEntity<ErrorDto> handleException(Throwable throwable, HttpStatusCode httpCode) {
|
||||
log.error("{}", throwable.getMessage());
|
||||
throwable.printStackTrace();
|
||||
final ErrorDto errorDto = new ErrorDto(throwable.getMessage(), AdviceController.getRootCause(throwable));
|
||||
return new ResponseEntity<>(errorDto, httpCode);
|
||||
}
|
||||
|
||||
@ExceptionHandler(NotFoundException.class)
|
||||
@ResponseStatus(HttpStatus.NOT_FOUND)
|
||||
public ResponseEntity<ErrorDto> handleNotFoundException(Throwable throwable) {
|
||||
return handleException(throwable, HttpStatus.NOT_FOUND);
|
||||
}
|
||||
|
||||
@ExceptionHandler(MethodArgumentNotValidException.class)
|
||||
@ResponseStatus(HttpStatus.BAD_REQUEST)
|
||||
public ResponseEntity<ErrorDto> handleDataIntegrityViolationException(Throwable throwable) {
|
||||
return handleException(throwable, HttpStatus.BAD_REQUEST);
|
||||
}
|
||||
|
||||
@ExceptionHandler(Exception.class)
|
||||
@ResponseStatus(HttpStatus.INTERNAL_SERVER_ERROR)
|
||||
public ResponseEntity<ErrorDto> handleAnyException(Throwable throwable) {
|
||||
return handleException(throwable, HttpStatus.INTERNAL_SERVER_ERROR);
|
||||
}
|
||||
}
|
@ -0,0 +1,31 @@
|
||||
package com.example.demo.core.error;
|
||||
|
||||
class ErrorCauseDto {
|
||||
private String exception;
|
||||
private String methodName;
|
||||
private String fineName;
|
||||
private int lineNumber;
|
||||
|
||||
ErrorCauseDto(String exception, String methodName, String fineName, int lineNumber) {
|
||||
this.exception = exception;
|
||||
this.methodName = methodName;
|
||||
this.fineName = fineName;
|
||||
this.lineNumber = lineNumber;
|
||||
}
|
||||
|
||||
public String getException() {
|
||||
return exception;
|
||||
}
|
||||
|
||||
public String getMethodName() {
|
||||
return methodName;
|
||||
}
|
||||
|
||||
public String getFineName() {
|
||||
return fineName;
|
||||
}
|
||||
|
||||
public int getLineNumber() {
|
||||
return lineNumber;
|
||||
}
|
||||
}
|
20
lab3/src/main/java/com/example/demo/core/error/ErrorDto.java
Normal file
20
lab3/src/main/java/com/example/demo/core/error/ErrorDto.java
Normal file
@ -0,0 +1,20 @@
|
||||
package com.example.demo.core.error;
|
||||
|
||||
public class ErrorDto {
|
||||
private String error;
|
||||
private ErrorCauseDto rootCause;
|
||||
|
||||
public ErrorDto(String error, ErrorCauseDto rootCause) {
|
||||
this.error = error;
|
||||
this.rootCause = rootCause;
|
||||
}
|
||||
|
||||
public String getError() {
|
||||
return error;
|
||||
}
|
||||
|
||||
public ErrorCauseDto getRootCause() {
|
||||
return rootCause;
|
||||
}
|
||||
|
||||
}
|
@ -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));
|
||||
}
|
||||
}
|
@ -0,0 +1,28 @@
|
||||
package com.example.demo.core.model;
|
||||
|
||||
import com.example.demo.core.configuration.Constants;
|
||||
|
||||
import jakarta.persistence.GeneratedValue;
|
||||
import jakarta.persistence.GenerationType;
|
||||
import jakarta.persistence.Id;
|
||||
import jakarta.persistence.MappedSuperclass;
|
||||
import jakarta.persistence.SequenceGenerator;
|
||||
|
||||
@MappedSuperclass
|
||||
public abstract class BaseEntity {
|
||||
@Id
|
||||
@GeneratedValue(strategy = GenerationType.SEQUENCE, generator = Constants.SEQUENCE_NAME)
|
||||
@SequenceGenerator(name = Constants.SEQUENCE_NAME, sequenceName = Constants.SEQUENCE_NAME, allocationSize = 1)
|
||||
protected Long id;
|
||||
|
||||
protected BaseEntity() {
|
||||
}
|
||||
|
||||
public Long getId() {
|
||||
return id;
|
||||
}
|
||||
|
||||
public void setId(Long id) {
|
||||
this.id = id;
|
||||
}
|
||||
}
|
@ -0,0 +1,77 @@
|
||||
package com.example.demo.favorites.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.favorites.model.FavoriteEntity;
|
||||
import com.example.demo.favorites.service.FavoriteService;
|
||||
import com.example.demo.books.service.BookService;
|
||||
import com.example.demo.users.service.UserService;
|
||||
|
||||
import jakarta.validation.Valid;
|
||||
|
||||
@RestController
|
||||
@RequestMapping(Constants.API_URL + "/favorite")
|
||||
public class FavoriteController {
|
||||
|
||||
private final FavoriteService favoriteService;
|
||||
private final UserService userService;
|
||||
private final BookService bookService;
|
||||
private final ModelMapper modelMapper;
|
||||
|
||||
public FavoriteController(FavoriteService favoriteService, UserService userService,
|
||||
BookService bookService, ModelMapper modelMapper) {
|
||||
this.modelMapper = modelMapper;
|
||||
this.userService = userService;
|
||||
this.favoriteService = favoriteService;
|
||||
this.bookService = bookService;
|
||||
}
|
||||
|
||||
private FavoriteDto toDto(FavoriteEntity entity) {
|
||||
return modelMapper.map(entity, FavoriteDto.class);
|
||||
}
|
||||
|
||||
private FavoriteEntity toEntity(FavoriteDto dto) {
|
||||
final FavoriteEntity entity = modelMapper.map(dto, FavoriteEntity.class);
|
||||
entity.setBook(bookService.get(dto.getBookId()));
|
||||
entity.setUser(userService.get(dto.getUserId()));
|
||||
return entity;
|
||||
}
|
||||
|
||||
@GetMapping
|
||||
public List<FavoriteDto> getAll(@RequestParam(name = "userId", defaultValue = "0") Long userId) {
|
||||
return favoriteService.getAll(userId).stream().map(this::toDto).toList();
|
||||
}
|
||||
|
||||
@GetMapping("/{id}")
|
||||
public FavoriteDto get(@PathVariable(name = "id") Long id) {
|
||||
return toDto(favoriteService.get(id));
|
||||
}
|
||||
|
||||
@PostMapping
|
||||
public FavoriteDto create(@RequestBody @Valid FavoriteDto dto) {
|
||||
return toDto(favoriteService.create(toEntity(dto)));
|
||||
}
|
||||
|
||||
@PutMapping("/{id}")
|
||||
public FavoriteDto update(@PathVariable(name = "id") Long id,
|
||||
@RequestBody FavoriteDto dto) {
|
||||
return toDto(favoriteService.update(id, toEntity(dto)));
|
||||
}
|
||||
|
||||
@DeleteMapping("/{id}")
|
||||
public FavoriteDto delete(@PathVariable(name = "id") Long id) {
|
||||
return toDto(favoriteService.delete(id));
|
||||
}
|
||||
}
|
@ -0,0 +1,45 @@
|
||||
package com.example.demo.favorites.api;
|
||||
|
||||
import com.fasterxml.jackson.annotation.JsonProperty;
|
||||
|
||||
import jakarta.validation.constraints.Min;
|
||||
import jakarta.validation.constraints.NotNull;
|
||||
|
||||
public class FavoriteDto {
|
||||
|
||||
@JsonProperty(access = JsonProperty.Access.READ_ONLY)
|
||||
private Long id;
|
||||
|
||||
@NotNull
|
||||
@Min(1)
|
||||
private Long userId;
|
||||
|
||||
@NotNull
|
||||
@Min(1)
|
||||
private Long bookId;
|
||||
|
||||
@JsonProperty(access = JsonProperty.Access.READ_ONLY)
|
||||
public Long getId() {
|
||||
return id;
|
||||
}
|
||||
|
||||
public void setId(Long id) {
|
||||
this.id = id;
|
||||
}
|
||||
|
||||
public Long getUserId() {
|
||||
return userId;
|
||||
}
|
||||
|
||||
public void setUserId(Long userId) {
|
||||
this.userId = userId;
|
||||
}
|
||||
|
||||
public Long getBookId() {
|
||||
return bookId;
|
||||
}
|
||||
|
||||
public void setBookId(Long bookId) {
|
||||
this.bookId = bookId;
|
||||
}
|
||||
}
|
@ -0,0 +1,66 @@
|
||||
package com.example.demo.favorites.model;
|
||||
|
||||
import java.util.Objects;
|
||||
|
||||
import com.example.demo.books.model.BookEntity;
|
||||
import com.example.demo.core.model.BaseEntity;
|
||||
import com.example.demo.users.model.UserEntity;
|
||||
|
||||
import jakarta.persistence.Entity;
|
||||
import jakarta.persistence.JoinColumn;
|
||||
import jakarta.persistence.ManyToOne;
|
||||
import jakarta.persistence.Table;
|
||||
|
||||
@Entity
|
||||
@Table(name = "favorites")
|
||||
public class FavoriteEntity extends BaseEntity {
|
||||
@ManyToOne
|
||||
@JoinColumn(name = "userId", nullable = false)
|
||||
private UserEntity user;
|
||||
|
||||
@ManyToOne
|
||||
@JoinColumn(name = "bookId", nullable = false)
|
||||
private BookEntity book;
|
||||
|
||||
public FavoriteEntity() {
|
||||
super();
|
||||
}
|
||||
|
||||
public FavoriteEntity(Integer id, UserEntity user, BookEntity book) {
|
||||
this.user = user;
|
||||
this.book = book;
|
||||
}
|
||||
|
||||
public UserEntity getUser() {
|
||||
return user;
|
||||
}
|
||||
|
||||
public void setUser(UserEntity user) {
|
||||
this.user = user;
|
||||
}
|
||||
|
||||
public BookEntity getBook() {
|
||||
return book;
|
||||
}
|
||||
|
||||
public void setBook(BookEntity book) {
|
||||
this.book = book;
|
||||
}
|
||||
|
||||
@Override
|
||||
public int hashCode() {
|
||||
return Objects.hash(id, user, book);
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean equals(Object obj) {
|
||||
if (this == obj)
|
||||
return true;
|
||||
if (obj == null || getClass() != obj.getClass())
|
||||
return false;
|
||||
final FavoriteEntity other = (FavoriteEntity) obj;
|
||||
return Objects.equals(other.getId(), id)
|
||||
&& Objects.equals(other.getUser(), user)
|
||||
&& Objects.equals(other.getBook(), book);
|
||||
}
|
||||
}
|
@ -0,0 +1,13 @@
|
||||
package com.example.demo.favorites.repository;
|
||||
|
||||
import java.util.Optional;
|
||||
import java.util.List;
|
||||
import org.springframework.data.repository.CrudRepository;
|
||||
|
||||
import com.example.demo.favorites.model.FavoriteEntity;
|
||||
|
||||
public interface FavoriteRepository extends CrudRepository<FavoriteEntity, Long> {
|
||||
List<FavoriteEntity> findByUserId(Long userId);
|
||||
|
||||
Optional<FavoriteEntity> findOneByUserIdAndId(Long userId, Long id);
|
||||
}
|
@ -0,0 +1,53 @@
|
||||
package com.example.demo.favorites.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.favorites.model.FavoriteEntity;
|
||||
import com.example.demo.favorites.repository.FavoriteRepository;
|
||||
|
||||
@Service
|
||||
public class FavoriteService {
|
||||
private final FavoriteRepository repository;
|
||||
|
||||
public FavoriteService(FavoriteRepository repository) {
|
||||
this.repository = repository;
|
||||
}
|
||||
|
||||
@Transactional(readOnly = true)
|
||||
public List<FavoriteEntity> getAll(Long userId) {
|
||||
if (userId == 0) {
|
||||
return StreamSupport.stream(repository.findAll().spliterator(), false).toList();
|
||||
}
|
||||
return repository.findByUserId(userId);
|
||||
}
|
||||
|
||||
@Transactional(readOnly = true)
|
||||
public FavoriteEntity get(Long id) {
|
||||
return repository.findById(id).orElseThrow(() -> new NotFoundException(null, id));
|
||||
}
|
||||
|
||||
@Transactional
|
||||
public FavoriteEntity create(FavoriteEntity entity) {
|
||||
return repository.save(entity);
|
||||
}
|
||||
|
||||
@Transactional
|
||||
public FavoriteEntity update(Long id, FavoriteEntity entity) {
|
||||
final FavoriteEntity exisEntity = get(id);
|
||||
exisEntity.setUser(entity.getUser());
|
||||
exisEntity.setBook(entity.getBook());
|
||||
return repository.save(exisEntity);
|
||||
}
|
||||
|
||||
@Transactional
|
||||
public FavoriteEntity delete(Long id) {
|
||||
final FavoriteEntity existEntity = get(id);
|
||||
repository.delete(existEntity);
|
||||
return existEntity;
|
||||
}
|
||||
}
|
@ -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));
|
||||
}
|
||||
}
|
30
lab3/src/main/java/com/example/demo/genres/api/GenreDto.java
Normal file
30
lab3/src/main/java/com/example/demo/genres/api/GenreDto.java
Normal file
@ -0,0 +1,30 @@
|
||||
package com.example.demo.genres.api;
|
||||
|
||||
import com.fasterxml.jackson.annotation.JsonProperty;
|
||||
|
||||
import jakarta.validation.constraints.NotBlank;
|
||||
import jakarta.validation.constraints.Size;
|
||||
|
||||
public class GenreDto {
|
||||
@JsonProperty(access = JsonProperty.Access.READ_ONLY)
|
||||
private Long id;
|
||||
@NotBlank
|
||||
@Size(min = 5, max = 50)
|
||||
private String name;
|
||||
|
||||
public Long getId() {
|
||||
return id;
|
||||
}
|
||||
|
||||
public void setId(Long id) {
|
||||
this.id = id;
|
||||
}
|
||||
|
||||
public String getName() {
|
||||
return name;
|
||||
}
|
||||
|
||||
public void setName(String name) {
|
||||
this.name = name;
|
||||
}
|
||||
}
|
@ -0,0 +1,53 @@
|
||||
package com.example.demo.genres.model;
|
||||
|
||||
import java.util.HashSet;
|
||||
import java.util.Objects;
|
||||
import java.util.Set;
|
||||
|
||||
import com.example.demo.books.model.BookEntity;
|
||||
import com.example.demo.core.model.BaseEntity;
|
||||
|
||||
import jakarta.persistence.CascadeType;
|
||||
import jakarta.persistence.Column;
|
||||
import jakarta.persistence.Entity;
|
||||
import jakarta.persistence.OneToMany;
|
||||
import jakarta.persistence.Table;
|
||||
|
||||
@Entity
|
||||
@Table(name = "genres")
|
||||
public class GenreEntity extends BaseEntity {
|
||||
@Column(nullable = false, unique = true, length = 50)
|
||||
private String name;
|
||||
@OneToMany(mappedBy = "genre", cascade = CascadeType.ALL)
|
||||
private Set<BookEntity> books = new HashSet<>();
|
||||
|
||||
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);
|
||||
}
|
||||
}
|
@ -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);
|
||||
}
|
@ -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("Genre 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;
|
||||
}
|
||||
}
|
@ -0,0 +1,74 @@
|
||||
package com.example.demo.users.api;
|
||||
|
||||
import org.modelmapper.ModelMapper;
|
||||
import org.springframework.data.domain.PageRequest;
|
||||
import org.springframework.web.bind.annotation.DeleteMapping;
|
||||
import org.springframework.web.bind.annotation.GetMapping;
|
||||
import org.springframework.web.bind.annotation.PathVariable;
|
||||
import org.springframework.web.bind.annotation.PostMapping;
|
||||
import org.springframework.web.bind.annotation.PutMapping;
|
||||
import org.springframework.web.bind.annotation.RequestBody;
|
||||
import org.springframework.web.bind.annotation.RequestMapping;
|
||||
import org.springframework.web.bind.annotation.RequestParam;
|
||||
import org.springframework.web.bind.annotation.RestController;
|
||||
|
||||
import com.example.demo.core.api.PageDto;
|
||||
import com.example.demo.core.api.PageDtoMapper;
|
||||
import com.example.demo.core.configuration.Constants;
|
||||
import com.example.demo.users.model.UserEntity;
|
||||
import com.example.demo.users.service.UserService;
|
||||
|
||||
import jakarta.validation.Valid;
|
||||
|
||||
@RestController
|
||||
@RequestMapping(Constants.API_URL + "/user")
|
||||
public class UserController {
|
||||
private final UserService userService;
|
||||
private final ModelMapper modelMapper;
|
||||
|
||||
public UserController(UserService userService, ModelMapper modelMapper) {
|
||||
this.modelMapper = modelMapper;
|
||||
this.userService = userService;
|
||||
}
|
||||
|
||||
private UserEntity toEntity(UserDto dto) {
|
||||
return modelMapper.map(dto, UserEntity.class);
|
||||
}
|
||||
|
||||
private UserDto toDto(UserEntity entity) {
|
||||
return modelMapper.map(entity, UserDto.class);
|
||||
}
|
||||
|
||||
// @GetMapping()
|
||||
// public List<UserDto> getAll() {
|
||||
// return userService.getAll().stream().map(this::toDto).toList();
|
||||
// }
|
||||
|
||||
@GetMapping
|
||||
public PageDto<UserDto> getAll(@RequestParam(name = "pageNumber", defaultValue = "0") Integer pageNumber,
|
||||
@RequestParam(name = "pageSize", defaultValue = "5") Integer pageSize) {
|
||||
PageRequest pageRequest = PageRequest.of(pageNumber, pageSize);
|
||||
return PageDtoMapper.toDto(userService.getAll(pageRequest), this::toDto);
|
||||
}
|
||||
|
||||
@GetMapping("/{id}")
|
||||
public UserDto get(@PathVariable(name = "id") Long id) {
|
||||
return toDto(userService.get(id));
|
||||
}
|
||||
|
||||
@PostMapping
|
||||
public UserDto create(@RequestBody @Valid UserDto userDTO) {
|
||||
|
||||
return toDto(userService.create(toEntity(userDTO)));
|
||||
}
|
||||
|
||||
@PutMapping("/{id}")
|
||||
public UserDto update(@PathVariable(name = "id") Long id, @RequestBody UserDto userDTO) {
|
||||
return toDto(userService.update(id, toEntity(userDTO)));
|
||||
}
|
||||
|
||||
@DeleteMapping("/{id}")
|
||||
public UserDto delete(@PathVariable(name = "id") Long id) {
|
||||
return toDto(userService.delete(id));
|
||||
}
|
||||
}
|
56
lab3/src/main/java/com/example/demo/users/api/UserDto.java
Normal file
56
lab3/src/main/java/com/example/demo/users/api/UserDto.java
Normal file
@ -0,0 +1,56 @@
|
||||
package com.example.demo.users.api;
|
||||
|
||||
import com.fasterxml.jackson.annotation.JsonProperty;
|
||||
|
||||
import jakarta.validation.constraints.NotBlank;
|
||||
import jakarta.validation.constraints.NotNull;
|
||||
import jakarta.validation.constraints.Size;
|
||||
|
||||
public class UserDto {
|
||||
@JsonProperty(access = JsonProperty.Access.READ_ONLY)
|
||||
private Long id;
|
||||
|
||||
@NotBlank
|
||||
@Size(min = 2, max = 50)
|
||||
private String username;
|
||||
|
||||
@NotBlank
|
||||
@Size(min = 2, max = 10)
|
||||
private String password;
|
||||
|
||||
@NotNull
|
||||
private boolean isAdmin;
|
||||
|
||||
@JsonProperty(access = JsonProperty.Access.READ_ONLY)
|
||||
public Long getId() {
|
||||
return id;
|
||||
}
|
||||
|
||||
public void setId(Long id) {
|
||||
this.id = id;
|
||||
}
|
||||
|
||||
public String getUsername() {
|
||||
return username;
|
||||
}
|
||||
|
||||
public void setUsername(String username) {
|
||||
this.username = username;
|
||||
}
|
||||
|
||||
public String getPassword() {
|
||||
return password;
|
||||
}
|
||||
|
||||
public void setPassword(String password) {
|
||||
this.password = password;
|
||||
}
|
||||
|
||||
public boolean getIsAdmin() {
|
||||
return isAdmin;
|
||||
}
|
||||
|
||||
public void setIsAdmin(boolean isAdmin) {
|
||||
this.isAdmin = isAdmin;
|
||||
}
|
||||
}
|
@ -0,0 +1,74 @@
|
||||
package com.example.demo.users.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 = "users")
|
||||
public class UserEntity extends BaseEntity {
|
||||
@Column(nullable = false, unique = true, length = 15)
|
||||
private String username;
|
||||
|
||||
@Column(nullable = false, length = 10)
|
||||
private String password;
|
||||
|
||||
@Column(nullable = false)
|
||||
private boolean isAdmin;
|
||||
|
||||
public UserEntity() {
|
||||
|
||||
}
|
||||
|
||||
public UserEntity(String username, String password, boolean isAdmin) {
|
||||
this.username = username;
|
||||
this.password = password;
|
||||
this.isAdmin = isAdmin;
|
||||
}
|
||||
|
||||
public String getUsername() {
|
||||
return username;
|
||||
}
|
||||
|
||||
public void setUsername(String username) {
|
||||
this.username = username;
|
||||
}
|
||||
|
||||
public String getPassword() {
|
||||
return password;
|
||||
}
|
||||
|
||||
public void setPassword(String password) {
|
||||
this.password = password;
|
||||
}
|
||||
|
||||
public boolean getIsAdmin() {
|
||||
return isAdmin;
|
||||
}
|
||||
|
||||
public void setIsAdmin(boolean isAdmin) {
|
||||
this.isAdmin = isAdmin;
|
||||
}
|
||||
|
||||
@Override
|
||||
public int hashCode() {
|
||||
return Objects.hash(id, username, password, isAdmin);
|
||||
}
|
||||
|
||||
@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.getUsername(), username) &&
|
||||
Objects.equals(other.getIsAdmin(), isAdmin) &&
|
||||
Objects.equals(other.getPassword(), password);
|
||||
}
|
||||
}
|
@ -0,0 +1,13 @@
|
||||
package com.example.demo.users.repository;
|
||||
|
||||
import java.util.Optional;
|
||||
|
||||
import org.springframework.data.repository.CrudRepository;
|
||||
import org.springframework.data.repository.PagingAndSortingRepository;
|
||||
|
||||
import com.example.demo.users.model.UserEntity;
|
||||
|
||||
public interface UserRepository
|
||||
extends CrudRepository<UserEntity, Long>, PagingAndSortingRepository<UserEntity, Long> {
|
||||
Optional<UserEntity> findByUsernameIgnoreCase(String username);
|
||||
}
|
@ -0,0 +1,59 @@
|
||||
package com.example.demo.users.service;
|
||||
|
||||
import java.util.List;
|
||||
import java.util.stream.StreamSupport;
|
||||
|
||||
import org.springframework.data.domain.Page;
|
||||
import org.springframework.data.domain.PageRequest;
|
||||
import org.springframework.stereotype.Service;
|
||||
import org.springframework.transaction.annotation.Transactional;
|
||||
|
||||
import com.example.demo.core.error.NotFoundException;
|
||||
import com.example.demo.users.model.UserEntity;
|
||||
import com.example.demo.users.repository.UserRepository;
|
||||
|
||||
@Service
|
||||
public class UserService {
|
||||
private final UserRepository repository;
|
||||
|
||||
public UserService(UserRepository repository) {
|
||||
this.repository = repository;
|
||||
}
|
||||
|
||||
@Transactional(readOnly = true)
|
||||
public List<UserEntity> getAll() {
|
||||
return StreamSupport.stream(repository.findAll().spliterator(), false).toList();
|
||||
}
|
||||
|
||||
@Transactional(readOnly = true)
|
||||
public Page<UserEntity> getAll(PageRequest pageRequest) {
|
||||
return repository.findAll(pageRequest);
|
||||
}
|
||||
|
||||
@Transactional(readOnly = true)
|
||||
public UserEntity get(Long id) {
|
||||
return repository.findById(id).orElseThrow(() -> new NotFoundException(null, id));
|
||||
}
|
||||
|
||||
@Transactional
|
||||
public UserEntity create(UserEntity entity) {
|
||||
return repository.save(entity);
|
||||
}
|
||||
|
||||
@Transactional
|
||||
public UserEntity update(Long id, UserEntity entity) {
|
||||
final UserEntity existsentity = get(id);
|
||||
existsentity.setUsername(entity.getUsername());
|
||||
existsentity.setPassword(entity.getPassword());
|
||||
existsentity.setIsAdmin(entity.getIsAdmin());
|
||||
return repository.save(existsentity);
|
||||
}
|
||||
|
||||
@Transactional
|
||||
public UserEntity delete(Long id) {
|
||||
final UserEntity existsentity = get(id);
|
||||
repository.delete(existsentity);
|
||||
return existsentity;
|
||||
}
|
||||
|
||||
}
|
20
lab3/src/main/resources/application.properties
Normal file
20
lab3/src/main/resources/application.properties
Normal file
@ -0,0 +1,20 @@
|
||||
# Server
|
||||
spring.main.banner-mode=off
|
||||
server.port=8080
|
||||
|
||||
# Logger settings
|
||||
# Available levels are: TRACE, DEBUG, INFO, WARN, ERROR, FATAL, OFF
|
||||
logging.level.com.example.demo=DEBUG
|
||||
|
||||
# JPA Settings
|
||||
spring.datasource.url=jdbc:h2:file:./data
|
||||
spring.datasource.username=sa
|
||||
spring.datasource.password=password
|
||||
spring.datasource.driver-class-name=org.h2.Driver
|
||||
spring.jpa.hibernate.ddl-auto=create
|
||||
spring.jpa.open-in-view=false
|
||||
# spring.jpa.show-sql=true
|
||||
# spring.jpa.properties.hibernate.format_sql=true
|
||||
|
||||
# H2 console
|
||||
spring.h2.console.enabled=true
|
77
lab3/src/test/java/com/example/demo/AuthorServiceTests.java
Normal file
77
lab3/src/test/java/com/example/demo/AuthorServiceTests.java
Normal file
@ -0,0 +1,77 @@
|
||||
package com.example.demo;
|
||||
|
||||
import org.junit.jupiter.api.AfterEach;
|
||||
import org.junit.jupiter.api.Assertions;
|
||||
import org.junit.jupiter.api.BeforeEach;
|
||||
import org.junit.jupiter.api.Test;
|
||||
import org.springframework.beans.factory.annotation.Autowired;
|
||||
import org.springframework.boot.test.context.SpringBootTest;
|
||||
import org.springframework.dao.DataIntegrityViolationException;
|
||||
|
||||
import com.example.demo.core.error.NotFoundException;
|
||||
import com.example.demo.authors.model.AuthorEntity;
|
||||
import com.example.demo.authors.service.AuthorService;
|
||||
|
||||
@SpringBootTest
|
||||
public class AuthorServiceTests {
|
||||
@Autowired
|
||||
private AuthorService authorService;
|
||||
|
||||
private AuthorEntity author;
|
||||
|
||||
@BeforeEach
|
||||
void createData() {
|
||||
removeData();
|
||||
|
||||
author = authorService.create(new AuthorEntity("А.С. Пушкин"));
|
||||
authorService.create(new AuthorEntity("А.П. Чехов"));
|
||||
|
||||
}
|
||||
|
||||
@AfterEach
|
||||
void removeData() {
|
||||
authorService.getAll().forEach(item -> authorService.delete(item.getId()));
|
||||
}
|
||||
|
||||
@Test
|
||||
void getTest() {
|
||||
Assertions.assertThrows(NotFoundException.class, () -> authorService.get(0));
|
||||
}
|
||||
|
||||
@Test
|
||||
void createTest() {
|
||||
Assertions.assertEquals(2, authorService.getAll().size());
|
||||
Assertions.assertEquals(author, authorService.get(author.getId()));
|
||||
}
|
||||
|
||||
@Test
|
||||
void createNotUniqueTest() {
|
||||
final AuthorEntity nonUniqueAuthor = new AuthorEntity("А.С. Пушкин");
|
||||
Assertions.assertThrows(IllegalArgumentException.class, () -> authorService.create(nonUniqueAuthor));
|
||||
}
|
||||
|
||||
@Test
|
||||
void createNullableTest() {
|
||||
final AuthorEntity nullableAuthor = new AuthorEntity(null);
|
||||
Assertions.assertThrows(DataIntegrityViolationException.class, () -> authorService.create(
|
||||
nullableAuthor));
|
||||
}
|
||||
|
||||
@Test
|
||||
void updateTest() {
|
||||
final String newName = "TEST";
|
||||
final String oldName = author.getName();
|
||||
final AuthorEntity cat = new AuthorEntity(newName);
|
||||
final AuthorEntity newEntity = authorService.update(author.getId(), cat);
|
||||
Assertions.assertEquals(newName, newEntity.getName());
|
||||
Assertions.assertNotEquals(oldName, newEntity.getName());
|
||||
}
|
||||
|
||||
@Test
|
||||
void deleteTest() {
|
||||
authorService.delete(author.getId());
|
||||
Assertions.assertEquals(1, authorService.getAll().size());
|
||||
|
||||
Assertions.assertNotEquals(3, authorService.getAll().size());
|
||||
}
|
||||
}
|
146
lab3/src/test/java/com/example/demo/BookServiceTests.java
Normal file
146
lab3/src/test/java/com/example/demo/BookServiceTests.java
Normal file
@ -0,0 +1,146 @@
|
||||
package com.example.demo;
|
||||
|
||||
import java.util.List;
|
||||
|
||||
import org.junit.jupiter.api.AfterEach;
|
||||
import org.junit.jupiter.api.Assertions;
|
||||
import org.junit.jupiter.api.BeforeEach;
|
||||
import org.junit.jupiter.api.MethodOrderer.OrderAnnotation;
|
||||
import org.junit.jupiter.api.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 org.springframework.dao.DataIntegrityViolationException;
|
||||
|
||||
import com.example.demo.authors.model.AuthorEntity;
|
||||
import com.example.demo.authors.service.AuthorService;
|
||||
import com.example.demo.books.model.BookEntity;
|
||||
import com.example.demo.books.service.BookService;
|
||||
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 BookServiceTests {
|
||||
@Autowired
|
||||
private BookService bookService;
|
||||
|
||||
private BookEntity book;
|
||||
private BookEntity book2;
|
||||
private BookEntity book3;
|
||||
private BookEntity book4;
|
||||
|
||||
@Autowired
|
||||
private GenreService genreService;
|
||||
|
||||
private GenreEntity genre;
|
||||
private GenreEntity genre2;
|
||||
|
||||
@Autowired
|
||||
private AuthorService authorService;
|
||||
|
||||
private AuthorEntity author;
|
||||
private AuthorEntity author2;
|
||||
|
||||
@BeforeEach
|
||||
void createData() {
|
||||
removeData();
|
||||
|
||||
genre = genreService.create(new GenreEntity("Мемуары"));
|
||||
genre2 = genreService.create(new GenreEntity("Фантастика"));
|
||||
|
||||
author = authorService.findByName("Вася Пупкин");
|
||||
if (author == null) {
|
||||
author = authorService.create(new AuthorEntity("Вася Пупкин"));
|
||||
}
|
||||
|
||||
author2 = authorService.findByName("Петя Иванов");
|
||||
if (author2 == null) {
|
||||
author2 = authorService.create(new AuthorEntity("Петя Иванов"));
|
||||
}
|
||||
|
||||
book = bookService.create(new BookEntity(genre, author, "Книга 1", "1", "Описание 1"));
|
||||
book2 = bookService.create(new BookEntity(genre, author, "Книга 2", "2", "Описание 2"));
|
||||
book3 = bookService.create(new BookEntity(genre2, author, "Книга 3", "3", "Описание 3"));
|
||||
book4 = bookService.create(new BookEntity(genre, author2, "Книга 4", "4", "Описание 4"));
|
||||
}
|
||||
|
||||
@AfterEach
|
||||
void removeData() {
|
||||
bookService.getAll(0, 0).forEach(item -> bookService.delete(item.getId()));
|
||||
genreService.getAll().forEach(item -> genreService.delete(item.getId()));
|
||||
}
|
||||
|
||||
@Test
|
||||
@Order(1)
|
||||
void getTest() {
|
||||
Assertions.assertThrows(NotFoundException.class, () -> bookService.get(10L));
|
||||
}
|
||||
|
||||
@Test
|
||||
@Order(2)
|
||||
void createTest() {
|
||||
Assertions.assertEquals(2, bookService.getAll(genre.getId(), author.getId()).size());
|
||||
Assertions.assertEquals(book, bookService.get(book.getId()));
|
||||
}
|
||||
|
||||
@Test
|
||||
@Order(3)
|
||||
void createNullableTest() {
|
||||
final BookEntity nullableGenre = new BookEntity(genre, null, "1", "1", "1");
|
||||
Assertions.assertThrows(DataIntegrityViolationException.class, () -> bookService.create(
|
||||
nullableGenre));
|
||||
}
|
||||
|
||||
@Test
|
||||
@Order(4)
|
||||
void updateTest() {
|
||||
final String newName = "TEST";
|
||||
final String oldName = book.getName();
|
||||
final BookEntity mov = new BookEntity(book.getGenre(), book.getAuthor(),
|
||||
newName, book.getYear(), book.getDescription());
|
||||
final BookEntity newEntity = bookService.update(book.getId(), mov);
|
||||
Assertions.assertEquals(newName, newEntity.getName());
|
||||
Assertions.assertNotEquals(oldName, newEntity.getName());
|
||||
}
|
||||
|
||||
@Test
|
||||
@Order(5)
|
||||
void deleteTest() {
|
||||
bookService.delete(book2.getId());
|
||||
Assertions.assertEquals(1, bookService.getAll(genre.getId(),
|
||||
author.getId()).size());
|
||||
|
||||
Assertions.assertNotEquals(3, bookService.getAll(genre.getId(),
|
||||
author.getId()).size());
|
||||
}
|
||||
|
||||
@Test
|
||||
@Order(6)
|
||||
void filterByGenreTest() {
|
||||
List<BookEntity> books = bookService.getAll(genre.getId(), 0);
|
||||
Assertions.assertFalse(books.isEmpty());
|
||||
Assertions.assertTrue(books.stream().allMatch(b -> b.getGenre().equals(genre)));
|
||||
Assertions.assertEquals(3, books.size());
|
||||
}
|
||||
|
||||
@Test
|
||||
@Order(7)
|
||||
void filterByAuthorTest() {
|
||||
List<BookEntity> books = bookService.getAll(0, author2.getId());
|
||||
Assertions.assertFalse(books.isEmpty());
|
||||
Assertions.assertTrue(books.stream().allMatch(b -> b.getAuthor().equals(author2)));
|
||||
Assertions.assertEquals(1, books.size());
|
||||
}
|
||||
|
||||
@Test
|
||||
@Order(8)
|
||||
void filterByGenreAndAuthorTest() {
|
||||
List<BookEntity> books = bookService.getAll(genre.getId(), author.getId());
|
||||
Assertions.assertFalse(books.isEmpty());
|
||||
Assertions.assertTrue(books.stream().allMatch(b -> b.getGenre().equals(genre) && b.getAuthor().equals(author)));
|
||||
Assertions.assertEquals(2, books.size());
|
||||
}
|
||||
}
|
115
lab3/src/test/java/com/example/demo/FavoriteServiceTests.java
Normal file
115
lab3/src/test/java/com/example/demo/FavoriteServiceTests.java
Normal file
@ -0,0 +1,115 @@
|
||||
package com.example.demo;
|
||||
|
||||
import org.junit.jupiter.api.TestMethodOrder;
|
||||
import org.junit.jupiter.api.AfterEach;
|
||||
import org.junit.jupiter.api.Assertions;
|
||||
import org.junit.jupiter.api.BeforeEach;
|
||||
import org.junit.jupiter.api.MethodOrderer.OrderAnnotation;
|
||||
import org.junit.jupiter.api.Order;
|
||||
import org.junit.jupiter.api.Test;
|
||||
import org.springframework.beans.factory.annotation.Autowired;
|
||||
import org.springframework.boot.test.context.SpringBootTest;
|
||||
|
||||
import com.example.demo.authors.model.AuthorEntity;
|
||||
import com.example.demo.authors.service.AuthorService;
|
||||
import com.example.demo.books.model.BookEntity;
|
||||
import com.example.demo.books.service.BookService;
|
||||
import com.example.demo.favorites.model.FavoriteEntity;
|
||||
import com.example.demo.favorites.service.FavoriteService;
|
||||
import com.example.demo.genres.model.GenreEntity;
|
||||
import com.example.demo.genres.service.GenreService;
|
||||
import com.example.demo.users.model.UserEntity;
|
||||
import com.example.demo.users.service.UserService;
|
||||
|
||||
@SpringBootTest
|
||||
@TestMethodOrder(OrderAnnotation.class)
|
||||
public class FavoriteServiceTests {
|
||||
|
||||
@Autowired
|
||||
private FavoriteService favoriteService;
|
||||
|
||||
private FavoriteEntity lastFavorite;
|
||||
private FavoriteEntity lastFavorite2;
|
||||
|
||||
private GenreEntity genre;
|
||||
private AuthorEntity author;
|
||||
private BookEntity book1;
|
||||
private BookEntity book2;
|
||||
private UserEntity user;
|
||||
|
||||
@Autowired
|
||||
private GenreService genreService;
|
||||
|
||||
@Autowired
|
||||
private AuthorService authorService;
|
||||
|
||||
@Autowired
|
||||
private BookService bookService;
|
||||
|
||||
@Autowired
|
||||
private UserService userService;
|
||||
|
||||
@BeforeEach
|
||||
void createData() {
|
||||
removeData();
|
||||
|
||||
genre = genreService.create(new GenreEntity("Трагедия"));
|
||||
author = authorService.findByName("И.С. Тургенев");
|
||||
if (author == null) {
|
||||
author = authorService.create(new AuthorEntity("И.С. Тургенев"));
|
||||
}
|
||||
|
||||
book1 = bookService.create(new BookEntity(genre, author, "какой-то фильм",
|
||||
"1", "1"));
|
||||
book2 = bookService.create(new BookEntity(genre, author, "2", "2", "2"));
|
||||
|
||||
user = userService.create(new UserEntity("elina", "123", true));
|
||||
|
||||
lastFavorite = favoriteService.create(new FavoriteEntity(null, user, book1));
|
||||
lastFavorite2 = favoriteService.create(new FavoriteEntity(null, user,
|
||||
book2));
|
||||
}
|
||||
|
||||
@AfterEach
|
||||
void removeData() {
|
||||
favoriteService.getAll(0L).forEach(fv -> favoriteService.delete(fv.getId()));
|
||||
userService.getAll().forEach(u -> userService.delete(u.getId()));
|
||||
bookService.getAll(0, 0).forEach(item -> bookService.delete(item.getId()));
|
||||
genreService.getAll().forEach(item -> genreService.delete(item.getId()));
|
||||
}
|
||||
|
||||
@Test
|
||||
void getTest() {
|
||||
Assertions.assertThrows(NullPointerException.class, () -> favoriteService.get(0L)); // NotFoundException
|
||||
}
|
||||
|
||||
@Test
|
||||
void createTest() {
|
||||
Assertions.assertEquals(2, favoriteService.getAll(user.getId()).size());
|
||||
}
|
||||
|
||||
@Test
|
||||
void update() {
|
||||
final FavoriteEntity fav = favoriteService.create(new FavoriteEntity(null,
|
||||
user, book2));
|
||||
|
||||
final FavoriteEntity oldFav = favoriteService.get(lastFavorite.getId());
|
||||
|
||||
final FavoriteEntity newFav = favoriteService.update(lastFavorite2.getId(),
|
||||
fav);
|
||||
|
||||
Assertions.assertNotEquals(oldFav.getBook().getName(),
|
||||
newFav.getBook().getName());
|
||||
|
||||
}
|
||||
|
||||
@Test
|
||||
|
||||
@Order(3)
|
||||
void delete() {
|
||||
|
||||
favoriteService.delete(lastFavorite.getId());
|
||||
|
||||
Assertions.assertEquals(1, favoriteService.getAll(user.getId()).size());
|
||||
}
|
||||
}
|
77
lab3/src/test/java/com/example/demo/GenreServiceTests.java
Normal file
77
lab3/src/test/java/com/example/demo/GenreServiceTests.java
Normal file
@ -0,0 +1,77 @@
|
||||
package com.example.demo;
|
||||
|
||||
import org.junit.jupiter.api.AfterEach;
|
||||
import org.junit.jupiter.api.Assertions;
|
||||
import org.junit.jupiter.api.BeforeEach;
|
||||
import org.junit.jupiter.api.Test;
|
||||
import org.springframework.beans.factory.annotation.Autowired;
|
||||
import org.springframework.boot.test.context.SpringBootTest;
|
||||
import org.springframework.dao.DataIntegrityViolationException;
|
||||
|
||||
import com.example.demo.core.error.NotFoundException;
|
||||
import com.example.demo.genres.model.GenreEntity;
|
||||
import com.example.demo.genres.service.GenreService;
|
||||
|
||||
@SpringBootTest
|
||||
class GenreServiceTests {
|
||||
@Autowired
|
||||
private GenreService genreService;
|
||||
|
||||
private GenreEntity genre;
|
||||
|
||||
@BeforeEach
|
||||
void createData() {
|
||||
removeData();
|
||||
|
||||
genre = genreService.create(new GenreEntity("Drama"));
|
||||
genreService.create(new GenreEntity("Comedy"));
|
||||
|
||||
}
|
||||
|
||||
@AfterEach
|
||||
void removeData() {
|
||||
genreService.getAll().forEach(item -> genreService.delete(item.getId()));
|
||||
}
|
||||
|
||||
@Test
|
||||
void getTest() {
|
||||
Assertions.assertThrows(NotFoundException.class, () -> genreService.get(0));
|
||||
}
|
||||
|
||||
@Test
|
||||
void createTest() {
|
||||
Assertions.assertEquals(2, genreService.getAll().size());
|
||||
Assertions.assertEquals(genre, genreService.get(genre.getId()));
|
||||
}
|
||||
|
||||
@Test
|
||||
void createNotUniqueTest() {
|
||||
final GenreEntity nonUniqueGenre = new GenreEntity("Drama");
|
||||
Assertions.assertThrows(IllegalArgumentException.class, () -> genreService.create(nonUniqueGenre));
|
||||
}
|
||||
|
||||
@Test
|
||||
void createNullableTest() {
|
||||
final GenreEntity nullableGenre = new GenreEntity(null);
|
||||
Assertions.assertThrows(DataIntegrityViolationException.class, () -> genreService.create(
|
||||
nullableGenre));
|
||||
}
|
||||
|
||||
@Test
|
||||
void updateTest() {
|
||||
final String newName = "TEST";
|
||||
final String oldName = genre.getName();
|
||||
final GenreEntity cat = new GenreEntity(newName);
|
||||
final GenreEntity newEntity = genreService.update(genre.getId(), cat);
|
||||
Assertions.assertEquals(newName, newEntity.getName());
|
||||
Assertions.assertNotEquals(oldName, newEntity.getName());
|
||||
}
|
||||
|
||||
@Test
|
||||
void deleteTest() {
|
||||
genreService.delete(genre.getId());
|
||||
Assertions.assertEquals(1, genreService.getAll().size());
|
||||
|
||||
Assertions.assertNotEquals(3, genreService.getAll().size());
|
||||
}
|
||||
}
|
75
lab3/src/test/java/com/example/demo/UserServiceTests.java
Normal file
75
lab3/src/test/java/com/example/demo/UserServiceTests.java
Normal file
@ -0,0 +1,75 @@
|
||||
package com.example.demo;
|
||||
|
||||
import org.junit.jupiter.api.AfterEach;
|
||||
import org.junit.jupiter.api.Assertions;
|
||||
import org.junit.jupiter.api.BeforeEach;
|
||||
import org.junit.jupiter.api.MethodOrderer.OrderAnnotation;
|
||||
import org.junit.jupiter.api.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.users.model.UserEntity;
|
||||
import com.example.demo.users.service.UserService;
|
||||
|
||||
@SpringBootTest
|
||||
@TestMethodOrder(OrderAnnotation.class)
|
||||
class UserServiceTests {
|
||||
@Autowired
|
||||
private UserService userService;
|
||||
|
||||
private UserEntity firstUser;
|
||||
|
||||
@BeforeEach
|
||||
void createData() {
|
||||
removeData();
|
||||
|
||||
firstUser = userService.create(new UserEntity("elina", "123", true));
|
||||
userService.create(new UserEntity("oleg", "789", false));
|
||||
userService.create(new UserEntity("nikita", "456", false));
|
||||
|
||||
}
|
||||
|
||||
@AfterEach
|
||||
void removeData() {
|
||||
userService.getAll().forEach(item -> userService.delete(item.getId()));
|
||||
}
|
||||
|
||||
@Test
|
||||
void getTest() {
|
||||
Assertions.assertThrows(NullPointerException.class, () -> userService.get(0L)); // NotFoundException
|
||||
}
|
||||
|
||||
@Test
|
||||
|
||||
@Order(1)
|
||||
void createTest() {
|
||||
|
||||
Assertions.assertEquals(firstUser, userService.get(firstUser.getId()));
|
||||
Assertions.assertEquals(3, userService.getAll().size());
|
||||
}
|
||||
|
||||
@Test
|
||||
|
||||
@Order(2)
|
||||
void update() {
|
||||
final String newPassword = "000";
|
||||
final UserEntity existEntity = userService.get(firstUser.getId());
|
||||
final String oldPassword = existEntity.getPassword();
|
||||
final UserEntity entity = new UserEntity(existEntity.getUsername(),
|
||||
newPassword, existEntity.getIsAdmin());
|
||||
final UserEntity newEntity = userService.update(firstUser.getId(), entity);
|
||||
Assertions.assertEquals(newPassword, newEntity.getPassword());
|
||||
Assertions.assertNotEquals(oldPassword, newEntity.getPassword());
|
||||
|
||||
}
|
||||
|
||||
@Test
|
||||
|
||||
@Order(3)
|
||||
void delete() {
|
||||
userService.delete(firstUser.getId());
|
||||
Assertions.assertEquals(2, userService.getAll().size());
|
||||
}
|
||||
}
|
14
lab3/src/test/resources/application.properties
Normal file
14
lab3/src/test/resources/application.properties
Normal file
@ -0,0 +1,14 @@
|
||||
# Server
|
||||
spring.main.banner-mode=off
|
||||
|
||||
# Logger settings
|
||||
# Available levels are: TRACE, DEBUG, INFO, WARN, ERROR, FATAL, OFF
|
||||
logging.level.com.example.demo=DEBUG
|
||||
|
||||
# JPA Settings
|
||||
spring.datasource.url=jdbc:h2:mem:testdb
|
||||
spring.datasource.username=sa
|
||||
spring.datasource.password=password
|
||||
spring.datasource.driver-class-name=org.h2.Driver
|
||||
spring.jpa.hibernate.ddl-auto=create
|
||||
spring.jpa.open-in-view=false
|
36
lab45/.gitignore
vendored
Normal file
36
lab45/.gitignore
vendored
Normal 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
|
12
lab45/.vscode/extensions.json
vendored
Normal file
12
lab45/.vscode/extensions.json
vendored
Normal 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"
|
||||
]
|
||||
}
|
14
lab45/.vscode/launch.json
vendored
Normal file
14
lab45/.vscode/launch.json
vendored
Normal file
@ -0,0 +1,14 @@
|
||||
{
|
||||
"configurations": [
|
||||
{
|
||||
"type": "java",
|
||||
"name": "Demo",
|
||||
"request": "launch",
|
||||
"cwd": "${workspaceFolder}",
|
||||
"mainClass": "com.example.demo.DemoApplication",
|
||||
"projectName": "lec6",
|
||||
"args": "--populate",
|
||||
"envFile": "${workspaceFolder}/.env"
|
||||
}
|
||||
]
|
||||
}
|
24
lab45/.vscode/settings.json
vendored
Normal file
24
lab45/.vscode/settings.json
vendored
Normal file
@ -0,0 +1,24 @@
|
||||
{
|
||||
"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,
|
||||
"cSpell.words": [
|
||||
"classappend"
|
||||
],
|
||||
}
|
51
lab45/build.gradle
Normal file
51
lab45/build.gradle
Normal file
@ -0,0 +1,51 @@
|
||||
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.modelmapper:modelmapper:3.2.0'
|
||||
|
||||
implementation 'org.springframework.boot:spring-boot-starter-data-jpa'
|
||||
implementation 'com.h2database:h2:2.2.224'
|
||||
|
||||
implementation 'org.springframework.boot:spring-boot-devtools'
|
||||
implementation 'org.springframework.boot:spring-boot-starter-thymeleaf'
|
||||
implementation 'nz.net.ultraq.thymeleaf:thymeleaf-layout-dialect:3.3.0'
|
||||
runtimeOnly 'org.webjars.npm:bootstrap:5.3.3'
|
||||
runtimeOnly 'org.webjars.npm:bootstrap-icons:1.11.3'
|
||||
|
||||
implementation 'org.springframework.boot:spring-boot-starter-security'
|
||||
implementation 'org.thymeleaf.extras:thymeleaf-extras-springsecurity6'
|
||||
|
||||
testImplementation 'org.springframework.boot:spring-boot-starter-test'
|
||||
}
|
||||
|
||||
tasks.named('test') {
|
||||
useJUnitPlatform()
|
||||
}
|
BIN
lab45/gradle/wrapper/gradle-wrapper.jar
vendored
Normal file
BIN
lab45/gradle/wrapper/gradle-wrapper.jar
vendored
Normal file
Binary file not shown.
7
lab45/gradle/wrapper/gradle-wrapper.properties
vendored
Normal file
7
lab45/gradle/wrapper/gradle-wrapper.properties
vendored
Normal file
@ -0,0 +1,7 @@
|
||||
distributionBase=GRADLE_USER_HOME
|
||||
distributionPath=wrapper/dists
|
||||
distributionUrl=https\://services.gradle.org/distributions/gradle-8.5-bin.zip
|
||||
networkTimeout=10000
|
||||
validateDistributionUrl=true
|
||||
zipStoreBase=GRADLE_USER_HOME
|
||||
zipStorePath=wrapper/dists
|
249
lab45/gradlew
vendored
Normal file
249
lab45/gradlew
vendored
Normal file
@ -0,0 +1,249 @@
|
||||
#!/bin/sh
|
||||
|
||||
#
|
||||
# Copyright © 2015-2021 the original authors.
|
||||
#
|
||||
# Licensed under the Apache License, Version 2.0 (the "License");
|
||||
# you may not use this file except in compliance with the License.
|
||||
# You may obtain a copy of the License at
|
||||
#
|
||||
# https://www.apache.org/licenses/LICENSE-2.0
|
||||
#
|
||||
# Unless required by applicable law or agreed to in writing, software
|
||||
# distributed under the License is distributed on an "AS IS" BASIS,
|
||||
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
# See the License for the specific language governing permissions and
|
||||
# limitations under the License.
|
||||
#
|
||||
|
||||
##############################################################################
|
||||
#
|
||||
# Gradle start up script for POSIX generated by Gradle.
|
||||
#
|
||||
# Important for running:
|
||||
#
|
||||
# (1) You need a POSIX-compliant shell to run this script. If your /bin/sh is
|
||||
# noncompliant, but you have some other compliant shell such as ksh or
|
||||
# bash, then to run this script, type that shell name before the whole
|
||||
# command line, like:
|
||||
#
|
||||
# ksh Gradle
|
||||
#
|
||||
# Busybox and similar reduced shells will NOT work, because this script
|
||||
# requires all of these POSIX shell features:
|
||||
# * functions;
|
||||
# * expansions «$var», «${var}», «${var:-default}», «${var+SET}»,
|
||||
# «${var#prefix}», «${var%suffix}», and «$( cmd )»;
|
||||
# * compound commands having a testable exit status, especially «case»;
|
||||
# * various built-in commands including «command», «set», and «ulimit».
|
||||
#
|
||||
# Important for patching:
|
||||
#
|
||||
# (2) This script targets any POSIX shell, so it avoids extensions provided
|
||||
# by Bash, Ksh, etc; in particular arrays are avoided.
|
||||
#
|
||||
# The "traditional" practice of packing multiple parameters into a
|
||||
# space-separated string is a well documented source of bugs and security
|
||||
# problems, so this is (mostly) avoided, by progressively accumulating
|
||||
# options in "$@", and eventually passing that to Java.
|
||||
#
|
||||
# Where the inherited environment variables (DEFAULT_JVM_OPTS, JAVA_OPTS,
|
||||
# and GRADLE_OPTS) rely on word-splitting, this is performed explicitly;
|
||||
# see the in-line comments for details.
|
||||
#
|
||||
# There are tweaks for specific operating systems such as AIX, CygWin,
|
||||
# Darwin, MinGW, and NonStop.
|
||||
#
|
||||
# (3) This script is generated from the Groovy template
|
||||
# https://github.com/gradle/gradle/blob/HEAD/subprojects/plugins/src/main/resources/org/gradle/api/internal/plugins/unixStartScript.txt
|
||||
# within the Gradle project.
|
||||
#
|
||||
# You can find Gradle at https://github.com/gradle/gradle/.
|
||||
#
|
||||
##############################################################################
|
||||
|
||||
# Attempt to set APP_HOME
|
||||
|
||||
# Resolve links: $0 may be a link
|
||||
app_path=$0
|
||||
|
||||
# Need this for daisy-chained symlinks.
|
||||
while
|
||||
APP_HOME=${app_path%"${app_path##*/}"} # leaves a trailing /; empty if no leading path
|
||||
[ -h "$app_path" ]
|
||||
do
|
||||
ls=$( ls -ld "$app_path" )
|
||||
link=${ls#*' -> '}
|
||||
case $link in #(
|
||||
/*) app_path=$link ;; #(
|
||||
*) app_path=$APP_HOME$link ;;
|
||||
esac
|
||||
done
|
||||
|
||||
# This is normally unused
|
||||
# shellcheck disable=SC2034
|
||||
APP_BASE_NAME=${0##*/}
|
||||
# Discard cd standard output in case $CDPATH is set (https://github.com/gradle/gradle/issues/25036)
|
||||
APP_HOME=$( cd "${APP_HOME:-./}" > /dev/null && pwd -P ) || exit
|
||||
|
||||
# Use the maximum available, or set MAX_FD != -1 to use that value.
|
||||
MAX_FD=maximum
|
||||
|
||||
warn () {
|
||||
echo "$*"
|
||||
} >&2
|
||||
|
||||
die () {
|
||||
echo
|
||||
echo "$*"
|
||||
echo
|
||||
exit 1
|
||||
} >&2
|
||||
|
||||
# OS specific support (must be 'true' or 'false').
|
||||
cygwin=false
|
||||
msys=false
|
||||
darwin=false
|
||||
nonstop=false
|
||||
case "$( uname )" in #(
|
||||
CYGWIN* ) cygwin=true ;; #(
|
||||
Darwin* ) darwin=true ;; #(
|
||||
MSYS* | MINGW* ) msys=true ;; #(
|
||||
NONSTOP* ) nonstop=true ;;
|
||||
esac
|
||||
|
||||
CLASSPATH=$APP_HOME/gradle/wrapper/gradle-wrapper.jar
|
||||
|
||||
|
||||
# Determine the Java command to use to start the JVM.
|
||||
if [ -n "$JAVA_HOME" ] ; then
|
||||
if [ -x "$JAVA_HOME/jre/sh/java" ] ; then
|
||||
# IBM's JDK on AIX uses strange locations for the executables
|
||||
JAVACMD=$JAVA_HOME/jre/sh/java
|
||||
else
|
||||
JAVACMD=$JAVA_HOME/bin/java
|
||||
fi
|
||||
if [ ! -x "$JAVACMD" ] ; then
|
||||
die "ERROR: JAVA_HOME is set to an invalid directory: $JAVA_HOME
|
||||
|
||||
Please set the JAVA_HOME variable in your environment to match the
|
||||
location of your Java installation."
|
||||
fi
|
||||
else
|
||||
JAVACMD=java
|
||||
if ! command -v java >/dev/null 2>&1
|
||||
then
|
||||
die "ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH.
|
||||
|
||||
Please set the JAVA_HOME variable in your environment to match the
|
||||
location of your Java installation."
|
||||
fi
|
||||
fi
|
||||
|
||||
# Increase the maximum file descriptors if we can.
|
||||
if ! "$cygwin" && ! "$darwin" && ! "$nonstop" ; then
|
||||
case $MAX_FD in #(
|
||||
max*)
|
||||
# In POSIX sh, ulimit -H is undefined. That's why the result is checked to see if it worked.
|
||||
# shellcheck disable=SC2039,SC3045
|
||||
MAX_FD=$( ulimit -H -n ) ||
|
||||
warn "Could not query maximum file descriptor limit"
|
||||
esac
|
||||
case $MAX_FD in #(
|
||||
'' | soft) :;; #(
|
||||
*)
|
||||
# In POSIX sh, ulimit -n is undefined. That's why the result is checked to see if it worked.
|
||||
# shellcheck disable=SC2039,SC3045
|
||||
ulimit -n "$MAX_FD" ||
|
||||
warn "Could not set maximum file descriptor limit to $MAX_FD"
|
||||
esac
|
||||
fi
|
||||
|
||||
# Collect all arguments for the java command, stacking in reverse order:
|
||||
# * args from the command line
|
||||
# * the main class name
|
||||
# * -classpath
|
||||
# * -D...appname settings
|
||||
# * --module-path (only if needed)
|
||||
# * DEFAULT_JVM_OPTS, JAVA_OPTS, and GRADLE_OPTS environment variables.
|
||||
|
||||
# For Cygwin or MSYS, switch paths to Windows format before running java
|
||||
if "$cygwin" || "$msys" ; then
|
||||
APP_HOME=$( cygpath --path --mixed "$APP_HOME" )
|
||||
CLASSPATH=$( cygpath --path --mixed "$CLASSPATH" )
|
||||
|
||||
JAVACMD=$( cygpath --unix "$JAVACMD" )
|
||||
|
||||
# Now convert the arguments - kludge to limit ourselves to /bin/sh
|
||||
for arg do
|
||||
if
|
||||
case $arg in #(
|
||||
-*) false ;; # don't mess with options #(
|
||||
/?*) t=${arg#/} t=/${t%%/*} # looks like a POSIX filepath
|
||||
[ -e "$t" ] ;; #(
|
||||
*) false ;;
|
||||
esac
|
||||
then
|
||||
arg=$( cygpath --path --ignore --mixed "$arg" )
|
||||
fi
|
||||
# Roll the args list around exactly as many times as the number of
|
||||
# args, so each arg winds up back in the position where it started, but
|
||||
# possibly modified.
|
||||
#
|
||||
# NB: a `for` loop captures its iteration list before it begins, so
|
||||
# changing the positional parameters here affects neither the number of
|
||||
# iterations, nor the values presented in `arg`.
|
||||
shift # remove old arg
|
||||
set -- "$@" "$arg" # push replacement arg
|
||||
done
|
||||
fi
|
||||
|
||||
|
||||
# Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script.
|
||||
DEFAULT_JVM_OPTS='"-Xmx64m" "-Xms64m"'
|
||||
|
||||
# Collect all arguments for the java command:
|
||||
# * DEFAULT_JVM_OPTS, JAVA_OPTS, JAVA_OPTS, and optsEnvironmentVar are not allowed to contain shell fragments,
|
||||
# and any embedded shellness will be escaped.
|
||||
# * For example: A user cannot expect ${Hostname} to be expanded, as it is an environment variable and will be
|
||||
# treated as '${Hostname}' itself on the command line.
|
||||
|
||||
set -- \
|
||||
"-Dorg.gradle.appname=$APP_BASE_NAME" \
|
||||
-classpath "$CLASSPATH" \
|
||||
org.gradle.wrapper.GradleWrapperMain \
|
||||
"$@"
|
||||
|
||||
# Stop when "xargs" is not available.
|
||||
if ! command -v xargs >/dev/null 2>&1
|
||||
then
|
||||
die "xargs is not available"
|
||||
fi
|
||||
|
||||
# Use "xargs" to parse quoted args.
|
||||
#
|
||||
# With -n1 it outputs one arg per line, with the quotes and backslashes removed.
|
||||
#
|
||||
# In Bash we could simply go:
|
||||
#
|
||||
# readarray ARGS < <( xargs -n1 <<<"$var" ) &&
|
||||
# set -- "${ARGS[@]}" "$@"
|
||||
#
|
||||
# but POSIX shell has neither arrays nor command substitution, so instead we
|
||||
# post-process each arg (as a line of input to sed) to backslash-escape any
|
||||
# character that might be a shell metacharacter, then use eval to reverse
|
||||
# that process (while maintaining the separation between arguments), and wrap
|
||||
# the whole thing up as a single "set" statement.
|
||||
#
|
||||
# This will of course break if any of these variables contains a newline or
|
||||
# an unmatched quote.
|
||||
#
|
||||
|
||||
eval "set -- $(
|
||||
printf '%s\n' "$DEFAULT_JVM_OPTS $JAVA_OPTS $GRADLE_OPTS" |
|
||||
xargs -n1 |
|
||||
sed ' s~[^-[:alnum:]+,./:=@_]~\\&~g; ' |
|
||||
tr '\n' ' '
|
||||
)" '"$@"'
|
||||
|
||||
exec "$JAVACMD" "$@"
|
92
lab45/gradlew.bat
vendored
Normal file
92
lab45/gradlew.bat
vendored
Normal file
@ -0,0 +1,92 @@
|
||||
@rem
|
||||
@rem Copyright 2015 the original author or authors.
|
||||
@rem
|
||||
@rem Licensed under the Apache License, Version 2.0 (the "License");
|
||||
@rem you may not use this file except in compliance with the License.
|
||||
@rem You may obtain a copy of the License at
|
||||
@rem
|
||||
@rem https://www.apache.org/licenses/LICENSE-2.0
|
||||
@rem
|
||||
@rem Unless required by applicable law or agreed to in writing, software
|
||||
@rem distributed under the License is distributed on an "AS IS" BASIS,
|
||||
@rem WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
@rem See the License for the specific language governing permissions and
|
||||
@rem limitations under the License.
|
||||
@rem
|
||||
|
||||
@if "%DEBUG%"=="" @echo off
|
||||
@rem ##########################################################################
|
||||
@rem
|
||||
@rem Gradle startup script for Windows
|
||||
@rem
|
||||
@rem ##########################################################################
|
||||
|
||||
@rem Set local scope for the variables with windows NT shell
|
||||
if "%OS%"=="Windows_NT" setlocal
|
||||
|
||||
set DIRNAME=%~dp0
|
||||
if "%DIRNAME%"=="" set DIRNAME=.
|
||||
@rem This is normally unused
|
||||
set APP_BASE_NAME=%~n0
|
||||
set APP_HOME=%DIRNAME%
|
||||
|
||||
@rem Resolve any "." and ".." in APP_HOME to make it shorter.
|
||||
for %%i in ("%APP_HOME%") do set APP_HOME=%%~fi
|
||||
|
||||
@rem Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script.
|
||||
set DEFAULT_JVM_OPTS="-Xmx64m" "-Xms64m"
|
||||
|
||||
@rem Find java.exe
|
||||
if defined JAVA_HOME goto findJavaFromJavaHome
|
||||
|
||||
set JAVA_EXE=java.exe
|
||||
%JAVA_EXE% -version >NUL 2>&1
|
||||
if %ERRORLEVEL% equ 0 goto execute
|
||||
|
||||
echo.
|
||||
echo ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH.
|
||||
echo.
|
||||
echo Please set the JAVA_HOME variable in your environment to match the
|
||||
echo location of your Java installation.
|
||||
|
||||
goto fail
|
||||
|
||||
:findJavaFromJavaHome
|
||||
set JAVA_HOME=%JAVA_HOME:"=%
|
||||
set JAVA_EXE=%JAVA_HOME%/bin/java.exe
|
||||
|
||||
if exist "%JAVA_EXE%" goto execute
|
||||
|
||||
echo.
|
||||
echo ERROR: JAVA_HOME is set to an invalid directory: %JAVA_HOME%
|
||||
echo.
|
||||
echo Please set the JAVA_HOME variable in your environment to match the
|
||||
echo location of your Java installation.
|
||||
|
||||
goto fail
|
||||
|
||||
:execute
|
||||
@rem Setup the command line
|
||||
|
||||
set CLASSPATH=%APP_HOME%\gradle\wrapper\gradle-wrapper.jar
|
||||
|
||||
|
||||
@rem Execute Gradle
|
||||
"%JAVA_EXE%" %DEFAULT_JVM_OPTS% %JAVA_OPTS% %GRADLE_OPTS% "-Dorg.gradle.appname=%APP_BASE_NAME%" -classpath "%CLASSPATH%" org.gradle.wrapper.GradleWrapperMain %*
|
||||
|
||||
:end
|
||||
@rem End local scope for the variables with windows NT shell
|
||||
if %ERRORLEVEL% equ 0 goto mainEnd
|
||||
|
||||
:fail
|
||||
rem Set variable GRADLE_EXIT_CONSOLE if you need the _script_ return code instead of
|
||||
rem the _cmd.exe /c_ return code!
|
||||
set EXIT_CODE=%ERRORLEVEL%
|
||||
if %EXIT_CODE% equ 0 set EXIT_CODE=1
|
||||
if not ""=="%GRADLE_EXIT_CONSOLE%" exit %EXIT_CODE%
|
||||
exit /b %EXIT_CODE%
|
||||
|
||||
:mainEnd
|
||||
if "%OS%"=="Windows_NT" endlocal
|
||||
|
||||
:omega
|
15
lab45/readme.md
Normal file
15
lab45/readme.md
Normal file
@ -0,0 +1,15 @@
|
||||
H2 Console: \
|
||||
http://localhost:8080/h2-console
|
||||
|
||||
JDBC URL: jdbc:h2:file:./data \
|
||||
User Name: sa \
|
||||
Password: password
|
||||
|
||||
Почитать:
|
||||
|
||||
- Spring Boot CRUD Application with Thymeleaf https://www.baeldung.com/spring-boot-crud-thymeleaf
|
||||
- Thymeleaf Layout Dialect https://ultraq.github.io/thymeleaf-layout-dialect/
|
||||
- Tutorial: Using Thymeleaf https://www.thymeleaf.org/doc/tutorials/3.1/usingthymeleaf.html#introducing-thymeleaf
|
||||
- Working with Cookies in Spring MVC using @CookieValue Annotation https://www.geeksforgeeks.org/working-with-cookies-in-spring-mvc-using-cookievalue-annotation/
|
||||
- Session Attributes in Spring MVC https://www.baeldung.com/spring-mvc-session-attributes
|
||||
- LazyInitializationException – What it is and the best way to fix it https://thorben-janssen.com/lazyinitializationexception/
|
1
lab45/settings.gradle
Normal file
1
lab45/settings.gradle
Normal file
@ -0,0 +1 @@
|
||||
rootProject.name = 'demo'
|
93
lab45/src/main/java/com/example/demo/DemoApplication.java
Normal file
93
lab45/src/main/java/com/example/demo/DemoApplication.java
Normal file
@ -0,0 +1,93 @@
|
||||
package com.example.demo;
|
||||
|
||||
import java.util.List;
|
||||
import java.util.Objects;
|
||||
import java.util.stream.IntStream;
|
||||
|
||||
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.authors.model.AuthorEntity;
|
||||
import com.example.demo.authors.service.AuthorService;
|
||||
import com.example.demo.books.model.BookEntity;
|
||||
import com.example.demo.books.service.BookService;
|
||||
import com.example.demo.core.configuration.Constants;
|
||||
import com.example.demo.favorites.model.FavoriteEntity;
|
||||
import com.example.demo.favorites.service.FavoriteService;
|
||||
import com.example.demo.genres.model.GenreEntity;
|
||||
import com.example.demo.genres.service.GenreService;
|
||||
import com.example.demo.users.model.UserEntity;
|
||||
import com.example.demo.users.model.UserRole;
|
||||
import com.example.demo.users.service.UserService;
|
||||
|
||||
@SpringBootApplication
|
||||
public class DemoApplication implements CommandLineRunner {
|
||||
private final Logger log = LoggerFactory.getLogger(DemoApplication.class);
|
||||
|
||||
private final GenreService genreService;
|
||||
private final AuthorService authorService;
|
||||
private final BookService bookService;
|
||||
private final UserService userService;
|
||||
private final FavoriteService favoriteService;
|
||||
|
||||
public DemoApplication(
|
||||
UserService userService,
|
||||
GenreService genreService,
|
||||
AuthorService authorService,
|
||||
BookService bookService,
|
||||
FavoriteService favoriteService) {
|
||||
this.userService = userService;
|
||||
this.genreService = genreService;
|
||||
this.authorService = authorService;
|
||||
this.bookService = bookService;
|
||||
this.favoriteService = favoriteService;
|
||||
}
|
||||
|
||||
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("Детектив"));
|
||||
final var genre2 = genreService.create(new GenreEntity("Роман"));
|
||||
final var genre3 = genreService.create(new GenreEntity("Трагедия"));
|
||||
|
||||
log.info("Create default author values");
|
||||
final var author1 = authorService.create(new AuthorEntity("А.С.Пушкин"));
|
||||
final var author2 = authorService.create(new AuthorEntity("М.Ю.Леромонтов"));
|
||||
final var author3 = authorService.create(new AuthorEntity("Л.Н.Толстой"));
|
||||
|
||||
log.info("Create default book values");
|
||||
final var book1 = bookService.create(new BookEntity(
|
||||
genre1, author1, "Книга1", "1900", "описание1"));
|
||||
final var book2 = bookService.create(new BookEntity(
|
||||
genre2, author2, "Книга2", "1890", "описание2"));
|
||||
final var book3 = bookService.create(new BookEntity(
|
||||
genre3, author3, "Книга3", "1890", "описание3"));
|
||||
|
||||
log.info("Create default user values");
|
||||
final var admin = new UserEntity("admin", "admin");
|
||||
admin.setRole(UserRole.ADMIN);
|
||||
userService.create(admin);
|
||||
|
||||
final var user1 = userService.create(new UserEntity("user1", Constants.DEFAULT_PASSWORD));
|
||||
|
||||
IntStream.range(2, 27)
|
||||
.forEach(value -> userService.create(
|
||||
new UserEntity("user".concat(String.valueOf(value)), Constants.DEFAULT_PASSWORD)));
|
||||
|
||||
log.info("Create default favorite values");
|
||||
final var favorites = List.of(
|
||||
new FavoriteEntity(user1, book1),
|
||||
new FavoriteEntity(user1, book2),
|
||||
new FavoriteEntity(user1, book3));
|
||||
favorites.forEach(favorite -> favoriteService.create(favorite, user1.getId()));
|
||||
}
|
||||
}
|
||||
}
|
@ -0,0 +1,104 @@
|
||||
package com.example.demo.authors.api;
|
||||
|
||||
import org.modelmapper.ModelMapper;
|
||||
import org.springframework.stereotype.Controller;
|
||||
import org.springframework.ui.Model;
|
||||
import org.springframework.validation.BindingResult;
|
||||
import org.springframework.web.bind.annotation.GetMapping;
|
||||
import org.springframework.web.bind.annotation.ModelAttribute;
|
||||
import org.springframework.web.bind.annotation.PathVariable;
|
||||
import org.springframework.web.bind.annotation.PostMapping;
|
||||
import org.springframework.web.bind.annotation.RequestMapping;
|
||||
|
||||
import com.example.demo.core.configuration.Constants;
|
||||
import com.example.demo.authors.model.AuthorEntity;
|
||||
import com.example.demo.authors.service.AuthorService;
|
||||
|
||||
import jakarta.validation.Valid;
|
||||
|
||||
@Controller
|
||||
@RequestMapping(AuthorController.URL)
|
||||
public class AuthorController {
|
||||
public static final String URL = Constants.ADMIN_PREFIX + "/author";
|
||||
private static final String AUTHOR_VIEW = "author";
|
||||
private static final String AUTHOR_EDIT_VIEW = "author-edit";
|
||||
private static final String AUTHOR_ATTRIBUTE = "author";
|
||||
|
||||
private final AuthorService authorService;
|
||||
private final ModelMapper modelMapper;
|
||||
|
||||
public AuthorController(AuthorService authorService, ModelMapper modelMapper) {
|
||||
this.authorService = authorService;
|
||||
this.modelMapper = modelMapper;
|
||||
}
|
||||
|
||||
private AuthorDto toDto(AuthorEntity entity) {
|
||||
return modelMapper.map(entity, AuthorDto.class);
|
||||
}
|
||||
|
||||
private AuthorEntity toEntity(AuthorDto dto) {
|
||||
return modelMapper.map(dto, AuthorEntity.class);
|
||||
}
|
||||
|
||||
@GetMapping
|
||||
public String getAll(Model model) {
|
||||
model.addAttribute(
|
||||
"items",
|
||||
authorService.getAll().stream()
|
||||
.map(this::toDto)
|
||||
.toList());
|
||||
return AUTHOR_VIEW;
|
||||
}
|
||||
|
||||
@GetMapping("/edit/")
|
||||
public String create(Model model) {
|
||||
model.addAttribute(AUTHOR_ATTRIBUTE, new AuthorDto());
|
||||
return AUTHOR_EDIT_VIEW;
|
||||
}
|
||||
|
||||
@PostMapping("/edit/")
|
||||
public String create(
|
||||
@ModelAttribute(name = AUTHOR_ATTRIBUTE) @Valid AuthorDto author,
|
||||
BindingResult bindingResult,
|
||||
Model model) {
|
||||
if (bindingResult.hasErrors()) {
|
||||
return AUTHOR_EDIT_VIEW;
|
||||
}
|
||||
authorService.create(toEntity(author));
|
||||
return Constants.REDIRECT_VIEW + URL;
|
||||
}
|
||||
|
||||
@GetMapping("/edit/{id}")
|
||||
public String update(
|
||||
@PathVariable(name = "id") Long id,
|
||||
Model model) {
|
||||
if (id <= 0) {
|
||||
throw new IllegalArgumentException();
|
||||
}
|
||||
model.addAttribute(AUTHOR_ATTRIBUTE, toDto(authorService.get(id)));
|
||||
return AUTHOR_EDIT_VIEW;
|
||||
}
|
||||
|
||||
@PostMapping("/edit/{id}")
|
||||
public String update(
|
||||
@PathVariable(name = "id") Long id,
|
||||
@ModelAttribute(name = AUTHOR_ATTRIBUTE) @Valid AuthorDto author,
|
||||
BindingResult bindingResult,
|
||||
Model model) {
|
||||
if (bindingResult.hasErrors()) {
|
||||
return AUTHOR_EDIT_VIEW;
|
||||
}
|
||||
if (id <= 0) {
|
||||
throw new IllegalArgumentException();
|
||||
}
|
||||
authorService.update(id, toEntity(author));
|
||||
return Constants.REDIRECT_VIEW + URL;
|
||||
}
|
||||
|
||||
@PostMapping("/delete/{id}")
|
||||
public String delete(
|
||||
@PathVariable(name = "id") Long id) {
|
||||
authorService.delete(id);
|
||||
return Constants.REDIRECT_VIEW + URL;
|
||||
}
|
||||
}
|
@ -0,0 +1,30 @@
|
||||
package com.example.demo.authors.api;
|
||||
|
||||
import com.fasterxml.jackson.annotation.JsonProperty;
|
||||
|
||||
import jakarta.validation.constraints.NotBlank;
|
||||
import jakarta.validation.constraints.Size;
|
||||
|
||||
public class AuthorDto {
|
||||
@JsonProperty(access = JsonProperty.Access.READ_ONLY)
|
||||
private Long id;
|
||||
@NotBlank
|
||||
@Size(min = 5, max = 50)
|
||||
private String name;
|
||||
|
||||
public Long getId() {
|
||||
return id;
|
||||
}
|
||||
|
||||
public void setId(Long id) {
|
||||
this.id = id;
|
||||
}
|
||||
|
||||
public String getName() {
|
||||
return name;
|
||||
}
|
||||
|
||||
public void setName(String name) {
|
||||
this.name = name;
|
||||
}
|
||||
}
|
@ -0,0 +1,53 @@
|
||||
package com.example.demo.authors.model;
|
||||
|
||||
import java.util.HashSet;
|
||||
import java.util.Objects;
|
||||
import java.util.Set;
|
||||
|
||||
import com.example.demo.books.model.BookEntity;
|
||||
import com.example.demo.core.model.BaseEntity;
|
||||
|
||||
import jakarta.persistence.CascadeType;
|
||||
import jakarta.persistence.Column;
|
||||
import jakarta.persistence.Entity;
|
||||
import jakarta.persistence.OneToMany;
|
||||
import jakarta.persistence.Table;
|
||||
|
||||
@Entity
|
||||
@Table(name = "authors")
|
||||
public class AuthorEntity extends BaseEntity {
|
||||
@Column(nullable = false, unique = true, length = 50)
|
||||
private String name;
|
||||
@OneToMany(mappedBy = "author", cascade = CascadeType.ALL)
|
||||
private Set<BookEntity> books = new HashSet<>();
|
||||
|
||||
public AuthorEntity() {
|
||||
}
|
||||
|
||||
public AuthorEntity(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 AuthorEntity other = (AuthorEntity) obj;
|
||||
return Objects.equals(other.getId(), id) && Objects.equals(other.getName(), name);
|
||||
}
|
||||
}
|
@ -0,0 +1,11 @@
|
||||
package com.example.demo.authors.repository;
|
||||
|
||||
import java.util.Optional;
|
||||
|
||||
import org.springframework.data.repository.CrudRepository;
|
||||
|
||||
import com.example.demo.authors.model.AuthorEntity;
|
||||
|
||||
public interface AuthorRepository extends CrudRepository<AuthorEntity, Long> {
|
||||
Optional<AuthorEntity> findByNameIgnoreCase(String name);
|
||||
}
|
@ -0,0 +1,68 @@
|
||||
package com.example.demo.authors.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.authors.model.AuthorEntity;
|
||||
import com.example.demo.authors.repository.AuthorRepository;
|
||||
|
||||
@Service
|
||||
public class AuthorService {
|
||||
private final AuthorRepository repository;
|
||||
|
||||
public AuthorService(AuthorRepository repository) {
|
||||
this.repository = repository;
|
||||
}
|
||||
|
||||
private void checkName(String name) {
|
||||
if (repository.findByNameIgnoreCase(name).isPresent()) {
|
||||
throw new IllegalArgumentException(
|
||||
String.format("Author with name %s is already exists", name));
|
||||
}
|
||||
}
|
||||
|
||||
public AuthorEntity findByName(String name) {
|
||||
return repository.findByNameIgnoreCase(name).orElse(null);
|
||||
}
|
||||
|
||||
@Transactional(readOnly = true)
|
||||
public List<AuthorEntity> getAll() {
|
||||
return StreamSupport.stream(repository.findAll().spliterator(), false).toList();
|
||||
}
|
||||
|
||||
@Transactional(readOnly = true)
|
||||
public AuthorEntity get(long id) {
|
||||
return repository.findById(id)
|
||||
.orElseThrow(() -> new NotFoundException(AuthorEntity.class, id));
|
||||
}
|
||||
|
||||
@Transactional
|
||||
public AuthorEntity create(AuthorEntity entity) {
|
||||
if (entity == null) {
|
||||
throw new IllegalArgumentException("Entity is null");
|
||||
}
|
||||
checkName(entity.getName());
|
||||
return repository.save(entity);
|
||||
}
|
||||
|
||||
@Transactional
|
||||
public AuthorEntity update(Long id, AuthorEntity entity) {
|
||||
final AuthorEntity existsEntity = get(id);
|
||||
if (!existsEntity.getName().equalsIgnoreCase(entity.getName())) {
|
||||
checkName(entity.getName());
|
||||
}
|
||||
existsEntity.setName(entity.getName());
|
||||
return repository.save(existsEntity);
|
||||
}
|
||||
|
||||
@Transactional
|
||||
public AuthorEntity delete(Long id) {
|
||||
final AuthorEntity existsEntity = get(id);
|
||||
repository.delete(existsEntity);
|
||||
return existsEntity;
|
||||
}
|
||||
}
|
@ -0,0 +1,186 @@
|
||||
package com.example.demo.books.api;
|
||||
|
||||
import java.util.Map;
|
||||
|
||||
import org.modelmapper.ModelMapper;
|
||||
import org.springframework.stereotype.Controller;
|
||||
import org.springframework.ui.Model;
|
||||
import org.springframework.validation.BindingResult;
|
||||
import org.springframework.web.bind.annotation.GetMapping;
|
||||
import org.springframework.web.bind.annotation.ModelAttribute;
|
||||
import org.springframework.web.bind.annotation.PathVariable;
|
||||
import org.springframework.web.bind.annotation.PostMapping;
|
||||
import org.springframework.web.bind.annotation.RequestMapping;
|
||||
import org.springframework.web.bind.annotation.RequestParam;
|
||||
import org.springframework.web.servlet.mvc.support.RedirectAttributes;
|
||||
|
||||
import com.example.demo.core.api.PageAttributesMapper;
|
||||
import com.example.demo.core.configuration.Constants;
|
||||
import com.example.demo.authors.api.AuthorDto;
|
||||
import com.example.demo.authors.model.AuthorEntity;
|
||||
import com.example.demo.authors.service.AuthorService;
|
||||
import com.example.demo.books.model.BookEntity;
|
||||
import com.example.demo.books.service.BookService;
|
||||
import com.example.demo.genres.api.GenreDto;
|
||||
import com.example.demo.genres.model.GenreEntity;
|
||||
import com.example.demo.genres.service.GenreService;
|
||||
|
||||
import jakarta.validation.Valid;
|
||||
|
||||
@Controller
|
||||
@RequestMapping(BookController.URL)
|
||||
public class BookController {
|
||||
public static final String URL = Constants.ADMIN_PREFIX + "/book";
|
||||
private static final String BOOK_VIEW = "book";
|
||||
private static final String BOOK_EDIT_VIEW = "book-edit";
|
||||
private static final String BOOK_ATTRIBUTE = "book";
|
||||
|
||||
private static final String PAGE_ATTRIBUTE = "page";
|
||||
|
||||
private final BookService bookService;
|
||||
private final GenreService genreService;
|
||||
private final AuthorService authorService;
|
||||
private final ModelMapper modelMapper;
|
||||
|
||||
public BookController(BookService bookService, GenreService genreService, AuthorService authorService,
|
||||
ModelMapper modelMapper) {
|
||||
this.bookService = bookService;
|
||||
this.modelMapper = modelMapper;
|
||||
this.genreService = genreService;
|
||||
this.authorService = authorService;
|
||||
}
|
||||
|
||||
private BookDto toDto(BookEntity entity) {
|
||||
return modelMapper.map(entity, BookDto.class);
|
||||
}
|
||||
|
||||
private BookEntity toEntity(BookDto dto) {
|
||||
final BookEntity entity = modelMapper.map(dto, BookEntity.class);
|
||||
entity.setGenre(genreService.get(dto.getGenreId()));
|
||||
entity.setAuthor(authorService.get(dto.getAuthorId()));
|
||||
return entity;
|
||||
}
|
||||
|
||||
private GenreDto toGenreDto(GenreEntity entity) {
|
||||
return modelMapper.map(entity, GenreDto.class);
|
||||
}
|
||||
|
||||
private AuthorDto toAuthorDto(AuthorEntity entity) {
|
||||
return modelMapper.map(entity, AuthorDto.class);
|
||||
}
|
||||
|
||||
public String getAllBooks(@RequestParam(name = PAGE_ATTRIBUTE, defaultValue = "0") int page,
|
||||
Model model) {
|
||||
|
||||
final Map<String, Object> attributes = PageAttributesMapper.toAttributes(
|
||||
bookService.getAllBooks(page, Constants.DEFUALT_PAGE_SIZE), this::toDto);
|
||||
|
||||
model.addAllAttributes(attributes);
|
||||
model.addAttribute(PAGE_ATTRIBUTE, page);
|
||||
|
||||
return BOOK_VIEW;
|
||||
}
|
||||
|
||||
@GetMapping
|
||||
public String getAll(@RequestParam(name = "genreId", defaultValue = "0") Long genreId,
|
||||
@RequestParam(name = "authorId", defaultValue = "0") Long authorId,
|
||||
@RequestParam(name = PAGE_ATTRIBUTE, defaultValue = "0") int page,
|
||||
Model model) {
|
||||
final Map<String, Object> attributes = PageAttributesMapper.toAttributes(
|
||||
bookService.getAllBooks(page, Constants.DEFUALT_PAGE_SIZE), this::toDto);
|
||||
|
||||
// book.setGenreName(genreService.get(book.getGenreId()));
|
||||
|
||||
model.addAllAttributes(attributes);
|
||||
model.addAttribute(PAGE_ATTRIBUTE, page);
|
||||
|
||||
model.addAttribute(
|
||||
"genres",
|
||||
genreService.getAll().stream().map(this::toGenreDto).toList());
|
||||
|
||||
model.addAttribute(
|
||||
"authors",
|
||||
authorService.getAll().stream().map(this::toAuthorDto).toList());
|
||||
|
||||
model.addAttribute(
|
||||
"books",
|
||||
bookService.getAllBooks(page, Constants.DEFUALT_PAGE_SIZE).stream().map(this::toDto).toList());
|
||||
|
||||
return BOOK_VIEW;
|
||||
}
|
||||
|
||||
@GetMapping("/edit/")
|
||||
public String create(@RequestParam(name = PAGE_ATTRIBUTE, defaultValue = "0") int page, Model model) {
|
||||
model.addAttribute(BOOK_ATTRIBUTE, new BookDto());
|
||||
model.addAttribute("genres", genreService.getAll().stream().map(this::toGenreDto).toList());
|
||||
model.addAttribute("authors", authorService.getAll().stream().map(this::toAuthorDto).toList());
|
||||
model.addAttribute(PAGE_ATTRIBUTE, page);
|
||||
return BOOK_EDIT_VIEW;
|
||||
}
|
||||
|
||||
@PostMapping("/edit/")
|
||||
public String create(@RequestParam(name = PAGE_ATTRIBUTE, defaultValue = "0") int page,
|
||||
@ModelAttribute(name = BOOK_ATTRIBUTE) @Valid BookDto book,
|
||||
BindingResult bindingResult, Model model, RedirectAttributes redirectAttributes) {
|
||||
|
||||
if (bindingResult.hasErrors()) {
|
||||
model.addAttribute(PAGE_ATTRIBUTE, page);
|
||||
return BOOK_EDIT_VIEW;
|
||||
}
|
||||
|
||||
redirectAttributes.addAttribute(PAGE_ATTRIBUTE, page);
|
||||
bookService.create(toEntity(book));
|
||||
return Constants.REDIRECT_VIEW + URL;
|
||||
}
|
||||
|
||||
@GetMapping("/edit/{id}")
|
||||
public String update(@PathVariable(name = "id") Long id,
|
||||
@RequestParam(name = PAGE_ATTRIBUTE, defaultValue = "0") int page,
|
||||
Model model) {
|
||||
|
||||
model.addAttribute(BOOK_ATTRIBUTE, toDto(bookService.get(id)));
|
||||
|
||||
model.addAttribute("books", bookService.getAllBooks().stream().map(this::toDto).toList());
|
||||
model.addAttribute("genres", genreService.getAll().stream().map(this::toGenreDto).toList());
|
||||
model.addAttribute("authors", authorService.getAll().stream().map(this::toAuthorDto).toList());
|
||||
model.addAttribute(PAGE_ATTRIBUTE, page);
|
||||
return BOOK_EDIT_VIEW;
|
||||
}
|
||||
|
||||
@PostMapping("/edit/{id}")
|
||||
public String update(@PathVariable(name = "id") Long id,
|
||||
@RequestParam(name = PAGE_ATTRIBUTE, defaultValue = "0") int page,
|
||||
@ModelAttribute(name = BOOK_ATTRIBUTE) @Valid BookDto book,
|
||||
BindingResult bindingResult, Model model, RedirectAttributes redirectAttributes) {
|
||||
|
||||
if (bindingResult.hasErrors()) {
|
||||
model.addAttribute(PAGE_ATTRIBUTE, page);
|
||||
return BOOK_EDIT_VIEW;
|
||||
}
|
||||
|
||||
if (id <= 0) {
|
||||
throw new IllegalArgumentException();
|
||||
}
|
||||
|
||||
model.addAttribute(
|
||||
"genres",
|
||||
genreService.getAll().stream().map(this::toGenreDto).toList());
|
||||
model.addAttribute(
|
||||
"authors",
|
||||
authorService.getAll().stream().map(this::toAuthorDto).toList());
|
||||
|
||||
redirectAttributes.addAttribute(PAGE_ATTRIBUTE, page);
|
||||
bookService.update(id, toEntity(book));
|
||||
return Constants.REDIRECT_VIEW + URL;
|
||||
}
|
||||
|
||||
@PostMapping("/delete/{id}")
|
||||
public String delete(@PathVariable(name = "id") Long id,
|
||||
@RequestParam(name = PAGE_ATTRIBUTE, defaultValue = "0") int page,
|
||||
RedirectAttributes redirectAttributes) {
|
||||
redirectAttributes.addAttribute(PAGE_ATTRIBUTE, page);
|
||||
bookService.delete(id);
|
||||
|
||||
return Constants.REDIRECT_VIEW + URL;
|
||||
}
|
||||
}
|
92
lab45/src/main/java/com/example/demo/books/api/BookDto.java
Normal file
92
lab45/src/main/java/com/example/demo/books/api/BookDto.java
Normal file
@ -0,0 +1,92 @@
|
||||
package com.example.demo.books.api;
|
||||
|
||||
import com.fasterxml.jackson.annotation.JsonProperty;
|
||||
|
||||
import jakarta.validation.constraints.Min;
|
||||
import jakarta.validation.constraints.NotBlank;
|
||||
import jakarta.validation.constraints.NotNull;
|
||||
import jakarta.validation.constraints.Size;
|
||||
|
||||
public class BookDto {
|
||||
@JsonProperty(access = JsonProperty.Access.READ_ONLY)
|
||||
private Long id;
|
||||
|
||||
@NotNull
|
||||
@Min(1)
|
||||
private Long genreId;
|
||||
|
||||
@NotNull
|
||||
@Min(1)
|
||||
private Long authorId;
|
||||
|
||||
@NotBlank
|
||||
@Size(min = 2, max = 50)
|
||||
private String name;
|
||||
|
||||
@NotBlank
|
||||
@Size(min = 2, max = 4)
|
||||
private String year;
|
||||
|
||||
@NotBlank
|
||||
@Size(min = 2, max = 250)
|
||||
private String description;
|
||||
|
||||
private boolean isFavourite;
|
||||
|
||||
@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 String getName() {
|
||||
return name;
|
||||
}
|
||||
|
||||
public void setName(String name) {
|
||||
this.name = name;
|
||||
}
|
||||
|
||||
public Long getAuthorId() {
|
||||
return authorId;
|
||||
}
|
||||
|
||||
public void setAuthorId(Long authorId) {
|
||||
this.authorId = authorId;
|
||||
}
|
||||
|
||||
public String getYear() {
|
||||
return year;
|
||||
}
|
||||
|
||||
public void setYear(String year) {
|
||||
this.year = year;
|
||||
}
|
||||
|
||||
public String getDescription() {
|
||||
return description;
|
||||
}
|
||||
|
||||
public void setDescription(String description) {
|
||||
this.description = description;
|
||||
}
|
||||
|
||||
public boolean getIsFavourite() {
|
||||
return isFavourite;
|
||||
}
|
||||
|
||||
public void setIsFavourite(boolean flag) {
|
||||
this.isFavourite = flag;
|
||||
}
|
||||
}
|
@ -0,0 +1,118 @@
|
||||
package com.example.demo.books.api;
|
||||
|
||||
import java.util.Collections;
|
||||
import java.util.List;
|
||||
import java.util.stream.Collectors;
|
||||
|
||||
import org.modelmapper.ModelMapper;
|
||||
import org.springframework.stereotype.Controller;
|
||||
import org.springframework.ui.Model;
|
||||
import org.springframework.web.bind.annotation.GetMapping;
|
||||
import org.springframework.web.bind.annotation.PathVariable;
|
||||
import org.springframework.web.bind.annotation.RequestMapping;
|
||||
import org.springframework.web.bind.annotation.RequestParam;
|
||||
|
||||
import com.example.demo.authors.api.AuthorDto;
|
||||
import com.example.demo.authors.model.AuthorEntity;
|
||||
import com.example.demo.authors.service.AuthorService;
|
||||
import com.example.demo.books.model.BookEntity;
|
||||
import com.example.demo.books.service.BookService;
|
||||
import com.example.demo.core.api.PageAttributesMapper;
|
||||
import com.example.demo.core.configuration.Constants;
|
||||
import com.example.demo.genres.api.GenreDto;
|
||||
import com.example.demo.genres.model.GenreEntity;
|
||||
import com.example.demo.genres.service.GenreService;
|
||||
|
||||
@Controller
|
||||
@RequestMapping(CatalogController.URL)
|
||||
public class CatalogController {
|
||||
private static final String CATALOG_VIEW = "catalog";
|
||||
private static final String URL = "/catalog";
|
||||
|
||||
private static final String BOOK_ATTRIBUTE = "book";
|
||||
private static final String BOOK_ONE = "book-one";
|
||||
|
||||
private static final String BOOK_RANDOM = "random-books";
|
||||
|
||||
private static final String GENREID_ATTRIBUTE = "genreId";
|
||||
private static final String AUTHORID_ATTRIBUTE = "authorId";
|
||||
|
||||
private static final String PAGE_ATTRIBUTE = "page";
|
||||
|
||||
private final BookService bookService;
|
||||
private final GenreService genreService;
|
||||
private final AuthorService authorService;
|
||||
private final ModelMapper modelMapper;
|
||||
|
||||
public CatalogController(BookService bookService, GenreService genreService,
|
||||
AuthorService authorService, ModelMapper modelMapper) {
|
||||
this.bookService = bookService;
|
||||
this.modelMapper = modelMapper;
|
||||
this.genreService = genreService;
|
||||
this.authorService = authorService;
|
||||
}
|
||||
|
||||
private BookDto toDto(BookEntity entity) {
|
||||
return modelMapper.map(entity, BookDto.class);
|
||||
}
|
||||
|
||||
private GenreDto toGenreDto(GenreEntity entity) {
|
||||
return modelMapper.map(entity, GenreDto.class);
|
||||
}
|
||||
|
||||
private AuthorDto toAuthorDto(AuthorEntity entity) {
|
||||
return modelMapper.map(entity, AuthorDto.class);
|
||||
}
|
||||
|
||||
@GetMapping
|
||||
public String getCatalog(@RequestParam(name = PAGE_ATTRIBUTE, defaultValue = "0") int page,
|
||||
@RequestParam(name = GENREID_ATTRIBUTE, defaultValue = "0") long genreId,
|
||||
@RequestParam(name = AUTHORID_ATTRIBUTE, defaultValue = "0") long authorId,
|
||||
Model model) {
|
||||
|
||||
model.addAttribute(PAGE_ATTRIBUTE, page);
|
||||
|
||||
model.addAllAttributes(PageAttributesMapper.toAttributes(
|
||||
bookService.getAll(genreId, authorId, page, Constants.DEFUALT_PAGE_SIZE), this::toDto));
|
||||
|
||||
model.addAttribute(
|
||||
"genres",
|
||||
genreService.getAll().stream().map(this::toGenreDto).toList());
|
||||
model.addAttribute("genreId", genreId);
|
||||
|
||||
model.addAttribute(
|
||||
"authors",
|
||||
authorService.getAll().stream().map(this::toAuthorDto).toList());
|
||||
model.addAttribute("authorId", authorId);
|
||||
|
||||
return CATALOG_VIEW;
|
||||
}
|
||||
|
||||
@GetMapping("/book-one/{id}")
|
||||
public String getOne(@PathVariable(name = "id") Long id,
|
||||
@RequestParam(name = PAGE_ATTRIBUTE, defaultValue = "0") int page,
|
||||
Model model) {
|
||||
|
||||
model.addAttribute(BOOK_ATTRIBUTE, toDto(bookService.get(id)));
|
||||
|
||||
model.addAttribute("books", bookService.getAllBooks().stream().map(this::toDto).toList());
|
||||
model.addAttribute("genres", genreService.getAll().stream().map(this::toGenreDto).toList());
|
||||
model.addAttribute("authors", authorService.getAll().stream().map(this::toAuthorDto).toList());
|
||||
model.addAttribute(PAGE_ATTRIBUTE, page);
|
||||
return BOOK_ONE;
|
||||
}
|
||||
|
||||
@GetMapping("/random-books")
|
||||
public String getRandomBooks(@RequestParam(name = PAGE_ATTRIBUTE, defaultValue = "0") int page, Model model) {
|
||||
List<BookDto> allBooks = bookService.getAllBooks().stream().map(this::toDto).collect(Collectors.toList());
|
||||
Collections.shuffle(allBooks);
|
||||
List<BookDto> randomBooks = allBooks.stream().limit(3).collect(Collectors.toList());
|
||||
|
||||
model.addAttribute("randomBooks", randomBooks);
|
||||
model.addAttribute("genres", genreService.getAll().stream().map(this::toGenreDto).toList());
|
||||
model.addAttribute("authors", authorService.getAll().stream().map(this::toAuthorDto).toList());
|
||||
model.addAttribute(PAGE_ATTRIBUTE, page);
|
||||
|
||||
return BOOK_RANDOM;
|
||||
}
|
||||
}
|
102
lab45/src/main/java/com/example/demo/books/model/BookEntity.java
Normal file
102
lab45/src/main/java/com/example/demo/books/model/BookEntity.java
Normal file
@ -0,0 +1,102 @@
|
||||
package com.example.demo.books.model;
|
||||
|
||||
import java.util.Objects;
|
||||
|
||||
import com.example.demo.authors.model.AuthorEntity;
|
||||
import com.example.demo.core.model.BaseEntity;
|
||||
import com.example.demo.genres.model.GenreEntity;
|
||||
|
||||
import jakarta.persistence.CascadeType;
|
||||
import jakarta.persistence.Column;
|
||||
import jakarta.persistence.Entity;
|
||||
import jakarta.persistence.JoinColumn;
|
||||
import jakarta.persistence.ManyToOne;
|
||||
import jakarta.persistence.Table;
|
||||
|
||||
@Entity
|
||||
@Table(name = "books")
|
||||
public class BookEntity extends BaseEntity {
|
||||
@ManyToOne
|
||||
@JoinColumn(name = "genreId", nullable = false)
|
||||
private GenreEntity genre;
|
||||
@ManyToOne
|
||||
@JoinColumn(name = "authorId", nullable = false)
|
||||
private AuthorEntity author;
|
||||
@Column(nullable = false, length = 50)
|
||||
private String name;
|
||||
@Column(name = "years", nullable = false, length = 4)
|
||||
private String year;
|
||||
@Column(nullable = false, length = 250)
|
||||
private String description;
|
||||
|
||||
public BookEntity() {
|
||||
}
|
||||
|
||||
public BookEntity(GenreEntity genre, AuthorEntity author, String name, String year, String description) {
|
||||
this.genre = genre;
|
||||
this.name = name;
|
||||
this.author = author;
|
||||
this.year = year;
|
||||
this.description = description;
|
||||
}
|
||||
|
||||
public GenreEntity getGenre() {
|
||||
return genre;
|
||||
}
|
||||
|
||||
public void setGenre(GenreEntity genre) {
|
||||
this.genre = genre;
|
||||
}
|
||||
|
||||
public AuthorEntity getAuthor() {
|
||||
return author;
|
||||
}
|
||||
|
||||
public void setAuthor(AuthorEntity author) {
|
||||
this.author = author;
|
||||
}
|
||||
|
||||
public String getName() {
|
||||
return name;
|
||||
}
|
||||
|
||||
public void setName(String name) {
|
||||
this.name = name;
|
||||
}
|
||||
|
||||
public String getYear() {
|
||||
return year;
|
||||
}
|
||||
|
||||
public void setYear(String year) {
|
||||
this.year = year;
|
||||
}
|
||||
|
||||
public String getDescription() {
|
||||
return description;
|
||||
}
|
||||
|
||||
public void setDescription(String description) {
|
||||
this.description = description;
|
||||
}
|
||||
|
||||
@Override
|
||||
public int hashCode() {
|
||||
return Objects.hash(id, genre, name, author, year, description);
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean equals(Object obj) {
|
||||
if (this == obj)
|
||||
return true;
|
||||
if (obj == null || getClass() != obj.getClass())
|
||||
return false;
|
||||
final BookEntity other = (BookEntity) obj;
|
||||
return Objects.equals(other.getId(), id)
|
||||
&& Objects.equals(other.getGenre(), genre)
|
||||
&& Objects.equals(other.getName(), name)
|
||||
&& Objects.equals(other.getAuthor(), author)
|
||||
&& Objects.equals(other.getYear(), year)
|
||||
&& Objects.equals(other.getDescription(), description);
|
||||
}
|
||||
}
|
@ -0,0 +1,28 @@
|
||||
package com.example.demo.books.repository;
|
||||
|
||||
import java.util.Optional;
|
||||
import java.util.List;
|
||||
|
||||
import org.springframework.data.domain.Page;
|
||||
import org.springframework.data.domain.Pageable;
|
||||
import org.springframework.data.repository.CrudRepository;
|
||||
import org.springframework.data.repository.PagingAndSortingRepository;
|
||||
|
||||
import com.example.demo.books.model.BookEntity;
|
||||
|
||||
public interface BookRepository
|
||||
extends CrudRepository<BookEntity, Long>, PagingAndSortingRepository<BookEntity, Long> {
|
||||
Optional<BookEntity> findByNameIgnoreCase(String name);
|
||||
|
||||
List<BookEntity> findByGenreId(Long genreId);
|
||||
|
||||
Page<BookEntity> findByGenreId(Long genreId, Pageable pageable);
|
||||
|
||||
List<BookEntity> findByAuthorId(Long authorId);
|
||||
|
||||
Page<BookEntity> findByAuthorId(Long authorId, Pageable pageable);
|
||||
|
||||
List<BookEntity> findByGenreIdAndAuthorId(Long genreId, Long authorId);
|
||||
|
||||
Page<BookEntity> findByGenreIdAndAuthorId(Long genreId, Long authorId, Pageable pageable);
|
||||
}
|
@ -0,0 +1,93 @@
|
||||
package com.example.demo.books.service;
|
||||
|
||||
import java.util.List;
|
||||
import java.util.stream.StreamSupport;
|
||||
|
||||
import org.springframework.data.domain.Page;
|
||||
import org.springframework.data.domain.PageRequest;
|
||||
import org.springframework.data.domain.Pageable;
|
||||
import org.springframework.data.domain.Sort;
|
||||
import org.springframework.stereotype.Service;
|
||||
import org.springframework.transaction.annotation.Transactional;
|
||||
|
||||
import com.example.demo.core.error.NotFoundException;
|
||||
import com.example.demo.books.model.BookEntity;
|
||||
import com.example.demo.books.repository.BookRepository;
|
||||
|
||||
@Service
|
||||
public class BookService {
|
||||
private final BookRepository repository;
|
||||
|
||||
public BookService(BookRepository repository) {
|
||||
this.repository = repository;
|
||||
}
|
||||
|
||||
@Transactional(readOnly = true)
|
||||
public List<BookEntity> getAllBooks() {
|
||||
return StreamSupport.stream(repository.findAll().spliterator(), false).toList();
|
||||
}
|
||||
|
||||
@Transactional(readOnly = true)
|
||||
public Page<BookEntity> getAllBooks(int page, int size) {
|
||||
return repository.findAll(PageRequest.of(page, size, Sort.by("id")));
|
||||
}
|
||||
|
||||
@Transactional(readOnly = true)
|
||||
public List<BookEntity> getAll(long genreId, long authorId) {
|
||||
if (genreId == 0L && authorId == 0L) {
|
||||
return StreamSupport.stream(repository.findAll().spliterator(), false).toList();
|
||||
} else if (genreId == 0L) {
|
||||
return repository.findByAuthorId(authorId);
|
||||
} else if (authorId == 0L) {
|
||||
return repository.findByGenreId(genreId);
|
||||
} else {
|
||||
return repository.findByGenreIdAndAuthorId(genreId, authorId);
|
||||
}
|
||||
}
|
||||
|
||||
@Transactional(readOnly = true)
|
||||
public Page<BookEntity> getAll(long genreId, long authorId, int page, int size) {
|
||||
final Pageable pageRequest = PageRequest.of(page, size);
|
||||
if (genreId == 0L && authorId == 0L) {
|
||||
return repository.findAll(pageRequest);
|
||||
} else if (genreId == 0L) {
|
||||
return repository.findByAuthorId(authorId, pageRequest);
|
||||
} else if (authorId == 0L) {
|
||||
return repository.findByGenreId(genreId, pageRequest);
|
||||
} else {
|
||||
return repository.findByGenreIdAndAuthorId(genreId, authorId, pageRequest);
|
||||
}
|
||||
}
|
||||
|
||||
@Transactional(readOnly = true)
|
||||
public BookEntity get(long id) {
|
||||
return repository.findById(id)
|
||||
.orElseThrow(() -> new NotFoundException(BookEntity.class, id));
|
||||
}
|
||||
|
||||
@Transactional
|
||||
public BookEntity create(BookEntity entity) {
|
||||
if (entity == null) {
|
||||
throw new IllegalArgumentException("Entity is null");
|
||||
}
|
||||
return repository.save(entity);
|
||||
}
|
||||
|
||||
@Transactional
|
||||
public BookEntity update(Long id, BookEntity entity) {
|
||||
final BookEntity existsEntity = get(id);
|
||||
existsEntity.setName(entity.getName());
|
||||
existsEntity.setAuthor(entity.getAuthor());
|
||||
existsEntity.setGenre(entity.getGenre());
|
||||
existsEntity.setYear(entity.getYear());
|
||||
existsEntity.setDescription(entity.getDescription());
|
||||
return repository.save(existsEntity);
|
||||
}
|
||||
|
||||
@Transactional
|
||||
public BookEntity delete(Long id) {
|
||||
final BookEntity existsEntity = get(id);
|
||||
repository.delete(existsEntity);
|
||||
return existsEntity;
|
||||
}
|
||||
}
|
@ -0,0 +1,28 @@
|
||||
package com.example.demo.core.api;
|
||||
|
||||
import org.springframework.web.bind.annotation.ControllerAdvice;
|
||||
import org.springframework.web.bind.annotation.ModelAttribute;
|
||||
|
||||
// import com.example.demo.core.session.SessionCart;
|
||||
|
||||
import jakarta.servlet.http.HttpServletRequest;
|
||||
import jakarta.servlet.http.HttpSession;
|
||||
|
||||
@ControllerAdvice
|
||||
public class GlobalController {
|
||||
// private final SessionCart cart;
|
||||
|
||||
// public GlobalController(SessionCart cart) {
|
||||
// this.cart = cart;
|
||||
// }
|
||||
|
||||
@ModelAttribute("servletPath")
|
||||
String getRequestServletPath(HttpServletRequest request) {
|
||||
return request.getServletPath();
|
||||
}
|
||||
|
||||
// @ModelAttribute("totalCart")
|
||||
// double getTotalCart(HttpSession session) {
|
||||
// return cart.getSum();
|
||||
// }
|
||||
}
|
@ -0,0 +1,18 @@
|
||||
package com.example.demo.core.api;
|
||||
|
||||
import java.util.Map;
|
||||
import java.util.function.Function;
|
||||
|
||||
import org.springframework.data.domain.Page;
|
||||
|
||||
public class PageAttributesMapper {
|
||||
private PageAttributesMapper() {
|
||||
}
|
||||
|
||||
public static <E, D> Map<String, Object> toAttributes(Page<E> page, Function<E, D> mapper) {
|
||||
return Map.of(
|
||||
"items", page.getContent().stream().map(mapper::apply).toList(),
|
||||
"currentPage", page.getNumber(),
|
||||
"totalPages", page.getTotalPages());
|
||||
}
|
||||
}
|
@ -0,0 +1,19 @@
|
||||
package com.example.demo.core.configuration;
|
||||
|
||||
public class Constants {
|
||||
public static final String SEQUENCE_NAME = "hibernate_sequence";
|
||||
|
||||
public static final int DEFUALT_PAGE_SIZE = 5;
|
||||
|
||||
public static final String REDIRECT_VIEW = "redirect:";
|
||||
|
||||
public static final String ADMIN_PREFIX = "/admin";
|
||||
|
||||
public static final String LOGIN_URL = "/login";
|
||||
public static final String LOGOUT_URL = "/logout";
|
||||
|
||||
public static final String DEFAULT_PASSWORD = "123456";
|
||||
|
||||
private Constants() {
|
||||
}
|
||||
}
|
@ -0,0 +1,23 @@
|
||||
package com.example.demo.core.configuration;
|
||||
|
||||
import org.modelmapper.ModelMapper;
|
||||
import org.modelmapper.PropertyMap;
|
||||
import org.springframework.context.annotation.Bean;
|
||||
import org.springframework.context.annotation.Configuration;
|
||||
|
||||
import com.example.demo.core.model.BaseEntity;
|
||||
|
||||
@Configuration
|
||||
public class MapperConfiguration {
|
||||
@Bean
|
||||
ModelMapper modelMapper() {
|
||||
final ModelMapper mapper = new ModelMapper();
|
||||
mapper.addMappings(new PropertyMap<Object, BaseEntity>() {
|
||||
@Override
|
||||
protected void configure() {
|
||||
skip(destination.getId());
|
||||
}
|
||||
});
|
||||
return mapper;
|
||||
}
|
||||
}
|
@ -0,0 +1,14 @@
|
||||
package com.example.demo.core.configuration;
|
||||
|
||||
import org.springframework.context.annotation.Configuration;
|
||||
import org.springframework.web.servlet.config.annotation.ViewControllerRegistry;
|
||||
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
|
||||
|
||||
@Configuration
|
||||
public class WebConfiguration implements WebMvcConfigurer {
|
||||
@Override
|
||||
public void addViewControllers(ViewControllerRegistry registry) {
|
||||
registry.addViewController("/login").setViewName("login");
|
||||
registry.addViewController("/").setViewName("home");
|
||||
}
|
||||
}
|
@ -0,0 +1,53 @@
|
||||
package com.example.demo.core.error;
|
||||
|
||||
import java.util.Map;
|
||||
|
||||
import org.slf4j.Logger;
|
||||
import org.slf4j.LoggerFactory;
|
||||
import org.springframework.core.annotation.AnnotationUtils;
|
||||
import org.springframework.web.bind.annotation.ControllerAdvice;
|
||||
import org.springframework.web.bind.annotation.ExceptionHandler;
|
||||
import org.springframework.web.bind.annotation.ResponseStatus;
|
||||
import org.springframework.web.servlet.ModelAndView;
|
||||
|
||||
import jakarta.servlet.http.HttpServletRequest;
|
||||
|
||||
@ControllerAdvice
|
||||
public class AdviceController {
|
||||
private final Logger log = LoggerFactory.getLogger(AdviceController.class);
|
||||
|
||||
private static Throwable getRootCause(Throwable throwable) {
|
||||
Throwable rootCause = throwable;
|
||||
while (rootCause.getCause() != null && rootCause.getCause() != rootCause) {
|
||||
rootCause = rootCause.getCause();
|
||||
}
|
||||
return rootCause;
|
||||
}
|
||||
|
||||
private static Map<String, Object> getAttributes(HttpServletRequest request, Throwable throwable) {
|
||||
final Throwable rootCause = getRootCause(throwable);
|
||||
final StackTraceElement firstError = rootCause.getStackTrace()[0];
|
||||
return Map.of(
|
||||
"message", rootCause.getMessage(),
|
||||
"url", request.getRequestURL(),
|
||||
"exception", rootCause.getClass().getName(),
|
||||
"file", firstError.getFileName(),
|
||||
"method", firstError.getMethodName(),
|
||||
"line", firstError.getLineNumber());
|
||||
}
|
||||
|
||||
@ExceptionHandler(value = Exception.class)
|
||||
public ModelAndView defaultErrorHandler(HttpServletRequest request, Throwable throwable) throws Throwable {
|
||||
if (AnnotationUtils.findAnnotation(throwable.getClass(),
|
||||
ResponseStatus.class) != null) {
|
||||
throw throwable;
|
||||
}
|
||||
|
||||
log.error("{}", throwable.getMessage());
|
||||
throwable.printStackTrace();
|
||||
final ModelAndView model = new ModelAndView();
|
||||
model.addAllObjects(getAttributes(request, throwable));
|
||||
model.setViewName("error");
|
||||
return model;
|
||||
}
|
||||
}
|
@ -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));
|
||||
}
|
||||
}
|
@ -0,0 +1,28 @@
|
||||
package com.example.demo.core.model;
|
||||
|
||||
import com.example.demo.core.configuration.Constants;
|
||||
|
||||
import jakarta.persistence.GeneratedValue;
|
||||
import jakarta.persistence.GenerationType;
|
||||
import jakarta.persistence.Id;
|
||||
import jakarta.persistence.MappedSuperclass;
|
||||
import jakarta.persistence.SequenceGenerator;
|
||||
|
||||
@MappedSuperclass
|
||||
public abstract class BaseEntity {
|
||||
@Id
|
||||
@GeneratedValue(strategy = GenerationType.SEQUENCE, generator = Constants.SEQUENCE_NAME)
|
||||
@SequenceGenerator(name = Constants.SEQUENCE_NAME, sequenceName = Constants.SEQUENCE_NAME, allocationSize = 1)
|
||||
protected Long id;
|
||||
|
||||
protected BaseEntity() {
|
||||
}
|
||||
|
||||
public Long getId() {
|
||||
return id;
|
||||
}
|
||||
|
||||
public void setId(Long id) {
|
||||
this.id = id;
|
||||
}
|
||||
}
|
@ -0,0 +1,63 @@
|
||||
package com.example.demo.core.security;
|
||||
|
||||
import org.springframework.context.annotation.Bean;
|
||||
import org.springframework.context.annotation.Configuration;
|
||||
import org.springframework.security.authentication.dao.DaoAuthenticationProvider;
|
||||
import org.springframework.security.config.Customizer;
|
||||
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
|
||||
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
|
||||
import org.springframework.security.config.annotation.web.configurers.AbstractHttpConfigurer;
|
||||
import org.springframework.security.config.annotation.web.configurers.HeadersConfigurer.FrameOptionsConfig;
|
||||
import org.springframework.security.core.userdetails.UserDetailsService;
|
||||
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
|
||||
import org.springframework.security.crypto.password.PasswordEncoder;
|
||||
import org.springframework.security.web.SecurityFilterChain;
|
||||
|
||||
import com.example.demo.core.configuration.Constants;
|
||||
import com.example.demo.users.api.UserSignupController;
|
||||
import com.example.demo.users.model.UserRole;
|
||||
|
||||
@Configuration
|
||||
@EnableWebSecurity
|
||||
public class SecurityConfiguration {
|
||||
@Bean
|
||||
SecurityFilterChain filterChain(HttpSecurity httpSecurity) throws Exception {
|
||||
httpSecurity.headers(headers -> headers.frameOptions(FrameOptionsConfig::sameOrigin));
|
||||
httpSecurity.csrf(AbstractHttpConfigurer::disable);
|
||||
httpSecurity.cors(Customizer.withDefaults());
|
||||
|
||||
httpSecurity.authorizeHttpRequests(requests -> requests
|
||||
.requestMatchers("/css/**", "/webjars/**", "/*.svg")
|
||||
.permitAll());
|
||||
|
||||
httpSecurity.authorizeHttpRequests(requests -> requests
|
||||
.requestMatchers(Constants.ADMIN_PREFIX + "/**").hasRole(UserRole.ADMIN.name())
|
||||
.requestMatchers("/h2-console/**").hasRole(UserRole.ADMIN.name())
|
||||
.requestMatchers(UserSignupController.URL).anonymous()
|
||||
.requestMatchers(Constants.LOGIN_URL).anonymous()
|
||||
.anyRequest().authenticated());
|
||||
|
||||
httpSecurity.formLogin(formLogin -> formLogin
|
||||
.loginPage(Constants.LOGIN_URL));
|
||||
|
||||
httpSecurity.rememberMe(rememberMe -> rememberMe.key("uniqueAndSecret"));
|
||||
|
||||
httpSecurity.logout(logout -> logout
|
||||
.deleteCookies("JSESSIONID"));
|
||||
|
||||
return httpSecurity.build();
|
||||
}
|
||||
|
||||
@Bean
|
||||
DaoAuthenticationProvider authenticationProvider(UserDetailsService userDetailsService) {
|
||||
final DaoAuthenticationProvider authProvider = new DaoAuthenticationProvider();
|
||||
authProvider.setUserDetailsService(userDetailsService);
|
||||
authProvider.setPasswordEncoder(passwordEncoder());
|
||||
return authProvider;
|
||||
}
|
||||
|
||||
@Bean
|
||||
PasswordEncoder passwordEncoder() {
|
||||
return new BCryptPasswordEncoder();
|
||||
}
|
||||
}
|
@ -0,0 +1,64 @@
|
||||
package com.example.demo.core.security;
|
||||
|
||||
import java.util.Collection;
|
||||
import java.util.Set;
|
||||
|
||||
import org.springframework.security.core.GrantedAuthority;
|
||||
import org.springframework.security.core.userdetails.UserDetails;
|
||||
|
||||
import com.example.demo.users.model.UserEntity;
|
||||
|
||||
public class UserPrincipal implements UserDetails {
|
||||
private final long id;
|
||||
private final String username;
|
||||
private final String password;
|
||||
private final Set<? extends GrantedAuthority> roles;
|
||||
private final boolean active;
|
||||
|
||||
public UserPrincipal(UserEntity user) {
|
||||
this.id = user.getId();
|
||||
this.username = user.getLogin();
|
||||
this.password = user.getPassword();
|
||||
this.roles = Set.of(user.getRole());
|
||||
this.active = true;
|
||||
}
|
||||
|
||||
public Long getId() {
|
||||
return id;
|
||||
}
|
||||
|
||||
@Override
|
||||
public String getUsername() {
|
||||
return username;
|
||||
}
|
||||
|
||||
@Override
|
||||
public String getPassword() {
|
||||
return password;
|
||||
}
|
||||
|
||||
@Override
|
||||
public Collection<? extends GrantedAuthority> getAuthorities() {
|
||||
return roles;
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean isEnabled() {
|
||||
return active;
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean isAccountNonExpired() {
|
||||
return isEnabled();
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean isAccountNonLocked() {
|
||||
return isEnabled();
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean isCredentialsNonExpired() {
|
||||
return isEnabled();
|
||||
}
|
||||
}
|
@ -0,0 +1,14 @@
|
||||
// package com.example.demo.core.session;
|
||||
|
||||
// import java.util.HashMap;
|
||||
|
||||
// import com.example.demo.users.api.UserCartDto;
|
||||
|
||||
// public class SessionCart extends HashMap<Integer, UserCartDto> {
|
||||
// public double getSum() {
|
||||
// return this.values().stream()
|
||||
// .map(item -> item.getCount() * item.getPrice())
|
||||
// .mapToDouble(Double::doubleValue)
|
||||
// .sum();
|
||||
// }
|
||||
// }
|
@ -0,0 +1,17 @@
|
||||
// package com.example.demo.core.session;
|
||||
|
||||
// import org.springframework.context.annotation.Bean;
|
||||
// import org.springframework.context.annotation.Configuration;
|
||||
// import org.springframework.context.annotation.Scope;
|
||||
// import org.springframework.context.annotation.ScopedProxyMode;
|
||||
// import org.springframework.web.context.WebApplicationContext;
|
||||
|
||||
// @Configuration
|
||||
// public class SessionHelper {
|
||||
// @Bean
|
||||
// @Scope(value = WebApplicationContext.SCOPE_SESSION, proxyMode =
|
||||
// ScopedProxyMode.TARGET_CLASS)
|
||||
// SessionCart todos() {
|
||||
// return new SessionCart();
|
||||
// }
|
||||
// }
|
@ -0,0 +1,151 @@
|
||||
package com.example.demo.favorites.api;
|
||||
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
import java.util.HashMap;
|
||||
import java.util.stream.Collectors;
|
||||
|
||||
import org.modelmapper.ModelMapper;
|
||||
import org.springframework.security.core.annotation.AuthenticationPrincipal;
|
||||
import org.springframework.stereotype.Controller;
|
||||
import org.springframework.ui.Model;
|
||||
import org.springframework.validation.BindingResult;
|
||||
import org.springframework.web.bind.annotation.DeleteMapping;
|
||||
import org.springframework.web.bind.annotation.GetMapping;
|
||||
import org.springframework.web.bind.annotation.ModelAttribute;
|
||||
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 org.springframework.web.servlet.mvc.support.RedirectAttributes;
|
||||
|
||||
import com.example.demo.core.api.PageAttributesMapper;
|
||||
import com.example.demo.core.configuration.Constants;
|
||||
import com.example.demo.core.security.UserPrincipal;
|
||||
import com.example.demo.favorites.model.FavoriteEntity;
|
||||
import com.example.demo.favorites.service.FavoriteService;
|
||||
import com.example.demo.genres.api.GenreDto;
|
||||
import com.example.demo.genres.model.GenreEntity;
|
||||
import com.example.demo.genres.service.GenreService;
|
||||
import com.example.demo.authors.api.AuthorDto;
|
||||
import com.example.demo.authors.model.AuthorEntity;
|
||||
import com.example.demo.authors.service.AuthorService;
|
||||
import com.example.demo.books.api.BookDto;
|
||||
import com.example.demo.books.model.BookEntity;
|
||||
import com.example.demo.books.service.BookService;
|
||||
import com.example.demo.users.api.UserDto;
|
||||
import com.example.demo.users.model.UserEntity;
|
||||
import com.example.demo.users.service.UserService;
|
||||
|
||||
import jakarta.validation.Valid;
|
||||
|
||||
@Controller
|
||||
@RequestMapping(FavoriteController.URL)
|
||||
public class FavoriteController {
|
||||
|
||||
public static final String URL = "/favorite";
|
||||
private static final String FAVORITE_VIEW = "favorite";
|
||||
private static final String FAVORITE_EDIT_VIEW = "favorite-edit";
|
||||
private static final String FAVORITE_ATTRIBUTE = "favorite";
|
||||
private static final String FAVORITE_DETAILS_VIEW = "favorite-details";
|
||||
|
||||
protected static final String PAGE_ATTRIBUTE = "page";
|
||||
protected String REDIRECT_AFTER_FAVOURITE_CLICK_PATH;
|
||||
protected static final String GENREID_ATTRIBUTE = "genreId";
|
||||
protected static final String AUTHORID_ATTRIBUTE = "authorId";
|
||||
|
||||
private final FavoriteService favoriteService;
|
||||
private final UserService userService;
|
||||
private final BookService bookService;
|
||||
private final AuthorService authorService;
|
||||
private final GenreService genreService;
|
||||
private final ModelMapper modelMapper;
|
||||
|
||||
public FavoriteController(FavoriteService favoriteService, UserService userService,
|
||||
BookService bookService, AuthorService authorService, GenreService genreService, ModelMapper modelMapper) {
|
||||
this.modelMapper = modelMapper;
|
||||
this.userService = userService;
|
||||
this.favoriteService = favoriteService;
|
||||
this.bookService = bookService;
|
||||
this.authorService = authorService;
|
||||
this.genreService = genreService;
|
||||
}
|
||||
|
||||
private FavoriteDto toDto(FavoriteEntity entity) {
|
||||
return modelMapper.map(entity, FavoriteDto.class);
|
||||
}
|
||||
|
||||
private FavoriteEntity toEntity(FavoriteDto dto) {
|
||||
final FavoriteEntity entity = modelMapper.map(dto, FavoriteEntity.class);
|
||||
entity.setBook(bookService.get(dto.getBookId()));
|
||||
// entity.setUser(userService.get(dto.getUserId()));
|
||||
return entity;
|
||||
}
|
||||
|
||||
private UserDto toUserDto(UserEntity entity) {
|
||||
return modelMapper.map(entity, UserDto.class);
|
||||
}
|
||||
|
||||
private BookDto toBookDto(BookEntity entity, Long userId) {
|
||||
BookDto dto = modelMapper.map(entity, BookDto.class);
|
||||
dto.setIsFavourite(true);
|
||||
dto.setGenreId(entity.getGenre().getId());
|
||||
return dto;
|
||||
}
|
||||
|
||||
private GenreDto toGenreDto(GenreEntity entity) {
|
||||
return modelMapper.map(entity, GenreDto.class);
|
||||
}
|
||||
|
||||
private AuthorDto toAuthorDto(AuthorEntity entity) {
|
||||
return modelMapper.map(entity, AuthorDto.class);
|
||||
}
|
||||
|
||||
@GetMapping
|
||||
public String getAll(
|
||||
@RequestParam(name = PAGE_ATTRIBUTE, defaultValue = "0") int page,
|
||||
@RequestParam(name = GENREID_ATTRIBUTE, defaultValue = "0") Long genreId,
|
||||
@RequestParam(name = AUTHORID_ATTRIBUTE, defaultValue = "0") Long authorId,
|
||||
Model model,
|
||||
@AuthenticationPrincipal UserPrincipal principal) {
|
||||
final Map<String, Object> attributes = PageAttributesMapper.toAttributes(
|
||||
favoriteService.getAll(principal.getId(), page,
|
||||
Constants.DEFUALT_PAGE_SIZE),
|
||||
book -> toBookDto(book.getBook(), principal.getId()));
|
||||
model.addAllAttributes(attributes);
|
||||
model.addAttribute(PAGE_ATTRIBUTE, page);
|
||||
|
||||
model.addAttribute("genres",
|
||||
genreService.getAll().stream()
|
||||
.map(this::toGenreDto)
|
||||
.toList());
|
||||
|
||||
model.addAttribute(GENREID_ATTRIBUTE, genreId);
|
||||
|
||||
model.addAttribute("authors",
|
||||
authorService.getAll().stream()
|
||||
.map(this::toAuthorDto)
|
||||
.toList());
|
||||
|
||||
model.addAttribute(GENREID_ATTRIBUTE, authorId);
|
||||
|
||||
return FAVORITE_VIEW;
|
||||
}
|
||||
|
||||
@PostMapping
|
||||
public String toggleFavourite(
|
||||
Model model,
|
||||
@RequestParam(name = "id") Long bookId,
|
||||
@RequestParam(name = "isFavourite") boolean isFavourite,
|
||||
@AuthenticationPrincipal UserPrincipal principal) {
|
||||
if (bookId <= 0) {
|
||||
throw new IllegalArgumentException();
|
||||
}
|
||||
|
||||
favoriteService.toggle(principal.getId(), bookId, isFavourite);
|
||||
return Constants.REDIRECT_VIEW + REDIRECT_AFTER_FAVOURITE_CLICK_PATH;
|
||||
}
|
||||
}
|
@ -0,0 +1,45 @@
|
||||
package com.example.demo.favorites.api;
|
||||
|
||||
import com.fasterxml.jackson.annotation.JsonProperty;
|
||||
|
||||
import jakarta.validation.constraints.Min;
|
||||
import jakarta.validation.constraints.NotNull;
|
||||
|
||||
public class FavoriteDto {
|
||||
|
||||
@JsonProperty(access = JsonProperty.Access.READ_ONLY)
|
||||
private Long id;
|
||||
|
||||
@NotNull
|
||||
@Min(1)
|
||||
private Long userId;
|
||||
|
||||
@NotNull
|
||||
@Min(1)
|
||||
private Long bookId;
|
||||
|
||||
@JsonProperty(access = JsonProperty.Access.READ_ONLY)
|
||||
public Long getId() {
|
||||
return id;
|
||||
}
|
||||
|
||||
public void setId(Long id) {
|
||||
this.id = id;
|
||||
}
|
||||
|
||||
public Long getUserId() {
|
||||
return userId;
|
||||
}
|
||||
|
||||
public void setUserId(Long userId) {
|
||||
this.userId = userId;
|
||||
}
|
||||
|
||||
public Long getBookId() {
|
||||
return bookId;
|
||||
}
|
||||
|
||||
public void setBookId(Long bookId) {
|
||||
this.bookId = bookId;
|
||||
}
|
||||
}
|
@ -0,0 +1,66 @@
|
||||
package com.example.demo.favorites.model;
|
||||
|
||||
import java.util.Objects;
|
||||
|
||||
import com.example.demo.books.model.BookEntity;
|
||||
import com.example.demo.core.model.BaseEntity;
|
||||
import com.example.demo.users.model.UserEntity;
|
||||
|
||||
import jakarta.persistence.CascadeType;
|
||||
import jakarta.persistence.Entity;
|
||||
import jakarta.persistence.JoinColumn;
|
||||
import jakarta.persistence.ManyToOne;
|
||||
import jakarta.persistence.Table;
|
||||
|
||||
@Entity
|
||||
@Table(name = "favorites")
|
||||
public class FavoriteEntity extends BaseEntity {
|
||||
@ManyToOne(cascade = CascadeType.REMOVE)
|
||||
@JoinColumn(name = "userId", nullable = false)
|
||||
private UserEntity user;
|
||||
|
||||
@ManyToOne(cascade = CascadeType.REMOVE)
|
||||
@JoinColumn(name = "bookId", nullable = false)
|
||||
private BookEntity book;
|
||||
|
||||
public FavoriteEntity() {
|
||||
}
|
||||
|
||||
public FavoriteEntity(UserEntity user, BookEntity book) {
|
||||
this.user = user;
|
||||
this.book = book;
|
||||
}
|
||||
|
||||
public UserEntity getUser() {
|
||||
return user;
|
||||
}
|
||||
|
||||
public void setUser(UserEntity user) {
|
||||
this.user = user;
|
||||
}
|
||||
|
||||
public BookEntity getBook() {
|
||||
return book;
|
||||
}
|
||||
|
||||
public void setBook(BookEntity book) {
|
||||
this.book = book;
|
||||
}
|
||||
|
||||
@Override
|
||||
public int hashCode() {
|
||||
return Objects.hash(id, user, book);
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean equals(Object obj) {
|
||||
if (this == obj)
|
||||
return true;
|
||||
if (obj == null || getClass() != obj.getClass())
|
||||
return false;
|
||||
final FavoriteEntity other = (FavoriteEntity) obj;
|
||||
return Objects.equals(other.getId(), id)
|
||||
&& Objects.equals(other.getUser(), user)
|
||||
&& Objects.equals(other.getBook(), book);
|
||||
}
|
||||
}
|
@ -0,0 +1,24 @@
|
||||
package com.example.demo.favorites.repository;
|
||||
|
||||
import java.util.List;
|
||||
import java.util.Optional;
|
||||
|
||||
import org.springframework.data.domain.Page;
|
||||
import org.springframework.data.domain.Pageable;
|
||||
import org.springframework.data.repository.CrudRepository;
|
||||
import org.springframework.data.repository.PagingAndSortingRepository;
|
||||
|
||||
import com.example.demo.favorites.model.FavoriteEntity;
|
||||
|
||||
public interface FavoriteRepository extends CrudRepository<FavoriteEntity, Long>,
|
||||
PagingAndSortingRepository<FavoriteEntity, Long> {
|
||||
List<FavoriteEntity> findByUserId(Long userId);
|
||||
|
||||
List<FavoriteEntity> findByUserId(long userId);
|
||||
|
||||
Page<FavoriteEntity> findByUserId(long userId, Pageable pageable);
|
||||
|
||||
List<FavoriteEntity> findByUserIdAndBookId(long userId, long bookId);
|
||||
|
||||
Optional<FavoriteEntity> findOneByUserIdAndId(long userId, long bookId);
|
||||
}
|
@ -0,0 +1,92 @@
|
||||
package com.example.demo.favorites.service;
|
||||
|
||||
import java.util.List;
|
||||
import java.util.stream.StreamSupport;
|
||||
|
||||
import org.springframework.data.domain.Page;
|
||||
import org.springframework.data.domain.PageRequest;
|
||||
import org.springframework.data.domain.Pageable;
|
||||
import org.springframework.stereotype.Service;
|
||||
import org.springframework.transaction.annotation.Transactional;
|
||||
|
||||
import com.example.demo.books.service.BookService;
|
||||
import com.example.demo.core.error.NotFoundException;
|
||||
import com.example.demo.favorites.model.FavoriteEntity;
|
||||
import com.example.demo.favorites.repository.FavoriteRepository;
|
||||
import com.example.demo.users.service.UserService;
|
||||
|
||||
@Service
|
||||
public class FavoriteService {
|
||||
private final FavoriteRepository repository;
|
||||
private final UserService userService;
|
||||
private final BookService bookService;
|
||||
|
||||
public FavoriteService(FavoriteRepository repository, UserService userService, BookService bookService) {
|
||||
this.repository = repository;
|
||||
this.userService = userService;
|
||||
this.bookService = bookService;
|
||||
}
|
||||
|
||||
@Transactional(readOnly = true)
|
||||
public List<FavoriteEntity> getAll(Long userId) {
|
||||
if (userId == 0) {
|
||||
return StreamSupport.stream(repository.findAll().spliterator(), false).toList();
|
||||
}
|
||||
return repository.findByUserId(userId);
|
||||
}
|
||||
|
||||
@Transactional(readOnly = true)
|
||||
public Page<FavoriteEntity> getAll(Long userId, int page, int size) {
|
||||
final Pageable pageRequest = PageRequest.of(page, size);
|
||||
if (userId == 0) {
|
||||
return repository.findAll(pageRequest);
|
||||
}
|
||||
return repository.findByUserId(userId, pageRequest);
|
||||
}
|
||||
|
||||
// @Transactional(readOnly = true)
|
||||
// public FavoriteEntity get(Long id) {
|
||||
// return repository.findById(id).orElseThrow(() -> new NotFoundException(null,
|
||||
// id));
|
||||
// }
|
||||
|
||||
@Transactional(readOnly = true)
|
||||
public FavoriteEntity get(long userId, long id) {
|
||||
userService.get(userId);
|
||||
return repository.findOneByUserIdAndId(userId, id)
|
||||
.orElseThrow(() -> new NotFoundException(FavoriteEntity.class, id));
|
||||
}
|
||||
|
||||
@Transactional()
|
||||
public FavoriteEntity create(FavoriteEntity entity, Long userId) {
|
||||
if (entity == null) {
|
||||
throw new IllegalArgumentException("Entity is null");
|
||||
}
|
||||
|
||||
entity.setUser(userService.get(userId));
|
||||
return repository.save(entity);
|
||||
}
|
||||
|
||||
@Transactional
|
||||
public FavoriteEntity toggle(Long userId, Long bookId, boolean isFavourite) {
|
||||
if (isFavourite)
|
||||
return delete(userId, bookId);
|
||||
|
||||
return create(new FavoriteEntity(userService.get(userId), bookService.get(bookId)), userId);
|
||||
}
|
||||
|
||||
@Transactional
|
||||
public FavoriteEntity update(long userId, Long id, FavoriteEntity entity) {
|
||||
final FavoriteEntity exisEntity = get(userId, id);
|
||||
exisEntity.setUser(entity.getUser());
|
||||
exisEntity.setBook(entity.getBook());
|
||||
return repository.save(exisEntity);
|
||||
}
|
||||
|
||||
@Transactional
|
||||
public FavoriteEntity delete(long userId, Long id) {
|
||||
final FavoriteEntity existEntity = get(userId, id);
|
||||
repository.delete(existEntity);
|
||||
return existEntity;
|
||||
}
|
||||
}
|
@ -0,0 +1,104 @@
|
||||
package com.example.demo.genres.api;
|
||||
|
||||
import org.modelmapper.ModelMapper;
|
||||
import org.springframework.stereotype.Controller;
|
||||
import org.springframework.ui.Model;
|
||||
import org.springframework.validation.BindingResult;
|
||||
import org.springframework.web.bind.annotation.GetMapping;
|
||||
import org.springframework.web.bind.annotation.ModelAttribute;
|
||||
import org.springframework.web.bind.annotation.PathVariable;
|
||||
import org.springframework.web.bind.annotation.PostMapping;
|
||||
import org.springframework.web.bind.annotation.RequestMapping;
|
||||
|
||||
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;
|
||||
|
||||
@Controller
|
||||
@RequestMapping(GenreController.URL)
|
||||
public class GenreController {
|
||||
public static final String URL = Constants.ADMIN_PREFIX + "/genre";
|
||||
private static final String GENRE_VIEW = "genre";
|
||||
private static final String GENRE_EDIT_VIEW = "genre-edit";
|
||||
private static final String GENRE_ATTRIBUTE = "genre";
|
||||
|
||||
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 String getAll(Model model) {
|
||||
model.addAttribute(
|
||||
"items",
|
||||
genreService.getAll().stream()
|
||||
.map(this::toDto)
|
||||
.toList());
|
||||
return GENRE_VIEW;
|
||||
}
|
||||
|
||||
@GetMapping("/edit/")
|
||||
public String create(Model model) {
|
||||
model.addAttribute(GENRE_ATTRIBUTE, new GenreDto());
|
||||
return GENRE_EDIT_VIEW;
|
||||
}
|
||||
|
||||
@PostMapping("/edit/")
|
||||
public String create(
|
||||
@ModelAttribute(name = GENRE_ATTRIBUTE) @Valid GenreDto genre,
|
||||
BindingResult bindingResult,
|
||||
Model model) {
|
||||
if (bindingResult.hasErrors()) {
|
||||
return GENRE_EDIT_VIEW;
|
||||
}
|
||||
genreService.create(toEntity(genre));
|
||||
return Constants.REDIRECT_VIEW + URL;
|
||||
}
|
||||
|
||||
@GetMapping("/edit/{id}")
|
||||
public String update(
|
||||
@PathVariable(name = "id") Long id,
|
||||
Model model) {
|
||||
if (id <= 0) {
|
||||
throw new IllegalArgumentException();
|
||||
}
|
||||
model.addAttribute(GENRE_ATTRIBUTE, toDto(genreService.get(id)));
|
||||
return GENRE_EDIT_VIEW;
|
||||
}
|
||||
|
||||
@PostMapping("/edit/{id}")
|
||||
public String update(
|
||||
@PathVariable(name = "id") Long id,
|
||||
@ModelAttribute(name = GENRE_ATTRIBUTE) @Valid GenreDto genre,
|
||||
BindingResult bindingResult,
|
||||
Model model) {
|
||||
if (bindingResult.hasErrors()) {
|
||||
return GENRE_EDIT_VIEW;
|
||||
}
|
||||
if (id <= 0) {
|
||||
throw new IllegalArgumentException();
|
||||
}
|
||||
genreService.update(id, toEntity(genre));
|
||||
return Constants.REDIRECT_VIEW + URL;
|
||||
}
|
||||
|
||||
@PostMapping("/delete/{id}")
|
||||
public String delete(
|
||||
@PathVariable(name = "id") Long id) {
|
||||
genreService.delete(id);
|
||||
return Constants.REDIRECT_VIEW + URL;
|
||||
}
|
||||
}
|
@ -0,0 +1,30 @@
|
||||
package com.example.demo.genres.api;
|
||||
|
||||
import com.fasterxml.jackson.annotation.JsonProperty;
|
||||
|
||||
import jakarta.validation.constraints.NotBlank;
|
||||
import jakarta.validation.constraints.Size;
|
||||
|
||||
public class GenreDto {
|
||||
@JsonProperty(access = JsonProperty.Access.READ_ONLY)
|
||||
private Long id;
|
||||
@NotBlank
|
||||
@Size(min = 5, max = 50)
|
||||
private String name;
|
||||
|
||||
public Long getId() {
|
||||
return id;
|
||||
}
|
||||
|
||||
public void setId(Long id) {
|
||||
this.id = id;
|
||||
}
|
||||
|
||||
public String getName() {
|
||||
return name;
|
||||
}
|
||||
|
||||
public void setName(String name) {
|
||||
this.name = name;
|
||||
}
|
||||
}
|
@ -0,0 +1,53 @@
|
||||
package com.example.demo.genres.model;
|
||||
|
||||
import java.util.HashSet;
|
||||
import java.util.Objects;
|
||||
import java.util.Set;
|
||||
|
||||
import com.example.demo.books.model.BookEntity;
|
||||
import com.example.demo.core.model.BaseEntity;
|
||||
|
||||
import jakarta.persistence.CascadeType;
|
||||
import jakarta.persistence.Column;
|
||||
import jakarta.persistence.Entity;
|
||||
import jakarta.persistence.OneToMany;
|
||||
import jakarta.persistence.Table;
|
||||
|
||||
@Entity
|
||||
@Table(name = "genres")
|
||||
public class GenreEntity extends BaseEntity {
|
||||
@Column(nullable = false, unique = true, length = 50)
|
||||
private String name;
|
||||
@OneToMany(mappedBy = "genre", cascade = CascadeType.ALL)
|
||||
private Set<BookEntity> books = new HashSet<>();
|
||||
|
||||
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);
|
||||
}
|
||||
}
|
@ -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);
|
||||
}
|
@ -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("Genre 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;
|
||||
}
|
||||
}
|
@ -0,0 +1,126 @@
|
||||
package com.example.demo.users.api;
|
||||
|
||||
import java.util.Map;
|
||||
import org.modelmapper.ModelMapper;
|
||||
import org.springframework.stereotype.Controller;
|
||||
import org.springframework.ui.Model;
|
||||
import org.springframework.validation.BindingResult;
|
||||
import org.springframework.web.bind.annotation.GetMapping;
|
||||
import org.springframework.web.bind.annotation.ModelAttribute;
|
||||
import org.springframework.web.bind.annotation.PathVariable;
|
||||
import org.springframework.web.bind.annotation.PostMapping;
|
||||
import org.springframework.web.bind.annotation.RequestMapping;
|
||||
import org.springframework.web.bind.annotation.RequestParam;
|
||||
import org.springframework.web.servlet.mvc.support.RedirectAttributes;
|
||||
|
||||
import com.example.demo.core.api.PageAttributesMapper;
|
||||
import com.example.demo.core.configuration.Constants;
|
||||
import com.example.demo.users.model.UserEntity;
|
||||
import com.example.demo.users.service.UserService;
|
||||
|
||||
import jakarta.validation.Valid;
|
||||
|
||||
@Controller
|
||||
@RequestMapping(UserController.URL)
|
||||
public class UserController {
|
||||
|
||||
public static final String URL = Constants.ADMIN_PREFIX + "/user";
|
||||
private static final String USER_VIEW = "user";
|
||||
private static final String USER_EDIT_VIEW = "user-edit";
|
||||
private static final String PAGE_ATTRIBUTE = "page";
|
||||
private static final String USER_ATTRIBUTE = "user";
|
||||
|
||||
private final UserService userService;
|
||||
private final ModelMapper modelMapper;
|
||||
|
||||
public UserController(UserService userService, ModelMapper modelMapper) {
|
||||
this.modelMapper = modelMapper;
|
||||
this.userService = userService;
|
||||
}
|
||||
|
||||
private UserEntity toEntity(UserDto dto) {
|
||||
return modelMapper.map(dto, UserEntity.class);
|
||||
}
|
||||
|
||||
private UserDto toDto(UserEntity entity) {
|
||||
return modelMapper.map(entity, UserDto.class);
|
||||
}
|
||||
|
||||
@GetMapping
|
||||
public String getAll(
|
||||
@RequestParam(name = PAGE_ATTRIBUTE, defaultValue = "0") int page,
|
||||
Model model) {
|
||||
final Map<String, Object> attributes = PageAttributesMapper.toAttributes(
|
||||
userService.getAll(page, Constants.DEFUALT_PAGE_SIZE), this::toDto);
|
||||
model.addAllAttributes(attributes);
|
||||
model.addAttribute(PAGE_ATTRIBUTE, page);
|
||||
return USER_VIEW;
|
||||
}
|
||||
|
||||
@GetMapping("/edit/")
|
||||
public String create(@RequestParam(name = PAGE_ATTRIBUTE, defaultValue = "0") int page,
|
||||
Model model) {
|
||||
model.addAttribute(USER_ATTRIBUTE, new UserDto());
|
||||
model.addAttribute(PAGE_ATTRIBUTE, page);
|
||||
return USER_EDIT_VIEW;
|
||||
}
|
||||
|
||||
@PostMapping("/edit/")
|
||||
public String create(
|
||||
@RequestParam(name = PAGE_ATTRIBUTE, defaultValue = "0") int page,
|
||||
@ModelAttribute(name = USER_ATTRIBUTE) @Valid UserDto user,
|
||||
BindingResult bindingResult,
|
||||
Model model,
|
||||
RedirectAttributes redirectAttributes) {
|
||||
if (bindingResult.hasErrors()) {
|
||||
model.addAttribute(PAGE_ATTRIBUTE, page);
|
||||
return USER_EDIT_VIEW;
|
||||
}
|
||||
redirectAttributes.addAttribute(PAGE_ATTRIBUTE, page);
|
||||
userService.create(toEntity(user));
|
||||
return Constants.REDIRECT_VIEW + URL;
|
||||
}
|
||||
|
||||
@GetMapping("/edit/{id}")
|
||||
public String update(
|
||||
@PathVariable(name = "id") Integer id,
|
||||
@RequestParam(name = PAGE_ATTRIBUTE, defaultValue = "0") int page,
|
||||
Model model) {
|
||||
if (id <= 0) {
|
||||
throw new IllegalArgumentException();
|
||||
}
|
||||
model.addAttribute(USER_ATTRIBUTE, toDto(userService.get(id)));
|
||||
model.addAttribute(PAGE_ATTRIBUTE, page);
|
||||
return USER_EDIT_VIEW;
|
||||
}
|
||||
|
||||
@PostMapping("/edit/{id}")
|
||||
public String update(
|
||||
@PathVariable(name = "id") Integer id,
|
||||
@RequestParam(name = PAGE_ATTRIBUTE, defaultValue = "0") int page,
|
||||
@ModelAttribute(name = USER_ATTRIBUTE) @Valid UserDto user,
|
||||
BindingResult bindingResult,
|
||||
Model model,
|
||||
RedirectAttributes redirectAttributes) {
|
||||
if (bindingResult.hasErrors()) {
|
||||
model.addAttribute(PAGE_ATTRIBUTE, page);
|
||||
return USER_EDIT_VIEW;
|
||||
}
|
||||
if (id <= 0) {
|
||||
throw new IllegalArgumentException();
|
||||
}
|
||||
redirectAttributes.addAttribute(PAGE_ATTRIBUTE, page);
|
||||
userService.update(id, toEntity(user));
|
||||
return Constants.REDIRECT_VIEW + URL;
|
||||
}
|
||||
|
||||
@PostMapping("/delete/{id}")
|
||||
public String delete(
|
||||
@PathVariable(name = "id") Integer id,
|
||||
@RequestParam(name = PAGE_ATTRIBUTE, defaultValue = "0") int page,
|
||||
RedirectAttributes redirectAttributes) {
|
||||
redirectAttributes.addAttribute(PAGE_ATTRIBUTE, page);
|
||||
userService.delete(id);
|
||||
return Constants.REDIRECT_VIEW + URL;
|
||||
}
|
||||
}
|
Some files were not shown because too many files have changed in this diff Show More
Loading…
Reference in New Issue
Block a user