diff --git a/.gitignore b/.gitignore index aa724b7..7b32cdf 100644 --- a/.gitignore +++ b/.gitignore @@ -13,3 +13,45 @@ .externalNativeBuild .cxx local.properties + +HELP.md +.gradle +build/ +!gradle/wrapper/gradle-wrapper.jar +!**/src/main/**/build/ +!**/src/test/**/build/ +data.mv.db +data.trace.db + +### 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/ + +node_modules diff --git a/backend/README.md b/backend/README.md new file mode 100644 index 0000000..9644d0b --- /dev/null +++ b/backend/README.md @@ -0,0 +1,2 @@ +# IP_1_Kalyshev_Yan_PIbd-22 + diff --git a/backend/build.gradle b/backend/build.gradle new file mode 100644 index 0000000..76dd18f --- /dev/null +++ b/backend/build.gradle @@ -0,0 +1,33 @@ +plugins { + id 'java' + id 'org.springframework.boot' version '3.2.0' + id 'io.spring.dependency-management' version '1.1.4' +} + +group = 'com.kalyshev' +version = '0.0.1-SNAPSHOT' +sourceCompatibility = '17' + +repositories { + mavenCentral() +} + +dependencies { + implementation 'org.springframework.boot:spring-boot-starter-web' + implementation 'org.springframework.boot:spring-boot-starter-thymeleaf' + implementation 'org.springframework.boot:spring-boot-devtools' + implementation 'nz.net.ultraq.thymeleaf:thymeleaf-layout-dialect' + + implementation 'org.springframework.boot:spring-boot-starter-data-jpa' + implementation 'com.h2database:h2' + + implementation 'org.hibernate.validator:hibernate-validator' + + //implementation 'org.springdoc:springdoc-openapi-ui' + + testImplementation 'org.springframework.boot:spring-boot-starter-test' +} + +tasks.named('test') { + useJUnitPlatform() +} diff --git a/backend/gradlew b/backend/gradlew new file mode 100755 index 0000000..1aa94a4 --- /dev/null +++ b/backend/gradlew @@ -0,0 +1,249 @@ +#!/bin/sh + +# +# Copyright © 2015-2021 the original authors. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# https://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# + +############################################################################## +# +# Gradle start up script for POSIX generated by Gradle. +# +# Important for running: +# +# (1) You need a POSIX-compliant shell to run this script. If your /bin/sh is +# noncompliant, but you have some other compliant shell such as ksh or +# bash, then to run this script, type that shell name before the whole +# command line, like: +# +# ksh Gradle +# +# Busybox and similar reduced shells will NOT work, because this script +# requires all of these POSIX shell features: +# * functions; +# * expansions «$var», «${var}», «${var:-default}», «${var+SET}», +# «${var#prefix}», «${var%suffix}», and «$( cmd )»; +# * compound commands having a testable exit status, especially «case»; +# * various built-in commands including «command», «set», and «ulimit». +# +# Important for patching: +# +# (2) This script targets any POSIX shell, so it avoids extensions provided +# by Bash, Ksh, etc; in particular arrays are avoided. +# +# The "traditional" practice of packing multiple parameters into a +# space-separated string is a well documented source of bugs and security +# problems, so this is (mostly) avoided, by progressively accumulating +# options in "$@", and eventually passing that to Java. +# +# Where the inherited environment variables (DEFAULT_JVM_OPTS, JAVA_OPTS, +# and GRADLE_OPTS) rely on word-splitting, this is performed explicitly; +# see the in-line comments for details. +# +# There are tweaks for specific operating systems such as AIX, CygWin, +# Darwin, MinGW, and NonStop. +# +# (3) This script is generated from the Groovy template +# https://github.com/gradle/gradle/blob/HEAD/subprojects/plugins/src/main/resources/org/gradle/api/internal/plugins/unixStartScript.txt +# within the Gradle project. +# +# You can find Gradle at https://github.com/gradle/gradle/. +# +############################################################################## + +# Attempt to set APP_HOME + +# Resolve links: $0 may be a link +app_path=$0 + +# Need this for daisy-chained symlinks. +while + APP_HOME=${app_path%"${app_path##*/}"} # leaves a trailing /; empty if no leading path + [ -h "$app_path" ] +do + ls=$( ls -ld "$app_path" ) + link=${ls#*' -> '} + case $link in #( + /*) app_path=$link ;; #( + *) app_path=$APP_HOME$link ;; + esac +done + +# This is normally unused +# shellcheck disable=SC2034 +APP_BASE_NAME=${0##*/} +# Discard cd standard output in case $CDPATH is set (https://github.com/gradle/gradle/issues/25036) +APP_HOME=$( cd "${APP_HOME:-./}" > /dev/null && pwd -P ) || exit + +# Use the maximum available, or set MAX_FD != -1 to use that value. +MAX_FD=maximum + +warn () { + echo "$*" +} >&2 + +die () { + echo + echo "$*" + echo + exit 1 +} >&2 + +# OS specific support (must be 'true' or 'false'). +cygwin=false +msys=false +darwin=false +nonstop=false +case "$( uname )" in #( + CYGWIN* ) cygwin=true ;; #( + Darwin* ) darwin=true ;; #( + MSYS* | MINGW* ) msys=true ;; #( + NONSTOP* ) nonstop=true ;; +esac + +CLASSPATH=$APP_HOME/gradle/wrapper/gradle-wrapper.jar + + +# Determine the Java command to use to start the JVM. +if [ -n "$JAVA_HOME" ] ; then + if [ -x "$JAVA_HOME/jre/sh/java" ] ; then + # IBM's JDK on AIX uses strange locations for the executables + JAVACMD=$JAVA_HOME/jre/sh/java + else + JAVACMD=$JAVA_HOME/bin/java + fi + if [ ! -x "$JAVACMD" ] ; then + die "ERROR: JAVA_HOME is set to an invalid directory: $JAVA_HOME + +Please set the JAVA_HOME variable in your environment to match the +location of your Java installation." + fi +else + JAVACMD=java + if ! command -v java >/dev/null 2>&1 + then + die "ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. + +Please set the JAVA_HOME variable in your environment to match the +location of your Java installation." + fi +fi + +# Increase the maximum file descriptors if we can. +if ! "$cygwin" && ! "$darwin" && ! "$nonstop" ; then + case $MAX_FD in #( + max*) + # In POSIX sh, ulimit -H is undefined. That's why the result is checked to see if it worked. + # shellcheck disable=SC2039,SC3045 + MAX_FD=$( ulimit -H -n ) || + warn "Could not query maximum file descriptor limit" + esac + case $MAX_FD in #( + '' | soft) :;; #( + *) + # In POSIX sh, ulimit -n is undefined. That's why the result is checked to see if it worked. + # shellcheck disable=SC2039,SC3045 + ulimit -n "$MAX_FD" || + warn "Could not set maximum file descriptor limit to $MAX_FD" + esac +fi + +# Collect all arguments for the java command, stacking in reverse order: +# * args from the command line +# * the main class name +# * -classpath +# * -D...appname settings +# * --module-path (only if needed) +# * DEFAULT_JVM_OPTS, JAVA_OPTS, and GRADLE_OPTS environment variables. + +# For Cygwin or MSYS, switch paths to Windows format before running java +if "$cygwin" || "$msys" ; then + APP_HOME=$( cygpath --path --mixed "$APP_HOME" ) + CLASSPATH=$( cygpath --path --mixed "$CLASSPATH" ) + + JAVACMD=$( cygpath --unix "$JAVACMD" ) + + # Now convert the arguments - kludge to limit ourselves to /bin/sh + for arg do + if + case $arg in #( + -*) false ;; # don't mess with options #( + /?*) t=${arg#/} t=/${t%%/*} # looks like a POSIX filepath + [ -e "$t" ] ;; #( + *) false ;; + esac + then + arg=$( cygpath --path --ignore --mixed "$arg" ) + fi + # Roll the args list around exactly as many times as the number of + # args, so each arg winds up back in the position where it started, but + # possibly modified. + # + # NB: a `for` loop captures its iteration list before it begins, so + # changing the positional parameters here affects neither the number of + # iterations, nor the values presented in `arg`. + shift # remove old arg + set -- "$@" "$arg" # push replacement arg + done +fi + + +# Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script. +DEFAULT_JVM_OPTS='"-Xmx64m" "-Xms64m"' + +# Collect all arguments for the java command: +# * DEFAULT_JVM_OPTS, JAVA_OPTS, JAVA_OPTS, and optsEnvironmentVar are not allowed to contain shell fragments, +# and any embedded shellness will be escaped. +# * For example: A user cannot expect ${Hostname} to be expanded, as it is an environment variable and will be +# treated as '${Hostname}' itself on the command line. + +set -- \ + "-Dorg.gradle.appname=$APP_BASE_NAME" \ + -classpath "$CLASSPATH" \ + org.gradle.wrapper.GradleWrapperMain \ + "$@" + +# Stop when "xargs" is not available. +if ! command -v xargs >/dev/null 2>&1 +then + die "xargs is not available" +fi + +# Use "xargs" to parse quoted args. +# +# With -n1 it outputs one arg per line, with the quotes and backslashes removed. +# +# In Bash we could simply go: +# +# readarray ARGS < <( xargs -n1 <<<"$var" ) && +# set -- "${ARGS[@]}" "$@" +# +# but POSIX shell has neither arrays nor command substitution, so instead we +# post-process each arg (as a line of input to sed) to backslash-escape any +# character that might be a shell metacharacter, then use eval to reverse +# that process (while maintaining the separation between arguments), and wrap +# the whole thing up as a single "set" statement. +# +# This will of course break if any of these variables contains a newline or +# an unmatched quote. +# + +eval "set -- $( + printf '%s\n' "$DEFAULT_JVM_OPTS $JAVA_OPTS $GRADLE_OPTS" | + xargs -n1 | + sed ' s~[^-[:alnum:]+,./:=@_]~\\&~g; ' | + tr '\n' ' ' + )" '"$@"' + +exec "$JAVACMD" "$@" diff --git a/backend/gradlew.bat b/backend/gradlew.bat new file mode 100644 index 0000000..6689b85 --- /dev/null +++ b/backend/gradlew.bat @@ -0,0 +1,92 @@ +@rem +@rem Copyright 2015 the original author or authors. +@rem +@rem Licensed under the Apache License, Version 2.0 (the "License"); +@rem you may not use this file except in compliance with the License. +@rem You may obtain a copy of the License at +@rem +@rem https://www.apache.org/licenses/LICENSE-2.0 +@rem +@rem Unless required by applicable law or agreed to in writing, software +@rem distributed under the License is distributed on an "AS IS" BASIS, +@rem WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +@rem See the License for the specific language governing permissions and +@rem limitations under the License. +@rem + +@if "%DEBUG%"=="" @echo off +@rem ########################################################################## +@rem +@rem Gradle startup script for Windows +@rem +@rem ########################################################################## + +@rem Set local scope for the variables with windows NT shell +if "%OS%"=="Windows_NT" setlocal + +set DIRNAME=%~dp0 +if "%DIRNAME%"=="" set DIRNAME=. +@rem This is normally unused +set APP_BASE_NAME=%~n0 +set APP_HOME=%DIRNAME% + +@rem Resolve any "." and ".." in APP_HOME to make it shorter. +for %%i in ("%APP_HOME%") do set APP_HOME=%%~fi + +@rem Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script. +set DEFAULT_JVM_OPTS="-Xmx64m" "-Xms64m" + +@rem Find java.exe +if defined JAVA_HOME goto findJavaFromJavaHome + +set JAVA_EXE=java.exe +%JAVA_EXE% -version >NUL 2>&1 +if %ERRORLEVEL% equ 0 goto execute + +echo. +echo ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. +echo. +echo Please set the JAVA_HOME variable in your environment to match the +echo location of your Java installation. + +goto fail + +:findJavaFromJavaHome +set JAVA_HOME=%JAVA_HOME:"=% +set JAVA_EXE=%JAVA_HOME%/bin/java.exe + +if exist "%JAVA_EXE%" goto execute + +echo. +echo ERROR: JAVA_HOME is set to an invalid directory: %JAVA_HOME% +echo. +echo Please set the JAVA_HOME variable in your environment to match the +echo location of your Java installation. + +goto fail + +:execute +@rem Setup the command line + +set CLASSPATH=%APP_HOME%\gradle\wrapper\gradle-wrapper.jar + + +@rem Execute Gradle +"%JAVA_EXE%" %DEFAULT_JVM_OPTS% %JAVA_OPTS% %GRADLE_OPTS% "-Dorg.gradle.appname=%APP_BASE_NAME%" -classpath "%CLASSPATH%" org.gradle.wrapper.GradleWrapperMain %* + +:end +@rem End local scope for the variables with windows NT shell +if %ERRORLEVEL% equ 0 goto mainEnd + +:fail +rem Set variable GRADLE_EXIT_CONSOLE if you need the _script_ return code instead of +rem the _cmd.exe /c_ return code! +set EXIT_CODE=%ERRORLEVEL% +if %EXIT_CODE% equ 0 set EXIT_CODE=1 +if not ""=="%GRADLE_EXIT_CONSOLE%" exit %EXIT_CODE% +exit /b %EXIT_CODE% + +:mainEnd +if "%OS%"=="Windows_NT" endlocal + +:omega diff --git a/backend/settings.gradle b/backend/settings.gradle new file mode 100644 index 0000000..be22ce2 --- /dev/null +++ b/backend/settings.gradle @@ -0,0 +1 @@ +rootProject.name = 'yan' diff --git a/backend/src/main/java/com/kalyshev/yan/WebConfiguration.java b/backend/src/main/java/com/kalyshev/yan/WebConfiguration.java new file mode 100644 index 0000000..23baa3b --- /dev/null +++ b/backend/src/main/java/com/kalyshev/yan/WebConfiguration.java @@ -0,0 +1,20 @@ +package com.kalyshev.yan; + +import org.springframework.context.annotation.Configuration; +import org.springframework.web.servlet.config.annotation.CorsRegistry; +import org.springframework.web.servlet.config.annotation.ViewControllerRegistry; +import org.springframework.web.servlet.config.annotation.WebMvcConfigurer; + +@Configuration +public class WebConfiguration implements WebMvcConfigurer { + public static final String REST_API = "/api"; + @Override + public void addViewControllers(ViewControllerRegistry registry) { + WebMvcConfigurer.super.addViewControllers(registry); + registry.addViewController("rest-test"); + } + @Override + public void addCorsMappings(CorsRegistry registry) { + registry.addMapping("/**").allowedMethods("*"); + } +} \ No newline at end of file diff --git a/backend/src/main/java/com/kalyshev/yan/YanApplication.java b/backend/src/main/java/com/kalyshev/yan/YanApplication.java new file mode 100644 index 0000000..8ba6732 --- /dev/null +++ b/backend/src/main/java/com/kalyshev/yan/YanApplication.java @@ -0,0 +1,11 @@ +package com.kalyshev.yan; + +import org.springframework.boot.SpringApplication; +import org.springframework.boot.autoconfigure.SpringBootApplication; + +@SpringBootApplication +public class YanApplication { + public static void main(String[] args) { + SpringApplication.run(YanApplication.class, args); + } +} diff --git a/backend/src/main/java/com/kalyshev/yan/cabinet/controller/CabinetController.java b/backend/src/main/java/com/kalyshev/yan/cabinet/controller/CabinetController.java new file mode 100644 index 0000000..bef385a --- /dev/null +++ b/backend/src/main/java/com/kalyshev/yan/cabinet/controller/CabinetController.java @@ -0,0 +1,64 @@ +package com.kalyshev.yan.cabinet.controller; + +import com.kalyshev.yan.WebConfiguration; +import com.kalyshev.yan.cabinet.service.CabinetService; +import com.kalyshev.yan.computer.controller.ComputerDto; +import jakarta.validation.Valid; +import org.springframework.web.bind.annotation.*; + +import java.util.List; + +@RestController +@RequestMapping(WebConfiguration.REST_API + "/cabinet") +public class CabinetController { + private final CabinetService cabinetService; + public CabinetController(CabinetService cabinetService) { + this.cabinetService = cabinetService; + } + @GetMapping("/{id}") + public CabinetDto getCabinet(@PathVariable Long id) { + return new CabinetDto(cabinetService.findCabinet(id)); + } + @GetMapping("/") + public List getCabinets() { + return cabinetService.findAllCabinets().stream() + .map(CabinetDto::new) + .toList(); + } + @GetMapping("/{id}/computers") + public List getCabinetComputers(@PathVariable Long id) { + return cabinetService.listComputersFromCabinet(id).stream() + .map(ComputerDto::new) + .toList(); + } + @GetMapping("/filter") + public List getFilteredCabinets(@RequestParam(value = "id", required = false) Long id, + @RequestParam(value = "number", required = false) String number) { + return cabinetService.findFilteredCabinets(id, number).stream() + .map(CabinetDto::new) + .toList(); + } + @PostMapping("/") + public CabinetDto createCabinet(@RequestBody @Valid CabinetDto cabinetDto) { + return new CabinetDto(cabinetService.addCabinet(cabinetDto.getNumber())); + } + @PostMapping("/{id}/computer") + public void createCabinetComputer(@PathVariable Long id, + @RequestParam("computerId") Long computerId) { + cabinetService.addComputerToCabinet(computerId, id); + } + @PutMapping("/{id}") + public CabinetDto updateCabinet(@PathVariable Long id, + @RequestBody @Valid CabinetDto cabinetDto) { + return new CabinetDto(cabinetService.updateCabinet(id, cabinetDto.getNumber())); + } + @DeleteMapping("/{id}") + public CabinetDto deleteCabinet(@PathVariable Long id) { + return new CabinetDto(cabinetService.deleteCabinet(id)); + } + @DeleteMapping("/{cabinetId}/computer") + public void deleteCabinetComputer(@PathVariable Long cabinetId, + @RequestParam("computerId") Long computerId) { + cabinetService.deleteComputerFromCabinet(computerId, cabinetId); + } +} \ No newline at end of file diff --git a/backend/src/main/java/com/kalyshev/yan/cabinet/controller/CabinetDto.java b/backend/src/main/java/com/kalyshev/yan/cabinet/controller/CabinetDto.java new file mode 100644 index 0000000..b996261 --- /dev/null +++ b/backend/src/main/java/com/kalyshev/yan/cabinet/controller/CabinetDto.java @@ -0,0 +1,33 @@ +package com.kalyshev.yan.cabinet.controller; + +import com.kalyshev.yan.cabinet.model.Cabinet; +import com.kalyshev.yan.computer.model.Computer; + +import java.util.ArrayList; +import java.util.List; + +public class CabinetDto { + private Long id; + private String number; + private List computerIds; + public CabinetDto() {} + public CabinetDto(Cabinet cabinet) { + this.id = cabinet.getId(); + this.number = cabinet.getNumber(); + if (cabinet.getComputers() == null) { + this.computerIds = new ArrayList<>(); + } else { + this.computerIds = new ArrayList<>(); + List computers = cabinet.getComputers(); + for (Computer computer : computers) { + computerIds.add(computer.getId()); + } + } + } + public Long getId() { return this.id; } + public void setId(Long id) { this.id = id; } + public String getNumber() { return this.number; } + public void setNumber(String number) { this.number = number; } + public List getComputerIds() { return this.computerIds; } + public void setComputerIds(List computerIds) { this.computerIds = computerIds; } +} diff --git a/backend/src/main/java/com/kalyshev/yan/cabinet/model/Cabinet.java b/backend/src/main/java/com/kalyshev/yan/cabinet/model/Cabinet.java new file mode 100644 index 0000000..b6ebdd6 --- /dev/null +++ b/backend/src/main/java/com/kalyshev/yan/cabinet/model/Cabinet.java @@ -0,0 +1,71 @@ +package com.kalyshev.yan.cabinet.model; + +import com.kalyshev.yan.computer.model.Computer; +import jakarta.persistence.*; + +import java.util.ArrayList; +import java.util.List; +import java.util.Objects; + +@Entity +@Table(name = "cabinet") +public class Cabinet { + @Id + @GeneratedValue + private Long id; + private String number; + @OneToMany(cascade = {CascadeType.MERGE}) + private List computers; + + public Cabinet() { + } + public Cabinet(String number) { + this.number = number; + } + public Long getId() { + return id; + } + public String getNumber() { + return number; + } + public void setNumber(String number) { + this.number = number; + } + public List getComputers() { + return computers; + } + public void addComputer(Computer computer){ + if (computers == null){ + this.computers = new ArrayList<>(); + } + if (!computers.contains(computer)) { + this.computers.add(computer); + computer.setCabinet(this); + } + } + public void removeComputer(Computer computer){ + if (computers.contains(computer)) + this.computers.remove(computer); + } + + @Override + public boolean equals(Object o) { + if (this == o) + return true; + if (!(o instanceof Cabinet)) + return false; + Cabinet cabinet = (Cabinet) o; + return Objects.equals(id, cabinet.id) && Objects.equals(this.number, cabinet.number); + } + @Override + public int hashCode() { + return Objects.hash(id); + } + @Override + public String toString() { + return "Cabinet{" + + "id=" + id + + ", number='" + number + '\'' + + '}'; + } +} diff --git a/backend/src/main/java/com/kalyshev/yan/cabinet/repository/CabinetNotFoundException.java b/backend/src/main/java/com/kalyshev/yan/cabinet/repository/CabinetNotFoundException.java new file mode 100644 index 0000000..519e713 --- /dev/null +++ b/backend/src/main/java/com/kalyshev/yan/cabinet/repository/CabinetNotFoundException.java @@ -0,0 +1,7 @@ +package com.kalyshev.yan.cabinet.repository; + +public class CabinetNotFoundException extends RuntimeException { + public CabinetNotFoundException(Long id) { + super(String.format("Cabinet with id [%s] is not found", id)); + } +} diff --git a/backend/src/main/java/com/kalyshev/yan/cabinet/repository/CabinetRepository.java b/backend/src/main/java/com/kalyshev/yan/cabinet/repository/CabinetRepository.java new file mode 100644 index 0000000..1edf33f --- /dev/null +++ b/backend/src/main/java/com/kalyshev/yan/cabinet/repository/CabinetRepository.java @@ -0,0 +1,15 @@ +package com.kalyshev.yan.cabinet.repository; + +import com.kalyshev.yan.cabinet.model.Cabinet; +import com.kalyshev.yan.monitor.model.Monitor; +import org.springframework.data.jpa.repository.JpaRepository; +import org.springframework.data.jpa.repository.Query; +import org.springframework.data.repository.query.Param; + +import java.util.List; + +public interface CabinetRepository extends JpaRepository { + @Query(value = "select s from Cabinet s where (s.id = :id or :id is Null) and (s.number = :number or :number is Null)") + public List findFilteredCabinets(@Param("id") Long id, + @Param("number") String number); +} \ No newline at end of file diff --git a/backend/src/main/java/com/kalyshev/yan/cabinet/service/CabinetService.java b/backend/src/main/java/com/kalyshev/yan/cabinet/service/CabinetService.java new file mode 100644 index 0000000..8ea00f4 --- /dev/null +++ b/backend/src/main/java/com/kalyshev/yan/cabinet/service/CabinetService.java @@ -0,0 +1,104 @@ +package com.kalyshev.yan.cabinet.service; + +import com.kalyshev.yan.cabinet.model.Cabinet; +import com.kalyshev.yan.cabinet.repository.CabinetNotFoundException; +import com.kalyshev.yan.cabinet.repository.CabinetRepository; +import com.kalyshev.yan.computer.model.Computer; +import com.kalyshev.yan.computer.service.ComputerService; +import com.kalyshev.yan.util.validation.ValidatorUtil; +import org.springframework.stereotype.Service; +import org.springframework.transaction.annotation.Transactional; +import org.springframework.util.StringUtils; + +import java.util.ArrayList; +import java.util.List; +import java.util.Objects; +import java.util.Optional; + +@Service +public class CabinetService { + private final CabinetRepository cabinetRepository; + private final ComputerService computerService; + private final ValidatorUtil validatorUtil; + public CabinetService(CabinetRepository cabinetRepository, + ComputerService computerService, + ValidatorUtil validatorUtil) { + this.cabinetRepository = cabinetRepository; + this.computerService = computerService; + this.validatorUtil = validatorUtil; + } + @Transactional + public Cabinet addCabinet(String number) { + if (!StringUtils.hasText(number)) { + throw new IllegalArgumentException("Cabinet number is null or empty"); + } + final Cabinet cabinet = new Cabinet(number); + validatorUtil.validate(cabinet); + return cabinetRepository.save(cabinet); + } + @Transactional(readOnly = true) + public Cabinet findCabinet(Long id) { + final Optional cabinet = cabinetRepository.findById(id); + return cabinet.orElseThrow(() -> new CabinetNotFoundException(id)); + } + @Transactional(readOnly = true) + public List findFilteredCabinets(Long id, String number) { + return cabinetRepository.findFilteredCabinets(id, number); + } + @Transactional(readOnly = true) + public List findAllCabinets() { + return cabinetRepository.findAll(); + } + @Transactional + public Cabinet updateCabinet(Long id, String number) { + if (!StringUtils.hasText(number)) { + throw new IllegalArgumentException("Cabinet number is null or empty"); + } + final Cabinet currentCabinet = findCabinet(id); + currentCabinet.setNumber(number); + validatorUtil.validate(currentCabinet); + return cabinetRepository.save(currentCabinet); + } + @Transactional + public Cabinet deleteCabinet(Long id) { + final Cabinet currentCabinet = findCabinet(id); + computerService.deleteRelationsWithCabinets(currentCabinet.getComputers()); + cabinetRepository.delete(currentCabinet); + return currentCabinet; + } + @Transactional + public void deleteAllCabinets() { + cabinetRepository.deleteAll(); + } + @Transactional + public List listComputersFromCabinet(Long id) { + if ((Object)id == null) { + throw new IllegalArgumentException("Cabinet id is null or empty"); + } + return findCabinet(id).getComputers(); + } + @Transactional + public void addComputerToCabinet(Long computerId, Long cabinetId) { + if ((Object)computerId == null) { + throw new IllegalArgumentException("Computer id is null or empty"); + } + if ((Object)cabinetId == null) { + throw new IllegalArgumentException("Cabinet id is null or empty"); + } + final Computer computer = computerService.findComputer(computerId); + final Cabinet cabinet = findCabinet(cabinetId); + cabinet.addComputer(computer); + } + @Transactional + public void deleteComputerFromCabinet(Long computerId, Long cabinetId) { + if ((Object) computerId == null) { + throw new IllegalArgumentException("Computer id is null or empty"); + } + if ((Object) cabinetId == null) { + throw new IllegalArgumentException("Cabinet id is null or empty"); + } + final Computer computer = computerService.findComputer(computerId); + final Cabinet cabinet = findCabinet(cabinetId); + cabinet.removeComputer(computer); + } +} \ No newline at end of file diff --git a/backend/src/main/java/com/kalyshev/yan/computer/controller/ComputerController.java b/backend/src/main/java/com/kalyshev/yan/computer/controller/ComputerController.java new file mode 100644 index 0000000..0254acb --- /dev/null +++ b/backend/src/main/java/com/kalyshev/yan/computer/controller/ComputerController.java @@ -0,0 +1,56 @@ +package com.kalyshev.yan.computer.controller; + +import com.kalyshev.yan.WebConfiguration; +import com.kalyshev.yan.computer.service.ComputerService; +import com.kalyshev.yan.monitor.controller.MonitorDto; +import jakarta.validation.Valid; +import org.springframework.web.bind.annotation.*; + +import java.util.List; + +@RestController +@RequestMapping(WebConfiguration.REST_API + "/computer") +public class ComputerController { + private final ComputerService computerService; + public ComputerController(ComputerService computerService) { + this.computerService = computerService; + } + @GetMapping("/{id}") + public ComputerDto getStudent(@PathVariable Long id) { + return new ComputerDto(computerService.findComputer(id)); + } + @GetMapping("/") + public List getComputers() { + return computerService.findAllComputers().stream() + .map(ComputerDto::new) + .toList(); + } + @GetMapping("/filter") + public List getFilteredComputers(@RequestParam(value = "id", required = false) Long id, + @RequestParam(value = "modelName", required = false) String modelName, + @RequestParam(value = "serialNum", required = false) String serialNum, + @RequestParam(value = "monitorId", required = false) Long monitorId, + @RequestParam(value = "cabinetId", required = false) Long cabinetId) { + return computerService.findFilteredComputers(id, modelName, serialNum, monitorId, cabinetId).stream() + .map(ComputerDto::new) + .toList(); + } + @PostMapping("/") + public ComputerDto createComputer(@RequestBody @Valid ComputerDto computerDto) { + return new ComputerDto(computerService.addComputer(computerDto.getModelName(), computerDto.getSerialNum(), computerDto.getMonitorId())); + } + @PostMapping("/{id}/monitor") + public MonitorDto setMonitorComputer(@PathVariable Long id, + @RequestParam("monitorId") Long monitorId) { + return new MonitorDto(computerService.setMonitor(monitorId, id)); + } + @PutMapping("/{id}") + public ComputerDto updateComputer(@PathVariable Long id, + @RequestBody @Valid ComputerDto computerDto) { + return new ComputerDto(computerService.updateComputer(id, computerDto.getModelName(), computerDto.getSerialNum(), computerDto.getMonitorId(), computerDto.getCabinetId())); + } + @DeleteMapping("/{id}") + public ComputerDto deleteComputer(@PathVariable Long id) { + return new ComputerDto(computerService.deleteComputer(id)); + } +} \ No newline at end of file diff --git a/backend/src/main/java/com/kalyshev/yan/computer/controller/ComputerDto.java b/backend/src/main/java/com/kalyshev/yan/computer/controller/ComputerDto.java new file mode 100644 index 0000000..bc6f794 --- /dev/null +++ b/backend/src/main/java/com/kalyshev/yan/computer/controller/ComputerDto.java @@ -0,0 +1,36 @@ +package com.kalyshev.yan.computer.controller; + +import com.kalyshev.yan.computer.model.Computer; + +public class ComputerDto { + private Long id; + private String modelName; + private String serialNum; + private Long monitorId; + private Long cabinetId; + public ComputerDto() {} + public ComputerDto(Computer computer) { + this.id = computer.getId(); + this.modelName = computer.getModelName(); + this.serialNum = computer.getSerialNum(); + if (computer.getMonitor() == null) { + this.monitorId = null; + } else { + this.monitorId = computer.getMonitor().getId(); + } + if (computer.getCabinet() == null) { + this.cabinetId = null; + } else { + this.cabinetId = computer.getCabinet().getId(); + } + } + public Long getId() { return this.id; } + public String getModelName() { return this.modelName; } + public void setModelName(String modelName) { this.modelName = modelName; } + public String getSerialNum() { return this.serialNum; } + public void setSerialNum(String serialNum) { this.serialNum = serialNum; } + public Long getMonitorId() { return this.monitorId; } + public void setMonitorId(Long monitorId) { this.monitorId = monitorId; } + public Long getCabinetId() { return this.cabinetId; } + public void setCabinetId(Long cabinetId) { this.cabinetId = cabinetId; } +} diff --git a/backend/src/main/java/com/kalyshev/yan/computer/model/Computer.java b/backend/src/main/java/com/kalyshev/yan/computer/model/Computer.java new file mode 100644 index 0000000..2cdf669 --- /dev/null +++ b/backend/src/main/java/com/kalyshev/yan/computer/model/Computer.java @@ -0,0 +1,81 @@ +package com.kalyshev.yan.computer.model; + +import com.kalyshev.yan.cabinet.model.Cabinet; +import com.kalyshev.yan.monitor.model.Monitor; +import jakarta.persistence.*; + +import java.util.Objects; + +@Entity +@Table(name = "computer") +public class Computer { + @Id + @GeneratedValue + private Long id; + private String modelName; + private String serialNum; + @ManyToOne( cascade = {CascadeType.MERGE}, fetch = FetchType.EAGER) + @JoinColumn(name = "cabinet", nullable = true) + private Cabinet cabinet; + @OneToOne(cascade = {CascadeType.MERGE}) + @JoinColumn(name = "monitor_id") + private Monitor monitor; + + public Computer() { + } + public Computer(String modelName, String serialNum) { + this.modelName = modelName; + this.serialNum = serialNum; + } + + public Long getId() { + return id; + } + public String getModelName() { + return modelName; + } + public void setModelName(String modelName) { + this.modelName = modelName; + } + public String getSerialNum() { + return serialNum; + } + public void setSerialNum(String serialNum) { this.serialNum = serialNum; } + public Cabinet getCabinet() { + return cabinet; + } + public void setCabinet(Cabinet cabinet) { this.cabinet = cabinet; } + + public Monitor getMonitor() { + return monitor; + } + public void setMonitor(Monitor monitor) { + this.monitor = monitor; + } + public Monitor removeMonitor() { + Monitor temp = this.monitor; + this.monitor = null; + return temp; + } + @Override + public boolean equals(Object o) { + if (this == o) + return true; + if (!(o instanceof Computer)) + return false; + Computer computer = (Computer) o; + return Objects.equals(id, computer.id) && Objects.equals(this.modelName, computer.modelName) && Objects.equals(this.monitor, computer.monitor) && Objects.equals(this.cabinet, computer.cabinet); + } + @Override + public int hashCode() { + return Objects.hash(id); + } + @Override + public String toString() { + return "Computer{" + + "id=" + id + + ", modelName='" + modelName + '\'' + + ", serialNum='" + serialNum + '\'' + + '}'; + } +} diff --git a/backend/src/main/java/com/kalyshev/yan/computer/repository/ComputerNotFoundException.java b/backend/src/main/java/com/kalyshev/yan/computer/repository/ComputerNotFoundException.java new file mode 100644 index 0000000..a6a3750 --- /dev/null +++ b/backend/src/main/java/com/kalyshev/yan/computer/repository/ComputerNotFoundException.java @@ -0,0 +1,7 @@ +package com.kalyshev.yan.computer.repository; + +public class ComputerNotFoundException extends RuntimeException { + public ComputerNotFoundException(Long id) { + super(String.format("Computer with id [%s] is not found", id)); + } +} \ No newline at end of file diff --git a/backend/src/main/java/com/kalyshev/yan/computer/repository/ComputerRepository.java b/backend/src/main/java/com/kalyshev/yan/computer/repository/ComputerRepository.java new file mode 100644 index 0000000..229ac63 --- /dev/null +++ b/backend/src/main/java/com/kalyshev/yan/computer/repository/ComputerRepository.java @@ -0,0 +1,34 @@ +package com.kalyshev.yan.computer.repository; + +import com.kalyshev.yan.computer.model.Computer; +import com.kalyshev.yan.monitor.model.Monitor; +import org.springframework.data.jpa.repository.JpaRepository; +import org.springframework.data.jpa.repository.Modifying; +import org.springframework.data.jpa.repository.Query; +import org.springframework.data.repository.query.Param; + +import java.util.Collection; +import java.util.List; + +public interface ComputerRepository extends JpaRepository { + @Query(value = "select * from Computer where (\"ID\" = :id or :id is Null) and " + + "(\"MODEL_NAME\" = :modelName or :modelName is Null) and " + + "(\"SERIAL_NUM\" = :serialNum or :serialNum is Null) and " + + "(\"MONITOR_ID\" = :monitorId or :monitorId is Null) and " + + "(\"CABINET\" = :cabinetId or :cabinetId is Null)", nativeQuery = true) + public List findFilteredComputers(@Param("id") Long id, + @Param("modelName") String modelName, + @Param("serialNum") String serialNum, + @Param("monitorId") Long monitorId, + @Param("cabinetId") Long cabinetId); + + @Query(value = "select * from Computer where \"MONITOR_ID\" = :monitorId", nativeQuery = true) + public Computer findComputerByMonitor(@Param("monitorId") Long monitorId); + + @Modifying + @Query(value = "update Computer set \"MONITOR_ID\" = null", nativeQuery = true) + public void removeAllComputerMonitorRelations(); + +// @Query(value = "update Computer where id in :computerIds set cabinet_id = null") +// public void deleteRelationsWithCabinets(@Param("computerIds") Collection computerIds); +} diff --git a/backend/src/main/java/com/kalyshev/yan/computer/service/ComputerService.java b/backend/src/main/java/com/kalyshev/yan/computer/service/ComputerService.java new file mode 100644 index 0000000..af1b1a1 --- /dev/null +++ b/backend/src/main/java/com/kalyshev/yan/computer/service/ComputerService.java @@ -0,0 +1,135 @@ +package com.kalyshev.yan.computer.service; + +import com.kalyshev.yan.cabinet.model.Cabinet; +import com.kalyshev.yan.computer.model.Computer; +import com.kalyshev.yan.computer.repository.ComputerNotFoundException; +import com.kalyshev.yan.computer.repository.ComputerRepository; +import com.kalyshev.yan.monitor.model.Monitor; +import com.kalyshev.yan.monitor.service.MonitorService; +import com.kalyshev.yan.util.validation.ValidatorUtil; +import jakarta.annotation.Nullable; +import org.springframework.stereotype.Service; +import org.springframework.transaction.annotation.Transactional; +import org.springframework.util.StringUtils; + +import java.util.*; + +@Service +public class ComputerService { + private final ComputerRepository computerRepository; + private final MonitorService monitorService; + private final ValidatorUtil validatorUtil; + public ComputerService(ComputerRepository computerRepository, + MonitorService monitorService, + ValidatorUtil validatorUtil) { + this.computerRepository = computerRepository; + this.monitorService = monitorService; + this.validatorUtil = validatorUtil; + } + @Transactional + public Computer addComputer(String modelName, String serialNum, @Nullable Long monitorId) { + if (!StringUtils.hasText(modelName)) { + throw new IllegalArgumentException("Computer model name is null or empty"); + } + if (!StringUtils.hasText(serialNum)) { + throw new IllegalArgumentException("Computer serial number is null or empty"); + } + final Computer computer = new Computer(modelName, serialNum); + if (monitorId != null) { + final Monitor monitor = monitorService.findMonitor(monitorId); + computer.setMonitor(monitor); + } + validatorUtil.validate(computer); + return computerRepository.save(computer); + } + @Transactional(readOnly = true) + public Computer findComputer(Long id) { + final Optional computer = computerRepository.findById(id); + return computer.orElseThrow(() -> new ComputerNotFoundException(id)); + } + @Transactional(readOnly = true) + public List findAllComputers() { + return computerRepository.findAll(); + } + @Transactional(readOnly = true) + public List findFilteredComputers(Long id, String modelName, String serialNum, Long monitorId, Long cabinetId) { + return computerRepository.findFilteredComputers(id, modelName, serialNum, monitorId, cabinetId); + } + @Transactional + public Computer updateComputer(Long id, String modelName, String serialNum, Long monitorId, Long cabinetId) { + if (!(StringUtils.hasText(modelName) || StringUtils.hasText(serialNum))) { + throw new IllegalArgumentException("Need at least one argument"); + } + final Computer currentComputer = findComputer(id); + if (modelName != null) { + currentComputer.setModelName(modelName); + } + if (serialNum != null) { + currentComputer.setSerialNum(serialNum); + } + if (monitorId != null) { + final Monitor monitor = monitorService.findMonitor(monitorId); + currentComputer.setMonitor(monitor); + } + validatorUtil.validate(currentComputer); + return computerRepository.save(currentComputer); + } + @Transactional + public Computer deleteComputer(Long id) { + final Computer currentComputer = findComputer(id); + Cabinet currentComputerCabinet = currentComputer.getCabinet(); + if (currentComputerCabinet != null) { + currentComputerCabinet.removeComputer(currentComputer); + } + computerRepository.delete(currentComputer); + return currentComputer; + } + @Transactional + public void deleteAllComputers() { + List computers = findAllComputers(); + for (Computer computer : computers) { + deleteComputer(computer.getId()); + } + } + @Transactional + public Monitor setMonitor(Long monitorId, Long computerId) { + if ((Object)computerId == null) { + throw new IllegalArgumentException("Computer id is null or empty"); + } + if ((Object)monitorId == null) { + throw new IllegalArgumentException("Monitor id is null or empty"); + } + final Computer computer = findComputer(computerId); + final Monitor monitor = monitorService.findMonitor(monitorId); + computer.setMonitor(monitor); + return monitor; + } + @Transactional + public void deleteRelationsWithCabinets(List computers) { + for (Computer computer: computers) { + computer.setCabinet(null); + } + } + @Transactional + public Computer findComputerByMonitor(Monitor monitor) { + if (monitor.getId() == null) { + return null; + } + return computerRepository.findComputerByMonitor(monitor.getId()); + } + @Transactional + public Monitor deleteMonitorWithRelation(Long id) { + final Monitor currentMonitor = monitorService.findMonitor(id); + Computer computer = findComputerByMonitor(currentMonitor); + if (computer != null) { + computer.removeMonitor(); + } + monitorService.deleteMonitor(currentMonitor); + return currentMonitor; + } + @Transactional + public void deleteAllMonitorsWithRelations() { + computerRepository.removeAllComputerMonitorRelations(); + monitorService.deleteAllMonitors(); + } +} \ No newline at end of file diff --git a/backend/src/main/java/com/kalyshev/yan/monitor/controller/MonitorController.java b/backend/src/main/java/com/kalyshev/yan/monitor/controller/MonitorController.java new file mode 100644 index 0000000..e8b58d3 --- /dev/null +++ b/backend/src/main/java/com/kalyshev/yan/monitor/controller/MonitorController.java @@ -0,0 +1,51 @@ +package com.kalyshev.yan.monitor.controller; + +import com.kalyshev.yan.WebConfiguration; +import com.kalyshev.yan.computer.service.ComputerService; +import com.kalyshev.yan.monitor.service.MonitorService; +import jakarta.validation.Valid; +import org.springframework.web.bind.annotation.*; + +import java.util.List; + +@RestController +@RequestMapping(WebConfiguration.REST_API + "/monitor") +public class MonitorController { + private final MonitorService monitorService; + private final ComputerService computerService; + public MonitorController(MonitorService monitorService, + ComputerService computerService) { + this.monitorService = monitorService; + this.computerService = computerService; + } + @GetMapping("/{id}") + public MonitorDto getMonitor(@PathVariable Long id) { + return new MonitorDto(monitorService.findMonitor(id)); + } + @GetMapping("/") + public List getMonitors() { + return monitorService.findAllMonitors().stream() + .map(MonitorDto::new) + .toList(); + } + @GetMapping("/filter") + public List getFilteredmonitors(@RequestParam(value = "id", required = false) Long id, + @RequestParam(value = "modelName", required = false) String modelName) { + return monitorService.findFilteredMonitors(id, modelName).stream() + .map(MonitorDto::new) + .toList(); + } + @PostMapping("/") + public MonitorDto createMonitor(@RequestBody @Valid MonitorDto monitorDto) { + return new MonitorDto(monitorService.addMonitor(monitorDto.getModelName())); + } + @PutMapping("/{id}") + public MonitorDto updateMonitor(@PathVariable Long id, + @RequestBody @Valid MonitorDto monitorDto) { + return new MonitorDto(monitorService.updateMonitor(id, monitorDto.getModelName())); + } + @DeleteMapping("/{id}") + public MonitorDto deleteMonitor(@PathVariable Long id) { + return new MonitorDto(computerService.deleteMonitorWithRelation(id)); + } +} \ No newline at end of file diff --git a/backend/src/main/java/com/kalyshev/yan/monitor/controller/MonitorDto.java b/backend/src/main/java/com/kalyshev/yan/monitor/controller/MonitorDto.java new file mode 100644 index 0000000..a26947f --- /dev/null +++ b/backend/src/main/java/com/kalyshev/yan/monitor/controller/MonitorDto.java @@ -0,0 +1,23 @@ +package com.kalyshev.yan.monitor.controller; + +import com.kalyshev.yan.monitor.model.Monitor; + +public class MonitorDto { + private Long id; + private String modelName; + public MonitorDto() { + } + public MonitorDto(Monitor monitor) { + this.id = monitor.getId(); + this.modelName = monitor.getModelName(); + } + public Long getId() { + return id; + } + public String getModelName() { + return modelName; + } + public void setModelName(String modelName) { + this.modelName = modelName; + } +} diff --git a/backend/src/main/java/com/kalyshev/yan/monitor/model/Monitor.java b/backend/src/main/java/com/kalyshev/yan/monitor/model/Monitor.java new file mode 100644 index 0000000..3fb247b --- /dev/null +++ b/backend/src/main/java/com/kalyshev/yan/monitor/model/Monitor.java @@ -0,0 +1,51 @@ +package com.kalyshev.yan.monitor.model; + +import jakarta.persistence.Entity; +import jakarta.persistence.GeneratedValue; +import jakarta.persistence.Id; +import jakarta.persistence.Table; + +import java.util.Objects; + +@Entity +@Table(name = "monitor") +public class Monitor { + @Id + @GeneratedValue + private Long id; + private String modelName; + public Monitor() { + } + public Monitor(String modelName) { + this.modelName = modelName; + } + public Long getId() { + return id; + } + public String getModelName() { + return modelName; + } + public void setModelName(String modelName) { + this.modelName = modelName; + } + @Override + public boolean equals(Object o) { + if (this == o) + return true; + if (!(o instanceof Monitor)) + return false; + Monitor monitor = (Monitor) o; + return Objects.equals(id, monitor.id) && Objects.equals(this.modelName, monitor.modelName); + } + @Override + public int hashCode() { + return Objects.hash(id); + } + @Override + public String toString() { + return "Monitor{" + + "id=" + id + + ", modelName='" + modelName + '\'' + + '}'; + } +} diff --git a/backend/src/main/java/com/kalyshev/yan/monitor/repository/MonitorNotFoundException.java b/backend/src/main/java/com/kalyshev/yan/monitor/repository/MonitorNotFoundException.java new file mode 100644 index 0000000..5a40a2b --- /dev/null +++ b/backend/src/main/java/com/kalyshev/yan/monitor/repository/MonitorNotFoundException.java @@ -0,0 +1,7 @@ +package com.kalyshev.yan.monitor.repository; + +public class MonitorNotFoundException extends RuntimeException { + public MonitorNotFoundException(Long id) { + super(String.format("Monitor with id [%s] is not found", id)); + } +} \ No newline at end of file diff --git a/backend/src/main/java/com/kalyshev/yan/monitor/repository/MonitorRepository.java b/backend/src/main/java/com/kalyshev/yan/monitor/repository/MonitorRepository.java new file mode 100644 index 0000000..04f7c07 --- /dev/null +++ b/backend/src/main/java/com/kalyshev/yan/monitor/repository/MonitorRepository.java @@ -0,0 +1,15 @@ +package com.kalyshev.yan.monitor.repository; + +import com.kalyshev.yan.monitor.model.Monitor; +import org.springframework.data.jpa.repository.JpaRepository; +import org.springframework.data.jpa.repository.Query; +import org.springframework.data.repository.query.Param; + +import java.util.List; + +public interface MonitorRepository extends JpaRepository { + @Query(value = "select * from Monitor where (\"ID\" = :id or :id is Null) and " + + "(\"MODEL_NAME\" = :modelName or :modelName is Null)", nativeQuery = true) + public List findFilteredMonitors(@Param("id") Long id, + @Param("modelName") String modelName); +} diff --git a/backend/src/main/java/com/kalyshev/yan/monitor/service/MonitorService.java b/backend/src/main/java/com/kalyshev/yan/monitor/service/MonitorService.java new file mode 100644 index 0000000..299f56d --- /dev/null +++ b/backend/src/main/java/com/kalyshev/yan/monitor/service/MonitorService.java @@ -0,0 +1,63 @@ +package com.kalyshev.yan.monitor.service; + +import com.kalyshev.yan.monitor.model.Monitor; +import com.kalyshev.yan.monitor.repository.MonitorNotFoundException; +import com.kalyshev.yan.monitor.repository.MonitorRepository; +import com.kalyshev.yan.util.validation.ValidatorUtil; +import org.springframework.stereotype.Service; +import org.springframework.transaction.annotation.Transactional; +import org.springframework.util.StringUtils; + +import java.util.ArrayList; +import java.util.List; +import java.util.Objects; +import java.util.Optional; + +@Service +public class MonitorService { + private final MonitorRepository monitorRepository; + private final ValidatorUtil validatorUtil; + public MonitorService(MonitorRepository monitorRepository, + ValidatorUtil validatorUtil) { + this.monitorRepository = monitorRepository; + this.validatorUtil = validatorUtil; + } + @Transactional + public Monitor addMonitor(String modelName) { + if (!StringUtils.hasText(modelName)) { + throw new IllegalArgumentException("Monitor model name is null or empty"); + } + final Monitor monitor = new Monitor(modelName); + validatorUtil.validate(monitor); + return monitorRepository.save(monitor); + } + @Transactional(readOnly = true) + public Monitor findMonitor(Long id) { + final Optional monitor = monitorRepository.findById(id); + return monitor.orElseThrow(() -> new MonitorNotFoundException(id)); + } + @Transactional(readOnly = true) + public List findAllMonitors() { + return monitorRepository.findAll(); + } + @Transactional(readOnly = true) + public List findFilteredMonitors(Long id, String modelName) { + return monitorRepository.findFilteredMonitors(id, modelName); + } + @Transactional + public Monitor updateMonitor(Long id, String modelName) { + if (!StringUtils.hasText(modelName)) { + throw new IllegalArgumentException("Monitor model name is null or empty"); + } + final Monitor currentMonitor = findMonitor(id); + currentMonitor.setModelName(modelName); + validatorUtil.validate(currentMonitor); + return monitorRepository.save(currentMonitor); + } + @Transactional + public void deleteMonitor(Monitor monitor) { + monitorRepository.delete(monitor); + } + @Transactional + public void deleteAllMonitors() { monitorRepository.deleteAll(); } +} \ No newline at end of file diff --git a/backend/src/main/java/com/kalyshev/yan/util/error/AdviceController.java b/backend/src/main/java/com/kalyshev/yan/util/error/AdviceController.java new file mode 100644 index 0000000..63f9aec --- /dev/null +++ b/backend/src/main/java/com/kalyshev/yan/util/error/AdviceController.java @@ -0,0 +1,37 @@ +package com.kalyshev.yan.util.error; + +import com.kalyshev.yan.cabinet.repository.CabinetNotFoundException; +import com.kalyshev.yan.util.validation.ValidationException; +import org.springframework.context.support.DefaultMessageSourceResolvable; +import org.springframework.http.HttpStatus; +import org.springframework.http.ResponseEntity; +import org.springframework.web.bind.MethodArgumentNotValidException; +import org.springframework.web.bind.annotation.ControllerAdvice; +import org.springframework.web.bind.annotation.ExceptionHandler; +import org.springframework.web.bind.annotation.RestController; + +import java.util.stream.Collectors; + +@ControllerAdvice(annotations = RestController.class) +public class AdviceController { + @ExceptionHandler({ + CabinetNotFoundException.class, + ValidationException.class + }) + public ResponseEntity handleException(Throwable e) { + return new ResponseEntity<>(e.getMessage(), HttpStatus.BAD_REQUEST); + } + @ExceptionHandler(MethodArgumentNotValidException.class) + public ResponseEntity handleBindException(MethodArgumentNotValidException e) { + final ValidationException validationException = new ValidationException( + e.getBindingResult().getAllErrors().stream() + .map(DefaultMessageSourceResolvable::getDefaultMessage) + .collect(Collectors.toSet())); + return handleException(validationException); + } + @ExceptionHandler(Exception.class) + public ResponseEntity handleUnknownException(Throwable e) { + e.printStackTrace(); + return new ResponseEntity<>(e.getMessage(), HttpStatus.INTERNAL_SERVER_ERROR); + } +} diff --git a/backend/src/main/java/com/kalyshev/yan/util/validation/ValidationException.java b/backend/src/main/java/com/kalyshev/yan/util/validation/ValidationException.java new file mode 100644 index 0000000..8c5664f --- /dev/null +++ b/backend/src/main/java/com/kalyshev/yan/util/validation/ValidationException.java @@ -0,0 +1,9 @@ +package com.kalyshev.yan.util.validation; + +import java.util.Set; + +public class ValidationException extends RuntimeException { + public ValidationException(Set errors) { + super(String.join("\n", errors)); + } +} diff --git a/backend/src/main/java/com/kalyshev/yan/util/validation/ValidatorUtil.java b/backend/src/main/java/com/kalyshev/yan/util/validation/ValidatorUtil.java new file mode 100644 index 0000000..d46a447 --- /dev/null +++ b/backend/src/main/java/com/kalyshev/yan/util/validation/ValidatorUtil.java @@ -0,0 +1,25 @@ +package com.kalyshev.yan.util.validation; + +import jakarta.validation.ConstraintViolation; +import jakarta.validation.Validation; +import jakarta.validation.Validator; +import org.springframework.stereotype.Component; + +import java.util.Set; +import java.util.stream.Collectors; + +@Component +public class ValidatorUtil { + private final Validator validator; + public ValidatorUtil() { + this.validator = Validation.buildDefaultValidatorFactory().getValidator(); + } + public void validate(T object) { + final Set> errors = validator.validate(object); + if (!errors.isEmpty()) { + throw new ValidationException(errors.stream() + .map(ConstraintViolation::getMessage) + .collect(Collectors.toSet())); + } + } +} diff --git a/backend/src/main/resources/application.properties b/backend/src/main/resources/application.properties new file mode 100644 index 0000000..ccc05e8 --- /dev/null +++ b/backend/src/main/resources/application.properties @@ -0,0 +1,11 @@ +spring.main.banner-mode=off +#server.port=8080 +spring.datasource.url=jdbc:h2:file:./data +spring.datasource.driverClassName=org.h2.Driver +spring.datasource.username=sa +spring.datasource.password=password +spring.jpa.database-platform=org.hibernate.dialect.H2Dialect +spring.jpa.hibernate.ddl-auto=update +spring.h2.console.enabled=true +spring.h2.console.settings.trace=false +spring.h2.console.settings.web-allow-others=false \ No newline at end of file diff --git a/backend/src/test/java/com/kalyshev/yan/JpaCabinetTests.java b/backend/src/test/java/com/kalyshev/yan/JpaCabinetTests.java new file mode 100644 index 0000000..b889fdc --- /dev/null +++ b/backend/src/test/java/com/kalyshev/yan/JpaCabinetTests.java @@ -0,0 +1,64 @@ +package com.kalyshev.yan; + +import com.kalyshev.yan.cabinet.model.Cabinet; +import com.kalyshev.yan.cabinet.repository.CabinetNotFoundException; +import com.kalyshev.yan.cabinet.service.CabinetService; +import com.kalyshev.yan.computer.service.ComputerService; +import com.kalyshev.yan.monitor.service.MonitorService; +import org.junit.jupiter.api.Assertions; +import org.junit.jupiter.api.Test; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.boot.test.context.SpringBootTest; + +import java.util.List; + +@SpringBootTest +public class JpaCabinetTests { + private static final Logger log = LoggerFactory.getLogger(JpaCabinetTests.class); + @Autowired + private ComputerService computerService; + @Autowired + private MonitorService monitorService; + @Autowired + private CabinetService cabinetService; + + @Test + void testCabinetCreate() { + cabinetService.deleteAllCabinets(); + final Cabinet cabinet = cabinetService.addCabinet("18"); + log.info(cabinet.toString()); + Assertions.assertNotNull(cabinet.getId()); + } + @Test + void testCabinetRead() { + cabinetService.deleteAllCabinets(); + final Cabinet cabinet = cabinetService.addCabinet("18"); + log.info(cabinet.toString()); + final Cabinet findCabinet = cabinetService.findCabinet(cabinet.getId()); + log.info(findCabinet.toString()); + Assertions.assertEquals(cabinet, findCabinet); + } + @Test + void testCabinetReadNotFound() { + cabinetService.deleteAllCabinets(); + Assertions.assertThrows(CabinetNotFoundException.class, () -> cabinetService.findCabinet(-1L)); + } + @Test + void testCabinetReadAll() { + cabinetService.deleteAllCabinets(); + cabinetService.addCabinet("18"); + cabinetService.addCabinet("19"); + final List cabinets = cabinetService.findAllCabinets(); + log.info(cabinets.toString()); + Assertions.assertEquals(cabinets.size(), 2); + } + @Test + void testComputerReadAllEmpty() { + cabinetService.deleteAllCabinets(); + final List cabinets = cabinetService.findAllCabinets(); + log.info(cabinets.toString()); + Assertions.assertEquals(cabinets.size(), 0); + } +} diff --git a/backend/src/test/java/com/kalyshev/yan/JpaComputerCabinetTests.java b/backend/src/test/java/com/kalyshev/yan/JpaComputerCabinetTests.java new file mode 100644 index 0000000..8c05d06 --- /dev/null +++ b/backend/src/test/java/com/kalyshev/yan/JpaComputerCabinetTests.java @@ -0,0 +1,85 @@ +package com.kalyshev.yan; + +import com.kalyshev.yan.cabinet.model.Cabinet; +import com.kalyshev.yan.cabinet.service.CabinetService; +import com.kalyshev.yan.computer.model.Computer; +import com.kalyshev.yan.computer.service.ComputerService; +import com.kalyshev.yan.monitor.model.Monitor; +import com.kalyshev.yan.monitor.service.MonitorService; +import org.junit.jupiter.api.Assertions; +import org.junit.jupiter.api.Test; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.boot.test.context.SpringBootTest; + +@SpringBootTest +public class JpaComputerCabinetTests { + private static final Logger log = LoggerFactory.getLogger(JpaCabinetTests.class); + @Autowired + private ComputerService computerService; + @Autowired + private MonitorService monitorService; + @Autowired + private CabinetService cabinetService; + + @Test + void testCabinetAddOneToMany() { + cabinetService.deleteAllCabinets(); + computerService.deleteAllComputers(); + computerService.deleteAllMonitorsWithRelations(); + final Cabinet cabinet = cabinetService.addCabinet("18"); + final Monitor monitor = monitorService.addMonitor("Asus"); + final Computer computer = computerService.addComputer("PC", "78457h", monitor.getId()); + cabinet.addComputer(computer); + log.info(cabinet.toString()); + log.info(computer.toString()); + Assertions.assertEquals(cabinet.getComputers().get(0).getSerialNum(), computer.getSerialNum()); + } + + @Test + void testCabinetDeleteOneToMany() { + cabinetService.deleteAllCabinets(); + computerService.deleteAllComputers(); + computerService.deleteAllMonitorsWithRelations(); + final Cabinet cabinet = cabinetService.addCabinet("18"); + final Monitor monitor = monitorService.addMonitor("Asus"); + final Computer computer = computerService.addComputer("PC", "78457h", monitor.getId()); + cabinet.addComputer(computer); + log.info(cabinet.toString()); + log.info(computer.toString()); + Assertions.assertEquals(cabinet.getComputers().get(0).getSerialNum(), computer.getSerialNum()); + cabinet.removeComputer(computer); + Assertions.assertEquals(cabinet.getComputers().size(), 0); + } + + @Test + void testComputerAddManyToMany() { + cabinetService.deleteAllCabinets(); + computerService.deleteAllComputers(); + computerService.deleteAllMonitorsWithRelations(); + final Cabinet cabinet = cabinetService.addCabinet("18"); + final Monitor monitor = monitorService.addMonitor("Asus"); + final Computer computer = computerService.addComputer("PC", "78457h", monitor.getId()); + computer.setCabinet(cabinet); + log.info(cabinet.toString()); + log.info(computer.toString()); + Assertions.assertEquals(computer.getCabinet().getNumber(), cabinet.getNumber()); + } + + @Test + void testComputerDeleteManyToMany() { + cabinetService.deleteAllCabinets(); + computerService.deleteAllComputers(); + computerService.deleteAllMonitorsWithRelations(); + final Cabinet cabinet = cabinetService.addCabinet("18"); + final Monitor monitor = monitorService.addMonitor("Asus"); + final Computer computer = computerService.addComputer("PC", "78457h", monitor.getId()); + computer.setCabinet(cabinet); + log.info(cabinet.toString()); + log.info(computer.toString()); + Assertions.assertEquals(computer.getCabinet().getNumber(), cabinet.getNumber()); + computer.setCabinet(null); + Assertions.assertNull(computer.getCabinet()); + } +} diff --git a/backend/src/test/java/com/kalyshev/yan/JpaComputerTests.java b/backend/src/test/java/com/kalyshev/yan/JpaComputerTests.java new file mode 100644 index 0000000..007d090 --- /dev/null +++ b/backend/src/test/java/com/kalyshev/yan/JpaComputerTests.java @@ -0,0 +1,89 @@ +package com.kalyshev.yan; + +import com.kalyshev.yan.cabinet.model.Cabinet; +import com.kalyshev.yan.cabinet.service.CabinetService; +import com.kalyshev.yan.computer.model.Computer; +import com.kalyshev.yan.computer.repository.ComputerNotFoundException; +import com.kalyshev.yan.computer.service.ComputerService; +import com.kalyshev.yan.monitor.model.Monitor; +import com.kalyshev.yan.monitor.service.MonitorService; +import org.junit.jupiter.api.Assertions; +import org.junit.jupiter.api.Test; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.boot.test.context.SpringBootTest; + +import java.util.List; + +@SpringBootTest +public class JpaComputerTests { + private static final Logger log = LoggerFactory.getLogger(JpaComputerTests.class); + @Autowired + private ComputerService computerService; + @Autowired + private MonitorService monitorService; + @Autowired + private CabinetService cabinetService; + + @Test + void testComputerPartialCreate() { + computerService.deleteAllComputers(); + final Monitor monitor = monitorService.addMonitor("Asus"); + final Computer computer = computerService.addComputer("Computer", "w7894572", monitor.getId()); + log.info(computer.toString()); + Assertions.assertNotNull(computer.getId()); + Assertions.assertNull(computer.getCabinet()); + } + @Test + void testComputerFullCreate() { + computerService.deleteAllComputers(); + final Monitor monitor = monitorService.addMonitor("Asus"); + final Cabinet cabinet = cabinetService.addCabinet("18a"); + final Computer computer = computerService.addComputer("Computer", "w7894572", monitor.getId()); + computer.setCabinet(cabinet); + log.info(computer.toString()); + Assertions.assertNotNull(computer.getId()); + Assertions.assertEquals(cabinet, computer.getCabinet()); + } + @Test + void testComputerDelete() { + computerService.deleteAllComputers(); + final Monitor monitor = monitorService.addMonitor("Asus"); + final Computer computer = computerService.addComputer("Computer", "w7894572", null); + log.info(computer.toString()); + computerService.deleteComputer(computer.getId()); + Assertions.assertThrows(ComputerNotFoundException.class, () -> computerService.findComputer(computer.getId())); + } + @Test + void testComputerRead() { + computerService.deleteAllComputers(); + final Computer computer = computerService.addComputer("Computer", "w7894572", null); + log.info(computer.toString()); + final Computer findComputer = computerService.findComputer(computer.getId()); + log.info(findComputer.toString()); + Assertions.assertEquals(computer, findComputer); + } + @Test + void testComputerReadNotFound() { + computerService.deleteAllComputers(); + Assertions.assertThrows(ComputerNotFoundException.class, () -> computerService.findComputer(-1L)); + } + @Test + void testComputerReadAll() { + computerService.deleteAllComputers(); + final Monitor monitor = monitorService.addMonitor("Asus"); + computerService.addComputer("Computer", "w7894572", null); + computerService.addComputer("Another comp", "3453s", null); + final List computers = computerService.findAllComputers(); + log.info(computers.toString()); + Assertions.assertEquals(computers.size(), 2); + } + @Test + void testComputerReadAllEmpty() { + computerService.deleteAllComputers(); + final List computers = computerService.findAllComputers(); + log.info(computers.toString()); + Assertions.assertEquals(computers.size(), 0); + } +} diff --git a/backend/src/test/java/com/kalyshev/yan/JpaMonitorTests.java b/backend/src/test/java/com/kalyshev/yan/JpaMonitorTests.java new file mode 100644 index 0000000..03dc8a5 --- /dev/null +++ b/backend/src/test/java/com/kalyshev/yan/JpaMonitorTests.java @@ -0,0 +1,78 @@ +package com.kalyshev.yan; + +import com.kalyshev.yan.computer.model.Computer; +import com.kalyshev.yan.computer.service.ComputerService; +import com.kalyshev.yan.monitor.model.Monitor; +import com.kalyshev.yan.monitor.repository.MonitorNotFoundException; +import com.kalyshev.yan.monitor.service.MonitorService; +import org.junit.jupiter.api.Assertions; +import org.junit.jupiter.api.Test; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.boot.test.context.SpringBootTest; + +import java.util.List; +@SpringBootTest +public class JpaMonitorTests { + private static final Logger log = LoggerFactory.getLogger(JpaMonitorTests.class); + @Autowired + private MonitorService monitorService; + @Autowired + private ComputerService computerService; + @Test + void testMonitorCreate() { + computerService.deleteAllMonitorsWithRelations(); + final Monitor monitor = monitorService.addMonitor("Asus"); + log.info(monitor.toString()); + Assertions.assertNotNull(monitor.getId()); + } + @Test + void testMonitorRead() { + computerService.deleteAllMonitorsWithRelations(); + final Monitor monitor = monitorService.addMonitor("Asus"); + log.info(monitor.toString()); + final Monitor findMonitor = monitorService.findMonitor(monitor.getId()); + log.info(findMonitor.toString()); + Assertions.assertEquals(monitor, findMonitor); + } + @Test + void testMonitorDelete() { + computerService.deleteAllMonitorsWithRelations(); + final Monitor monitor = monitorService.addMonitor("Asus"); + log.info(monitor.toString()); + computerService.deleteMonitorWithRelation(monitor.getId()); + Assertions.assertThrows(MonitorNotFoundException.class, () -> monitorService.findMonitor(monitor.getId())); + } + @Test + void testMonitorReadNotFound() { + computerService.deleteAllMonitorsWithRelations(); + Assertions.assertThrows(MonitorNotFoundException.class, () -> monitorService.findMonitor(-1L)); + } + @Test + void testMonitorReadAll() { + computerService.deleteAllMonitorsWithRelations(); + monitorService.addMonitor("Asus"); + monitorService.addMonitor("HP"); + final List monitors = monitorService.findAllMonitors(); + log.info(monitors.toString()); + Assertions.assertEquals(monitors.size(), 2); + } + @Test + void testMonitorReadAllEmpty() { + computerService.deleteAllMonitorsWithRelations(); + final List monitors = monitorService.findAllMonitors(); + log.info(monitors.toString()); + Assertions.assertEquals(monitors.size(), 0); + } + @Test + void testMonitorGetComputer() { + computerService.deleteAllMonitorsWithRelations(); + computerService.deleteAllComputers(); + Monitor monitor = monitorService.addMonitor("Asus"); + Computer computer = computerService.addComputer("Model", "6sfv4", monitor.getId()); + log.info(computer.toString()); + Computer fetchedComputer = computerService.findComputerByMonitor(monitor); + Assertions.assertEquals(computer, fetchedComputer); + } +}