commit 9d6a80ec1304cb7c8e4c782c6180c932f85b6a60 Author: Галина Федоренко Date: Thu May 2 15:55:59 2024 +0400 Забытые 1 и 2 лабы diff --git a/lab1/.gitignore b/lab1/.gitignore new file mode 100644 index 0000000..c2065bc --- /dev/null +++ b/lab1/.gitignore @@ -0,0 +1,37 @@ +HELP.md +.gradle +build/ +!gradle/wrapper/gradle-wrapper.jar +!**/src/main/**/build/ +!**/src/test/**/build/ + +### STS ### +.apt_generated +.classpath +.factorypath +.project +.settings +.springBeans +.sts4-cache +bin/ +!**/src/main/**/bin/ +!**/src/test/**/bin/ + +### IntelliJ IDEA ### +.idea +*.iws +*.iml +*.ipr +out/ +!**/src/main/**/out/ +!**/src/test/**/out/ + +### NetBeans ### +/nbproject/private/ +/nbbuild/ +/dist/ +/nbdist/ +/.nb-gradle/ + +### VS Code ### +.vscode/ diff --git a/lab1/build.gradle b/lab1/build.gradle new file mode 100644 index 0000000..2263922 --- /dev/null +++ b/lab1/build.gradle @@ -0,0 +1,27 @@ +plugins { + id 'java' + id 'org.springframework.boot' version '3.2.2' + id 'io.spring.dependency-management' version '1.1.4' +} + +group = 'com.example' +version = '0.0.1-SNAPSHOT' + +java { + sourceCompatibility = '17' +} + +repositories { + mavenCentral() +} + +dependencies { + implementation 'org.springframework.boot:spring-boot-starter-web' + implementation 'org.springdoc:springdoc-openapi-starter-webmvc-ui:2.3.0' + + testImplementation 'org.springframework.boot:spring-boot-starter-test' +} + +tasks.named('test') { + useJUnitPlatform() +} diff --git a/lab1/gradle/wrapper/gradle-wrapper.jar b/lab1/gradle/wrapper/gradle-wrapper.jar new file mode 100644 index 0000000..d64cd49 Binary files /dev/null and b/lab1/gradle/wrapper/gradle-wrapper.jar differ diff --git a/lab1/gradle/wrapper/gradle-wrapper.properties b/lab1/gradle/wrapper/gradle-wrapper.properties new file mode 100644 index 0000000..1af9e09 --- /dev/null +++ b/lab1/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/lab1/gradlew b/lab1/gradlew new file mode 100644 index 0000000..1aa94a4 --- /dev/null +++ b/lab1/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/lab1/gradlew.bat b/lab1/gradlew.bat new file mode 100644 index 0000000..93e3f59 --- /dev/null +++ b/lab1/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/lab1/index.html b/lab1/index.html new file mode 100644 index 0000000..55419a6 --- /dev/null +++ b/lab1/index.html @@ -0,0 +1,61 @@ + + + + + + Document + + +

Push the button

+ +
+ +
+ +
+ +
+ + + + \ No newline at end of file diff --git a/lab1/settings.gradle b/lab1/settings.gradle new file mode 100644 index 0000000..0a383dd --- /dev/null +++ b/lab1/settings.gradle @@ -0,0 +1 @@ +rootProject.name = 'demo' diff --git a/lab1/src/main/java/com/example/demo/ApiController.java b/lab1/src/main/java/com/example/demo/ApiController.java new file mode 100644 index 0000000..6d7d425 --- /dev/null +++ b/lab1/src/main/java/com/example/demo/ApiController.java @@ -0,0 +1,49 @@ +package com.example.demo; + +import java.util.ArrayList; +import java.util.List; + +import org.springframework.web.bind.annotation.DeleteMapping; +import org.springframework.web.bind.annotation.GetMapping; +import org.springframework.web.bind.annotation.PathVariable; +import org.springframework.web.bind.annotation.PostMapping; +import org.springframework.web.bind.annotation.PutMapping; +import org.springframework.web.bind.annotation.RequestBody; +import org.springframework.web.bind.annotation.RequestMapping; +import org.springframework.web.bind.annotation.RequestParam; +import org.springframework.web.bind.annotation.RestController; + +@RestController +@RequestMapping("/api/book") +public class ApiController { + private final List books = new ArrayList<>(); + + @GetMapping + public List getBooks() { + return books; + } + + @GetMapping("/{id}") + public BookDto getBook(@PathVariable(name = "id") int id) { + return books.get(id); + } + + @PostMapping + public BookDto postMap(@RequestBody BookDto bookDto) { + books.add(bookDto); + return bookDto; + } + + @PutMapping("/{id}") + public BookDto putMap(@RequestBody BookDto bookDto, @PathVariable(name = "id") int id) { + books.set(id, bookDto); + return bookDto; + } + + @DeleteMapping("/{id}") + public BookDto delete(@RequestParam(name = "id") int id) { + BookDto bk = books.get(id); + books.remove(id); + return bk; + } +} \ No newline at end of file diff --git a/lab1/src/main/java/com/example/demo/BookDto.java b/lab1/src/main/java/com/example/demo/BookDto.java new file mode 100644 index 0000000..e8e430e --- /dev/null +++ b/lab1/src/main/java/com/example/demo/BookDto.java @@ -0,0 +1,49 @@ +package com.example.demo; + +import com.fasterxml.jackson.annotation.JsonCreator; +import com.fasterxml.jackson.annotation.JsonProperty; + +public class BookDto { + private String name; + private String author; + private String genre; + private String year; + private String description; + + public BookDto() { + } + + @JsonCreator + public BookDto( + @JsonProperty(value = "name") String name, + @JsonProperty(value = "author") String author, + @JsonProperty(value = "genre") String genre, + @JsonProperty(value = "year") String year, + @JsonProperty(value = "description") String description) { + this.name = name; + this.author = author; + this.genre = genre; + this.year = year; + this.description = description; + } + + public String getName() { + return name; + } + + public String getAuthor() { + return author; + } + + public String getGenre() { + return genre; + } + + public String getYear() { + return year; + } + + public String getDescription() { + return description; + } +} diff --git a/lab1/src/main/java/com/example/demo/DemoApplication.java b/lab1/src/main/java/com/example/demo/DemoApplication.java new file mode 100644 index 0000000..e03ec75 --- /dev/null +++ b/lab1/src/main/java/com/example/demo/DemoApplication.java @@ -0,0 +1,12 @@ +package com.example.demo; + +import org.springframework.boot.SpringApplication; +import org.springframework.boot.autoconfigure.SpringBootApplication; + +@SpringBootApplication +public class DemoApplication { + + public static void main(String[] args) { + SpringApplication.run(DemoApplication.class, args); + } +} diff --git a/lab1/src/main/java/com/example/demo/WebConfig.java b/lab1/src/main/java/com/example/demo/WebConfig.java new file mode 100644 index 0000000..d5585a1 --- /dev/null +++ b/lab1/src/main/java/com/example/demo/WebConfig.java @@ -0,0 +1,15 @@ +package com.example.demo; + +import org.springframework.context.annotation.Configuration; +import org.springframework.lang.NonNull; +import org.springframework.web.servlet.config.annotation.CorsRegistry; +import org.springframework.web.servlet.config.annotation.WebMvcConfigurer; + +@Configuration +public class WebConfig implements WebMvcConfigurer { + @Override + public void addCorsMappings(@NonNull CorsRegistry registry) { + registry.addMapping("/**") + .allowedMethods("GET", "POST", "PUT", "DELETE"); + } +} diff --git a/lab1/src/main/resources/application.properties b/lab1/src/main/resources/application.properties new file mode 100644 index 0000000..8b13789 --- /dev/null +++ b/lab1/src/main/resources/application.properties @@ -0,0 +1 @@ + diff --git a/lab1/src/test/java/com/example/demo/DemoApplicationTests.java b/lab1/src/test/java/com/example/demo/DemoApplicationTests.java new file mode 100644 index 0000000..2778a6a --- /dev/null +++ b/lab1/src/test/java/com/example/demo/DemoApplicationTests.java @@ -0,0 +1,13 @@ +package com.example.demo; + +import org.junit.jupiter.api.Test; +import org.springframework.boot.test.context.SpringBootTest; + +@SpringBootTest +class DemoApplicationTests { + + @Test + void contextLoads() { + } + +} diff --git a/lab2/.gitignore b/lab2/.gitignore new file mode 100644 index 0000000..c2065bc --- /dev/null +++ b/lab2/.gitignore @@ -0,0 +1,37 @@ +HELP.md +.gradle +build/ +!gradle/wrapper/gradle-wrapper.jar +!**/src/main/**/build/ +!**/src/test/**/build/ + +### STS ### +.apt_generated +.classpath +.factorypath +.project +.settings +.springBeans +.sts4-cache +bin/ +!**/src/main/**/bin/ +!**/src/test/**/bin/ + +### IntelliJ IDEA ### +.idea +*.iws +*.iml +*.ipr +out/ +!**/src/main/**/out/ +!**/src/test/**/out/ + +### NetBeans ### +/nbproject/private/ +/nbbuild/ +/dist/ +/nbdist/ +/.nb-gradle/ + +### VS Code ### +.vscode/ diff --git a/lab2/build.gradle b/lab2/build.gradle new file mode 100644 index 0000000..4e31e6a --- /dev/null +++ b/lab2/build.gradle @@ -0,0 +1,29 @@ +plugins { + id 'java' + id 'org.springframework.boot' version '3.2.3' + id 'io.spring.dependency-management' version '1.1.4' +} + +group = 'com.example' +version = '0.0.1-SNAPSHOT' + +java { + sourceCompatibility = '17' +} + +repositories { + mavenCentral() +} + +dependencies { + implementation 'org.springframework.boot:spring-boot-starter-web' + implementation 'org.springdoc:springdoc-openapi-starter-webmvc-ui:2.3.0' + implementation 'org.modelmapper:modelmapper:3.2.0' + implementation 'org.springframework.boot:spring-boot-starter-validation' + + testImplementation 'org.springframework.boot:spring-boot-starter-test' +} + +tasks.named('test') { + useJUnitPlatform() +} diff --git a/lab2/gradle/wrapper/gradle-wrapper.jar b/lab2/gradle/wrapper/gradle-wrapper.jar new file mode 100644 index 0000000..d64cd49 Binary files /dev/null and b/lab2/gradle/wrapper/gradle-wrapper.jar differ diff --git a/lab2/gradle/wrapper/gradle-wrapper.properties b/lab2/gradle/wrapper/gradle-wrapper.properties new file mode 100644 index 0000000..1af9e09 --- /dev/null +++ b/lab2/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/lab2/gradlew b/lab2/gradlew new file mode 100644 index 0000000..1aa94a4 --- /dev/null +++ b/lab2/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/lab2/gradlew.bat b/lab2/gradlew.bat new file mode 100644 index 0000000..93e3f59 --- /dev/null +++ b/lab2/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/lab2/settings.gradle b/lab2/settings.gradle new file mode 100644 index 0000000..0a383dd --- /dev/null +++ b/lab2/settings.gradle @@ -0,0 +1 @@ +rootProject.name = 'demo' diff --git a/lab2/src/main/java/com/example/demo/DemoApplication.java b/lab2/src/main/java/com/example/demo/DemoApplication.java new file mode 100644 index 0000000..a60ff02 --- /dev/null +++ b/lab2/src/main/java/com/example/demo/DemoApplication.java @@ -0,0 +1,50 @@ +package com.example.demo; + +import java.util.Objects; + +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.springframework.boot.CommandLineRunner; +import org.springframework.boot.SpringApplication; +import org.springframework.boot.autoconfigure.SpringBootApplication; + +import com.example.demo.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 BookService bookService; + + public DemoApplication(GenreService genreService, BookService bookService) { + this.genreService = genreService; + 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 && Objects.equals("--populate", args[0])) { + log.info("Create default genres values"); + final var genre1 = genreService.create(new GenreEntity(null, "Роман")); + final var genre2 = genreService.create(new GenreEntity(null, "Фэнтези")); + final var genre3 = genreService.create(new GenreEntity(null, "Трагедия")); + + log.info("Create default books values"); + bookService.create(new BookEntity(null, genre1, "g", "g", "g", "g")); + bookService.create(new BookEntity(null, genre1, "q", "y", "q", "y")); + bookService.create(new BookEntity(null, genre2, "w", "t", "w", "t")); + bookService.create(new BookEntity(null, genre2, "e", "r", "e", "r")); + bookService.create(new BookEntity(null, genre3, "r", "e", "r", "e")); + bookService.create(new BookEntity(null, genre3, "t", "w", "t", "w")); + bookService.create(new BookEntity(null, genre1, "y", "q", "y", "q")); + } + } +} diff --git a/lab2/src/main/java/com/example/demo/books/api/BookController.java b/lab2/src/main/java/com/example/demo/books/api/BookController.java new file mode 100644 index 0000000..9f5bc98 --- /dev/null +++ b/lab2/src/main/java/com/example/demo/books/api/BookController.java @@ -0,0 +1,71 @@ +package com.example.demo.books.api; + +import java.util.List; + +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.configuration.Constants; +import com.example.demo.books.model.BookEntity; +import com.example.demo.books.service.BookService; + +import jakarta.validation.Valid; + +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") Integer genreId) { + return bookService.getAll(genreId).stream().map(this::toDto).toList(); + } + + @GetMapping("/{id}") + public BookDto get(@PathVariable(name = "id") Integer 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") Integer id, @RequestBody BookDto dto) { + return toDto(bookService.update(id, toEntity(dto))); + } + + @DeleteMapping("/{id}") + public BookDto delete(@PathVariable(name = "id") Integer id) { + return toDto(bookService.delete(id)); + } +} diff --git a/lab2/src/main/java/com/example/demo/books/api/BookDto.java b/lab2/src/main/java/com/example/demo/books/api/BookDto.java new file mode 100644 index 0000000..8066730 --- /dev/null +++ b/lab2/src/main/java/com/example/demo/books/api/BookDto.java @@ -0,0 +1,76 @@ +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; + + @NotBlank + private String name; + + @NotBlank + private String author; + + @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 String getAuthor() { + return author; + } + + public void setAuthor(String author) { + this.author = author; + } + + 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/lab2/src/main/java/com/example/demo/books/model/BookEntity.java b/lab2/src/main/java/com/example/demo/books/model/BookEntity.java new file mode 100644 index 0000000..e9a2655 --- /dev/null +++ b/lab2/src/main/java/com/example/demo/books/model/BookEntity.java @@ -0,0 +1,87 @@ +package com.example.demo.books.model; + +import java.util.Objects; + +import com.example.demo.core.model.BaseEntity; +import com.example.demo.genres.model.GenreEntity; + +public class BookEntity extends BaseEntity { + private GenreEntity genre; + private String name; + private String author; + private String year; + private String description; + + public BookEntity() { + super(); + } + + public BookEntity(Integer id, GenreEntity genre, String name, String author, String year, String description) { + super(id); + 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 String getAuthor() { + return author; + } + + public void setAuthor(String 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/lab2/src/main/java/com/example/demo/books/repository/BookRepository.java b/lab2/src/main/java/com/example/demo/books/repository/BookRepository.java new file mode 100644 index 0000000..d1df467 --- /dev/null +++ b/lab2/src/main/java/com/example/demo/books/repository/BookRepository.java @@ -0,0 +1,11 @@ +package com.example.demo.books.repository; + +import org.springframework.stereotype.Repository; + +import com.example.demo.core.repository.MapRepository; +import com.example.demo.books.model.BookEntity; + +@Repository +public class BookRepository extends MapRepository { + +} diff --git a/lab2/src/main/java/com/example/demo/books/service/BookService.java b/lab2/src/main/java/com/example/demo/books/service/BookService.java new file mode 100644 index 0000000..90af4b4 --- /dev/null +++ b/lab2/src/main/java/com/example/demo/books/service/BookService.java @@ -0,0 +1,57 @@ +package com.example.demo.books.service; + +import java.util.List; +import java.util.Objects; +import java.util.Optional; + +import org.springframework.stereotype.Service; + +import com.example.demo.core.error.NotFoundException; +import com.example.demo.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; + } + + public List getAll(Integer genreId) { + if (Objects.equals(genreId, 0)) { + return repository.getAll(); + } + return repository.getAll().stream() + .filter(book -> book.getGenre().getId().equals(genreId)) + .toList(); + } + + public BookEntity get(Integer id) { + return Optional.ofNullable(repository.get(id)) + .orElseThrow(() -> new NotFoundException(id)); + } + + public BookEntity create(BookEntity entity) { + return repository.create(entity); + } + + public BookEntity update(Integer id, BookEntity entity) { + final BookEntity existsEntity = get(id); + existsEntity.setGenre(entity.getGenre()); + existsEntity.setName(entity.getName()); + existsEntity.setAuthor(entity.getAuthor()); + existsEntity.setYear(entity.getYear()); + existsEntity.setDescription(entity.getDescription()); + return repository.update(existsEntity); + } + + public BookEntity delete(Integer id) { + final BookEntity existsEntity = get(id); + return repository.delete(existsEntity); + } + + public void deleteAll() { + repository.deleteAll(); + } +} diff --git a/lab2/src/main/java/com/example/demo/core/configuration/Constants.java b/lab2/src/main/java/com/example/demo/core/configuration/Constants.java new file mode 100644 index 0000000..8ff48af --- /dev/null +++ b/lab2/src/main/java/com/example/demo/core/configuration/Constants.java @@ -0,0 +1,8 @@ +package com.example.demo.core.configuration; + +public class Constants { + public static final String API_URL = "/api"; + + private Constants() { + } +} diff --git a/lab2/src/main/java/com/example/demo/core/configuration/MapperConfiguration.java b/lab2/src/main/java/com/example/demo/core/configuration/MapperConfiguration.java new file mode 100644 index 0000000..a5ad6f3 --- /dev/null +++ b/lab2/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/lab2/src/main/java/com/example/demo/core/configuration/WebConfiguration.java b/lab2/src/main/java/com/example/demo/core/configuration/WebConfiguration.java new file mode 100644 index 0000000..762e85a --- /dev/null +++ b/lab2/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/lab2/src/main/java/com/example/demo/core/error/NotFoundException.java b/lab2/src/main/java/com/example/demo/core/error/NotFoundException.java new file mode 100644 index 0000000..0364ae8 --- /dev/null +++ b/lab2/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(Integer id) { + super(String.format("Entity with id [%s] is not found or not exists", id)); + } +} diff --git a/lab2/src/main/java/com/example/demo/core/model/BaseEntity.java b/lab2/src/main/java/com/example/demo/core/model/BaseEntity.java new file mode 100644 index 0000000..32fa796 --- /dev/null +++ b/lab2/src/main/java/com/example/demo/core/model/BaseEntity.java @@ -0,0 +1,23 @@ +package com.example.demo.core.model; + +public class BaseEntity { + + public Integer id; + + protected BaseEntity() { + + } + + protected BaseEntity(Integer id) { + this.id = id; + } + + public Integer getId() { + return id; + } + + public void setId(Integer id) { + this.id = id; + } + +} diff --git a/lab2/src/main/java/com/example/demo/core/repository/CommonRepository.java b/lab2/src/main/java/com/example/demo/core/repository/CommonRepository.java new file mode 100644 index 0000000..85e1e6d --- /dev/null +++ b/lab2/src/main/java/com/example/demo/core/repository/CommonRepository.java @@ -0,0 +1,17 @@ +package com.example.demo.core.repository; + +import java.util.List; + +public interface CommonRepository { + List getAll(); + + E get(T id); + + E create(E entity); + + E update(E entity); + + E delete(E entity); + + void deleteAll(); +} diff --git a/lab2/src/main/java/com/example/demo/core/repository/MapRepository.java b/lab2/src/main/java/com/example/demo/core/repository/MapRepository.java new file mode 100644 index 0000000..eb40093 --- /dev/null +++ b/lab2/src/main/java/com/example/demo/core/repository/MapRepository.java @@ -0,0 +1,63 @@ +package com.example.demo.core.repository; + +import java.util.List; +import java.util.Map; +import java.util.TreeMap; + +import com.example.demo.core.model.BaseEntity; + +public abstract class MapRepository implements CommonRepository { + private final Map entities = new TreeMap<>(); + private Integer lastId = 0; + + private boolean checkNull(E entity) { + if (get(entity.getId()) == null) + return false; + return true; + } + + protected MapRepository() { + } + + @Override + public List getAll() { + return entities.values().stream().toList(); + } + + @Override + public E get(Integer id) { + return entities.get(id); + } + + @Override + public E create(E entity) { + lastId++; + entity.setId(lastId); + entities.put(lastId, entity); + return entity; + } + + @Override + public E update(E entity) { + if (checkNull(entity)) { + entities.put(entity.getId(), entity); + return entity; + } + return null; + } + + @Override + public E delete(E entity) { + if (checkNull(entity)) { + entities.remove(entity.getId()); + return entity; + } + return null; + } + + @Override + public void deleteAll() { + entities.clear(); + lastId = 0; + } +} diff --git a/lab2/src/main/java/com/example/demo/genres/api/GenreController.java b/lab2/src/main/java/com/example/demo/genres/api/GenreController.java new file mode 100644 index 0000000..985921e --- /dev/null +++ b/lab2/src/main/java/com/example/demo/genres/api/GenreController.java @@ -0,0 +1,64 @@ +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") Integer 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") Integer id, @RequestBody GenreDto dto) { + return toDto(genreService.update(id, toEntity(dto))); + } + + @DeleteMapping("/{id}") + public GenreDto delete(@PathVariable(name = "id") Integer id) { + return toDto(genreService.delete(id)); + } +} diff --git a/lab2/src/main/java/com/example/demo/genres/api/GenreDto.java b/lab2/src/main/java/com/example/demo/genres/api/GenreDto.java new file mode 100644 index 0000000..052bea3 --- /dev/null +++ b/lab2/src/main/java/com/example/demo/genres/api/GenreDto.java @@ -0,0 +1,28 @@ +package com.example.demo.genres.api; + +import com.fasterxml.jackson.annotation.JsonProperty; + +import jakarta.validation.constraints.NotBlank; + +public class GenreDto { + private Integer id; + @NotBlank + private String name; + + @JsonProperty(access = JsonProperty.Access.READ_ONLY) + public Integer getId() { + return id; + } + + public void setId(Integer id) { + this.id = id; + } + + public String getName() { + return name; + } + + public void setName(String name) { + this.name = name; + } +} diff --git a/lab2/src/main/java/com/example/demo/genres/model/GenreEntity.java b/lab2/src/main/java/com/example/demo/genres/model/GenreEntity.java new file mode 100644 index 0000000..d2a338e --- /dev/null +++ b/lab2/src/main/java/com/example/demo/genres/model/GenreEntity.java @@ -0,0 +1,41 @@ +package com.example.demo.genres.model; + +import java.util.Objects; + +import com.example.demo.core.model.BaseEntity; + +public class GenreEntity extends BaseEntity { + private String name; + + public GenreEntity() { + super(); + } + + public GenreEntity(Integer id, String name) { + super(id); + this.name = name; + } + + public String getName() { + return name; + } + + public void setName(String name) { + this.name = name; + } + + @Override + public int hashCode() { + return Objects.hash(id, name); + } + + @Override + public boolean equals(Object obj) { + if (this == obj) + return true; + if (obj == null || getClass() != obj.getClass()) + return false; + final GenreEntity other = (GenreEntity) obj; + return Objects.equals(other.getId(), id) && Objects.equals(other.getName(), name); + } +} diff --git a/lab2/src/main/java/com/example/demo/genres/repository/GenreRepository.java b/lab2/src/main/java/com/example/demo/genres/repository/GenreRepository.java new file mode 100644 index 0000000..bd86082 --- /dev/null +++ b/lab2/src/main/java/com/example/demo/genres/repository/GenreRepository.java @@ -0,0 +1,10 @@ +package com.example.demo.genres.repository; + +import org.springframework.stereotype.Repository; + +import com.example.demo.core.repository.MapRepository; +import com.example.demo.genres.model.GenreEntity; + +@Repository +public class GenreRepository extends MapRepository { +} diff --git a/lab2/src/main/java/com/example/demo/genres/service/GenreService.java b/lab2/src/main/java/com/example/demo/genres/service/GenreService.java new file mode 100644 index 0000000..3857ea1 --- /dev/null +++ b/lab2/src/main/java/com/example/demo/genres/service/GenreService.java @@ -0,0 +1,46 @@ +package com.example.demo.genres.service; + +import org.springframework.stereotype.Service; +import java.util.List; +import java.util.Optional; + +import com.example.demo.core.error.NotFoundException; +import com.example.demo.genres.model.GenreEntity; + +import com.example.demo.genres.repository.GenreRepository; + +@Service +public class GenreService { + private final GenreRepository repository; + + public GenreService(GenreRepository repository) { + this.repository = repository; + } + + public List getAll() { + return repository.getAll(); + } + + public GenreEntity get(Integer id) { + return Optional.ofNullable(repository.get(id)).orElseThrow(() -> new NotFoundException(id)); + } + + public GenreEntity create(GenreEntity entity) { + return repository.create(entity); + } + + public GenreEntity update(Integer id, GenreEntity entity) { + final GenreEntity exisEntity = get(id); + exisEntity.setName(entity.getName()); + return repository.update(exisEntity); + } + + public GenreEntity delete(Integer id) { + final GenreEntity existEntity = get(id); + return repository.delete(existEntity); + } + + public void deleteAll() { + repository.deleteAll(); + } +} diff --git a/lab2/src/main/java/com/example/demo/users/api/UserController.java b/lab2/src/main/java/com/example/demo/users/api/UserController.java new file mode 100644 index 0000000..875743c --- /dev/null +++ b/lab2/src/main/java/com/example/demo/users/api/UserController.java @@ -0,0 +1,85 @@ +package com.example.demo.users.api; + +import java.util.List; + +import org.modelmapper.ModelMapper; +import org.springframework.web.bind.annotation.DeleteMapping; +import org.springframework.web.bind.annotation.GetMapping; +import org.springframework.web.bind.annotation.PathVariable; +import org.springframework.web.bind.annotation.PostMapping; +import org.springframework.web.bind.annotation.PutMapping; +import org.springframework.web.bind.annotation.RequestBody; +import org.springframework.web.bind.annotation.RequestMapping; +import org.springframework.web.bind.annotation.RestController; + +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.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; + private final BookService bookService; + + public UserController(UserService userService, ModelMapper modelMapper, BookService bookService) { + this.modelMapper = modelMapper; + this.userService = userService; + this.bookService = bookService; + } + + private UserDto toDto(UserEntity entity) { + // return modelMapper.map(entity, UserDto.class); + final var dto = new UserDto(); + dto.setId(entity.getId()); + dto.setUsername(entity.getUsername()); + dto.setPassword(entity.getPassword()); + dto.setIsAdmin(entity.getIsAdmin()); + dto.setBooks(entity.getBooks().stream().map(BookEntity::getId).toList()); + return dto; + } + + private UserEntity toEntity(UserDto dto) { + return modelMapper.map(dto, UserEntity.class); + } + + @GetMapping() + public List getAll() { + return userService.getAll().stream().map(this::toDto).toList(); + } + + @GetMapping("/{id}") + public UserDto get(@PathVariable(name = "id") Integer id) { + return toDto(userService.get(id)); + } + + @PostMapping + public UserDto create(@Valid @RequestBody UserDto dto) { + return toDto(userService.create(toEntity(dto))); + } + + @PostMapping("/{id}/book/{bookId}") + public UserDto addBook(@PathVariable(name = "id") Integer id, @PathVariable(name = "bookId") Integer bookId) { + return toDto(userService.addBook(id, bookService.get(bookId))); + } + + @PutMapping("/{id}") + public UserDto update(@PathVariable(name = "id") Integer id, @RequestBody UserDto userDto) { + return toDto(userService.update(id, toEntity(userDto))); + } + + @DeleteMapping("/{id}") + public UserDto delete(@PathVariable(name = "id") Integer id) { + return toDto(userService.delete(id)); + } + + @DeleteMapping("/{id}/book/{bookId}") + public UserDto deleteBook(@PathVariable(name = "id") Integer id, @PathVariable(name = "bookId") Integer bookId) { + return toDto(userService.deleteBook(id, bookService.get(bookId))); + } +} diff --git a/lab2/src/main/java/com/example/demo/users/api/UserDto.java b/lab2/src/main/java/com/example/demo/users/api/UserDto.java new file mode 100644 index 0000000..230c1eb --- /dev/null +++ b/lab2/src/main/java/com/example/demo/users/api/UserDto.java @@ -0,0 +1,66 @@ +package com.example.demo.users.api; + +import java.util.ArrayList; +import java.util.List; + +import com.fasterxml.jackson.annotation.JsonProperty; + +import jakarta.validation.constraints.NotBlank; +import jakarta.validation.constraints.NotNull; + +public class UserDto { + private Integer id; + + @NotBlank + private String username; + + @NotBlank + private String password; + + @NotNull + private boolean isAdmin; + + @JsonProperty(access = JsonProperty.Access.READ_ONLY) + private List books = new ArrayList<>(); + + @JsonProperty(access = JsonProperty.Access.READ_ONLY) + public Integer getId() { + return id; + } + + public void setId(Integer 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; + } + + public List getBooks() { + return books; + } + + public void setBooks(List list) { + this.books = list; + } +} diff --git a/lab2/src/main/java/com/example/demo/users/model/UserEntity.java b/lab2/src/main/java/com/example/demo/users/model/UserEntity.java new file mode 100644 index 0000000..d20a742 --- /dev/null +++ b/lab2/src/main/java/com/example/demo/users/model/UserEntity.java @@ -0,0 +1,82 @@ +package com.example.demo.users.model; + +import java.util.Objects; +import java.util.Set; +import java.util.LinkedHashSet; + +import com.example.demo.core.model.BaseEntity; +import com.example.demo.books.model.BookEntity; + +public class UserEntity extends BaseEntity { + + private String username; + private String password; + private boolean isAdmin; + private final Set books = new LinkedHashSet<>(); + + public UserEntity() { + super(); + } + + public UserEntity(Integer id, String username, String password, boolean isAdmin) { + super(id); + 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; + } + + public Set getBooks() { + return books; + } + + public void addBook(BookEntity book) { + books.add(book); + } + + public void deleteBook(BookEntity book) { + books.remove(book); + } + + @Override + public int hashCode() { + return Objects.hash(id, username); + } + + @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) && + Objects.equals(other.getBooks(), books); + } +} diff --git a/lab2/src/main/java/com/example/demo/users/repository/UserRepository.java b/lab2/src/main/java/com/example/demo/users/repository/UserRepository.java new file mode 100644 index 0000000..dbc0e52 --- /dev/null +++ b/lab2/src/main/java/com/example/demo/users/repository/UserRepository.java @@ -0,0 +1,11 @@ +package com.example.demo.users.repository; + +import org.springframework.stereotype.Repository; + +import com.example.demo.core.repository.MapRepository; +import com.example.demo.users.model.UserEntity; + +@Repository +public class UserRepository extends MapRepository { + +} diff --git a/lab2/src/main/java/com/example/demo/users/service/UserService.java b/lab2/src/main/java/com/example/demo/users/service/UserService.java new file mode 100644 index 0000000..2be73b3 --- /dev/null +++ b/lab2/src/main/java/com/example/demo/users/service/UserService.java @@ -0,0 +1,61 @@ +package com.example.demo.users.service; + +import java.util.List; +import java.util.Optional; + +import org.springframework.stereotype.Service; + +import com.example.demo.books.model.BookEntity; +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; + } + + public List getAll() { + return repository.getAll(); + } + + public UserEntity get(Integer id) { + return Optional.ofNullable(repository.get(id)).orElseThrow(() -> new NotFoundException(id)); + } + + public UserEntity create(UserEntity entity) { + return repository.create(entity); + } + + public UserEntity update(Integer id, UserEntity entity) { + final UserEntity existedEntity = get(id); + existedEntity.setUsername(entity.getUsername()); + existedEntity.setPassword(entity.getPassword()); + existedEntity.setIsAdmin(entity.getIsAdmin()); + return repository.update(existedEntity); + } + + public UserEntity delete(Integer id) { + final UserEntity existsentity = get(id); + return repository.delete(existsentity); + } + + public UserEntity addBook(Integer id, BookEntity book) { + final UserEntity existedEntity = get(id); + existedEntity.addBook(book); + return existedEntity; + } + + public UserEntity deleteBook(Integer id, BookEntity book) { + final UserEntity existedEntity = get(id); + existedEntity.deleteBook(book); + return existedEntity; + } + + public void deleteAll() { + repository.deleteAll(); + } +} \ No newline at end of file diff --git a/lab2/src/main/resources/application.properties b/lab2/src/main/resources/application.properties new file mode 100644 index 0000000..8b13789 --- /dev/null +++ b/lab2/src/main/resources/application.properties @@ -0,0 +1 @@ + diff --git a/lab2/src/test/java/com/example/demo/BookServiceTests.java b/lab2/src/test/java/com/example/demo/BookServiceTests.java new file mode 100644 index 0000000..353cc8a --- /dev/null +++ b/lab2/src/test/java/com/example/demo/BookServiceTests.java @@ -0,0 +1,139 @@ +package com.example.demo; + +import org.junit.jupiter.api.TestMethodOrder; +import org.junit.jupiter.api.Assertions; +import org.junit.jupiter.api.MethodOrderer.OrderAnnotation; +import org.junit.jupiter.api.Order; +import org.junit.jupiter.api.Test; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.boot.test.context.SpringBootTest; + +import com.example.demo.genres.model.GenreEntity; +import com.example.demo.genres.service.GenreService; +import com.example.demo.core.error.NotFoundException; +import com.example.demo.books.model.BookEntity; +import com.example.demo.books.service.BookService; + +@SpringBootTest +@TestMethodOrder(OrderAnnotation.class) +public class BookServiceTests { + @Autowired + private BookService bookService; + @Autowired + private GenreService genreService; + + @Test + void getTest() { + Assertions.assertThrows(NotFoundException.class, () -> bookService.get(0)); + } + + @Test + @Order(1) + void createTest() { + genreService.deleteAll(); + bookService.deleteAll(); + + genreService.create(new GenreEntity(null, "Роман")); + genreService.create(new GenreEntity(null, "Комедия")); + genreService.create(new GenreEntity(null, "Трагедия")); + + bookService.create( + new BookEntity(null, genreService.get(1), "Гордость и предубеждение", "автор1", "год1", "описание")); + + bookService.create(new BookEntity(null, genreService.get(2), "Недоросль", "автор2", "год1", "описание")); + + final BookEntity last = bookService + .create(new BookEntity(null, genreService.get(3), "Грозовой перевал", "автор3", "год1", "описание")); + + // проверка, что кол-во игр в хранилище равно кол-ву добавленных (проверка, что + // все добавились) + Assertions.assertEquals(3, bookService.getAll(0).size()); + // проверка, что в хранилище последняя игра та, которую добавили последней + // (проверка, что всё правильно добавилось) + Assertions.assertEquals(last, bookService.get(3)); + } + + @Test + @Order(2) + void update() { + // на какой жанр будем менять (со Стратегии на FMV) + final GenreEntity testEntity = genreService.get(1); + + // на какое название будем менять название игры + final String testName = "Война и мир"; + + // на какое название будем менять название игры + final String testAuthor = "Л.Н.Толстой"; + + // на какое название будем менять название игры + final String testYear = "1892"; + + // на какое описание будем менять описание игры + final String testDescription = "Много французских букв"; + + // получение последней в списке игры + final BookEntity entity = bookService.get(3); + + // запоминание старого жанра игры + final GenreEntity oldGenreEntity = entity.getGenre(); + + // запоминание её названия до обновления + final String oldName = entity.getName(); + + // запоминание её цены до обновления + final String oldAuthor = entity.getAuthor(); + + // запоминание её описания до обновления + final String oldDescription = entity.getDescription(); + + // запоминание её описания до обновления + final String oldYear = entity.getYear(); + + // запоминание новых данных жанра + final BookEntity newEntity = bookService.update(3, + new BookEntity(1, testEntity, testName, testAuthor, testYear, testDescription)); + + // Проверка, что кол-во игр до сих пор 3 + Assertions.assertEquals(3, bookService.getAll(0).size()); + + Assertions.assertEquals(newEntity, bookService.get(3)); + + // Проверка, что жанр поменялся + Assertions.assertEquals(testEntity, newEntity.getGenre()); + Assertions.assertNotEquals(oldGenreEntity, newEntity.getGenre()); + + // Проверка, что название поменялось + Assertions.assertEquals(testName, newEntity.getName()); + Assertions.assertNotEquals(oldName, newEntity.getName()); + + // Проверка, что название поменялось + Assertions.assertEquals(testAuthor, newEntity.getAuthor()); + Assertions.assertNotEquals(oldAuthor, newEntity.getAuthor()); + + // Проверка, что цена поменялась + Assertions.assertEquals(testYear, newEntity.getYear()); + Assertions.assertNotEquals(oldYear, newEntity.getYear()); + + // Проверка, что описание поменялось + Assertions.assertEquals(testDescription, newEntity.getDescription()); + Assertions.assertNotEquals(oldDescription, newEntity.getDescription()); + } + + @Test + @Order(3) + void delete() { + bookService.delete(3); + // Проверка, что после удаления в хранилище осталось 2 игры + Assertions.assertEquals(2, bookService.getAll(0).size()); + + final BookEntity last = bookService.get(2); + Assertions.assertEquals(2, last.getId()); + + final BookEntity newEntity = bookService + .create(new BookEntity(null, genreService.get(3), "книжка", "автор3", "год1", "описание")); + // Проверка, что в хранилище теперь снова 3 игры + Assertions.assertEquals(3, genreService.getAll().size()); + // Проверка, что id у добавленной игры стал 4 + Assertions.assertEquals(4, newEntity.getId()); + } +} diff --git a/lab2/src/test/java/com/example/demo/GenreServiceTests.java b/lab2/src/test/java/com/example/demo/GenreServiceTests.java new file mode 100644 index 0000000..eb35091 --- /dev/null +++ b/lab2/src/test/java/com/example/demo/GenreServiceTests.java @@ -0,0 +1,74 @@ +package com.example.demo; + +import org.junit.jupiter.api.Assertions; +import org.junit.jupiter.api.MethodOrderer.OrderAnnotation; +import org.junit.jupiter.api.Order; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.TestMethodOrder; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.boot.test.context.SpringBootTest; + +import com.example.demo.genres.model.GenreEntity; +import com.example.demo.genres.service.GenreService; +import com.example.demo.core.error.NotFoundException; + +@SpringBootTest +@TestMethodOrder(OrderAnnotation.class) +public class GenreServiceTests { + @Autowired + private GenreService genreService; + + @Test + void getTest() { + Assertions.assertThrows(NotFoundException.class, () -> genreService.get(0)); + } + + @Test + @Order(1) + void createTest() { + genreService.deleteAll(); + genreService.create(new GenreEntity(null, "Роман")); + genreService.create(new GenreEntity(null, "Комедия")); + final GenreEntity last = genreService.create(new GenreEntity(null, "Трагедия")); + + // Проверки, что значения равны. Первый параметр - эталон (ожидаемое значение), + // второй - получаемое значение + // проверка, что кол-во жанров в хранилище равно кол-ву добавленных (проверка, + // что все добавились) + + Assertions.assertEquals(3, genreService.getAll().size()); + // проверка, что в хранилище последний жанр тот жанр, который добавили последним + // (проверка, что всё правильно добавилось) + Assertions.assertEquals(last, genreService.get(3)); + } + + @Test + @Order(2) + void update() { + // на какое название будем менять название жанра + final String test = "Антиутопия"; + // получение последнего в списке жанра + final GenreEntity entity = genreService.get(3); + // запоминание его названия до обновления + final String oldName = entity.getName(); + // запоминание новых данных жанра + final GenreEntity newEntity = genreService.update(3, new GenreEntity(1, test)); + // Проверка, что название поменялось + Assertions.assertEquals(test, newEntity.getName()); + Assertions.assertNotEquals(oldName, newEntity.getName()); + } + + @Test + @Order(3) + void delete() { + genreService.delete(3); + // Проверка, что после удаления в хранилище осталось 2 жанра + Assertions.assertEquals(2, genreService.getAll().size()); + + final GenreEntity newEntity = genreService.create(new GenreEntity(null, "Стратегия")); + // Проверка, что в хранилище теперь снова 3 жанра + Assertions.assertEquals(3, genreService.getAll().size()); + // Проверка, что id у добавленного жанра стал 4 + Assertions.assertEquals(4, newEntity.getId()); + } +} diff --git a/lab2/src/test/java/com/example/demo/UserServiceTests.java b/lab2/src/test/java/com/example/demo/UserServiceTests.java new file mode 100644 index 0000000..0bfdeb2 --- /dev/null +++ b/lab2/src/test/java/com/example/demo/UserServiceTests.java @@ -0,0 +1,98 @@ +package com.example.demo; + +import org.junit.jupiter.api.TestMethodOrder; + +import org.junit.jupiter.api.Assertions; +import org.junit.jupiter.api.MethodOrderer.OrderAnnotation; +import org.junit.jupiter.api.Order; +import org.junit.jupiter.api.Test; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.boot.test.context.SpringBootTest; + +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; +import com.example.demo.users.model.UserEntity; +import com.example.demo.users.service.UserService; + +@SpringBootTest +@TestMethodOrder(OrderAnnotation.class) +public class UserServiceTests { + @Autowired + private UserService userService; + @Autowired + private BookService bookService; + @Autowired + private GenreService genreService; + + @Test + void getTest() { + Assertions.assertThrows(NotFoundException.class, () -> userService.get(0)); + } + + @Test + @Order(1) + void createTest() { + genreService.deleteAll(); + bookService.deleteAll(); + + genreService.create(new GenreEntity(null, "Роман")); + genreService.create(new GenreEntity(null, "Комедия")); + genreService.create(new GenreEntity(null, "Трагедия")); + + bookService.create(new BookEntity(null, genreService.get(1), "Гордость и предубеждение", null, null, null)); + bookService.create(new BookEntity(null, genreService.get(2), "Недоросль", null, null, null)); + bookService.create(new BookEntity(null, genreService.get(3), "Грозовой перевал", null, null, null)); + + userService.create(new UserEntity(null, "Пупа", "password", false)); + userService.create(new UserEntity(null, "Лупа", "password", false)); + + Assertions.assertEquals(2, userService.getAll().size()); + } + + @Test + @Order(2) + void update() { + // на какой ник будем менять ник пользователя + final String testName = "Вася"; + + // на какой пароль будем менять пароль пользователя + final String testPassword = "TEST PASSWORD"; + + // запоминание обновлённого пользователя + final UserEntity newEntity = userService.update(1, new UserEntity(1, testName, testPassword, true)); + + // Проверка, что кол-во пользователей до сих пор 2 + Assertions.assertEquals(2, userService.getAll().size()); + + Assertions.assertEquals(newEntity, userService.get(1)); + + // Проверка, что у пользователя нет игр + Assertions.assertEquals(0, userService.get(1).getBooks().size()); + + // Добавление пользователю 2 игр + userService.addBook(1, bookService.get(3)); + userService.addBook(1, bookService.get(2)); + // Проверка, что у пользователя теперь есть 2 игры + Assertions.assertEquals(2, userService.get(1).getBooks().size()); + + // Удаление у пользователя игры + userService.deleteBook(1, bookService.get(2)); + // Проверка, что у пользователя 1 игра + Assertions.assertEquals(1, userService.get(1).getBooks().size()); + } + + @Test + @Order(3) + void delete() { + userService.delete(1); + // Проверка, что после удаления в хранилище осталcя пользователей + Assertions.assertEquals(1, userService.getAll().size()); + + userService.create(new UserEntity(null, "Пупа", "password", false)); + // Проверка, что в хранилище теперь снова 2 пользователя + Assertions.assertEquals(2, userService.getAll().size()); + } +}