LabWork_2.2

This commit is contained in:
2025-10-02 13:27:17 +04:00
parent 8a19ddbffb
commit 8a7eb58d7c
36 changed files with 8595 additions and 0 deletions

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

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

54
.vscode/settings.json vendored Normal file
View File

@@ -0,0 +1,54 @@
{
"files.autoSave": "onFocusChange",
"files.eol": "\n",
"editor.detectIndentation": false,
"editor.formatOnType": false,
"editor.formatOnPaste": true,
"editor.formatOnSave": true,
"editor.tabSize": 4,
"editor.insertSpaces": true,
"editor.codeActionsOnSave": {
"source.organizeImports": "explicit",
"source.sortImports": "explicit"
},
"editor.snippetSuggestions": "bottom",
"debug.toolBarLocation": "commandCenter",
"debug.showVariableTypes": true,
"errorLens.gutterIconsEnabled": true,
"errorLens.messageEnabled": false,
"prettier.tabWidth": 4,
"prettier.singleQuote": false,
"prettier.printWidth": 120,
"prettier.trailingComma": "es5",
"prettier.useTabs": false,
"[json]": {
"editor.defaultFormatter": "esbenp.prettier-vscode"
},
"[jsonc]": {
"editor.defaultFormatter": "esbenp.prettier-vscode"
},
"[javascript]": {
"editor.defaultFormatter": "esbenp.prettier-vscode"
},
"[css]": {
"editor.defaultFormatter": "esbenp.prettier-vscode"
},
"[html]": {
"editor.defaultFormatter": "esbenp.prettier-vscode"
},
"java.compile.nullAnalysis.mode": "automatic",
"java.configuration.updateBuildConfiguration": "automatic",
"[java]": {
"editor.pasteAs.enabled": false,
"editor.codeActionsOnSave": {
"source.organizeImports": "never",
"source.sortImports": "explicit"
}
},
"gradle.nestedProjects": true,
"java.saveActions.organizeImports": true,
"java.dependency.packagePresentation": "hierarchical",
"java.codeGeneration.hashCodeEquals.useJava7Objects": true,
"spring-boot.ls.problem.boot2.JAVA_CONSTRUCTOR_PARAMETER_INJECTION": "WARNING",
"spring.initializr.defaultLanguage": "Java"
}

64
MyWebSite/dist/assets/main-9YKRXbpb.js vendored Normal file

File diff suppressed because one or more lines are too long

File diff suppressed because one or more lines are too long

3
MyWebSite/server/.gitattributes vendored Normal file
View File

@@ -0,0 +1,3 @@
/gradlew text eol=lf
*.bat text eol=crlf
*.jar binary

37
MyWebSite/server/.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,53 @@
plugins {
id 'java'
id 'org.springframework.boot' version '3.5.5'
id 'io.spring.dependency-management' version '1.1.7'
}
group = 'com.example'
version = '0.0.1-SNAPSHOT'
description = 'Demo project for Spring Boot'
jar {
enabled = false
}
bootJar {
archiveFileName = String.format("%s-%s.jar", rootProject.name, version)
}
java {
toolchain {
languageVersion = JavaLanguageVersion.of(21)
}
}
repositories {
mavenCentral()
}
ext {
springdocVersion = "2.8.11"
mockitoVersion = "5.19.0"
}
configurations {
mockitoAgent
}
dependencies {
implementation 'org.springframework.boot:spring-boot-starter-web'
implementation "org.springdoc:springdoc-openapi-starter-webmvc-ui:${springdocVersion}"
testImplementation 'org.springframework.boot:spring-boot-starter-test'
testRuntimeOnly 'org.junit.platform:junit-platform-launcher'
testImplementation "org.mockito:mockito-core:${mockitoVersion}"
mockitoAgent("org.mockito:mockito-core:${mockitoVersion}") {
transitive = false
}
}
tasks.named('test') {
useJUnitPlatform()
jvmArgs += "-Xshare:off"
jvmArgs += "-javaagent:${configurations.mockitoAgent.asPath}"
}

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

251
MyWebSite/server/gradlew vendored Normal file
View File

@@ -0,0 +1,251 @@
#!/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.
#
# SPDX-License-Identifier: Apache-2.0
#
##############################################################################
#
# 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/platforms/jvm/plugins-application/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 -P "${APP_HOME:-./}" > /dev/null && printf '%s\n' "$PWD" ) || 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="\\\"\\\""
# 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, 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" \
-jar "$APP_HOME/gradle/wrapper/gradle-wrapper.jar" \
"$@"
# 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" "$@"

94
MyWebSite/server/gradlew.bat vendored Normal file
View File

@@ -0,0 +1,94 @@
@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
@rem SPDX-License-Identifier: Apache-2.0
@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. 1>&2
echo ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. 1>&2
echo. 1>&2
echo Please set the JAVA_HOME variable in your environment to match the 1>&2
echo location of your Java installation. 1>&2
goto fail
:findJavaFromJavaHome
set JAVA_HOME=%JAVA_HOME:"=%
set JAVA_EXE=%JAVA_HOME%/bin/java.exe
if exist "%JAVA_EXE%" goto execute
echo. 1>&2
echo ERROR: JAVA_HOME is set to an invalid directory: %JAVA_HOME% 1>&2
echo. 1>&2
echo Please set the JAVA_HOME variable in your environment to match the 1>&2
echo location of your Java installation. 1>&2
goto fail
:execute
@rem Setup the command line
set CLASSPATH=
@rem Execute Gradle
"%JAVA_EXE%" %DEFAULT_JVM_OPTS% %JAVA_OPTS% %GRADLE_OPTS% "-Dorg.gradle.appname=%APP_BASE_NAME%" -classpath "%CLASSPATH%" -jar "%APP_HOME%\gradle\wrapper\gradle-wrapper.jar" %*
: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,2 @@
rootProject.name = 'server'

View File

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

View File

@@ -0,0 +1,85 @@
package com.example.server.api.book;
import java.util.List;
import java.util.concurrent.ConcurrentLinkedQueue;
import java.util.concurrent.atomic.AtomicInteger;
import com.example.server.api.genre.GenreController;
import com.example.server.error.NotFoundException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import com.example.server.configuration.Constants;
@RestController
@RequestMapping(Constants.API_URL + BookController.URL)
public class BookController {
public static final String URL = "/book";
private final Logger log = LoggerFactory.getLogger(BookController.class);
private final AtomicInteger idGenerator = new AtomicInteger();
private final ConcurrentLinkedQueue<BookDto> books;
private final GenreController genreController;
public BookController(GenreController genreController) {
this.genreController = genreController;
this.books = new ConcurrentLinkedQueue<>(List.of(
new BookDto(idGenerator.incrementAndGet(), "Дюна", "Фрэнк Герберт", 700, "Эпическая история о борьбе за контроль над планетой Арракис, источником самого ценного вещества во вселенной.", 1, "images/dune.jpg"),
new BookDto(idGenerator.incrementAndGet(), "Убийство в Восточном экспрессе", "Агата Кристи", 750, "Загадочное убийство на поезде, где каждый пассажир может быть подозреваемым.", 2, "images/murder_on_the_orient_express.jpg"),
new BookDto(idGenerator.incrementAndGet(), "Гарри Поттер и философский камень", "Дж.К. Роулинг", 800, "Приключения молодого волшебника в школе магии Хогвартс.", 1, "images/harry_potter.webp")
));
}
@GetMapping
public List<BookDto> getAll() {
log.debug("Get all books");
return books.stream().toList();
}
@GetMapping("/{id}")
public BookDto get(@PathVariable int id) {
log.debug("Get book wtih id {}", id);
return books.stream()
.filter(book -> book.getId() == id)
.findAny()
.orElseThrow(() -> new NotFoundException(BookDto.class, id));
}
@PostMapping
public BookDto create(@RequestBody BookDto newBook) {
log.debug("Create book wtih data {}", newBook);
newBook.setId(idGenerator.incrementAndGet());
newBook.setGenre(genreController.get(newBook.getGenreId()));
books.add(newBook);
return newBook;
}
@PutMapping("/{id}")
public BookDto edit(@PathVariable int id, @RequestBody BookDto newBook) {
log.debug("Edit book wtih id {} and data {}", id, newBook);
final BookDto existsBook = get(id);
existsBook.setTitle(newBook.getTitle());
existsBook.setAuthor(newBook.getAuthor());
existsBook.setPrice(newBook.getPrice());
existsBook.setDescription(newBook.getDescription());
existsBook.setImage(newBook.getImage());
existsBook.setGenreId(newBook.getGenreId());
existsBook.setGenre(genreController.get(existsBook.getGenreId()));
return existsBook;
}
@DeleteMapping("/{id}")
public BookDto delete(@PathVariable int id) {
log.debug("Delete book wtih id {}", id);
final BookDto book = get(id);
books.remove(book);
return book;
}
}

View File

@@ -0,0 +1,111 @@
package com.example.server.api.book;
import com.example.server.api.genre.GenreDto;
import com.fasterxml.jackson.annotation.JsonProperty;
import com.fasterxml.jackson.annotation.JsonProperty.Access;
public class BookDto {
@JsonProperty(access = Access.READ_ONLY)
private int id;
@JsonProperty("title")
private String title;
@JsonProperty("author")
private String author;
private int price;
private String description;
private int genreId;
@JsonProperty(access = Access.READ_ONLY)
private GenreDto genre;
private String image;
public BookDto() {
}
public BookDto(
int id,
String title,
String author,
int price,
String description,
int genreId, String image) {
this.id = id;
this.title = title;
this.author = author;
this.price = price;
this.description = description;
this.genreId = genreId;
this.image = image;
this.genre = null;
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
public String getAuthor() {
return author;
}
public void setAuthor(String author) {
this.author = author;
}
public int getPrice() {
return price;
}
public void setPrice(int price) {
this.price = price;
}
public String getDescription() {
return description;
}
public void setDescription(String description) {
this.description = description;
}
public int getGenreId() {
return genreId;
}
public void setGenreId(int genreId) {
this.genreId = genreId;
}
public GenreDto getGenre() {
return genre;
}
public void setGenre(GenreDto newGenre) {
genre = newGenre;
}
public String getImage() {
return image;
}
public void setImage(String image) {
this.image = image;
}
@Override
public String toString() {
return "StudentDto [title=" + title + ", author=" + author + ", price=" +
price + ", description=" + description + ", genreId=" + genreId + ", image=" + image + "]";
}
}

View File

@@ -0,0 +1,108 @@
package com.example.server.api.cartItem;
import java.util.List;
import java.util.concurrent.ConcurrentLinkedQueue;
import java.util.concurrent.atomic.AtomicInteger;
import com.example.server.api.book.BookController;
import org.slf4j.*;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PatchMapping;
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.server.error.NotFoundException;
import com.example.server.configuration.Constants;
@RestController
@RequestMapping(Constants.API_URL + CartController.URL)
public class CartController {
public static final String URL = "/cart";
private final Logger log = LoggerFactory.getLogger(CartController.class);
private final AtomicInteger idGenerator = new AtomicInteger();
private final ConcurrentLinkedQueue<CartItemDto> cartItems;
private final BookController bookController;
public CartController(BookController bookController) {
this.bookController = bookController;
this.cartItems = new ConcurrentLinkedQueue<>();
}
@GetMapping
public List<CartItemDto> getAll() {
log.debug("Get all cart items");
return cartItems.stream().toList();
}
@GetMapping("/{id}")
public CartItemDto get(@PathVariable int id) {
log.debug("Get cart item with id {}", id);
return cartItems.stream()
.filter(item -> item.getId() == id)
.findAny()
.orElseThrow(() -> new NotFoundException(CartItemDto.class, id));
}
@PostMapping
public CartItemDto addToCart(@RequestBody CartItemDto newItem) {
log.debug("Add to cart: {}", newItem);
// Проверяем, есть ли уже такая книга в корзине
CartItemDto existingItem = cartItems.stream()
.filter(item -> item.getBookId() == newItem.getBookId())
.findFirst()
.orElse(null);
if (existingItem != null) {
// Увеличиваем количество
existingItem.setQuantity(existingItem.getQuantity() + newItem.getQuantity());
return existingItem;
} else {
// Добавляем новый элемент
newItem.setId(idGenerator.incrementAndGet());
newItem.setBook(bookController.get(newItem.getBookId()));
cartItems.add(newItem);
return newItem;
}
}
@PutMapping("/{id}")
public CartItemDto updateCartItem(@PathVariable int id, @RequestBody CartItemDto updatedItem) {
log.debug("Update cart item with id {}: {}", id, updatedItem);
CartItemDto existingItem = get(id);
existingItem.setQuantity(updatedItem.getQuantity());
return existingItem;
}
@DeleteMapping("/{id}")
public CartItemDto removeFromCart(@PathVariable int id) {
log.debug("Remove from cart: {}", id);
CartItemDto item = get(id);
cartItems.remove(item);
return item;
}
@PatchMapping("/{id}/{quantity}")
public CartItemDto updateQuantity(@PathVariable int id, @PathVariable int quantity) {
log.debug("Update quantity for cart item with id {} to {}", id, quantity);
CartItemDto existingItem = get(id);
if (quantity <= 0) {
throw new IllegalArgumentException("Quantity must be positive");
}
existingItem.setQuantity(quantity);
return existingItem;
}
@DeleteMapping
public void clearCart() {
log.debug("Clear cart");
cartItems.clear();
}
}

View File

@@ -0,0 +1,62 @@
package com.example.server.api.cartItem;
import com.example.server.api.book.BookDto;
import com.fasterxml.jackson.annotation.JsonProperty;
import com.fasterxml.jackson.annotation.JsonProperty.Access;
public class CartItemDto {
@JsonProperty(access = Access.READ_ONLY)
private int id;
private int bookId;
@JsonProperty(access = Access.READ_ONLY)
private BookDto book;
private int quantity;
public CartItemDto() {
}
public CartItemDto(int id, int bookId, BookDto book, int quantity) {
this.id = id;
this.bookId = bookId;
this.book = book;
this.quantity = quantity;
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public int getBookId() {
return bookId;
}
public void setBookId(int bookId) {
this.bookId = bookId;
}
public BookDto getBook() {
return book;
}
public void setBook(BookDto book) {
this.book = book;
}
public int getQuantity() {
return quantity;
}
public void setQuantity(int quantity) {
this.quantity = quantity;
}
@Override
public String toString() {
return "CartItemDto [id=" + id + ", bookId=" + bookId +
", quantity=" + quantity + "]";
}
}

View File

@@ -0,0 +1,64 @@
package com.example.server.api.genre;
import java.util.List;
import java.util.concurrent.ConcurrentLinkedQueue;
import java.util.concurrent.atomic.AtomicInteger;
import com.example.server.error.NotFoundException;
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.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import com.example.server.configuration.Constants;
@RestController
@RequestMapping(Constants.API_URL + GenreController.URL)
public class GenreController {
public static final String URL = "/genre";
private final AtomicInteger idGenerator = new AtomicInteger(3);
private final ConcurrentLinkedQueue<GenreDto> genres;
public GenreController() {
this.genres = new ConcurrentLinkedQueue<>(List.of(
new GenreDto(1, "Фантастика"),
new GenreDto(2, "Ужасы"),
new GenreDto(3, "Роман")));
}
@GetMapping
public List<GenreDto> getAll() {
return genres.stream().toList();
}
@GetMapping("/{id}")
public GenreDto get(@PathVariable int id) {
return genres.stream()
.filter(genre -> genre.getId() == id)
.findAny()
.orElseThrow(() -> new NotFoundException(GenreDto.class, id));
}
@PostMapping
public GenreDto create(@RequestBody GenreDto newGenre) {
int newId = idGenerator.incrementAndGet();
GenreDto createdGenre = new GenreDto(newId, newGenre.getName());
genres.add(createdGenre);
return createdGenre;
}
@DeleteMapping("/{id}")
public GenreDto delete(@PathVariable int id) {
GenreDto genreToDelete = get(id);
boolean removed = genres.removeIf(genre -> genre.getId() == id);
if (!removed) {
throw new NotFoundException(GenreDto.class, id);
}
return genreToDelete;
}
}

View File

@@ -0,0 +1,30 @@
package com.example.server.api.genre;
public class GenreDto {
private int id;
private String name;
public GenreDto() {
}
public GenreDto(Integer id, String name) {
this.id = id;
this.name = name;
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}

View File

@@ -0,0 +1,9 @@
package com.example.server.configuration;
public class Constants {
public static final String DEV_ORIGIN = "http://localhost:5173";
public static final String API_URL = "/api/1.0";
private Constants() {
}
}

View File

@@ -0,0 +1,17 @@
package com.example.server.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(Constants.API_URL + "/**")
.allowedMethods("GET", "POST", "PUT", "DELETE")
.allowedOrigins(Constants.DEV_ORIGIN);
}
}

View File

@@ -0,0 +1,15 @@
package com.example.server.entity;
public abstract class BaseEntity {
protected Long Id;
protected BaseEntity() {}
public Long getId() {
return Id;
}
public void setId(Long id) {
Id = id;
}
}

View File

@@ -0,0 +1,72 @@
package com.example.server.entity;
public class BookEntity extends BaseEntity{
private String title;
private String author;
private int price;
private String description;
private GenteEntity genre;
private String image;
public BookEntity() {
super();
}
public BookEntity(String title, String author, int price, String description, GenteEntity gente, String image) {
this();
this.title = title;
this.author = author;
this.price = price;
this.description = description;
this.genre = gente;
this.image = image;
}
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
public String getAuthor() {
return author;
}
public void setAuthor(String author) {
this.author = author;
}
public int getPrice() {
return price;
}
public void setPrice(int price) {
this.price = price;
}
public String getDescription() {
return description;
}
public void setDescription(String description) {
this.description = description;
}
public String getImage() {
return image;
}
public void setImage(String image) {
this.image = image;
}
public GenteEntity getGenre() {
return genre;
}
public void setGenre(GenteEntity genre) {
this.genre = genre;
}
}

View File

@@ -0,0 +1,32 @@
package com.example.server.entity;
public class CartItemEntity extends BaseEntity{
private BookEntity book;
private int quantity;
public CartItemEntity() {
super();
}
public CartItemEntity(BookEntity book, int quantity) {
this();
this.book = book;
this.quantity = quantity;
}
public BookEntity getBook() {
return book;
}
public void setBook(BookEntity book) {
this.book = book;
}
public int getQuantity() {
return quantity;
}
public void setQuantity(int quantity) {
this.quantity = quantity;
}
}

View File

@@ -0,0 +1,21 @@
package com.example.server.entity;
public class GenteEntity extends BaseEntity{
private String name;
public GenteEntity() {
super();
}
public GenteEntity(String name) {
this();
this.name = name;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}

View File

@@ -0,0 +1,26 @@
package com.example.server.error;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseStatus;
import org.springframework.web.bind.annotation.RestControllerAdvice;
import jakarta.servlet.RequestDispatcher;
import jakarta.servlet.http.HttpServletRequest;
@RestControllerAdvice
public class AdviceController {
private HttpStatus getStatus(HttpServletRequest request) {
final Integer code = (Integer) request.getAttribute(RequestDispatcher.ERROR_STATUS_CODE);
final HttpStatus status = (code != null) ? HttpStatus.resolve(code) : null;
return (status != null) ? status : HttpStatus.INTERNAL_SERVER_ERROR;
}
@ExceptionHandler(Exception.class)
@ResponseStatus(HttpStatus.INTERNAL_SERVER_ERROR)
public ResponseEntity<AdviceErrorBody> handleAnyException(HttpServletRequest request, Throwable ex) {
final HttpStatus status = getStatus(request);
return new ResponseEntity<>(new AdviceErrorBody(status.value(), ex.getMessage()), status);
}
}

View File

@@ -0,0 +1,5 @@
package com.example.server.error;
public record AdviceErrorBody(int status, String message) {
}

View File

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

View File

@@ -0,0 +1,8 @@
package com.example.server.repository;
import com.example.server.entity.BookEntity;
import org.springframework.stereotype.Repository;
@Repository
public class BookRepository extends MapRepository<BookEntity> {
}

View File

@@ -0,0 +1,10 @@
package com.example.server.repository;
import com.example.server.entity.CartItemEntity;
import org.springframework.stereotype.Repository;
import java.util.Map;
@Repository
public class CartItemRepository extends MapRepository<CartItemEntity> {
}

View File

@@ -0,0 +1,15 @@
package com.example.server.repository;
import java.util.Optional;
public interface CommonRepository<E, T> {
Iterable<E> findAll();
Optional<E> findById(T id);
E save(E entity);
void delete(E entity);
void deleteAll();
}

View File

@@ -0,0 +1,8 @@
package com.example.server.repository;
import com.example.server.entity.GenteEntity;
import org.springframework.stereotype.Repository;
@Repository
public class GenreRepository extends MapRepository<GenteEntity> {
}

View File

@@ -0,0 +1,68 @@
package com.example.server.repository;
import com.example.server.entity.BaseEntity;
import java.util.Objects;
import java.util.Optional;
import java.util.concurrent.ConcurrentNavigableMap;
import java.util.concurrent.ConcurrentSkipListMap;
import java.util.concurrent.atomic.AtomicLong;
public abstract class MapRepository<E extends BaseEntity> implements CommonRepository<E, Long> {
private final ConcurrentNavigableMap<Long, E> entities = new ConcurrentSkipListMap<>();
private final AtomicLong idGenerator = new AtomicLong(0L);
protected MapRepository() {
}
private boolean isNew(E entity) {
return Objects.isNull(entity.getId());
}
private E create(E entity) {
final Long lastId = idGenerator.incrementAndGet();
entity.setId(lastId);
entities.put(lastId, entity);
return entity;
}
private E update(E entity) {
if (findById(entity.getId()).isEmpty()) {
return null;
}
entities.put(entity.getId(), entity);
return entity;
}
@Override
public Iterable<E> findAll() {
return entities.values();
}
@Override
public Optional<E> findById(Long id) {
return Optional.ofNullable(entities.get(id));
}
@Override
public E save(E entity) {
if (isNew(entity)) {
return create(entity);
}
return update(entity);
}
@Override
public void delete(E entity) {
if (findById(entity.getId()).isEmpty()) {
return;
}
entities.remove(entity.getId());
}
@Override
public void deleteAll() {
entities.clear();
idGenerator.set(0L);
}
}

View File

@@ -0,0 +1,4 @@
spring.application.name=server
spring.main.banner-mode=off
logging.level.com.server=DEBUG

7181
package-lock.json generated Normal file

File diff suppressed because it is too large Load Diff

40
package.json Normal file
View File

@@ -0,0 +1,40 @@
{
"name": "mywebsite",
"version": "1.0.0",
"main": "vite.config.js",
"scripts": {
"test": "echo \"Error: no test specified\" && exit 1",
"build": "vite build",
"lint": "eslint . --ext js --report-unused-disable-directives --max-warnings 0",
"dev": "vite",
"start": "npm-run-all -p dev"
},
"dependencies": {
"@popperjs/core": "^2.11.8",
"axios": "^1.9.0",
"bootstrap": "^5.3.6",
"bootstrap-icons": "1.11.3",
"json-server": "^0.17.4",
"react": "^19.1.0",
"react-bootstrap": "^2.10.10",
"react-dom": "^19.1.0",
"react-icons": "^5.5.0",
"react-router-dom": "^7.6.0"
},
"devDependencies": {
"@vitejs/plugin-react": "^4.4.1",
"eslint": "8.56.0",
"eslint-config-airbnb-base": "15.0.0",
"eslint-config-prettier": "10.0.2",
"eslint-plugin-html": "8.1.2",
"eslint-plugin-import": "2.31.0",
"eslint-plugin-prettier": "5.2.3",
"http-server": "14.1.1",
"npm-run-all": "4.1.5",
"vite": "^6.3.5"
},
"keywords": [],
"author": "denis",
"license": "ISC",
"description": ""
}