diff --git a/lab3/.gitignore b/lab3/.gitignore new file mode 100644 index 0000000..546ecee --- /dev/null +++ b/lab3/.gitignore @@ -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 \ No newline at end of file diff --git a/lab3/.vscode/extensions.json b/lab3/.vscode/extensions.json new file mode 100644 index 0000000..42cf79d --- /dev/null +++ b/lab3/.vscode/extensions.json @@ -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" + ] +} \ No newline at end of file diff --git a/lab3/.vscode/launch.json b/lab3/.vscode/launch.json new file mode 100644 index 0000000..5992c40 --- /dev/null +++ b/lab3/.vscode/launch.json @@ -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" + } + ] +} \ No newline at end of file diff --git a/lab3/.vscode/settings.json b/lab3/.vscode/settings.json new file mode 100644 index 0000000..eab3db6 --- /dev/null +++ b/lab3/.vscode/settings.json @@ -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, +} \ No newline at end of file diff --git a/lab3/build.gradle b/lab3/build.gradle new file mode 100644 index 0000000..f2ab11e --- /dev/null +++ b/lab3/build.gradle @@ -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() +} \ No newline at end of file diff --git a/lab3/gradle/wrapper/gradle-wrapper.jar b/lab3/gradle/wrapper/gradle-wrapper.jar new file mode 100644 index 0000000..d64cd49 Binary files /dev/null and b/lab3/gradle/wrapper/gradle-wrapper.jar differ diff --git a/lab3/gradle/wrapper/gradle-wrapper.properties b/lab3/gradle/wrapper/gradle-wrapper.properties new file mode 100644 index 0000000..1af9e09 --- /dev/null +++ b/lab3/gradle/wrapper/gradle-wrapper.properties @@ -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 diff --git a/lab3/gradlew b/lab3/gradlew new file mode 100644 index 0000000..1aa94a4 --- /dev/null +++ b/lab3/gradlew @@ -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" "$@" diff --git a/lab3/gradlew.bat b/lab3/gradlew.bat new file mode 100644 index 0000000..93e3f59 --- /dev/null +++ b/lab3/gradlew.bat @@ -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 diff --git a/lab3/readme.md b/lab3/readme.md new file mode 100644 index 0000000..8eef312 --- /dev/null +++ b/lab3/readme.md @@ -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/ diff --git a/lab3/settings.gradle b/lab3/settings.gradle new file mode 100644 index 0000000..0a383dd --- /dev/null +++ b/lab3/settings.gradle @@ -0,0 +1 @@ +rootProject.name = 'demo' diff --git a/lab3/src/main/java/com/example/demo/DemoApplication.java b/lab3/src/main/java/com/example/demo/DemoApplication.java new file mode 100644 index 0000000..71ead95 --- /dev/null +++ b/lab3/src/main/java/com/example/demo/DemoApplication.java @@ -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)); + } + } +} diff --git a/lab3/src/main/java/com/example/demo/authors/api/AuthorController.java b/lab3/src/main/java/com/example/demo/authors/api/AuthorController.java new file mode 100644 index 0000000..1d2b8d9 --- /dev/null +++ b/lab3/src/main/java/com/example/demo/authors/api/AuthorController.java @@ -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 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)); + } +} diff --git a/lab3/src/main/java/com/example/demo/authors/api/AuthorDto.java b/lab3/src/main/java/com/example/demo/authors/api/AuthorDto.java new file mode 100644 index 0000000..4719dd7 --- /dev/null +++ b/lab3/src/main/java/com/example/demo/authors/api/AuthorDto.java @@ -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; + } +} diff --git a/lab3/src/main/java/com/example/demo/authors/model/AuthorEntity.java b/lab3/src/main/java/com/example/demo/authors/model/AuthorEntity.java new file mode 100644 index 0000000..c6bc30d --- /dev/null +++ b/lab3/src/main/java/com/example/demo/authors/model/AuthorEntity.java @@ -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 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); + } +} diff --git a/lab3/src/main/java/com/example/demo/authors/repository/AuthorRepository.java b/lab3/src/main/java/com/example/demo/authors/repository/AuthorRepository.java new file mode 100644 index 0000000..7243ec4 --- /dev/null +++ b/lab3/src/main/java/com/example/demo/authors/repository/AuthorRepository.java @@ -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 { + Optional findByNameIgnoreCase(String name); +} diff --git a/lab3/src/main/java/com/example/demo/authors/service/AuthorService.java b/lab3/src/main/java/com/example/demo/authors/service/AuthorService.java new file mode 100644 index 0000000..cc3ff40 --- /dev/null +++ b/lab3/src/main/java/com/example/demo/authors/service/AuthorService.java @@ -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 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; + } +} diff --git a/lab3/src/main/java/com/example/demo/books/api/BookController.java b/lab3/src/main/java/com/example/demo/books/api/BookController.java new file mode 100644 index 0000000..48360ad --- /dev/null +++ b/lab3/src/main/java/com/example/demo/books/api/BookController.java @@ -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 getAll(@RequestParam(name = "genreId", defaultValue = + // "0") Long genreId) { + // return bookService.getAll(genreId).stream().map(this::toDto).toList(); + // } + + @GetMapping + public PageDto 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)); + } +} diff --git a/lab3/src/main/java/com/example/demo/books/api/BookDto.java b/lab3/src/main/java/com/example/demo/books/api/BookDto.java new file mode 100644 index 0000000..8aac185 --- /dev/null +++ b/lab3/src/main/java/com/example/demo/books/api/BookDto.java @@ -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; + } +} diff --git a/lab3/src/main/java/com/example/demo/books/model/BookEntity.java b/lab3/src/main/java/com/example/demo/books/model/BookEntity.java new file mode 100644 index 0000000..6ca6e8d --- /dev/null +++ b/lab3/src/main/java/com/example/demo/books/model/BookEntity.java @@ -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); + } +} diff --git a/lab3/src/main/java/com/example/demo/books/repository/BookRepository.java b/lab3/src/main/java/com/example/demo/books/repository/BookRepository.java new file mode 100644 index 0000000..1d53910 --- /dev/null +++ b/lab3/src/main/java/com/example/demo/books/repository/BookRepository.java @@ -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, PagingAndSortingRepository { + Optional findByNameIgnoreCase(String name); + + List findByGenreId(Long genreId); + + Page findByGenreId(Long genreId, PageRequest pageable); + + List findByAuthorId(Long authorId); + + Page findByAuthorId(Long authorId, PageRequest pageable); + + List findByGenreIdAndAuthorId(Long genreId, Long authorId); + + Page findByGenreIdAndAuthorId(Long genreId, Long authorId, PageRequest pageable); +} diff --git a/lab3/src/main/java/com/example/demo/books/service/BookService.java b/lab3/src/main/java/com/example/demo/books/service/BookService.java new file mode 100644 index 0000000..826d5cb --- /dev/null +++ b/lab3/src/main/java/com/example/demo/books/service/BookService.java @@ -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 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 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; + } +} diff --git a/lab3/src/main/java/com/example/demo/core/api/PageDto.java b/lab3/src/main/java/com/example/demo/core/api/PageDto.java new file mode 100644 index 0000000..4cae429 --- /dev/null +++ b/lab3/src/main/java/com/example/demo/core/api/PageDto.java @@ -0,0 +1,97 @@ +package com.example.demo.core.api; + +import java.util.ArrayList; +import java.util.List; + +public class PageDto { + private List 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 getItems() { + return items; + } + + public void setItems(List 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; + } +} diff --git a/lab3/src/main/java/com/example/demo/core/api/PageDtoMapper.java b/lab3/src/main/java/com/example/demo/core/api/PageDtoMapper.java new file mode 100644 index 0000000..e8d3dd0 --- /dev/null +++ b/lab3/src/main/java/com/example/demo/core/api/PageDtoMapper.java @@ -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 PageDto toDto(Page page, Function mapper) { + final PageDto 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; + } +} diff --git a/lab3/src/main/java/com/example/demo/core/configuration/Constants.java b/lab3/src/main/java/com/example/demo/core/configuration/Constants.java new file mode 100644 index 0000000..4bd6a8d --- /dev/null +++ b/lab3/src/main/java/com/example/demo/core/configuration/Constants.java @@ -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() { + } +} diff --git a/lab3/src/main/java/com/example/demo/core/configuration/MapperConfiguration.java b/lab3/src/main/java/com/example/demo/core/configuration/MapperConfiguration.java new file mode 100644 index 0000000..a5ad6f3 --- /dev/null +++ b/lab3/src/main/java/com/example/demo/core/configuration/MapperConfiguration.java @@ -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(); + } +} diff --git a/lab3/src/main/java/com/example/demo/core/configuration/WebConfiguration.java b/lab3/src/main/java/com/example/demo/core/configuration/WebConfiguration.java new file mode 100644 index 0000000..762e85a --- /dev/null +++ b/lab3/src/main/java/com/example/demo/core/configuration/WebConfiguration.java @@ -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"); + } +} diff --git a/lab3/src/main/java/com/example/demo/core/error/AdviceController.java b/lab3/src/main/java/com/example/demo/core/error/AdviceController.java new file mode 100644 index 0000000..9aa33cc --- /dev/null +++ b/lab3/src/main/java/com/example/demo/core/error/AdviceController.java @@ -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 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 handleNotFoundException(Throwable throwable) { + return handleException(throwable, HttpStatus.NOT_FOUND); + } + + @ExceptionHandler(MethodArgumentNotValidException.class) + @ResponseStatus(HttpStatus.BAD_REQUEST) + public ResponseEntity handleDataIntegrityViolationException(Throwable throwable) { + return handleException(throwable, HttpStatus.BAD_REQUEST); + } + + @ExceptionHandler(Exception.class) + @ResponseStatus(HttpStatus.INTERNAL_SERVER_ERROR) + public ResponseEntity handleAnyException(Throwable throwable) { + return handleException(throwable, HttpStatus.INTERNAL_SERVER_ERROR); + } +} diff --git a/lab3/src/main/java/com/example/demo/core/error/ErrorCauseDto.java b/lab3/src/main/java/com/example/demo/core/error/ErrorCauseDto.java new file mode 100644 index 0000000..602ce70 --- /dev/null +++ b/lab3/src/main/java/com/example/demo/core/error/ErrorCauseDto.java @@ -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; + } +} diff --git a/lab3/src/main/java/com/example/demo/core/error/ErrorDto.java b/lab3/src/main/java/com/example/demo/core/error/ErrorDto.java new file mode 100644 index 0000000..457975c --- /dev/null +++ b/lab3/src/main/java/com/example/demo/core/error/ErrorDto.java @@ -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; + } + +} diff --git a/lab3/src/main/java/com/example/demo/core/error/NotFoundException.java b/lab3/src/main/java/com/example/demo/core/error/NotFoundException.java new file mode 100644 index 0000000..a61d118 --- /dev/null +++ b/lab3/src/main/java/com/example/demo/core/error/NotFoundException.java @@ -0,0 +1,7 @@ +package com.example.demo.core.error; + +public class NotFoundException extends RuntimeException { + public NotFoundException(Class clazz, Long id) { + super(String.format("%s with id [%s] is not found or not exists", clazz.getSimpleName(), id)); + } +} diff --git a/lab3/src/main/java/com/example/demo/core/model/BaseEntity.java b/lab3/src/main/java/com/example/demo/core/model/BaseEntity.java new file mode 100644 index 0000000..eba74ad --- /dev/null +++ b/lab3/src/main/java/com/example/demo/core/model/BaseEntity.java @@ -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; + } +} diff --git a/lab3/src/main/java/com/example/demo/favorites/api/FavoriteController.java b/lab3/src/main/java/com/example/demo/favorites/api/FavoriteController.java new file mode 100644 index 0000000..4fa52d3 --- /dev/null +++ b/lab3/src/main/java/com/example/demo/favorites/api/FavoriteController.java @@ -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 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)); + } +} diff --git a/lab3/src/main/java/com/example/demo/favorites/api/FavoriteDto.java b/lab3/src/main/java/com/example/demo/favorites/api/FavoriteDto.java new file mode 100644 index 0000000..f798428 --- /dev/null +++ b/lab3/src/main/java/com/example/demo/favorites/api/FavoriteDto.java @@ -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; + } +} diff --git a/lab3/src/main/java/com/example/demo/favorites/model/FavoriteEntity.java b/lab3/src/main/java/com/example/demo/favorites/model/FavoriteEntity.java new file mode 100644 index 0000000..6044564 --- /dev/null +++ b/lab3/src/main/java/com/example/demo/favorites/model/FavoriteEntity.java @@ -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); + } +} diff --git a/lab3/src/main/java/com/example/demo/favorites/repository/FavoriteRepository.java b/lab3/src/main/java/com/example/demo/favorites/repository/FavoriteRepository.java new file mode 100644 index 0000000..86c07f1 --- /dev/null +++ b/lab3/src/main/java/com/example/demo/favorites/repository/FavoriteRepository.java @@ -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 { + List findByUserId(Long userId); + + Optional findOneByUserIdAndId(Long userId, Long id); +} diff --git a/lab3/src/main/java/com/example/demo/favorites/service/FavoriteService.java b/lab3/src/main/java/com/example/demo/favorites/service/FavoriteService.java new file mode 100644 index 0000000..b23721b --- /dev/null +++ b/lab3/src/main/java/com/example/demo/favorites/service/FavoriteService.java @@ -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 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; + } +} diff --git a/lab3/src/main/java/com/example/demo/genres/api/GenreController.java b/lab3/src/main/java/com/example/demo/genres/api/GenreController.java new file mode 100644 index 0000000..3d483b1 --- /dev/null +++ b/lab3/src/main/java/com/example/demo/genres/api/GenreController.java @@ -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 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)); + } +} diff --git a/lab3/src/main/java/com/example/demo/genres/api/GenreDto.java b/lab3/src/main/java/com/example/demo/genres/api/GenreDto.java new file mode 100644 index 0000000..6598b12 --- /dev/null +++ b/lab3/src/main/java/com/example/demo/genres/api/GenreDto.java @@ -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; + } +} diff --git a/lab3/src/main/java/com/example/demo/genres/model/GenreEntity.java b/lab3/src/main/java/com/example/demo/genres/model/GenreEntity.java new file mode 100644 index 0000000..4998665 --- /dev/null +++ b/lab3/src/main/java/com/example/demo/genres/model/GenreEntity.java @@ -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 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); + } +} diff --git a/lab3/src/main/java/com/example/demo/genres/repository/GenreRepository.java b/lab3/src/main/java/com/example/demo/genres/repository/GenreRepository.java new file mode 100644 index 0000000..13d6932 --- /dev/null +++ b/lab3/src/main/java/com/example/demo/genres/repository/GenreRepository.java @@ -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 { + Optional findByNameIgnoreCase(String name); +} diff --git a/lab3/src/main/java/com/example/demo/genres/service/GenreService.java b/lab3/src/main/java/com/example/demo/genres/service/GenreService.java new file mode 100644 index 0000000..57358b0 --- /dev/null +++ b/lab3/src/main/java/com/example/demo/genres/service/GenreService.java @@ -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 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; + } +} diff --git a/lab3/src/main/java/com/example/demo/users/api/UserController.java b/lab3/src/main/java/com/example/demo/users/api/UserController.java new file mode 100644 index 0000000..f31a352 --- /dev/null +++ b/lab3/src/main/java/com/example/demo/users/api/UserController.java @@ -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 getAll() { + // return userService.getAll().stream().map(this::toDto).toList(); + // } + + @GetMapping + public PageDto 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)); + } +} diff --git a/lab3/src/main/java/com/example/demo/users/api/UserDto.java b/lab3/src/main/java/com/example/demo/users/api/UserDto.java new file mode 100644 index 0000000..17c7b6b --- /dev/null +++ b/lab3/src/main/java/com/example/demo/users/api/UserDto.java @@ -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; + } +} diff --git a/lab3/src/main/java/com/example/demo/users/model/UserEntity.java b/lab3/src/main/java/com/example/demo/users/model/UserEntity.java new file mode 100644 index 0000000..ec2e575 --- /dev/null +++ b/lab3/src/main/java/com/example/demo/users/model/UserEntity.java @@ -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); + } +} diff --git a/lab3/src/main/java/com/example/demo/users/repository/UserRepository.java b/lab3/src/main/java/com/example/demo/users/repository/UserRepository.java new file mode 100644 index 0000000..d7ad406 --- /dev/null +++ b/lab3/src/main/java/com/example/demo/users/repository/UserRepository.java @@ -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, PagingAndSortingRepository { + Optional findByUsernameIgnoreCase(String username); +} diff --git a/lab3/src/main/java/com/example/demo/users/service/UserService.java b/lab3/src/main/java/com/example/demo/users/service/UserService.java new file mode 100644 index 0000000..7ebb872 --- /dev/null +++ b/lab3/src/main/java/com/example/demo/users/service/UserService.java @@ -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 getAll() { + return StreamSupport.stream(repository.findAll().spliterator(), false).toList(); + } + + @Transactional(readOnly = true) + public Page 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; + } + +} \ No newline at end of file diff --git a/lab3/src/main/resources/application.properties b/lab3/src/main/resources/application.properties new file mode 100644 index 0000000..62ab433 --- /dev/null +++ b/lab3/src/main/resources/application.properties @@ -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 \ No newline at end of file diff --git a/lab3/src/test/java/com/example/demo/AuthorServiceTests.java b/lab3/src/test/java/com/example/demo/AuthorServiceTests.java new file mode 100644 index 0000000..da8e92b --- /dev/null +++ b/lab3/src/test/java/com/example/demo/AuthorServiceTests.java @@ -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()); + } +} diff --git a/lab3/src/test/java/com/example/demo/BookServiceTests.java b/lab3/src/test/java/com/example/demo/BookServiceTests.java new file mode 100644 index 0000000..e521839 --- /dev/null +++ b/lab3/src/test/java/com/example/demo/BookServiceTests.java @@ -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 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 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 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()); + } +} diff --git a/lab3/src/test/java/com/example/demo/FavoriteServiceTests.java b/lab3/src/test/java/com/example/demo/FavoriteServiceTests.java new file mode 100644 index 0000000..82de3e3 --- /dev/null +++ b/lab3/src/test/java/com/example/demo/FavoriteServiceTests.java @@ -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()); + } +} diff --git a/lab3/src/test/java/com/example/demo/GenreServiceTests.java b/lab3/src/test/java/com/example/demo/GenreServiceTests.java new file mode 100644 index 0000000..7d5dba5 --- /dev/null +++ b/lab3/src/test/java/com/example/demo/GenreServiceTests.java @@ -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()); + } +} diff --git a/lab3/src/test/java/com/example/demo/UserServiceTests.java b/lab3/src/test/java/com/example/demo/UserServiceTests.java new file mode 100644 index 0000000..813ed7f --- /dev/null +++ b/lab3/src/test/java/com/example/demo/UserServiceTests.java @@ -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()); + } +} diff --git a/lab3/src/test/resources/application.properties b/lab3/src/test/resources/application.properties new file mode 100644 index 0000000..d5f355c --- /dev/null +++ b/lab3/src/test/resources/application.properties @@ -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 \ No newline at end of file diff --git a/lab45/.gitignore b/lab45/.gitignore new file mode 100644 index 0000000..546ecee --- /dev/null +++ b/lab45/.gitignore @@ -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 \ No newline at end of file diff --git a/lab45/.vscode/extensions.json b/lab45/.vscode/extensions.json new file mode 100644 index 0000000..42cf79d --- /dev/null +++ b/lab45/.vscode/extensions.json @@ -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" + ] +} \ No newline at end of file diff --git a/lab45/.vscode/launch.json b/lab45/.vscode/launch.json new file mode 100644 index 0000000..e33f790 --- /dev/null +++ b/lab45/.vscode/launch.json @@ -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" + } + ] +} \ No newline at end of file diff --git a/lab45/.vscode/settings.json b/lab45/.vscode/settings.json new file mode 100644 index 0000000..95915c9 --- /dev/null +++ b/lab45/.vscode/settings.json @@ -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" + ], +} \ No newline at end of file diff --git a/lab45/build.gradle b/lab45/build.gradle new file mode 100644 index 0000000..138fe43 --- /dev/null +++ b/lab45/build.gradle @@ -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() +} diff --git a/lab45/gradle/wrapper/gradle-wrapper.jar b/lab45/gradle/wrapper/gradle-wrapper.jar new file mode 100644 index 0000000..d64cd49 Binary files /dev/null and b/lab45/gradle/wrapper/gradle-wrapper.jar differ diff --git a/lab45/gradle/wrapper/gradle-wrapper.properties b/lab45/gradle/wrapper/gradle-wrapper.properties new file mode 100644 index 0000000..1af9e09 --- /dev/null +++ b/lab45/gradle/wrapper/gradle-wrapper.properties @@ -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 diff --git a/lab45/gradlew b/lab45/gradlew new file mode 100644 index 0000000..1aa94a4 --- /dev/null +++ b/lab45/gradlew @@ -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" "$@" diff --git a/lab45/gradlew.bat b/lab45/gradlew.bat new file mode 100644 index 0000000..93e3f59 --- /dev/null +++ b/lab45/gradlew.bat @@ -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 diff --git a/lab45/readme.md b/lab45/readme.md new file mode 100644 index 0000000..ac4a1d0 --- /dev/null +++ b/lab45/readme.md @@ -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/ diff --git a/lab45/settings.gradle b/lab45/settings.gradle new file mode 100644 index 0000000..0a383dd --- /dev/null +++ b/lab45/settings.gradle @@ -0,0 +1 @@ +rootProject.name = 'demo' diff --git a/lab45/src/main/java/com/example/demo/DemoApplication.java b/lab45/src/main/java/com/example/demo/DemoApplication.java new file mode 100644 index 0000000..8bfda88 --- /dev/null +++ b/lab45/src/main/java/com/example/demo/DemoApplication.java @@ -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())); + } + } +} diff --git a/lab45/src/main/java/com/example/demo/authors/api/AuthorController.java b/lab45/src/main/java/com/example/demo/authors/api/AuthorController.java new file mode 100644 index 0000000..58a418f --- /dev/null +++ b/lab45/src/main/java/com/example/demo/authors/api/AuthorController.java @@ -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; + } +} diff --git a/lab45/src/main/java/com/example/demo/authors/api/AuthorDto.java b/lab45/src/main/java/com/example/demo/authors/api/AuthorDto.java new file mode 100644 index 0000000..4719dd7 --- /dev/null +++ b/lab45/src/main/java/com/example/demo/authors/api/AuthorDto.java @@ -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; + } +} diff --git a/lab45/src/main/java/com/example/demo/authors/model/AuthorEntity.java b/lab45/src/main/java/com/example/demo/authors/model/AuthorEntity.java new file mode 100644 index 0000000..c6bc30d --- /dev/null +++ b/lab45/src/main/java/com/example/demo/authors/model/AuthorEntity.java @@ -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 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); + } +} diff --git a/lab45/src/main/java/com/example/demo/authors/repository/AuthorRepository.java b/lab45/src/main/java/com/example/demo/authors/repository/AuthorRepository.java new file mode 100644 index 0000000..7243ec4 --- /dev/null +++ b/lab45/src/main/java/com/example/demo/authors/repository/AuthorRepository.java @@ -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 { + Optional findByNameIgnoreCase(String name); +} diff --git a/lab45/src/main/java/com/example/demo/authors/service/AuthorService.java b/lab45/src/main/java/com/example/demo/authors/service/AuthorService.java new file mode 100644 index 0000000..cc3ff40 --- /dev/null +++ b/lab45/src/main/java/com/example/demo/authors/service/AuthorService.java @@ -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 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; + } +} diff --git a/lab45/src/main/java/com/example/demo/books/api/BookController.java b/lab45/src/main/java/com/example/demo/books/api/BookController.java new file mode 100644 index 0000000..c95ed69 --- /dev/null +++ b/lab45/src/main/java/com/example/demo/books/api/BookController.java @@ -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 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 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; + } +} diff --git a/lab45/src/main/java/com/example/demo/books/api/BookDto.java b/lab45/src/main/java/com/example/demo/books/api/BookDto.java new file mode 100644 index 0000000..49f71e4 --- /dev/null +++ b/lab45/src/main/java/com/example/demo/books/api/BookDto.java @@ -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; + } +} diff --git a/lab45/src/main/java/com/example/demo/books/api/CatalogController.java b/lab45/src/main/java/com/example/demo/books/api/CatalogController.java new file mode 100644 index 0000000..02351ba --- /dev/null +++ b/lab45/src/main/java/com/example/demo/books/api/CatalogController.java @@ -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 allBooks = bookService.getAllBooks().stream().map(this::toDto).collect(Collectors.toList()); + Collections.shuffle(allBooks); + List 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; + } +} diff --git a/lab45/src/main/java/com/example/demo/books/model/BookEntity.java b/lab45/src/main/java/com/example/demo/books/model/BookEntity.java new file mode 100644 index 0000000..e706c19 --- /dev/null +++ b/lab45/src/main/java/com/example/demo/books/model/BookEntity.java @@ -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); + } +} diff --git a/lab45/src/main/java/com/example/demo/books/repository/BookRepository.java b/lab45/src/main/java/com/example/demo/books/repository/BookRepository.java new file mode 100644 index 0000000..7c9fc94 --- /dev/null +++ b/lab45/src/main/java/com/example/demo/books/repository/BookRepository.java @@ -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, PagingAndSortingRepository { + Optional findByNameIgnoreCase(String name); + + List findByGenreId(Long genreId); + + Page findByGenreId(Long genreId, Pageable pageable); + + List findByAuthorId(Long authorId); + + Page findByAuthorId(Long authorId, Pageable pageable); + + List findByGenreIdAndAuthorId(Long genreId, Long authorId); + + Page findByGenreIdAndAuthorId(Long genreId, Long authorId, Pageable pageable); +} diff --git a/lab45/src/main/java/com/example/demo/books/service/BookService.java b/lab45/src/main/java/com/example/demo/books/service/BookService.java new file mode 100644 index 0000000..328df53 --- /dev/null +++ b/lab45/src/main/java/com/example/demo/books/service/BookService.java @@ -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 getAllBooks() { + return StreamSupport.stream(repository.findAll().spliterator(), false).toList(); + } + + @Transactional(readOnly = true) + public Page getAllBooks(int page, int size) { + return repository.findAll(PageRequest.of(page, size, Sort.by("id"))); + } + + @Transactional(readOnly = true) + public List 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 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; + } +} diff --git a/lab45/src/main/java/com/example/demo/core/api/GlobalController.java b/lab45/src/main/java/com/example/demo/core/api/GlobalController.java new file mode 100644 index 0000000..da1dc82 --- /dev/null +++ b/lab45/src/main/java/com/example/demo/core/api/GlobalController.java @@ -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(); + // } +} diff --git a/lab45/src/main/java/com/example/demo/core/api/PageAttributesMapper.java b/lab45/src/main/java/com/example/demo/core/api/PageAttributesMapper.java new file mode 100644 index 0000000..74ee38d --- /dev/null +++ b/lab45/src/main/java/com/example/demo/core/api/PageAttributesMapper.java @@ -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 Map toAttributes(Page page, Function mapper) { + return Map.of( + "items", page.getContent().stream().map(mapper::apply).toList(), + "currentPage", page.getNumber(), + "totalPages", page.getTotalPages()); + } +} diff --git a/lab45/src/main/java/com/example/demo/core/configuration/Constants.java b/lab45/src/main/java/com/example/demo/core/configuration/Constants.java new file mode 100644 index 0000000..0bf6e30 --- /dev/null +++ b/lab45/src/main/java/com/example/demo/core/configuration/Constants.java @@ -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() { + } +} diff --git a/lab45/src/main/java/com/example/demo/core/configuration/MapperConfiguration.java b/lab45/src/main/java/com/example/demo/core/configuration/MapperConfiguration.java new file mode 100644 index 0000000..44defae --- /dev/null +++ b/lab45/src/main/java/com/example/demo/core/configuration/MapperConfiguration.java @@ -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() { + @Override + protected void configure() { + skip(destination.getId()); + } + }); + return mapper; + } +} diff --git a/lab45/src/main/java/com/example/demo/core/configuration/WebConfiguration.java b/lab45/src/main/java/com/example/demo/core/configuration/WebConfiguration.java new file mode 100644 index 0000000..7863ed5 --- /dev/null +++ b/lab45/src/main/java/com/example/demo/core/configuration/WebConfiguration.java @@ -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"); + } +} diff --git a/lab45/src/main/java/com/example/demo/core/error/AdviceController.java b/lab45/src/main/java/com/example/demo/core/error/AdviceController.java new file mode 100644 index 0000000..65f0c3e --- /dev/null +++ b/lab45/src/main/java/com/example/demo/core/error/AdviceController.java @@ -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 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; + } +} diff --git a/lab45/src/main/java/com/example/demo/core/error/NotFoundException.java b/lab45/src/main/java/com/example/demo/core/error/NotFoundException.java new file mode 100644 index 0000000..a61d118 --- /dev/null +++ b/lab45/src/main/java/com/example/demo/core/error/NotFoundException.java @@ -0,0 +1,7 @@ +package com.example.demo.core.error; + +public class NotFoundException extends RuntimeException { + public NotFoundException(Class clazz, Long id) { + super(String.format("%s with id [%s] is not found or not exists", clazz.getSimpleName(), id)); + } +} diff --git a/lab45/src/main/java/com/example/demo/core/model/BaseEntity.java b/lab45/src/main/java/com/example/demo/core/model/BaseEntity.java new file mode 100644 index 0000000..eba74ad --- /dev/null +++ b/lab45/src/main/java/com/example/demo/core/model/BaseEntity.java @@ -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; + } +} diff --git a/lab45/src/main/java/com/example/demo/core/security/SecurityConfiguration.java b/lab45/src/main/java/com/example/demo/core/security/SecurityConfiguration.java new file mode 100644 index 0000000..6b375a3 --- /dev/null +++ b/lab45/src/main/java/com/example/demo/core/security/SecurityConfiguration.java @@ -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(); + } +} diff --git a/lab45/src/main/java/com/example/demo/core/security/UserPrincipal.java b/lab45/src/main/java/com/example/demo/core/security/UserPrincipal.java new file mode 100644 index 0000000..ce646c6 --- /dev/null +++ b/lab45/src/main/java/com/example/demo/core/security/UserPrincipal.java @@ -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 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 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(); + } +} diff --git a/lab45/src/main/java/com/example/demo/core/session/SessionCart.java b/lab45/src/main/java/com/example/demo/core/session/SessionCart.java new file mode 100644 index 0000000..02e4a17 --- /dev/null +++ b/lab45/src/main/java/com/example/demo/core/session/SessionCart.java @@ -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 { +// public double getSum() { +// return this.values().stream() +// .map(item -> item.getCount() * item.getPrice()) +// .mapToDouble(Double::doubleValue) +// .sum(); +// } +// } diff --git a/lab45/src/main/java/com/example/demo/core/session/SessionHelper.java b/lab45/src/main/java/com/example/demo/core/session/SessionHelper.java new file mode 100644 index 0000000..831b13c --- /dev/null +++ b/lab45/src/main/java/com/example/demo/core/session/SessionHelper.java @@ -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(); +// } +// } diff --git a/lab45/src/main/java/com/example/demo/favorites/api/FavoriteController.java b/lab45/src/main/java/com/example/demo/favorites/api/FavoriteController.java new file mode 100644 index 0000000..00232fd --- /dev/null +++ b/lab45/src/main/java/com/example/demo/favorites/api/FavoriteController.java @@ -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 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; + } +} diff --git a/lab45/src/main/java/com/example/demo/favorites/api/FavoriteDto.java b/lab45/src/main/java/com/example/demo/favorites/api/FavoriteDto.java new file mode 100644 index 0000000..f798428 --- /dev/null +++ b/lab45/src/main/java/com/example/demo/favorites/api/FavoriteDto.java @@ -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; + } +} diff --git a/lab45/src/main/java/com/example/demo/favorites/model/FavoriteEntity.java b/lab45/src/main/java/com/example/demo/favorites/model/FavoriteEntity.java new file mode 100644 index 0000000..24f035a --- /dev/null +++ b/lab45/src/main/java/com/example/demo/favorites/model/FavoriteEntity.java @@ -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); + } +} diff --git a/lab45/src/main/java/com/example/demo/favorites/repository/FavoriteRepository.java b/lab45/src/main/java/com/example/demo/favorites/repository/FavoriteRepository.java new file mode 100644 index 0000000..deb9dae --- /dev/null +++ b/lab45/src/main/java/com/example/demo/favorites/repository/FavoriteRepository.java @@ -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, + PagingAndSortingRepository { + List findByUserId(Long userId); + + List findByUserId(long userId); + + Page findByUserId(long userId, Pageable pageable); + + List findByUserIdAndBookId(long userId, long bookId); + + Optional findOneByUserIdAndId(long userId, long bookId); +} diff --git a/lab45/src/main/java/com/example/demo/favorites/service/FavoriteService.java b/lab45/src/main/java/com/example/demo/favorites/service/FavoriteService.java new file mode 100644 index 0000000..b744085 --- /dev/null +++ b/lab45/src/main/java/com/example/demo/favorites/service/FavoriteService.java @@ -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 getAll(Long userId) { + if (userId == 0) { + return StreamSupport.stream(repository.findAll().spliterator(), false).toList(); + } + return repository.findByUserId(userId); + } + + @Transactional(readOnly = true) + public Page 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; + } +} diff --git a/lab45/src/main/java/com/example/demo/genres/api/GenreController.java b/lab45/src/main/java/com/example/demo/genres/api/GenreController.java new file mode 100644 index 0000000..9b079a2 --- /dev/null +++ b/lab45/src/main/java/com/example/demo/genres/api/GenreController.java @@ -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; + } +} diff --git a/lab45/src/main/java/com/example/demo/genres/api/GenreDto.java b/lab45/src/main/java/com/example/demo/genres/api/GenreDto.java new file mode 100644 index 0000000..6598b12 --- /dev/null +++ b/lab45/src/main/java/com/example/demo/genres/api/GenreDto.java @@ -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; + } +} diff --git a/lab45/src/main/java/com/example/demo/genres/model/GenreEntity.java b/lab45/src/main/java/com/example/demo/genres/model/GenreEntity.java new file mode 100644 index 0000000..4998665 --- /dev/null +++ b/lab45/src/main/java/com/example/demo/genres/model/GenreEntity.java @@ -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 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); + } +} diff --git a/lab45/src/main/java/com/example/demo/genres/repository/GenreRepository.java b/lab45/src/main/java/com/example/demo/genres/repository/GenreRepository.java new file mode 100644 index 0000000..13d6932 --- /dev/null +++ b/lab45/src/main/java/com/example/demo/genres/repository/GenreRepository.java @@ -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 { + Optional findByNameIgnoreCase(String name); +} diff --git a/lab45/src/main/java/com/example/demo/genres/service/GenreService.java b/lab45/src/main/java/com/example/demo/genres/service/GenreService.java new file mode 100644 index 0000000..57358b0 --- /dev/null +++ b/lab45/src/main/java/com/example/demo/genres/service/GenreService.java @@ -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 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; + } +} diff --git a/lab45/src/main/java/com/example/demo/users/api/UserController.java b/lab45/src/main/java/com/example/demo/users/api/UserController.java new file mode 100644 index 0000000..578ff0d --- /dev/null +++ b/lab45/src/main/java/com/example/demo/users/api/UserController.java @@ -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 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; + } +} diff --git a/lab45/src/main/java/com/example/demo/users/api/UserDto.java b/lab45/src/main/java/com/example/demo/users/api/UserDto.java new file mode 100644 index 0000000..7904847 --- /dev/null +++ b/lab45/src/main/java/com/example/demo/users/api/UserDto.java @@ -0,0 +1,36 @@ +package com.example.demo.users.api; + +import jakarta.validation.constraints.NotBlank; +import jakarta.validation.constraints.Size; + +public class UserDto { + private Long id; + @NotBlank + @Size(min = 3, max = 20) + private String login; + private String role; + + public Long getId() { + return id; + } + + public void setId(Long id) { + this.id = id; + } + + public String getLogin() { + return login; + } + + public void setLogin(String login) { + this.login = login; + } + + public String getRole() { + return role; + } + + public void setRole(String role) { + this.role = role; + } +} diff --git a/lab45/src/main/java/com/example/demo/users/api/UserSignupController.java b/lab45/src/main/java/com/example/demo/users/api/UserSignupController.java new file mode 100644 index 0000000..c092739 --- /dev/null +++ b/lab45/src/main/java/com/example/demo/users/api/UserSignupController.java @@ -0,0 +1,66 @@ +package com.example.demo.users.api; + +import java.util.Objects; + +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.PostMapping; +import org.springframework.web.bind.annotation.RequestMapping; + +import com.example.demo.core.configuration.Constants; +import com.example.demo.users.model.UserEntity; +import com.example.demo.users.model.UserRole; +import com.example.demo.users.service.UserService; + +import jakarta.validation.Valid; + +@Controller +@RequestMapping(UserSignupController.URL) +public class UserSignupController { + public static final String URL = "/signup"; + + private static final String SIGNUP_VIEW = "signup"; + private static final String USER_ATTRIBUTE = "user"; + + private final UserService userService; + + public UserSignupController( + UserService userService) { + this.userService = userService; + } + + private UserEntity toEntity(UserSignupDto dto) { + final UserEntity entity = new UserEntity(); + entity.setLogin(dto.getLogin()); + entity.setPassword(dto.getPassword()); + entity.setRole(dto.getIsAdmin() ? UserRole.ADMIN : UserRole.USER); + return entity; + } + + @GetMapping + public String getSignup(Model model) { + model.addAttribute(USER_ATTRIBUTE, new UserSignupDto()); + return SIGNUP_VIEW; + } + + @PostMapping + public String signup( + @ModelAttribute(name = USER_ATTRIBUTE) @Valid UserSignupDto user, + BindingResult bindingResult, + Model model) { + if (bindingResult.hasErrors()) { + return SIGNUP_VIEW; + } + if (!Objects.equals(user.getPassword(), user.getPasswordConfirm())) { + bindingResult.rejectValue("password", "signup:passwords", "Пароли не совпадают."); + model.addAttribute(USER_ATTRIBUTE, user); + return SIGNUP_VIEW; + } + userService.create(toEntity(user)); + return Constants.REDIRECT_VIEW + Constants.LOGIN_URL + "?signup"; + } + +} diff --git a/lab45/src/main/java/com/example/demo/users/api/UserSignupDto.java b/lab45/src/main/java/com/example/demo/users/api/UserSignupDto.java new file mode 100644 index 0000000..d593aaa --- /dev/null +++ b/lab45/src/main/java/com/example/demo/users/api/UserSignupDto.java @@ -0,0 +1,50 @@ +package com.example.demo.users.api; + +import jakarta.validation.constraints.NotBlank; +import jakarta.validation.constraints.Size; + +public class UserSignupDto { + @NotBlank + @Size(min = 3, max = 20) + private String login; + @NotBlank + @Size(min = 3, max = 20) + private String password; + @NotBlank + @Size(min = 3, max = 20) + private String passwordConfirm; + + private boolean isAdmin; + + public String getLogin() { + return login; + } + + public void setLogin(String login) { + this.login = login; + } + + public String getPassword() { + return password; + } + + public void setPassword(String password) { + this.password = password; + } + + public String getPasswordConfirm() { + return passwordConfirm; + } + + public void setPasswordConfirm(String passwordConfirm) { + this.passwordConfirm = passwordConfirm; + } + + public boolean getIsAdmin() { + return isAdmin; + } + + public void setIsAdmin(boolean isAdmin) { + this.isAdmin = isAdmin; + } +} diff --git a/lab45/src/main/java/com/example/demo/users/model/UserEntity.java b/lab45/src/main/java/com/example/demo/users/model/UserEntity.java new file mode 100644 index 0000000..9570090 --- /dev/null +++ b/lab45/src/main/java/com/example/demo/users/model/UserEntity.java @@ -0,0 +1,70 @@ +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 = 20) + private String login; + @Column(nullable = false, length = 60) + private String password; + private UserRole role; + + public UserEntity() { + } + + public UserEntity(String login, String password) { + this.login = login; + this.password = password; + this.role = UserRole.USER; + } + + public String getLogin() { + return login; + } + + public void setLogin(String login) { + this.login = login; + } + + public String getPassword() { + return password; + } + + public void setPassword(String password) { + this.password = password; + } + + public UserRole getRole() { + return role; + } + + public void setRole(UserRole role) { + this.role = role; + } + + @Override + public int hashCode() { + return Objects.hash(id, login, password, role); + } + + @Override + public boolean equals(Object obj) { + if (this == obj) + return true; + if (obj == null || getClass() != obj.getClass()) + return false; + UserEntity other = (UserEntity) obj; + return Objects.equals(other.getId(), id) + && Objects.equals(other.getLogin(), login) + && Objects.equals(other.getPassword(), password) + && Objects.equals(other.getRole(), role); + } +} diff --git a/lab45/src/main/java/com/example/demo/users/model/UserRole.java b/lab45/src/main/java/com/example/demo/users/model/UserRole.java new file mode 100644 index 0000000..00e8efa --- /dev/null +++ b/lab45/src/main/java/com/example/demo/users/model/UserRole.java @@ -0,0 +1,15 @@ +package com.example.demo.users.model; + +import org.springframework.security.core.GrantedAuthority; + +public enum UserRole implements GrantedAuthority { + ADMIN, + USER; + + private static final String PREFIX = "ROLE_"; + + @Override + public String getAuthority() { + return PREFIX + this.name(); + } +} diff --git a/lab45/src/main/java/com/example/demo/users/repository/UserRepository.java b/lab45/src/main/java/com/example/demo/users/repository/UserRepository.java new file mode 100644 index 0000000..9bf3cae --- /dev/null +++ b/lab45/src/main/java/com/example/demo/users/repository/UserRepository.java @@ -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, PagingAndSortingRepository { + Optional findByLoginIgnoreCase(String login); +} diff --git a/lab45/src/main/java/com/example/demo/users/service/UserService.java b/lab45/src/main/java/com/example/demo/users/service/UserService.java new file mode 100644 index 0000000..547a1a5 --- /dev/null +++ b/lab45/src/main/java/com/example/demo/users/service/UserService.java @@ -0,0 +1,105 @@ +package com.example.demo.users.service; + +import java.util.List; +import java.util.Optional; +import java.util.stream.StreamSupport; + +import org.springframework.data.domain.Page; +import org.springframework.data.domain.PageRequest; +import org.springframework.data.domain.Sort; +import org.springframework.security.core.userdetails.UserDetails; +import org.springframework.security.core.userdetails.UserDetailsService; +import org.springframework.security.core.userdetails.UsernameNotFoundException; +import org.springframework.security.crypto.password.PasswordEncoder; +import org.springframework.stereotype.Service; +import org.springframework.transaction.annotation.Transactional; +import org.springframework.util.StringUtils; + +import com.example.demo.core.configuration.Constants; +import com.example.demo.core.error.NotFoundException; +import com.example.demo.core.security.UserPrincipal; +import com.example.demo.users.model.UserEntity; +import com.example.demo.users.model.UserRole; +import com.example.demo.users.repository.UserRepository; + +@Service +public class UserService implements UserDetailsService { + private final UserRepository repository; + private final PasswordEncoder passwordEncoder; + + public UserService( + UserRepository repository, + PasswordEncoder passwordEncoder) { + this.repository = repository; + this.passwordEncoder = passwordEncoder; + } + + private void checkLogin(Long id, String login) { + final Optional existsUser = repository.findByLoginIgnoreCase(login); + if (existsUser.isPresent() && !existsUser.get().getId().equals(id)) { + throw new IllegalArgumentException( + String.format("User with login %s is already exists", login)); + } + } + + @Transactional(readOnly = true) + public List getAll() { + return StreamSupport.stream(repository.findAll().spliterator(), false).toList(); + } + + @Transactional(readOnly = true) + public Page getAll(int page, int size) { + return repository.findAll(PageRequest.of(page, size, Sort.by("id"))); + } + + @Transactional(readOnly = true) + public UserEntity get(long id) { + return repository.findById(id) + .orElseThrow(() -> new NotFoundException(UserEntity.class, id)); + } + + @Transactional(readOnly = true) + public UserEntity getByLogin(String login) { + return repository.findByLoginIgnoreCase(login) + .orElseThrow(() -> new IllegalArgumentException("Invalid login")); + } + + @Transactional + public UserEntity create(UserEntity entity) { + if (entity == null) { + throw new IllegalArgumentException("Entity is null"); + } + checkLogin(null, entity.getLogin()); + final String password = Optional.ofNullable(entity.getPassword()).orElse(""); + entity.setPassword( + passwordEncoder.encode(StringUtils.hasText(password.strip()) ? password : Constants.DEFAULT_PASSWORD)); + entity.setRole(Optional.ofNullable(entity.getRole()).orElse(UserRole.USER)); + repository.save(entity); + return repository.save(entity); + } + + @Transactional + public UserEntity update(long id, UserEntity entity) { + final UserEntity existsentity = get(id); + checkLogin(id, entity.getLogin()); + existsentity.setLogin(entity.getLogin()); + existsentity.setPassword(entity.getPassword()); + existsentity.setRole(entity.getRole()); + repository.save(existsentity); + return existsentity; + } + + @Transactional + public UserEntity delete(long id) { + final UserEntity existsEntity = get(id); + repository.delete(existsEntity); + return existsEntity; + } + + @Override + @Transactional(readOnly = true) + public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException { + final UserEntity existsUser = getByLogin(username); + return new UserPrincipal(existsUser); + } +} diff --git a/lab45/src/main/resources/application.properties b/lab45/src/main/resources/application.properties new file mode 100644 index 0000000..62ab433 --- /dev/null +++ b/lab45/src/main/resources/application.properties @@ -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 \ No newline at end of file diff --git a/lab45/src/main/resources/public/css/style.css b/lab45/src/main/resources/public/css/style.css new file mode 100644 index 0000000..c0c042a --- /dev/null +++ b/lab45/src/main/resources/public/css/style.css @@ -0,0 +1,96 @@ +html, +body { + height: 100%; + background-color: #79584c !important; +} + +h1 { + font-size: 1.5em; +} + +h2 { + font-size: 1.25em; +} + +h3 { + font-size: 1.1em; +} + +td form { + margin: 0; + padding: 0; + margin-top: -.25em; +} + +.button-fixed-width { + width: 150px; +} + +.button-link { + padding: 0; +} + +.invalid-feedback { + display: block; +} + +.w-10 { + width: 10% !important; +} + +.my-navbar { + background-color: #3c3c3c !important; +} + +.my-navbar .link a:hover { + text-decoration: underline; +} + +.my-navbar .logo { + width: 26px; + height: 26px; +} + +.my-footer { + background-color: #452A21 !important; + height: 52px; + color: rgba(255, 255, 255, 0.5); +} + +.cart-image { + width: 3.1rem; + padding: 0.25rem; + border-radius: 0.5rem; +} + +.title-text { + color: black; +} + +.card-text { + color: black; + width: 250px; + overflow: auto; +} + +.card-text-full { + color: black; + width: 450px; + overflow: auto; +} + +.cart-item { + height: auto; +} + +.card { + background-color: white; + width: 18rem; + text-overflow: clip; + overflow: auto; +} + +.card-text { + width: 250px; + overflow: auto; +} \ No newline at end of file diff --git a/lab45/src/main/resources/public/css/title.css b/lab45/src/main/resources/public/css/title.css new file mode 100644 index 0000000..7a4d1ed --- /dev/null +++ b/lab45/src/main/resources/public/css/title.css @@ -0,0 +1,31 @@ +.background-style { + /* background-image: url("../../../public/background.jpg"); */ + background-size: cover; + background-position: center; + width: 100%; + margin: 0; + padding: 0; +} + +.display-4 { + color: #FFF; + font-family: 'Source Serif 4'; + font-size: 96px; + font-style: normal; + margin-top: 100px; +} + +blockquote { + color: white; + font-family: 'Source Serif 4'; + text-align: right; + font-size: 24px; + margin-top: 30px; +} + +blockquote footer { + color: white !important; + font-family: 'Source Serif 4'; + text-align: right; + font-size: 24px; +} diff --git a/lab45/src/main/resources/public/favicon.svg b/lab45/src/main/resources/public/favicon.svg new file mode 100644 index 0000000..1276678 --- /dev/null +++ b/lab45/src/main/resources/public/favicon.svg @@ -0,0 +1,2 @@ + \ No newline at end of file diff --git a/lab45/src/main/resources/templates/author-edit.html b/lab45/src/main/resources/templates/author-edit.html new file mode 100644 index 0000000..0224827 --- /dev/null +++ b/lab45/src/main/resources/templates/author-edit.html @@ -0,0 +1,28 @@ + + + + + Редакторовать автора + + + +
+
+
+ + +
+
+ + +
+
+
+ + Отмена +
+
+
+ + + \ No newline at end of file diff --git a/lab45/src/main/resources/templates/author.html b/lab45/src/main/resources/templates/author.html new file mode 100644 index 0000000..43191c7 --- /dev/null +++ b/lab45/src/main/resources/templates/author.html @@ -0,0 +1,50 @@ + + + + + Авторы + + + +
+ +

Данные отсутствуют

+ +

Авторы

+ + + + + + + + + + + + + + + + + + + +
IDАвтор
+
+ +
+
+
+ +
+
+
+
+
+ + + \ No newline at end of file diff --git a/lab45/src/main/resources/templates/book-edit.html b/lab45/src/main/resources/templates/book-edit.html new file mode 100644 index 0000000..da60f74 --- /dev/null +++ b/lab45/src/main/resources/templates/book-edit.html @@ -0,0 +1,56 @@ + + + + + Редакторовать книгу + + + +
+
+
+ + +
+
+ + +
+
+
+ + +
+
+ + +
+
+ + +
+
+
+
+ + +
+
+
+
+ + Отмена +
+
+
+ + + \ No newline at end of file diff --git a/lab45/src/main/resources/templates/book-one.html b/lab45/src/main/resources/templates/book-one.html new file mode 100644 index 0000000..504d317 --- /dev/null +++ b/lab45/src/main/resources/templates/book-one.html @@ -0,0 +1,50 @@ + + + + + Книга + + + +
+
+
+
+
+
Информация о книге
+

Название + книги: +

+

Жанр книги: + + + + + +

+

Автор книги: + + + + + +

+

Год: + +

+

Описание: + +

+ +
+
+
+
+
+ + + \ No newline at end of file diff --git a/lab45/src/main/resources/templates/book.html b/lab45/src/main/resources/templates/book.html new file mode 100644 index 0000000..6b68df1 --- /dev/null +++ b/lab45/src/main/resources/templates/book.html @@ -0,0 +1,72 @@ + + + + + Книги + + + +
+ +

Данные отсутствуют

+ +

Книги

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
IDНазвание Автор Жанр Год Описание Редактировать Удаление
+
+ + +
+
+
+ + +
+
+
+ + +
+ + + \ No newline at end of file diff --git a/lab45/src/main/resources/templates/catalog.html b/lab45/src/main/resources/templates/catalog.html new file mode 100644 index 0000000..e1ddad5 --- /dev/null +++ b/lab45/src/main/resources/templates/catalog.html @@ -0,0 +1,80 @@ + + + + + Каталог + + + +
+
+
+
+
+ + + +
+ +
+ + + + + + + + + + + + + + + + + + + +
НазваниеАвтор
+
+ + +
+
+ +
+
+
+ + + \ No newline at end of file diff --git a/lab45/src/main/resources/templates/default.html b/lab45/src/main/resources/templates/default.html new file mode 100644 index 0000000..38cdaf8 --- /dev/null +++ b/lab45/src/main/resources/templates/default.html @@ -0,0 +1,77 @@ + + + + + + + + Книжный подвальчик + + + + + + + + +
+
+
+ Автор, [[${#dates.year(#dates.createNow())}]] +
+ + + \ No newline at end of file diff --git a/lab45/src/main/resources/templates/error.html b/lab45/src/main/resources/templates/error.html new file mode 100644 index 0000000..faa6b0a --- /dev/null +++ b/lab45/src/main/resources/templates/error.html @@ -0,0 +1,37 @@ + + + + + Ошибка + + + +
+
    + +
  • + Неизвестная ошибка +
  • +
    + +
  • + Ошибка: [[${message}]] +
  • +
    + +
  • + Адрес: [[${url}]] +
  • +
  • + Класс исключения: [[${exception}]] +
  • +
  • + [[${method}]] ([[${file}]]:[[${line}]]) +
  • +
    +
+ На главную +
+ + + \ No newline at end of file diff --git a/lab45/src/main/resources/templates/favorite.html b/lab45/src/main/resources/templates/favorite.html new file mode 100644 index 0000000..2f9068d --- /dev/null +++ b/lab45/src/main/resources/templates/favorite.html @@ -0,0 +1,44 @@ + + + + + Избранные + + + +
+
+
+ + + + + + + + + + + + + + + + + + + + + + +
НазваниеАвторЖанрГодОписание
+ +
+
+
+ + + \ No newline at end of file diff --git a/lab45/src/main/resources/templates/genre-edit.html b/lab45/src/main/resources/templates/genre-edit.html new file mode 100644 index 0000000..7d981b7 --- /dev/null +++ b/lab45/src/main/resources/templates/genre-edit.html @@ -0,0 +1,28 @@ + + + + + Редакторовать жанр + + + +
+
+
+ + +
+
+ + +
+
+
+ + Отмена +
+
+
+ + + \ No newline at end of file diff --git a/lab45/src/main/resources/templates/genre.html b/lab45/src/main/resources/templates/genre.html new file mode 100644 index 0000000..1d0a9d8 --- /dev/null +++ b/lab45/src/main/resources/templates/genre.html @@ -0,0 +1,50 @@ + + + + + Жанры + + + +
+ +

Данные отсутствуют

+ +

Жанры

+ + + + + + + + + + + + + + + + + + + +
IDЖанр
+
+ +
+
+
+ +
+
+
+
+
+ + + \ No newline at end of file diff --git a/lab45/src/main/resources/templates/home.html b/lab45/src/main/resources/templates/home.html new file mode 100644 index 0000000..bf2dcd0 --- /dev/null +++ b/lab45/src/main/resources/templates/home.html @@ -0,0 +1,42 @@ + + + + + + + Главная + + + +
+
+
+

Книжный подвальчик

+
+
+
+
+

+ Без книг пуста человеческая жизнь. Книга не только наш друг, но и + постоянный вечный спутник. +

+
Д. Бедный
+
+
+
+
+
+
+ +
+ +
+
+
+ + + diff --git a/lab45/src/main/resources/templates/login.html b/lab45/src/main/resources/templates/login.html new file mode 100644 index 0000000..eb3a6d7 --- /dev/null +++ b/lab45/src/main/resources/templates/login.html @@ -0,0 +1,44 @@ + + + + + Вход + + + +
+
+
+ Неверный логин или пароль +
+
+ Выход успешно произведен +
+
+ Пользователь успешно создан +
+
+ + +
+
+ + +
+
+ + +
+
+ + Регистрация +
+
+
+ + + + + \ No newline at end of file diff --git a/lab45/src/main/resources/templates/pagination.html b/lab45/src/main/resources/templates/pagination.html new file mode 100644 index 0000000..b11664a --- /dev/null +++ b/lab45/src/main/resources/templates/pagination.html @@ -0,0 +1,51 @@ + + + + + + + + + + + + \ No newline at end of file diff --git a/lab45/src/main/resources/templates/profile.html b/lab45/src/main/resources/templates/profile.html new file mode 100644 index 0000000..c5dd854 --- /dev/null +++ b/lab45/src/main/resources/templates/profile.html @@ -0,0 +1,57 @@ + + + + + Личный кабинет + + + +
+ + +
+
+ +
+
+
    +
  • + [[${stat.typeName}]]: + [[${#numbers.formatDecimal(stat.totalPrice, 1, 2)}]] ₽ + ([[${stat.totalCount}]] шт.) +
  • +
+
+
+
+
+ + + +
+ +
+
+
+
+ + + \ No newline at end of file diff --git a/lab45/src/main/resources/templates/random-books.html b/lab45/src/main/resources/templates/random-books.html new file mode 100644 index 0000000..37cc41e --- /dev/null +++ b/lab45/src/main/resources/templates/random-books.html @@ -0,0 +1,23 @@ + + + + + + + Случайные книги + + + +
+
+

Случайные книги

+ +
+
+ + + \ No newline at end of file diff --git a/lab45/src/main/resources/templates/signup.html b/lab45/src/main/resources/templates/signup.html new file mode 100644 index 0000000..293fcaa --- /dev/null +++ b/lab45/src/main/resources/templates/signup.html @@ -0,0 +1,37 @@ + + + + + Вход + + + +
+
+
+ + +
+
+
+ + +
+
+
+ + +
+
+
+ + Отмена +
+
+
+ + + + + \ No newline at end of file diff --git a/lab45/src/main/resources/templates/user-edit.html b/lab45/src/main/resources/templates/user-edit.html new file mode 100644 index 0000000..659be54 --- /dev/null +++ b/lab45/src/main/resources/templates/user-edit.html @@ -0,0 +1,29 @@ + + + + + Редакторовать пользователя + + + +
+
+
+ + +
+
+ + +
+
+
+ + Отмена +
+
+
+ + + \ No newline at end of file diff --git a/lab45/src/main/resources/templates/user.html b/lab45/src/main/resources/templates/user.html new file mode 100644 index 0000000..cce1336 --- /dev/null +++ b/lab45/src/main/resources/templates/user.html @@ -0,0 +1,56 @@ + + + + + Пользователи + + + +
+ +

Данные отсутствуют

+ +

Пользователи

+ + + + + + + + + + + + + + + + + + + +
IDИмя пользователя
+
+ + +
+
+
+ + +
+
+
+ + +
+ + + \ No newline at end of file diff --git a/lab45/src/test/java/com/example/demo/AuthorServiceTests.java b/lab45/src/test/java/com/example/demo/AuthorServiceTests.java new file mode 100644 index 0000000..e5eb7f6 --- /dev/null +++ b/lab45/src/test/java/com/example/demo/AuthorServiceTests.java @@ -0,0 +1,80 @@ +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 +class AuthorServiceTests { + @Autowired + private AuthorService authorService; + + private AuthorEntity author; + + @BeforeEach + void createData() { + removeData(); + + } + + @AfterEach + void removeData() { + } + + @Test + void getTest() { + author = authorService.create(new AuthorEntity("Студия-дом")); + Assertions.assertThrows(NotFoundException.class, () -> authorService.get(0L)); + } + + @Test + void createTest() { + author = authorService.create(new AuthorEntity("Дом")); + Assertions.assertEquals(9, 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() { + author = authorService.create(new AuthorEntity("Квартира")); + final AuthorEntity nullableAuthor = new AuthorEntity(null); + Assertions.assertThrows(DataIntegrityViolationException.class, () -> authorService.create(nullableAuthor)); + } + + @Test + void updateTest() { + author = authorService.create(new AuthorEntity("Дом на колёсах")); + final String test = "TEST"; + final String oldName = author.getName(); + final AuthorEntity newEntity = authorService.update(author.getId(), new AuthorEntity(test)); + Assertions.assertEquals(7, authorService.getAll().size()); + Assertions.assertEquals(newEntity, authorService.get(author.getId())); + Assertions.assertEquals(test, newEntity.getName()); + Assertions.assertNotEquals(oldName, newEntity.getName()); + } + + @Test + void deleteTest() { + author = authorService.create(new AuthorEntity("2х ярусная квартира")); + authorService.delete(author.getId()); + Assertions.assertEquals(9, authorService.getAll().size()); + + final AuthorEntity newEntity = authorService.create(new AuthorEntity(author.getName())); + Assertions.assertEquals(10, authorService.getAll().size()); + Assertions.assertNotEquals(author.getId(), newEntity.getId()); + } +} \ No newline at end of file diff --git a/lab45/src/test/java/com/example/demo/BookServiceTests.java b/lab45/src/test/java/com/example/demo/BookServiceTests.java new file mode 100644 index 0000000..e521839 --- /dev/null +++ b/lab45/src/test/java/com/example/demo/BookServiceTests.java @@ -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 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 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 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()); + } +} diff --git a/lab45/src/test/java/com/example/demo/FavoriteServiceTests.java b/lab45/src/test/java/com/example/demo/FavoriteServiceTests.java new file mode 100644 index 0000000..57b8e0a --- /dev/null +++ b/lab45/src/test/java/com/example/demo/FavoriteServiceTests.java @@ -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.model.UserRole; +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")); + user.setRole(UserRole.ADMIN); + + lastFavorite = favoriteService.create(new FavoriteEntity(user, book1), user.getId()); + lastFavorite2 = favoriteService.create(new FavoriteEntity(user, book2), user.getId()); + } + + @AfterEach + void removeData() { + favoriteService.getAll(0L).forEach(fv -> favoriteService.delete(user.getId(), 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(user.getId(), 0L)); // NotFoundException + } + + @Test + void createTest() { + Assertions.assertEquals(2, favoriteService.getAll(user.getId()).size()); + } + + @Test + void update() { + final FavoriteEntity fav = favoriteService.create(new FavoriteEntity(user, book2), user.getId()); + + final FavoriteEntity oldFav = favoriteService.get(user.getId(), lastFavorite.getId()); + + final FavoriteEntity newFav = favoriteService.update(user.getId(), lastFavorite2.getId(), + fav); + + Assertions.assertNotEquals(oldFav.getBook().getName(), + newFav.getBook().getName()); + + } + + @Test + + @Order(3) + void delete() { + + favoriteService.delete(user.getId(), lastFavorite.getId()); + + Assertions.assertEquals(1, favoriteService.getAll(user.getId()).size()); + } +} diff --git a/lab45/src/test/java/com/example/demo/GenreServiceTests.java b/lab45/src/test/java/com/example/demo/GenreServiceTests.java new file mode 100644 index 0000000..2c8d67b --- /dev/null +++ b/lab45/src/test/java/com/example/demo/GenreServiceTests.java @@ -0,0 +1,80 @@ +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(); + + } + + @AfterEach + void removeData() { + } + + @Test + void getTest() { + genre = genreService.create(new GenreEntity("Студия-дом")); + Assertions.assertThrows(NotFoundException.class, () -> genreService.get(0L)); + } + + @Test + void createTest() { + genre = genreService.create(new GenreEntity("Дом")); + Assertions.assertEquals(9, genreService.getAll().size()); + Assertions.assertEquals(genre, genreService.get(genre.getId())); + } + + @Test + void createNotUniqueTest() { + final GenreEntity nonUniqueGenre = new GenreEntity("Студия"); + Assertions.assertThrows(IllegalArgumentException.class, () -> genreService.create(nonUniqueGenre)); + } + + @Test + void createNullableTest() { + genre = genreService.create(new GenreEntity("Квартира")); + final GenreEntity nullableGenre = new GenreEntity(null); + Assertions.assertThrows(DataIntegrityViolationException.class, () -> genreService.create(nullableGenre)); + } + + @Test + void updateTest() { + genre = genreService.create(new GenreEntity("Дом на колёсах")); + final String test = "TEST"; + final String oldName = genre.getName(); + final GenreEntity newEntity = genreService.update(genre.getId(), new GenreEntity(test)); + Assertions.assertEquals(7, genreService.getAll().size()); + Assertions.assertEquals(newEntity, genreService.get(genre.getId())); + Assertions.assertEquals(test, newEntity.getName()); + Assertions.assertNotEquals(oldName, newEntity.getName()); + } + + @Test + void deleteTest() { + genre = genreService.create(new GenreEntity("2х ярусная квартира")); + genreService.delete(genre.getId()); + Assertions.assertEquals(9, genreService.getAll().size()); + + final GenreEntity newEntity = genreService.create(new GenreEntity(genre.getName())); + Assertions.assertEquals(10, genreService.getAll().size()); + Assertions.assertNotEquals(genre.getId(), newEntity.getId()); + } +} \ No newline at end of file diff --git a/lab45/src/test/java/com/example/demo/UserServiceTests1.java b/lab45/src/test/java/com/example/demo/UserServiceTests1.java new file mode 100644 index 0000000..09fb50c --- /dev/null +++ b/lab45/src/test/java/com/example/demo/UserServiceTests1.java @@ -0,0 +1,76 @@ +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.model.UserRole; +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")); + firstUser.setRole(UserRole.ADMIN); + userService.create(new UserEntity("oleg", "789")).setRole(UserRole.USER); + userService.create(new UserEntity("nikita", "456")).setRole(UserRole.USER); + + } + + @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.getLogin(), newPassword); + entity.setRole(existEntity.getRole()); + 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()); + } +} diff --git a/lab45/src/test/resources/application.properties b/lab45/src/test/resources/application.properties new file mode 100644 index 0000000..d5f355c --- /dev/null +++ b/lab45/src/test/resources/application.properties @@ -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 \ No newline at end of file