хромая третья лаба

This commit is contained in:
Allllen4a 2024-05-09 20:08:23 +04:00
commit 10311a3b0c
49 changed files with 100167 additions and 0 deletions

63
3 лаба/.gitignore vendored Normal file
View File

@ -0,0 +1,63 @@
# ---> VisualStudioCode
.vscode/*
!.vscode/settings.json
!.vscode/tasks.json
!.vscode/launch.json
!.vscode/extensions.json
!.vscode/*.code-snippets
# Local History for Visual Studio Code
.history/
# Built Visual Studio Code Extensions
*.vsix
# ---> Java
# Compiled class file
*.class
# Log file
*.log
# BlueJ files
*.ctxt
# Mobile Tools for Java (J2ME)
.mtj.tmp/
# Package Files #
*.jar
*.war
*.nar
*.ear
*.zip
*.tar.gz
*.rar
# virtual machine crash logs, see http://www.java.com/en/download/help/error_hotspot.xml
hs_err_pid*
replay_pid*
# ---> Gradle
.gradle
**/build/
!src/**/build/
# Ignore Gradle GUI config
gradle-app.setting
# Avoid ignoring Gradle wrapper jar file (.jar files are usually ignored)
!gradle-wrapper.jar
# Avoid ignore Gradle wrappper properties
!gradle-wrapper.properties
# Cache of project
.gradletasknamecache
# Eclipse Gradle plugin generated files
# Eclipse Core
.project
# JDT-specific (Eclipse Java Development Tools)
.classpath

14
3 лаба/.vscode/launch.json vendored Normal file
View File

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

4
3 лаба/.vscode/settings.json vendored Normal file
View File

@ -0,0 +1,4 @@
{
"java.configuration.updateBuildConfiguration": "automatic",
"java.debug.settings.onBuildFailureProceed": true
}

2
3 лаба/README.md Normal file
View File

@ -0,0 +1,2 @@
# PIbd-21_Bakalskaya_E.D._INTERNET_PROGRAMMING_BACKEND

37
3 лаба/backend/.gitignore vendored Normal file
View File

@ -0,0 +1,37 @@
HELP.md
.gradle
build/
!gradle/wrapper/gradle-wrapper.jar
!**/src/main/**/build/
!**/src/test/**/build/
### STS ###
.apt_generated
.classpath
.factorypath
.project
.settings
.springBeans
.sts4-cache
bin/
!**/src/main/**/bin/
!**/src/test/**/bin/
### IntelliJ IDEA ###
.idea
*.iws
*.iml
*.ipr
out/
!**/src/main/**/out/
!**/src/test/**/out/
### NetBeans ###
/nbproject/private/
/nbbuild/
/dist/
/nbdist/
/.nb-gradle/
### VS Code ###
.vscode/

View File

@ -0,0 +1,31 @@
plugins {
id 'java'
id 'org.springframework.boot' version '3.2.5'
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-data-jpa'
implementation 'com.h2database:h2:2.2.224'
testImplementation 'org.springframework.boot:spring-boot-starter-test'
}
tasks.named('test') {
useJUnitPlatform()
}

Binary file not shown.

File diff suppressed because it is too large Load Diff

Binary file not shown.

View File

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

249
3 лаба/backend/gradlew vendored Normal file
View File

@ -0,0 +1,249 @@
#!/bin/sh
#
# Copyright © 2015-2021 the original authors.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# https://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
#
##############################################################################
#
# Gradle start up script for POSIX generated by Gradle.
#
# Important for running:
#
# (1) You need a POSIX-compliant shell to run this script. If your /bin/sh is
# noncompliant, but you have some other compliant shell such as ksh or
# bash, then to run this script, type that shell name before the whole
# command line, like:
#
# ksh Gradle
#
# Busybox and similar reduced shells will NOT work, because this script
# requires all of these POSIX shell features:
# * functions;
# * expansions «$var», «${var}», «${var:-default}», «${var+SET}»,
# «${var#prefix}», «${var%suffix}», and «$( cmd )»;
# * compound commands having a testable exit status, especially «case»;
# * various built-in commands including «command», «set», and «ulimit».
#
# Important for patching:
#
# (2) This script targets any POSIX shell, so it avoids extensions provided
# by Bash, Ksh, etc; in particular arrays are avoided.
#
# The "traditional" practice of packing multiple parameters into a
# space-separated string is a well documented source of bugs and security
# problems, so this is (mostly) avoided, by progressively accumulating
# options in "$@", and eventually passing that to Java.
#
# Where the inherited environment variables (DEFAULT_JVM_OPTS, JAVA_OPTS,
# and GRADLE_OPTS) rely on word-splitting, this is performed explicitly;
# see the in-line comments for details.
#
# There are tweaks for specific operating systems such as AIX, CygWin,
# Darwin, MinGW, and NonStop.
#
# (3) This script is generated from the Groovy template
# https://github.com/gradle/gradle/blob/HEAD/subprojects/plugins/src/main/resources/org/gradle/api/internal/plugins/unixStartScript.txt
# within the Gradle project.
#
# You can find Gradle at https://github.com/gradle/gradle/.
#
##############################################################################
# Attempt to set APP_HOME
# Resolve links: $0 may be a link
app_path=$0
# Need this for daisy-chained symlinks.
while
APP_HOME=${app_path%"${app_path##*/}"} # leaves a trailing /; empty if no leading path
[ -h "$app_path" ]
do
ls=$( ls -ld "$app_path" )
link=${ls#*' -> '}
case $link in #(
/*) app_path=$link ;; #(
*) app_path=$APP_HOME$link ;;
esac
done
# This is normally unused
# shellcheck disable=SC2034
APP_BASE_NAME=${0##*/}
# Discard cd standard output in case $CDPATH is set (https://github.com/gradle/gradle/issues/25036)
APP_HOME=$( cd "${APP_HOME:-./}" > /dev/null && pwd -P ) || exit
# Use the maximum available, or set MAX_FD != -1 to use that value.
MAX_FD=maximum
warn () {
echo "$*"
} >&2
die () {
echo
echo "$*"
echo
exit 1
} >&2
# OS specific support (must be 'true' or 'false').
cygwin=false
msys=false
darwin=false
nonstop=false
case "$( uname )" in #(
CYGWIN* ) cygwin=true ;; #(
Darwin* ) darwin=true ;; #(
MSYS* | MINGW* ) msys=true ;; #(
NONSTOP* ) nonstop=true ;;
esac
CLASSPATH=$APP_HOME/gradle/wrapper/gradle-wrapper.jar
# Determine the Java command to use to start the JVM.
if [ -n "$JAVA_HOME" ] ; then
if [ -x "$JAVA_HOME/jre/sh/java" ] ; then
# IBM's JDK on AIX uses strange locations for the executables
JAVACMD=$JAVA_HOME/jre/sh/java
else
JAVACMD=$JAVA_HOME/bin/java
fi
if [ ! -x "$JAVACMD" ] ; then
die "ERROR: JAVA_HOME is set to an invalid directory: $JAVA_HOME
Please set the JAVA_HOME variable in your environment to match the
location of your Java installation."
fi
else
JAVACMD=java
if ! command -v java >/dev/null 2>&1
then
die "ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH.
Please set the JAVA_HOME variable in your environment to match the
location of your Java installation."
fi
fi
# Increase the maximum file descriptors if we can.
if ! "$cygwin" && ! "$darwin" && ! "$nonstop" ; then
case $MAX_FD in #(
max*)
# In POSIX sh, ulimit -H is undefined. That's why the result is checked to see if it worked.
# shellcheck disable=SC2039,SC3045
MAX_FD=$( ulimit -H -n ) ||
warn "Could not query maximum file descriptor limit"
esac
case $MAX_FD in #(
'' | soft) :;; #(
*)
# In POSIX sh, ulimit -n is undefined. That's why the result is checked to see if it worked.
# shellcheck disable=SC2039,SC3045
ulimit -n "$MAX_FD" ||
warn "Could not set maximum file descriptor limit to $MAX_FD"
esac
fi
# Collect all arguments for the java command, stacking in reverse order:
# * args from the command line
# * the main class name
# * -classpath
# * -D...appname settings
# * --module-path (only if needed)
# * DEFAULT_JVM_OPTS, JAVA_OPTS, and GRADLE_OPTS environment variables.
# For Cygwin or MSYS, switch paths to Windows format before running java
if "$cygwin" || "$msys" ; then
APP_HOME=$( cygpath --path --mixed "$APP_HOME" )
CLASSPATH=$( cygpath --path --mixed "$CLASSPATH" )
JAVACMD=$( cygpath --unix "$JAVACMD" )
# Now convert the arguments - kludge to limit ourselves to /bin/sh
for arg do
if
case $arg in #(
-*) false ;; # don't mess with options #(
/?*) t=${arg#/} t=/${t%%/*} # looks like a POSIX filepath
[ -e "$t" ] ;; #(
*) false ;;
esac
then
arg=$( cygpath --path --ignore --mixed "$arg" )
fi
# Roll the args list around exactly as many times as the number of
# args, so each arg winds up back in the position where it started, but
# possibly modified.
#
# NB: a `for` loop captures its iteration list before it begins, so
# changing the positional parameters here affects neither the number of
# iterations, nor the values presented in `arg`.
shift # remove old arg
set -- "$@" "$arg" # push replacement arg
done
fi
# Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script.
DEFAULT_JVM_OPTS='"-Xmx64m" "-Xms64m"'
# Collect all arguments for the java command:
# * DEFAULT_JVM_OPTS, JAVA_OPTS, JAVA_OPTS, and optsEnvironmentVar are not allowed to contain shell fragments,
# and any embedded shellness will be escaped.
# * For example: A user cannot expect ${Hostname} to be expanded, as it is an environment variable and will be
# treated as '${Hostname}' itself on the command line.
set -- \
"-Dorg.gradle.appname=$APP_BASE_NAME" \
-classpath "$CLASSPATH" \
org.gradle.wrapper.GradleWrapperMain \
"$@"
# Stop when "xargs" is not available.
if ! command -v xargs >/dev/null 2>&1
then
die "xargs is not available"
fi
# Use "xargs" to parse quoted args.
#
# With -n1 it outputs one arg per line, with the quotes and backslashes removed.
#
# In Bash we could simply go:
#
# readarray ARGS < <( xargs -n1 <<<"$var" ) &&
# set -- "${ARGS[@]}" "$@"
#
# but POSIX shell has neither arrays nor command substitution, so instead we
# post-process each arg (as a line of input to sed) to backslash-escape any
# character that might be a shell metacharacter, then use eval to reverse
# that process (while maintaining the separation between arguments), and wrap
# the whole thing up as a single "set" statement.
#
# This will of course break if any of these variables contains a newline or
# an unmatched quote.
#
eval "set -- $(
printf '%s\n' "$DEFAULT_JVM_OPTS $JAVA_OPTS $GRADLE_OPTS" |
xargs -n1 |
sed ' s~[^-[:alnum:]+,./:=@_]~\\&~g; ' |
tr '\n' ' '
)" '"$@"'
exec "$JAVACMD" "$@"

92
3 лаба/backend/gradlew.bat vendored Normal file
View File

@ -0,0 +1,92 @@
@rem
@rem Copyright 2015 the original author or authors.
@rem
@rem Licensed under the Apache License, Version 2.0 (the "License");
@rem you may not use this file except in compliance with the License.
@rem You may obtain a copy of the License at
@rem
@rem https://www.apache.org/licenses/LICENSE-2.0
@rem
@rem Unless required by applicable law or agreed to in writing, software
@rem distributed under the License is distributed on an "AS IS" BASIS,
@rem WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
@rem See the License for the specific language governing permissions and
@rem limitations under the License.
@rem
@if "%DEBUG%"=="" @echo off
@rem ##########################################################################
@rem
@rem Gradle startup script for Windows
@rem
@rem ##########################################################################
@rem Set local scope for the variables with windows NT shell
if "%OS%"=="Windows_NT" setlocal
set DIRNAME=%~dp0
if "%DIRNAME%"=="" set DIRNAME=.
@rem This is normally unused
set APP_BASE_NAME=%~n0
set APP_HOME=%DIRNAME%
@rem Resolve any "." and ".." in APP_HOME to make it shorter.
for %%i in ("%APP_HOME%") do set APP_HOME=%%~fi
@rem Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script.
set DEFAULT_JVM_OPTS="-Xmx64m" "-Xms64m"
@rem Find java.exe
if defined JAVA_HOME goto findJavaFromJavaHome
set JAVA_EXE=java.exe
%JAVA_EXE% -version >NUL 2>&1
if %ERRORLEVEL% equ 0 goto execute
echo.
echo ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH.
echo.
echo Please set the JAVA_HOME variable in your environment to match the
echo location of your Java installation.
goto fail
:findJavaFromJavaHome
set JAVA_HOME=%JAVA_HOME:"=%
set JAVA_EXE=%JAVA_HOME%/bin/java.exe
if exist "%JAVA_EXE%" goto execute
echo.
echo ERROR: JAVA_HOME is set to an invalid directory: %JAVA_HOME%
echo.
echo Please set the JAVA_HOME variable in your environment to match the
echo location of your Java installation.
goto fail
:execute
@rem Setup the command line
set CLASSPATH=%APP_HOME%\gradle\wrapper\gradle-wrapper.jar
@rem Execute Gradle
"%JAVA_EXE%" %DEFAULT_JVM_OPTS% %JAVA_OPTS% %GRADLE_OPTS% "-Dorg.gradle.appname=%APP_BASE_NAME%" -classpath "%CLASSPATH%" org.gradle.wrapper.GradleWrapperMain %*
:end
@rem End local scope for the variables with windows NT shell
if %ERRORLEVEL% equ 0 goto mainEnd
:fail
rem Set variable GRADLE_EXIT_CONSOLE if you need the _script_ return code instead of
rem the _cmd.exe /c_ return code!
set EXIT_CODE=%ERRORLEVEL%
if %EXIT_CODE% equ 0 set EXIT_CODE=1
if not ""=="%GRADLE_EXIT_CONSOLE%" exit %EXIT_CODE%
exit /b %EXIT_CODE%
:mainEnd
if "%OS%"=="Windows_NT" endlocal
:omega

View File

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

View File

@ -0,0 +1,61 @@
package com.example.backend;
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.backend.books.model.BookEntity;
import com.example.backend.books.service.BookService;
import com.example.backend.genres.model.GenreEntity;
import com.example.backend.genres.service.GenreService;
// create lab 2
@SpringBootApplication
public class BackendApplication implements CommandLineRunner {
private final Logger _logger = LoggerFactory.getLogger(BackendApplication.class);
private final GenreService genreService;
private final BookService bookService;
public BackendApplication(GenreService genreService, BookService bookService) {
this.genreService = genreService;
this.bookService = bookService;
}
public static void main(String[] args) {
SpringApplication.run(BackendApplication.class, args);
}
@Override
public void run(String... args) throws Exception {
if (args.length > 0 && Objects.equals("--populate", args[0])) {
_logger.info("Create default categories values");
final var genre1 = genreService.create(new GenreEntity(1,
"Драма"));
final var genre2 = genreService.create(new GenreEntity(2,
"Комедия"));
final var genre3 = genreService.create(new GenreEntity(4,
"Хоррор"));
_logger.info("Create default movies values");
bookService.create(new BookEntity(1, genre3, "Астрал", "1", "1", "1"));
bookService.create(new BookEntity(1, genre1, "Хатико", "2", "2", "2"));
bookService.create(new BookEntity(1, genre2, "Бабушка легкого ", "3", "3", "3"));
bookService.create(new BookEntity(1, genre3, "Пиковая дама", "4", "4",
"4"));
bookService.create(new BookEntity(1, genre3, "Баба-Яга", "5", "5", "5"));
}
}
}

View File

@ -0,0 +1,53 @@
package com.example.backend;
import com.fasterxml.jackson.annotation.JsonCreator;
import com.fasterxml.jackson.annotation.JsonProperty;
public class TestDTO {
private Integer id;
private String name;
private String img;
public TestDTO() {
}
@JsonCreator
public TestDTO(
@JsonProperty(value = "id") Integer id,
@JsonProperty(value = "name") String name,
@JsonProperty(value = "img") String img) {
this.id = id;
this.name = name;
this.img = img;
}
// GET
public Integer getId() {
return id;
}
public String getName() {
return name;
}
public String getImg() {
return img;
}
// SET
public void setId(Integer Id) {
id = Id;
}
public void setName(String Name) {
name = Name;
}
public void setImg(String Img) {
img = Img;
}
}

View File

@ -0,0 +1,74 @@
package com.example.backend.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.backend.books.model.BookEntity;
import com.example.backend.books.service.BookService;
import com.example.backend.core.configurations.Constants;
import com.example.backend.genres.service.GenreService;
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<BookDTO> 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));
}
}

View File

@ -0,0 +1,81 @@
package com.example.backend.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 Integer id;
@NotNull
@Min(1)
private Integer genreId;
@NotBlank
@Size(min = 2, max = 50)
private String name;
@NotBlank
@Size(min = 2, max = 50)
private String description;
@NotBlank
@Size(min = 2, max = 50)
private String duration;
private String image;
@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 getDescription() {
return description;
}
public void setDescription(String description) {
this.description = description;
}
public String getDuration() {
return duration;
}
public void setDuration(String duration) {
this.duration = duration;
}
public String getImage() {
return image;
}
public void setImage(String image) {
this.image = image;
}
}

View File

@ -0,0 +1,108 @@
package com.example.backend.books.model;
import java.util.Objects;
import com.example.backend.core.model.BaseEntity;
import com.example.backend.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;
@Column(nullable = false, unique = true, length = 50)
private String name;
@Column(nullable = false, unique = true, length = 300)
private String description;
@Column(nullable = false, unique = true, length = 50)
private String duration;
@Column(nullable = true)
private String image;
public BookEntity() {
super();
}
public BookEntity(Integer id, GenreEntity genre, String name, String description, String duration,
String image) {
this.genre = genre;
this.name = name;
this.description = description;
this.duration = duration;
this.image = image;
}
public GenreEntity getGenre() {
return genre;
}
public void setGenre(GenreEntity genre) {
this.genre = genre;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getDescription() {
return description;
}
public void setDescription(String description) {
this.description = description;
}
public String getDuration() {
return duration;
}
public void setDuration(String duration) {
this.duration = duration;
}
public String getImage() {
return image;
}
public void setImage(String image) {
this.image = image;
}
@Override
public int hashCode() {
return Objects.hash(id, genre, name, description, duration, image);
}
@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.getDescription(), description)
&& Objects.equals(other.getDuration(), duration)
&& Objects.equals(other.getImage(), image);
}
}

View File

@ -0,0 +1,22 @@
package com.example.backend.books.repository;
import java.util.Optional;
import java.util.List;
import org.springframework.data.jpa.repository.Query;
import org.springframework.data.repository.CrudRepository;
import org.springframework.data.repository.query.Param;
import com.example.backend.books.model.BookEntity;
public interface BookRepository extends CrudRepository<BookEntity, Integer> {
Optional<BookEntity> findByNameIgnoreCase(String name);
Optional<BookEntity> findByGenreIdAndId(Integer genreId, Integer id);
List<BookEntity> findByGenreId(Integer genreId);
}

View File

@ -0,0 +1,71 @@
package com.example.backend.books.service;
import java.util.List;
import java.util.stream.StreamSupport;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import com.example.backend.books.model.BookEntity;
import com.example.backend.books.repository.BookRepository;
import com.example.backend.core.errors.NotFoundException;
@Service
public class BookService {
private final BookRepository repository;
public BookService(BookRepository repository) {
this.repository = repository;
}
private void checkName(String name) {
if (repository.findByNameIgnoreCase(name).isPresent()) {
throw new IllegalArgumentException(
String.format("Type with name %s is already exists", name));
}
}
@Transactional(readOnly = true)
public List<BookEntity> getAll(Integer genreId) {
if (genreId == 0) {
return StreamSupport.stream(repository.findAll().spliterator(), false).toList();
}
return repository.findByGenreId(genreId);
}
@Transactional(readOnly = true)
public BookEntity get(Integer id) {
return repository.findById(id).orElseThrow(() -> new NotFoundException(id));
}
@Transactional
public BookEntity create(BookEntity entity) {
if (entity == null) {
throw new IllegalArgumentException("Сущность не найдена");
}
checkName(entity.getName());
return repository.save(entity);
}
@Transactional
public BookEntity update(Integer id, BookEntity entity) {
final BookEntity exisEntity = get(id);
exisEntity.setGenre(entity.getGenre());
exisEntity.setName(entity.getName());
exisEntity.setDescription(entity.getDescription());
exisEntity.setDuration(entity.getDuration());
exisEntity.setImage(entity.getImage());
return repository.save(exisEntity);
}
@Transactional
public BookEntity delete(Integer id) {
final BookEntity exisEntity = get(id);
repository.delete(exisEntity);
return exisEntity;
}
}

View File

@ -0,0 +1,9 @@
package com.example.backend.core.configurations;
public class Constants {
public static final String API_URL = "/api";
public static final String SEQUENCE_NAME = "hibernate_sequence";
private Constants() {
}
}

View File

@ -0,0 +1,13 @@
package com.example.backend.core.configurations;
import org.modelmapper.ModelMapper;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
@Configuration
public class MapperConfiguration {
@Bean
ModelMapper modelMapper() {
return new ModelMapper();
}
}

View File

@ -0,0 +1,16 @@
package com.example.backend.core.configurations;
import org.springframework.context.annotation.Configuration;
import org.springframework.lang.NonNull;
import org.springframework.web.servlet.config.annotation.CorsRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
@Configuration
public class WebConfig implements WebMvcConfigurer{
@Override
public void addCorsMappings(@NonNull CorsRegistry registry){
registry.addMapping("/**")
.allowedMethods("GET", "POST", "PUT", "DELETE");
}
}

View File

@ -0,0 +1,7 @@
package com.example.backend.core.errors;
public class NotFoundException extends RuntimeException {
public NotFoundException(Integer id) {
super(String.format("Сущность с айдишником <[%s]> не найден, либо его не существует", id));
}
}

View File

@ -0,0 +1,7 @@
package com.example.backend.core.errors;
public class NullArgumentException extends RuntimeException {
public NullArgumentException(Integer id) {
super(String.format("В данной сущности нет объектов в айдишником <[%s]>", id));
}
}

View File

@ -0,0 +1,28 @@
package com.example.backend.core.model;
import com.example.backend.core.configurations.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 Integer id;
protected BaseEntity() {
}
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
}

View File

@ -0,0 +1,77 @@
package com.example.backend.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.backend.books.service.BookService;
import com.example.backend.core.configurations.Constants;
import com.example.backend.favorites.model.FavoriteEntity;
import com.example.backend.favorites.service.FavoriteService;
import com.example.backend.users.service.UserService;
import jakarta.validation.Valid;
@RestController
@RequestMapping(Constants.API_URL + "/favorite")
public class FavoriteController {
private final FavoriteService favoriteService;
private final UserService userService;
private final BookService bookService;
private final ModelMapper modelMapper;
public FavoriteController(FavoriteService favoriteService, UserService userService,
BookService bookService, ModelMapper modelMapper) {
this.modelMapper = modelMapper;
this.userService = userService;
this.favoriteService = favoriteService;
this.bookService = bookService;
}
private FavoriteDto toDto(FavoriteEntity entity) {
return modelMapper.map(entity, FavoriteDto.class);
}
private FavoriteEntity toEntity(FavoriteDto dto) {
final FavoriteEntity entity = modelMapper.map(dto, FavoriteEntity.class);
entity.setBook(bookService.get(dto.getBookId()));
entity.setUser(userService.get(dto.getUserId()));
return entity;
}
@GetMapping
public List<FavoriteDto> getAll(@RequestParam(name = "userId", defaultValue = "0") Integer userId) {
return favoriteService.getAll(userId).stream().map(this::toDto).toList();
}
@GetMapping("/{id}")
public FavoriteDto get(@PathVariable(name = "id") Integer 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") Integer id,
@RequestBody FavoriteDto dto) {
return toDto(favoriteService.update(id, toEntity(dto)));
}
@DeleteMapping("/{id}")
public FavoriteDto delete(@PathVariable(name = "id") Integer id) {
return toDto(favoriteService.delete(id));
}
}

View File

@ -0,0 +1,45 @@
package com.example.backend.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 Integer id;
@NotNull
@Min(1)
private Integer userId;
@NotNull
@Min(1)
private Integer bookId;
@JsonProperty(access = JsonProperty.Access.READ_ONLY)
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public Integer getUserId() {
return userId;
}
public void setUserId(Integer userId) {
this.userId = userId;
}
public Integer getBookId() {
return bookId;
}
public void setBookId(Integer bookId) {
this.bookId = bookId;
}
}

View File

@ -0,0 +1,67 @@
package com.example.backend.favorites.model;
import java.util.Objects;
import com.example.backend.books.model.BookEntity;
import com.example.backend.core.model.BaseEntity;
import com.example.backend.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);
}
}

View File

@ -0,0 +1,5 @@
package com.example.backend.favorites.repository;
public class CrudRepository<T1, T2> {
}

View File

@ -0,0 +1,13 @@
package com.example.backend.favorites.repository;
import java.util.Optional;
import java.util.List;
import org.springframework.data.repository.CrudRepository;
import com.example.backend.favorites.model.FavoriteEntity;
public interface FavoriteRepository extends CrudRepository<FavoriteEntity, Integer> {
List<FavoriteEntity> findByUserId(Integer userId);
Optional<FavoriteEntity> findOneByUserIdAndId(Integer userId, Integer id);
}

View File

@ -0,0 +1,53 @@
package com.example.backend.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.backend.core.errors.NotFoundException;
import com.example.backend.favorites.model.FavoriteEntity;
import com.example.backend.favorites.repository.FavoriteRepository;
@Service
public class FavoriteService {
private final FavoriteRepository repository;
public FavoriteService(FavoriteRepository repository) {
this.repository = repository;
}
@Transactional(readOnly = true)
public List<FavoriteEntity> getAll(Integer userId) {
if (userId == 0) {
return StreamSupport.stream(repository.findAll().spliterator(), false).toList();
}
return repository.findByUserId(userId);
}
@Transactional(readOnly = true)
public FavoriteEntity get(Integer id) {
return repository.findById(id).orElseThrow(() -> new NotFoundException(id));
}
@Transactional
public FavoriteEntity create(FavoriteEntity entity) {
return repository.save(entity);
}
@Transactional
public FavoriteEntity update(Integer id, FavoriteEntity entity) {
final FavoriteEntity exisEntity = get(id);
exisEntity.setUser(entity.getUser());
exisEntity.setBook(entity.getBook());
return repository.save(exisEntity);
}
@Transactional
public FavoriteEntity delete(Integer id) {
final FavoriteEntity exisEntity = get(id);
repository.delete(exisEntity);
return exisEntity;
}
}

View File

@ -0,0 +1,69 @@
package com.example.backend.genres.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.backend.core.configurations.Constants;
import com.example.backend.genres.model.GenreEntity;
import com.example.backend.genres.service.GenreService;
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.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.PutMapping;
@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 genreDTO) {
return modelMapper.map(genreDTO, GenreEntity.class);
}
@GetMapping()
public List<GenreDTO> 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 genreDTO) {
return toDto(genreService.create(toEntity(genreDTO)));
}
@PutMapping("/{id}")
public GenreDTO update(@PathVariable(name = "id") Integer id, @RequestBody GenreDTO genreDTO) {
return toDto(genreService.update(id, toEntity(genreDTO)));
}
@DeleteMapping("/{id}")
public GenreDTO delete(@PathVariable(name = "id") Integer id) {
return toDto(genreService.delete(id));
}
}

View File

@ -0,0 +1,37 @@
package com.example.backend.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 Integer id;
@NotBlank
@Size(min = 5, max = 50)
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;
}
}

View File

@ -0,0 +1,53 @@
package com.example.backend.genres.model;
import java.util.Objects;
import com.example.backend.core.model.BaseEntity;
import jakarta.persistence.Column;
import jakarta.persistence.Entity;
import jakarta.persistence.Table;
@Entity
@Table(name = "genres")
public class GenreEntity extends BaseEntity {
@Column(nullable = false, unique = true, length = 50)
private String name;
public GenreEntity() {
}
public GenreEntity(Integer id, String name) {
this.name = name;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
@Override
public int hashCode() {
return Objects.hash(id, name);
}
@Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null || getClass() != obj.getClass())
return false;
final GenreEntity other = (GenreEntity) obj;
return Objects.equals(other.getId(), id) &&
Objects.equals(other.getName(), name);
}
}

View File

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

View File

@ -0,0 +1,63 @@
package com.example.backend.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.backend.core.errors.NotFoundException;
import com.example.backend.genres.model.GenreEntity;
import com.example.backend.genres.repository.GenreRepository;
@Service
public class GenreService {
private final GenreRepository repository;
public GenreService(GenreRepository repository) {
this.repository = repository;
}
private void checkName(String name) {
if (repository.findByNameIgnoreCase(name).isPresent()) {
throw new IllegalArgumentException(
String.format("Type with name %s is already exists", name));
}
}
@Transactional(readOnly = true)
public List<GenreEntity> getAll() {
return StreamSupport.stream(repository.findAll().spliterator(), false).toList();
}
@Transactional(readOnly = true)
public GenreEntity get(Integer id) {
return repository.findById(id).orElseThrow(() -> new NotFoundException(id));
}
@Transactional
public GenreEntity create(GenreEntity entity) {
if (entity == null) {
throw new IllegalArgumentException("Сущность не найдена");
}
checkName(entity.getName());
return repository.save(entity);
}
@Transactional
public GenreEntity update(Integer id, GenreEntity entity) {
final GenreEntity existsentity = get(id);
existsentity.setName(entity.getName());
return repository.save(existsentity);
}
@Transactional
public GenreEntity delete(Integer id) {
final GenreEntity existsentity = get(id);
repository.delete(existsentity);
return existsentity;
}
}

View File

@ -0,0 +1,66 @@
package com.example.backend.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.backend.core.configurations.Constants;
import com.example.backend.users.model.UserEntity;
import com.example.backend.users.service.UserService;
import jakarta.validation.Valid;
@RestController
@RequestMapping(Constants.API_URL + "/user")
public class UserController {
private final UserService userService;
private final ModelMapper modelMapper;
public UserController(UserService userService, ModelMapper modelMapper) {
this.modelMapper = modelMapper;
this.userService = userService;
}
private UserEntity toEntity(UserDTO dto) {
return modelMapper.map(dto, UserEntity.class);
}
private UserDTO toDto(UserEntity entity) {
return modelMapper.map(entity, UserDTO.class);
}
@GetMapping()
public List<UserDTO> getAll() {
return userService.getAll().stream().map(this::toDto).toList();
}
@GetMapping("/{id}")
public UserDTO get(@PathVariable(name = "id") Integer 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") 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));
}
}

View File

@ -0,0 +1,57 @@
package com.example.backend.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 Integer 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 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;
}
}

View File

@ -0,0 +1,75 @@
package com.example.backend.users.model;
import java.util.Objects;
import com.example.backend.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 = 5)
private String password;
@Column(nullable = false)
private boolean isAdmin;
public UserEntity() {
}
public UserEntity(Integer id, 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);
}
}

View File

@ -0,0 +1,10 @@
package com.example.backend.users.repository;
import java.util.Optional;
import org.springframework.data.repository.CrudRepository;
import com.example.backend.users.model.UserEntity;
public interface UserRepository extends CrudRepository<UserEntity, Integer> {
Optional<UserEntity> findByUsernameIgnoreCase(String username);
}

View File

@ -0,0 +1,53 @@
package com.example.backend.users.service;
import java.util.List;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import java.util.stream.StreamSupport;
import com.example.backend.core.errors.NotFoundException;
import com.example.backend.users.model.UserEntity;
import com.example.backend.users.repository.UserRepository;
@Service
public class UserService {
private final UserRepository repository;
public UserService(UserRepository repository) {
this.repository = repository;
}
@Transactional(readOnly = true)
public List<UserEntity> getAll() {
return StreamSupport.stream(repository.findAll().spliterator(), false).toList();
}
@Transactional(readOnly = true)
public UserEntity get(Integer id) {
return repository.findById(id).orElseThrow(() -> new NotFoundException(id));
}
@Transactional
public UserEntity create(UserEntity entity) {
return repository.save(entity);
}
@Transactional
public UserEntity update(Integer 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(Integer id) {
final UserEntity existsentity = get(id);
repository.delete(existsentity);
return existsentity;
}
}

View File

@ -0,0 +1,20 @@
# Server
spring.main.banner-mode=off
server.port=8080
# Logger settings
# Available levels are: TRACE, DEBUG, INFO, WARN, ERROR, FATAL, OFF
logging.level.com.example.demo=DEBUG
# JPA Settings
spring.datasource.url=jdbc:h2:file:./data
spring.datasource.username=alyona
spring.datasource.password=alyona
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

View File

@ -0,0 +1,129 @@
package com.example.backend;
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.backend.books.model.BookEntity;
import com.example.backend.books.service.BookService;
import com.example.backend.core.errors.NotFoundException;
import com.example.backend.genres.model.GenreEntity;
import com.example.backend.genres.service.GenreService;
import com.example.backend.users.model.UserEntity;
import com.example.backend.users.service.UserService;
@SpringBootTest
@TestMethodOrder(OrderAnnotation.class)
class BookServiceTest {
@Autowired
private BookService bookService;
private BookEntity book;
private BookEntity book2;
@Autowired
private GenreService genreService;
private GenreEntity cat;
@Autowired
private UserService userService;
private UserEntity user;
private UserEntity user1;
private UserEntity user2;
private UserEntity user3;
@BeforeEach
void createData() {
removeData();
cat = genreService.create(new GenreEntity(0, "Drama"));
user = userService.create(new UserEntity(0, "1", "1", true));
user1 = userService.create(new UserEntity(0, "2", "2", true));
user2 = userService.create(new UserEntity(0, "3", "3", true));
user3 = userService.create(new UserEntity(0, "4", "4", true));
book = bookService.create(new BookEntity(0, cat, "1", "1", "1", "1"));
book2 = bookService.create(new BookEntity(0, cat, "2", "2", "2", "2"));
}
@AfterEach
void removeData() {
userService.getAll().forEach(u -> userService.delete(u.getId()));
bookService.getAll(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(10));
}
@Test
@Order(2)
void createTest() {
Assertions.assertEquals(2, bookService.getAll(cat.getId()).size());
Assertions.assertEquals(book, bookService.get(book.getId()));
}
@Test
@Order(3)
void createNotUniqueTest() {
final BookEntity nonUniqueGenre = new BookEntity(3, cat, "1", "1", "1",
"1");
Assertions.assertThrows(IllegalArgumentException.class, () -> bookService.create(nonUniqueGenre));
}
@Test
@Order(4)
void createNullableTest() {
final BookEntity nullableGenre = new BookEntity(1, cat, null, "1", "1",
"1");
Assertions.assertThrows(DataIntegrityViolationException.class, () -> bookService.create(
nullableGenre));
}
@Test
@Order(5)
void updateTest() {
final String newName = "TEST";
final String oldName = book.getName();
final BookEntity mov = new BookEntity(book.getId(), book.getGenre(),
newName, book.getDescription(),
book.getDuration(), book.getImage());
final BookEntity newEntity = bookService.update(book.getId(), mov);
Assertions.assertEquals(newName, newEntity.getName());
Assertions.assertNotEquals(oldName, newEntity.getName());
}
@Test
@Order(6)
void deleteTest() {
bookService.delete(book2.getId());
Assertions.assertEquals(1, bookService.getAll(cat.getId()).size());
Assertions.assertNotEquals(3, bookService.getAll(cat.getId()).size());
}
}

View File

@ -0,0 +1,103 @@
package com.example.backend;
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.backend.books.model.BookEntity;
import com.example.backend.books.service.BookService;
import com.example.backend.core.errors.NotFoundException;
import com.example.backend.favorites.model.FavoriteEntity;
import com.example.backend.favorites.service.FavoriteService;
import com.example.backend.genres.model.GenreEntity;
import com.example.backend.genres.service.GenreService;
import com.example.backend.users.model.UserEntity;
import com.example.backend.users.service.UserService;
@SpringBootTest
@TestMethodOrder(OrderAnnotation.class)
public class FavoriteServiceTests {
@Autowired
private FavoriteService favoriteService;
private FavoriteEntity lastFavorite;
private FavoriteEntity lastFavorite2;
private GenreEntity cat1;
private BookEntity mov1;
private BookEntity mov2;
private UserEntity us1;
@Autowired
private GenreService genreService;
@Autowired
private BookService bookService;
@Autowired
private UserService userService;
@BeforeEach
void createData() {
removeData();
cat1 = genreService.create(new GenreEntity(null, "Драма"));
mov1 = bookService.create(new BookEntity(null, cat1, "Хатико", "какой-то фильм",
"1", "1"));
mov2 = bookService.create(new BookEntity(null, cat1, "Унесеснные призраками",
"2", "2", "2"));
us1 = userService.create(new UserEntity(null, "elina", "123", true));
lastFavorite = favoriteService.create(new FavoriteEntity(null, us1, mov1));
lastFavorite2 = favoriteService.create(new FavoriteEntity(null, us1, mov2));
}
@AfterEach
void removeData() {
favoriteService.getAll(0).forEach(fv -> favoriteService.delete(fv.getId()));
userService.getAll().forEach(u -> userService.delete(u.getId()));
bookService.getAll(0).forEach(item -> bookService.delete(item.getId()));
genreService.getAll().forEach(item -> genreService.delete(item.getId()));
}
@Test
void getTest() {
Assertions.assertThrows(NotFoundException.class, () -> favoriteService.get(0));
}
@Test
void createTest() {
Assertions.assertEquals(2, favoriteService.getAll(us1.getId()).size());
}
@Test
void update() {
final FavoriteEntity fav = favoriteService.create(new FavoriteEntity(null, us1, mov2));
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(us1.getId()).size());
}
}

View File

@ -0,0 +1,77 @@
package com.example.backend;
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.backend.core.errors.NotFoundException;
import com.example.backend.genres.model.GenreEntity;
import com.example.backend.genres.service.GenreService;
@SpringBootTest
class GenreServiceTests {
@Autowired
private GenreService genreService;
private GenreEntity genre;
@BeforeEach
void createData() {
removeData();
genre = genreService.create(new GenreEntity(1, "Drama"));
genreService.create(new GenreEntity(2, "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(1, "Drama");
Assertions.assertThrows(IllegalArgumentException.class, () -> genreService.create(nonUniqueGenre));
}
@Test
void createNullableTest() {
final GenreEntity nullableGenre = new GenreEntity(1, 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(genre.getId(), 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());
}
}

View File

@ -0,0 +1,74 @@
package com.example.backend;
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.backend.core.errors.NotFoundException;
import com.example.backend.users.model.UserEntity;
import com.example.backend.users.service.UserService;
@SpringBootTest
@TestMethodOrder(OrderAnnotation.class)
public class UserServiceTests {
@Autowired
private UserService userService;
private UserEntity firstUser;
@BeforeEach
void createData() {
removeData();
firstUser = userService.create(new UserEntity(null, "elina", "123", true));
userService.create(new UserEntity(null, "oleg", "789", false));
userService.create(new UserEntity(null, "nikita", "456", false));
}
@AfterEach
void removeData() {
userService.getAll().forEach(item -> userService.delete(item.getId()));
}
@Test
void getTest() {
Assertions.assertThrows(NotFoundException.class, () -> userService.get(0));
}
@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(null, 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());
}
}

BIN
3 лаба/data.mv.db Normal file

Binary file not shown.

74
3 лаба/data.trace.db Normal file
View File

@ -0,0 +1,74 @@
2024-04-15 12:19:20.050452+04:00 database: wrong user or password; user: "SA"
org.h2.message.DbException: Неверное имя пользователя или пароль
Wrong user name or password [28000-224]
at org.h2.message.DbException.get(DbException.java:223)
at org.h2.message.DbException.get(DbException.java:199)
at org.h2.message.DbException.get(DbException.java:188)
at org.h2.engine.Engine.openSession(Engine.java:154)
at org.h2.engine.Engine.openSession(Engine.java:222)
at org.h2.engine.Engine.createSession(Engine.java:201)
at org.h2.engine.SessionRemote.connectEmbeddedOrServer(SessionRemote.java:343)
at org.h2.jdbc.JdbcConnection.<init>(JdbcConnection.java:125)
at org.h2.util.JdbcUtils.getConnection(JdbcUtils.java:288)
at org.h2.server.web.WebServer.getConnection(WebServer.java:811)
at org.h2.server.web.WebApp.login(WebApp.java:1039)
at org.h2.server.web.WebApp.process(WebApp.java:227)
at org.h2.server.web.WebApp.processRequest(WebApp.java:177)
at org.h2.server.web.JakartaWebServlet.doGet(JakartaWebServlet.java:129)
at org.h2.server.web.JakartaWebServlet.doPost(JakartaWebServlet.java:166)
at jakarta.servlet.http.HttpServlet.service(HttpServlet.java:590)
at jakarta.servlet.http.HttpServlet.service(HttpServlet.java:658)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:205)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:149)
at org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:51)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:174)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:149)
at org.springframework.web.filter.RequestContextFilter.doFilterInternal(RequestContextFilter.java:100)
at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:116)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:174)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:149)
at org.springframework.web.filter.FormContentFilter.doFilterInternal(FormContentFilter.java:93)
at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:116)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:174)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:149)
at org.springframework.web.filter.CharacterEncodingFilter.doFilterInternal(CharacterEncodingFilter.java:201)
at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:116)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:174)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:149)
at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:167)
at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:90)
at org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:482)
at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:115)
at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:93)
at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:74)
at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:344)
at org.apache.coyote.http11.Http11Processor.service(Http11Processor.java:391)
at org.apache.coyote.AbstractProcessorLight.process(AbstractProcessorLight.java:63)
at org.apache.coyote.AbstractProtocol$ConnectionHandler.process(AbstractProtocol.java:896)
at org.apache.tomcat.util.net.NioEndpoint$SocketProcessor.doRun(NioEndpoint.java:1744)
at org.apache.tomcat.util.net.SocketProcessorBase.run(SocketProcessorBase.java:52)
at org.apache.tomcat.util.threads.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1191)
at org.apache.tomcat.util.threads.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:659)
at org.apache.tomcat.util.threads.TaskThread$WrappingRunnable.run(TaskThread.java:63)
at java.base/java.lang.Thread.run(Thread.java:842)
Caused by: org.h2.jdbc.JdbcSQLInvalidAuthorizationSpecException: Неверное имя пользователя или пароль
Wrong user name or password [28000-224]
at org.h2.message.DbException.getJdbcSQLException(DbException.java:522)
at org.h2.message.DbException.getJdbcSQLException(DbException.java:489)
... 50 more
2024-04-15 12:20:09.391447+04:00 jdbc[13]: exception
org.h2.jdbc.JdbcSQLSyntaxErrorException: Синтаксическая ошибка в выражении SQL "SELECT * FROM CATEGORIES CATEGORIES [*]FAVORITES"
Syntax error in SQL statement "SELECT * FROM CATEGORIES CATEGORIES [*]FAVORITES"; SQL statement:
SELECT * FROM CATEGORIES CATEGORIES FAVORITES [42000-224]
2024-04-15 16:29:01.404545+04:00 jdbc[3]: exception
org.h2.jdbc.JdbcSQLDataException: Значение слишком длинное для поля "PASSWORD CHARACTER VARYING(5)": "'string' (6)"
Value too long for column "PASSWORD CHARACTER VARYING(5)": "'string' (6)"; SQL statement:
insert into users (is_admin,password,username,id) values (?,?,?,?) [22001-224]
2024-04-15 16:29:07.847974+04:00 jdbc[3]: exception
org.h2.jdbc.JdbcSQLDataException: Значение слишком длинное для поля "PASSWORD CHARACTER VARYING(5)": "'string' (6)"
Value too long for column "PASSWORD CHARACTER VARYING(5)": "'string' (6)"; SQL statement:
insert into users (is_admin,password,username,id) values (?,?,?,?) [22001-224]
2024-04-29 00:12:28.578523+04:00 jdbc[3]: exception
org.h2.jdbc.JdbcSQLDataException: Значение слишком длинное для поля "PASSWORD CHARACTER VARYING(5)": "'string' (6)"
Value too long for column "PASSWORD CHARACTER VARYING(5)": "'string' (6)"; SQL statement:
insert into users (is_admin,password,username,id) values (?,?,?,?) [22001-224]