Compare commits

...

22 Commits

Author SHA1 Message Date
22fcd61211 done 2023-05-16 10:55:37 +04:00
c6d8371cc7 added columns id and role to users page 2023-05-15 18:35:59 +04:00
87c21ffc90 added user page 2023-05-15 18:02:29 +04:00
26b3c76145 init of users page (not work) 2023-05-15 16:32:21 +04:00
89dacc5f7a fixed warnings 2023-05-13 15:57:39 +04:00
464d7f112b added signup 2023-05-13 15:56:13 +04:00
d47e866492 fixed warnings 2023-05-13 00:18:55 +04:00
10a413e9c1 added login and start of signup 2023-05-13 00:12:10 +04:00
e007f51d04 done 2023-04-25 16:24:49 +04:00
1faa719f92 final 2023-04-25 09:54:52 +04:00
root
5c09ff94f8 started front and changes in back 2023-04-24 23:23:43 +04:00
root
e64d4e6434 fixed issues and tests 2023-04-23 19:08:08 +04:00
root
019bcc6411 added repositories, dtos, validator, changed services and controllers 2023-04-23 18:49:35 +04:00
a73685f3b3 done 2023-04-11 19:23:19 +04:00
e620af3165 some done 2023-04-11 11:37:31 +04:00
13a162f744 19 version 2023-04-11 00:55:22 +04:00
6f91e433fa fixed for vscode 2023-04-11 00:51:47 +04:00
root
7eff23080c final 2023-04-10 20:58:47 +04:00
Zyzf
951bf3001f backend 2023-03-28 08:54:21 +04:00
Zyzf
a15ed7c52b backend 2023-03-28 08:53:50 +04:00
Zyzf
edbbe4d2b1 done 2023-02-28 13:51:45 +04:00
Zyzf
7330e6e550 backend 2023-02-28 12:15:53 +04:00
85 changed files with 4920 additions and 667 deletions

2
.gitignore vendored
View File

@ -4,6 +4,8 @@ build/
!gradle/wrapper/gradle-wrapper.jar
!**/src/main/**/build/
!**/src/test/**/build/
data.mv.db
data.trace.db
### STS ###
.apt_generated

View File

@ -1,6 +1,6 @@
plugins {
id 'java'
id 'org.springframework.boot' version '3.0.2'
id 'org.springframework.boot' version '2.6.3'
id 'io.spring.dependency-management' version '1.1.0'
}
@ -12,8 +12,26 @@ repositories {
mavenCentral()
}
jar {
enabled = false
}
dependencies {
annotationProcessor "org.springframework.boot:spring-boot-configuration-processor"
implementation 'org.springframework.boot:spring-boot-starter-web'
implementation 'org.springframework.boot:spring-boot-starter-data-jpa'
implementation 'com.h2database:h2:2.1.210'
implementation 'org.springframework.boot:spring-boot-starter-security'
implementation 'com.auth0:java-jwt:4.4.0'
implementation 'org.hibernate.validator:hibernate-validator'
implementation 'org.springdoc:springdoc-openapi-ui:1.6.5'
testImplementation 'org.springframework.boot:spring-boot-starter-test'
}

View File

@ -1,49 +0,0 @@
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="content-type" content="text/html; charset=utf-8" />
<title>Тестовое приложение</title>
<link href="/node_modules/bootstrap/dist/css/bootstrap.min.css" rel="stylesheet">
</head>
<body style="padding: 10px;">
<h2>Конвертр текста!</h2>
<form class="needs-validation" novalidate>
<div class="mb-3">
<label for="input" class="form-label">Ваш текст</label>
<input type="text" class="form-control" id="input" required>
<div class="invalid-feedback">Пожалуйста, введите текст</div>
</div>
<div class="mb-3">
<div class="form-check">
<input class="form-check-input" type="radio" name="radio" id="radioUppercase" checked>
<label class="form-check-label" for="radioUppercase">Undercase</label>
</div>
</div>
<div class="mb-3">
<div class="form-check">
<input class="form-check-input" type="radio" name="radio" id="radioLowcase">
<label class="form-check-label" for="radioLowcase">Lowcase</label>
</div>
</div>
<div class="mb-3">
<div class="form-check">
<input class="form-check-input" type="radio" name="radio" id="radioSplit">
<label class="form-check-label" for="radioSplit">Split</label>
<input type="text" class="form-control" id="inputSplitBy">
</div>
</div>
<div class="mb-3">
<div class="form-check">
<input class="form-check-input" type="radio" name="radio" id="radioReplace">
<label class="form-check-label" for="radioReplace">Replace</label>
<input type="text" class="form-control" id="inputReplaceOld" maxlength="1">
<input type="text" class="form-control" id="inputReplaceNew" maxlength="1">
</div>
</div>
<button type="submit" class="btn btn-primary">Обработать</button>
</form>
<h2>Результат:</h2>
<p id="result"></p>
</body>
<script src="index.js"></script>
</html>

View File

@ -1,41 +0,0 @@
document.addEventListener('DOMContentLoaded', function() {
var forms = document.querySelectorAll('.needs-validation');
Array.from(forms).forEach(form => {
form.addEventListener('submit', event => {
if (!form.checkValidity()) {
event.preventDefault();
event.stopPropagation();
}
form.classList.add('was-validated');
}, false);
});
});
document.getElementsByClassName("needs-validation")[0].addEventListener('submit', async function(event) {
event.preventDefault();
url = ""
if (document.getElementById("radioUppercase").checked) {
url = "http://localhost:8080/uppercase?value=" + document.getElementById("input").value
}
if (document.getElementById("radioLowcase").checked) {
url = "http://localhost:8080/lowercase?value=" + document.getElementById("input").value
}
if (document.getElementById("radioSplit").checked) {
url = "http://localhost:8080/split?value=" + document.getElementById("input").value + "&splitBy=" + document.getElementById("inputSplitBy").value
}
if (document.getElementById("radioReplace").checked) {
url = "http://localhost:8080/replace?value=" + document.getElementById("input").value + "&old=" + document.getElementById("inputReplaceOld").value + "&new=" + document.getElementById("inputReplaceNew").value
}
if (url == "") {
document.getElementById("result").innerHTML = "Выберите действие!"
}
// performFetch(url).then(data => {document.getElementById("result").innerHTML = data})
document.getElementById("result").innerHTML = await performFetch(url)
});
async function performFetch(url) {
let resp = await fetch(url)
return await resp.text()
}

472
front/package-lock.json generated
View File

@ -1,472 +0,0 @@
{
"name": "front",
"version": "1.0.0",
"lockfileVersion": 3,
"requires": true,
"packages": {
"": {
"name": "front",
"version": "1.0.0",
"dependencies": {
"bootstrap": "5.2.1"
},
"devDependencies": {
"http-server": "14.1.1"
}
},
"node_modules/@popperjs/core": {
"version": "2.11.6",
"resolved": "https://registry.npmjs.org/@popperjs/core/-/core-2.11.6.tgz",
"integrity": "sha512-50/17A98tWUfQ176raKiOGXuYpLyyVMkxxG6oylzL3BPOlA6ADGdK7EYunSa4I064xerltq9TGXs8HmOk5E+vw==",
"peer": true,
"funding": {
"type": "opencollective",
"url": "https://opencollective.com/popperjs"
}
},
"node_modules/ansi-styles": {
"version": "4.3.0",
"resolved": "https://registry.npmjs.org/ansi-styles/-/ansi-styles-4.3.0.tgz",
"integrity": "sha512-zbB9rCJAT1rbjiVDb2hqKFHNYLxgtk8NURxZ3IZwD3F6NtxbXZQCnnSi1Lkx+IDohdPlFp222wVALIheZJQSEg==",
"dev": true,
"dependencies": {
"color-convert": "^2.0.1"
},
"engines": {
"node": ">=8"
},
"funding": {
"url": "https://github.com/chalk/ansi-styles?sponsor=1"
}
},
"node_modules/async": {
"version": "2.6.4",
"resolved": "https://registry.npmjs.org/async/-/async-2.6.4.tgz",
"integrity": "sha512-mzo5dfJYwAn29PeiJ0zvwTo04zj8HDJj0Mn8TD7sno7q12prdbnasKJHhkm2c1LgrhlJ0teaea8860oxi51mGA==",
"dev": true,
"dependencies": {
"lodash": "^4.17.14"
}
},
"node_modules/basic-auth": {
"version": "2.0.1",
"resolved": "https://registry.npmjs.org/basic-auth/-/basic-auth-2.0.1.tgz",
"integrity": "sha512-NF+epuEdnUYVlGuhaxbbq+dvJttwLnGY+YixlXlME5KpQ5W3CnXA5cVTneY3SPbPDRkcjMbifrwmFYcClgOZeg==",
"dev": true,
"dependencies": {
"safe-buffer": "5.1.2"
},
"engines": {
"node": ">= 0.8"
}
},
"node_modules/bootstrap": {
"version": "5.2.1",
"resolved": "https://registry.npmjs.org/bootstrap/-/bootstrap-5.2.1.tgz",
"integrity": "sha512-UQi3v2NpVPEi1n35dmRRzBJFlgvWHYwyem6yHhuT6afYF+sziEt46McRbT//kVXZ7b1YUYEVGdXEH74Nx3xzGA==",
"funding": [
{
"type": "github",
"url": "https://github.com/sponsors/twbs"
},
{
"type": "opencollective",
"url": "https://opencollective.com/bootstrap"
}
],
"peerDependencies": {
"@popperjs/core": "^2.11.6"
}
},
"node_modules/call-bind": {
"version": "1.0.2",
"resolved": "https://registry.npmjs.org/call-bind/-/call-bind-1.0.2.tgz",
"integrity": "sha512-7O+FbCihrB5WGbFYesctwmTKae6rOiIzmz1icreWJ+0aA7LJfuqhEso2T9ncpcFtzMQtzXf2QGGueWJGTYsqrA==",
"dev": true,
"dependencies": {
"function-bind": "^1.1.1",
"get-intrinsic": "^1.0.2"
},
"funding": {
"url": "https://github.com/sponsors/ljharb"
}
},
"node_modules/chalk": {
"version": "4.1.2",
"resolved": "https://registry.npmjs.org/chalk/-/chalk-4.1.2.tgz",
"integrity": "sha512-oKnbhFyRIXpUuez8iBMmyEa4nbj4IOQyuhc/wy9kY7/WVPcwIO9VA668Pu8RkO7+0G76SLROeyw9CpQ061i4mA==",
"dev": true,
"dependencies": {
"ansi-styles": "^4.1.0",
"supports-color": "^7.1.0"
},
"engines": {
"node": ">=10"
},
"funding": {
"url": "https://github.com/chalk/chalk?sponsor=1"
}
},
"node_modules/color-convert": {
"version": "2.0.1",
"resolved": "https://registry.npmjs.org/color-convert/-/color-convert-2.0.1.tgz",
"integrity": "sha512-RRECPsj7iu/xb5oKYcsFHSppFNnsj/52OVTRKb4zP5onXwVF3zVmmToNcOfGC+CRDpfK/U584fMg38ZHCaElKQ==",
"dev": true,
"dependencies": {
"color-name": "~1.1.4"
},
"engines": {
"node": ">=7.0.0"
}
},
"node_modules/color-name": {
"version": "1.1.4",
"resolved": "https://registry.npmjs.org/color-name/-/color-name-1.1.4.tgz",
"integrity": "sha512-dOy+3AuW3a2wNbZHIuMZpTcgjGuLU/uBL/ubcZF9OXbDo8ff4O8yVp5Bf0efS8uEoYo5q4Fx7dY9OgQGXgAsQA==",
"dev": true
},
"node_modules/corser": {
"version": "2.0.1",
"resolved": "https://registry.npmjs.org/corser/-/corser-2.0.1.tgz",
"integrity": "sha512-utCYNzRSQIZNPIcGZdQc92UVJYAhtGAteCFg0yRaFm8f0P+CPtyGyHXJcGXnffjCybUCEx3FQ2G7U3/o9eIkVQ==",
"dev": true,
"engines": {
"node": ">= 0.4.0"
}
},
"node_modules/debug": {
"version": "3.2.7",
"resolved": "https://registry.npmjs.org/debug/-/debug-3.2.7.tgz",
"integrity": "sha512-CFjzYYAi4ThfiQvizrFQevTTXHtnCqWfe7x1AhgEscTz6ZbLbfoLRLPugTQyBth6f8ZERVUSyWHFD/7Wu4t1XQ==",
"dev": true,
"dependencies": {
"ms": "^2.1.1"
}
},
"node_modules/eventemitter3": {
"version": "4.0.7",
"resolved": "https://registry.npmjs.org/eventemitter3/-/eventemitter3-4.0.7.tgz",
"integrity": "sha512-8guHBZCwKnFhYdHr2ysuRWErTwhoN2X8XELRlrRwpmfeY2jjuUN4taQMsULKUVo1K4DvZl+0pgfyoysHxvmvEw==",
"dev": true
},
"node_modules/follow-redirects": {
"version": "1.15.2",
"resolved": "https://registry.npmjs.org/follow-redirects/-/follow-redirects-1.15.2.tgz",
"integrity": "sha512-VQLG33o04KaQ8uYi2tVNbdrWp1QWxNNea+nmIB4EVM28v0hmP17z7aG1+wAkNzVq4KeXTq3221ye5qTJP91JwA==",
"dev": true,
"funding": [
{
"type": "individual",
"url": "https://github.com/sponsors/RubenVerborgh"
}
],
"engines": {
"node": ">=4.0"
},
"peerDependenciesMeta": {
"debug": {
"optional": true
}
}
},
"node_modules/function-bind": {
"version": "1.1.1",
"resolved": "https://registry.npmjs.org/function-bind/-/function-bind-1.1.1.tgz",
"integrity": "sha512-yIovAzMX49sF8Yl58fSCWJ5svSLuaibPxXQJFLmBObTuCr0Mf1KiPopGM9NiFjiYBCbfaa2Fh6breQ6ANVTI0A==",
"dev": true
},
"node_modules/get-intrinsic": {
"version": "1.2.0",
"resolved": "https://registry.npmjs.org/get-intrinsic/-/get-intrinsic-1.2.0.tgz",
"integrity": "sha512-L049y6nFOuom5wGyRc3/gdTLO94dySVKRACj1RmJZBQXlbTMhtNIgkWkUHq+jYmZvKf14EW1EoJnnjbmoHij0Q==",
"dev": true,
"dependencies": {
"function-bind": "^1.1.1",
"has": "^1.0.3",
"has-symbols": "^1.0.3"
},
"funding": {
"url": "https://github.com/sponsors/ljharb"
}
},
"node_modules/has": {
"version": "1.0.3",
"resolved": "https://registry.npmjs.org/has/-/has-1.0.3.tgz",
"integrity": "sha512-f2dvO0VU6Oej7RkWJGrehjbzMAjFp5/VKPp5tTpWIV4JHHZK1/BxbFRtf/siA2SWTe09caDmVtYYzWEIbBS4zw==",
"dev": true,
"dependencies": {
"function-bind": "^1.1.1"
},
"engines": {
"node": ">= 0.4.0"
}
},
"node_modules/has-flag": {
"version": "4.0.0",
"resolved": "https://registry.npmjs.org/has-flag/-/has-flag-4.0.0.tgz",
"integrity": "sha512-EykJT/Q1KjTWctppgIAgfSO0tKVuZUjhgMr17kqTumMl6Afv3EISleU7qZUzoXDFTAHTDC4NOoG/ZxU3EvlMPQ==",
"dev": true,
"engines": {
"node": ">=8"
}
},
"node_modules/has-symbols": {
"version": "1.0.3",
"resolved": "https://registry.npmjs.org/has-symbols/-/has-symbols-1.0.3.tgz",
"integrity": "sha512-l3LCuF6MgDNwTDKkdYGEihYjt5pRPbEg46rtlmnSPlUbgmB8LOIrKJbYYFBSbnPaJexMKtiPO8hmeRjRz2Td+A==",
"dev": true,
"engines": {
"node": ">= 0.4"
},
"funding": {
"url": "https://github.com/sponsors/ljharb"
}
},
"node_modules/he": {
"version": "1.2.0",
"resolved": "https://registry.npmjs.org/he/-/he-1.2.0.tgz",
"integrity": "sha512-F/1DnUGPopORZi0ni+CvrCgHQ5FyEAHRLSApuYWMmrbSwoN2Mn/7k+Gl38gJnR7yyDZk6WLXwiGod1JOWNDKGw==",
"dev": true,
"bin": {
"he": "bin/he"
}
},
"node_modules/html-encoding-sniffer": {
"version": "3.0.0",
"resolved": "https://registry.npmjs.org/html-encoding-sniffer/-/html-encoding-sniffer-3.0.0.tgz",
"integrity": "sha512-oWv4T4yJ52iKrufjnyZPkrN0CH3QnrUqdB6In1g5Fe1mia8GmF36gnfNySxoZtxD5+NmYw1EElVXiBk93UeskA==",
"dev": true,
"dependencies": {
"whatwg-encoding": "^2.0.0"
},
"engines": {
"node": ">=12"
}
},
"node_modules/http-proxy": {
"version": "1.18.1",
"resolved": "https://registry.npmjs.org/http-proxy/-/http-proxy-1.18.1.tgz",
"integrity": "sha512-7mz/721AbnJwIVbnaSv1Cz3Am0ZLT/UBwkC92VlxhXv/k/BBQfM2fXElQNC27BVGr0uwUpplYPQM9LnaBMR5NQ==",
"dev": true,
"dependencies": {
"eventemitter3": "^4.0.0",
"follow-redirects": "^1.0.0",
"requires-port": "^1.0.0"
},
"engines": {
"node": ">=8.0.0"
}
},
"node_modules/http-server": {
"version": "14.1.1",
"resolved": "https://registry.npmjs.org/http-server/-/http-server-14.1.1.tgz",
"integrity": "sha512-+cbxadF40UXd9T01zUHgA+rlo2Bg1Srer4+B4NwIHdaGxAGGv59nYRnGGDJ9LBk7alpS0US+J+bLLdQOOkJq4A==",
"dev": true,
"dependencies": {
"basic-auth": "^2.0.1",
"chalk": "^4.1.2",
"corser": "^2.0.1",
"he": "^1.2.0",
"html-encoding-sniffer": "^3.0.0",
"http-proxy": "^1.18.1",
"mime": "^1.6.0",
"minimist": "^1.2.6",
"opener": "^1.5.1",
"portfinder": "^1.0.28",
"secure-compare": "3.0.1",
"union": "~0.5.0",
"url-join": "^4.0.1"
},
"bin": {
"http-server": "bin/http-server"
},
"engines": {
"node": ">=12"
}
},
"node_modules/iconv-lite": {
"version": "0.6.3",
"resolved": "https://registry.npmjs.org/iconv-lite/-/iconv-lite-0.6.3.tgz",
"integrity": "sha512-4fCk79wshMdzMp2rH06qWrJE4iolqLhCUH+OiuIgU++RB0+94NlDL81atO7GX55uUKueo0txHNtvEyI6D7WdMw==",
"dev": true,
"dependencies": {
"safer-buffer": ">= 2.1.2 < 3.0.0"
},
"engines": {
"node": ">=0.10.0"
}
},
"node_modules/lodash": {
"version": "4.17.21",
"resolved": "https://registry.npmjs.org/lodash/-/lodash-4.17.21.tgz",
"integrity": "sha512-v2kDEe57lecTulaDIuNTPy3Ry4gLGJ6Z1O3vE1krgXZNrsQ+LFTGHVxVjcXPs17LhbZVGedAJv8XZ1tvj5FvSg==",
"dev": true
},
"node_modules/mime": {
"version": "1.6.0",
"resolved": "https://registry.npmjs.org/mime/-/mime-1.6.0.tgz",
"integrity": "sha512-x0Vn8spI+wuJ1O6S7gnbaQg8Pxh4NNHb7KSINmEWKiPE4RKOplvijn+NkmYmmRgP68mc70j2EbeTFRsrswaQeg==",
"dev": true,
"bin": {
"mime": "cli.js"
},
"engines": {
"node": ">=4"
}
},
"node_modules/minimist": {
"version": "1.2.8",
"resolved": "https://registry.npmjs.org/minimist/-/minimist-1.2.8.tgz",
"integrity": "sha512-2yyAR8qBkN3YuheJanUpWC5U3bb5osDywNB8RzDVlDwDHbocAJveqqj1u8+SVD7jkWT4yvsHCpWqqWqAxb0zCA==",
"dev": true,
"funding": {
"url": "https://github.com/sponsors/ljharb"
}
},
"node_modules/mkdirp": {
"version": "0.5.6",
"resolved": "https://registry.npmjs.org/mkdirp/-/mkdirp-0.5.6.tgz",
"integrity": "sha512-FP+p8RB8OWpF3YZBCrP5gtADmtXApB5AMLn+vdyA+PyxCjrCs00mjyUozssO33cwDeT3wNGdLxJ5M//YqtHAJw==",
"dev": true,
"dependencies": {
"minimist": "^1.2.6"
},
"bin": {
"mkdirp": "bin/cmd.js"
}
},
"node_modules/ms": {
"version": "2.1.3",
"resolved": "https://registry.npmjs.org/ms/-/ms-2.1.3.tgz",
"integrity": "sha512-6FlzubTLZG3J2a/NVCAleEhjzq5oxgHyaCU9yYXvcLsvoVaHJq/s5xXI6/XXP6tz7R9xAOtHnSO/tXtF3WRTlA==",
"dev": true
},
"node_modules/object-inspect": {
"version": "1.12.3",
"resolved": "https://registry.npmjs.org/object-inspect/-/object-inspect-1.12.3.tgz",
"integrity": "sha512-geUvdk7c+eizMNUDkRpW1wJwgfOiOeHbxBR/hLXK1aT6zmVSO0jsQcs7fj6MGw89jC/cjGfLcNOrtMYtGqm81g==",
"dev": true,
"funding": {
"url": "https://github.com/sponsors/ljharb"
}
},
"node_modules/opener": {
"version": "1.5.2",
"resolved": "https://registry.npmjs.org/opener/-/opener-1.5.2.tgz",
"integrity": "sha512-ur5UIdyw5Y7yEj9wLzhqXiy6GZ3Mwx0yGI+5sMn2r0N0v3cKJvUmFH5yPP+WXh9e0xfyzyJX95D8l088DNFj7A==",
"dev": true,
"bin": {
"opener": "bin/opener-bin.js"
}
},
"node_modules/portfinder": {
"version": "1.0.32",
"resolved": "https://registry.npmjs.org/portfinder/-/portfinder-1.0.32.tgz",
"integrity": "sha512-on2ZJVVDXRADWE6jnQaX0ioEylzgBpQk8r55NE4wjXW1ZxO+BgDlY6DXwj20i0V8eB4SenDQ00WEaxfiIQPcxg==",
"dev": true,
"dependencies": {
"async": "^2.6.4",
"debug": "^3.2.7",
"mkdirp": "^0.5.6"
},
"engines": {
"node": ">= 0.12.0"
}
},
"node_modules/qs": {
"version": "6.11.0",
"resolved": "https://registry.npmjs.org/qs/-/qs-6.11.0.tgz",
"integrity": "sha512-MvjoMCJwEarSbUYk5O+nmoSzSutSsTwF85zcHPQ9OrlFoZOYIjaqBAJIqIXjptyD5vThxGq52Xu/MaJzRkIk4Q==",
"dev": true,
"dependencies": {
"side-channel": "^1.0.4"
},
"engines": {
"node": ">=0.6"
},
"funding": {
"url": "https://github.com/sponsors/ljharb"
}
},
"node_modules/requires-port": {
"version": "1.0.0",
"resolved": "https://registry.npmjs.org/requires-port/-/requires-port-1.0.0.tgz",
"integrity": "sha512-KigOCHcocU3XODJxsu8i/j8T9tzT4adHiecwORRQ0ZZFcp7ahwXuRU1m+yuO90C5ZUyGeGfocHDI14M3L3yDAQ==",
"dev": true
},
"node_modules/safe-buffer": {
"version": "5.1.2",
"resolved": "https://registry.npmjs.org/safe-buffer/-/safe-buffer-5.1.2.tgz",
"integrity": "sha512-Gd2UZBJDkXlY7GbJxfsE8/nvKkUEU1G38c1siN6QP6a9PT9MmHB8GnpscSmMJSoF8LOIrt8ud/wPtojys4G6+g==",
"dev": true
},
"node_modules/safer-buffer": {
"version": "2.1.2",
"resolved": "https://registry.npmjs.org/safer-buffer/-/safer-buffer-2.1.2.tgz",
"integrity": "sha512-YZo3K82SD7Riyi0E1EQPojLz7kpepnSQI9IyPbHHg1XXXevb5dJI7tpyN2ADxGcQbHG7vcyRHk0cbwqcQriUtg==",
"dev": true
},
"node_modules/secure-compare": {
"version": "3.0.1",
"resolved": "https://registry.npmjs.org/secure-compare/-/secure-compare-3.0.1.tgz",
"integrity": "sha512-AckIIV90rPDcBcglUwXPF3kg0P0qmPsPXAj6BBEENQE1p5yA1xfmDJzfi1Tappj37Pv2mVbKpL3Z1T+Nn7k1Qw==",
"dev": true
},
"node_modules/side-channel": {
"version": "1.0.4",
"resolved": "https://registry.npmjs.org/side-channel/-/side-channel-1.0.4.tgz",
"integrity": "sha512-q5XPytqFEIKHkGdiMIrY10mvLRvnQh42/+GoBlFW3b2LXLE2xxJpZFdm94we0BaoV3RwJyGqg5wS7epxTv0Zvw==",
"dev": true,
"dependencies": {
"call-bind": "^1.0.0",
"get-intrinsic": "^1.0.2",
"object-inspect": "^1.9.0"
},
"funding": {
"url": "https://github.com/sponsors/ljharb"
}
},
"node_modules/supports-color": {
"version": "7.2.0",
"resolved": "https://registry.npmjs.org/supports-color/-/supports-color-7.2.0.tgz",
"integrity": "sha512-qpCAvRl9stuOHveKsn7HncJRvv501qIacKzQlO/+Lwxc9+0q2wLyv4Dfvt80/DPn2pqOBsJdDiogXGR9+OvwRw==",
"dev": true,
"dependencies": {
"has-flag": "^4.0.0"
},
"engines": {
"node": ">=8"
}
},
"node_modules/union": {
"version": "0.5.0",
"resolved": "https://registry.npmjs.org/union/-/union-0.5.0.tgz",
"integrity": "sha512-N6uOhuW6zO95P3Mel2I2zMsbsanvvtgn6jVqJv4vbVcz/JN0OkL9suomjQGmWtxJQXOCqUJvquc1sMeNz/IwlA==",
"dev": true,
"dependencies": {
"qs": "^6.4.0"
},
"engines": {
"node": ">= 0.8.0"
}
},
"node_modules/url-join": {
"version": "4.0.1",
"resolved": "https://registry.npmjs.org/url-join/-/url-join-4.0.1.tgz",
"integrity": "sha512-jk1+QP6ZJqyOiuEI9AEWQfju/nB2Pw466kbA0LEZljHwKeMgd9WrAEgEGxjPDD2+TNbbb37rTyhEfrCXfuKXnA==",
"dev": true
},
"node_modules/whatwg-encoding": {
"version": "2.0.0",
"resolved": "https://registry.npmjs.org/whatwg-encoding/-/whatwg-encoding-2.0.0.tgz",
"integrity": "sha512-p41ogyeMUrw3jWclHWTQg1k05DSVXPLcVxRTYsXUk+ZooOCZLcoYgPZ/HL/D/N+uQPOtcp1me1WhBEaX02mhWg==",
"dev": true,
"dependencies": {
"iconv-lite": "0.6.3"
},
"engines": {
"node": ">=12"
}
}
}
}

View File

@ -1,15 +0,0 @@
{
"name": "front",
"version": "1.0.0",
"main": "index.html",
"scripts": {
"web-server": "http-server -p 3000 ./",
"start": "npm run web-server"
},
"dependencies": {
"bootstrap": "5.2.1"
},
"devDependencies": {
"http-server": "14.1.1"
}
}

28
frontend/.gitignore vendored Normal file
View File

@ -0,0 +1,28 @@
# Logs
logs
*.log
npm-debug.log*
yarn-debug.log*
yarn-error.log*
pnpm-debug.log*
lerna-debug.log*
node_modules
.DS_Store
dist
dist-ssr
coverage
*.local
/cypress/videos/
/cypress/screenshots/
# Editor directories and files
.vscode/*
!.vscode/extensions.json
.idea
*.suo
*.ntvs*
*.njsproj
*.sln
*.sw?

29
frontend/README.md Normal file
View File

@ -0,0 +1,29 @@
# frontend
This template should help get you started developing with Vue 3 in Vite.
## Recommended IDE Setup
[VSCode](https://code.visualstudio.com/) + [Volar](https://marketplace.visualstudio.com/items?itemName=Vue.volar) (and disable Vetur) + [TypeScript Vue Plugin (Volar)](https://marketplace.visualstudio.com/items?itemName=Vue.vscode-typescript-vue-plugin).
## Customize configuration
See [Vite Configuration Reference](https://vitejs.dev/config/).
## Project Setup
```sh
npm install
```
### Compile and Hot-Reload for Development
```sh
npm run dev
```
### Compile and Minify for Production
```sh
npm run build
```

14
frontend/index.html Normal file
View File

@ -0,0 +1,14 @@
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<link rel="stylesheet" href="/node_modules/bootstrap/dist/css/bootstrap.min.css">
<title>Vite App</title>
</head>
<body>
<div id="app"></div>
<script type="module" src="/node_modules/bootstrap/dist/js/bootstrap.bundle.min.js"></script>
<script type="module" src="/src/main.js"></script>
</body>
</html>

1694
frontend/package-lock.json generated Normal file

File diff suppressed because it is too large Load Diff

21
frontend/package.json Normal file
View File

@ -0,0 +1,21 @@
{
"name": "frontend",
"version": "0.0.0",
"private": true,
"scripts": {
"dev": "vite",
"build": "vite build",
"preview": "vite preview"
},
"dependencies": {
"axios": "^1.3.6",
"bootstrap": "^5.2.3",
"vue": "^3.2.47",
"vue-router": "^4.1.6"
},
"devDependencies": {
"@vitejs/plugin-vue": "^4.0.0",
"@vitejs/plugin-vue-jsx": "^3.0.0",
"vite": "^4.1.4"
}
}

BIN
frontend/public/favicon.ico Normal file

Binary file not shown.

After

Width:  |  Height:  |  Size: 4.2 KiB

19
frontend/src/App.vue Normal file
View File

@ -0,0 +1,19 @@
<script>
import Header from './components/Header.vue';
export default {
components: {
Header
}
}
</script>
<template>
<Header></Header>
<div class="container-fluid">
<router-view></router-view>
</div>
</template>
<style scoped>
</style>

View File

@ -0,0 +1,140 @@
<script>
import axios from 'axios';
import CatalogMixins from '../mixins/CatalogMixins.js';
import Cabinet from "../models/Cabinet";
import Computer from '../models/Computer';
import Monitor from '../models/Monitor';
import DataService from '../services/DataService';
export default {
mixins: [
CatalogMixins
],
data() {
return {
getAllUrl: 'cabinet/',
dataUrl: 'cabinet',
transformer: (data) => new Cabinet(data),
headers: [
{ name: 'number', label: 'Номер кабинета' }
],
headersComps: [
{ name: 'modelName', label: 'Модель' },
{ name: 'serialNum', label: 'Серийный номер' },
{ name: 'monitorName', label: 'Модель монитора' }
],
selectedItemsComps: [],
dataFilterUrl: 'cabinet/filter?',
computerUrl: 'computer/',
computers: [],
monitorUrl: 'monitor/',
monitors: []
}
},
beforeCreate() {
if (localStorage.getItem("token") == null) {
this.$router.push("/login");
}
},
created() {
DataService.readAll(this.computerUrl, (data) => new Computer(data))
.then(data => {
this.computers = data;
});
DataService.readAll(this.monitorUrl, (data) => new Monitor(data))
.then(data => {
this.monitors = data;
});
},
methods: {
filter() {
let urlParams = ""
if (document.getElementById('numberFilterInput').value !== "") {
urlParams += "number=" + this.number;
}
DataService.readAll(this.dataFilterUrl + urlParams, (data) => new Cabinet(data))
.then(data => {
this.items = data;
});
},
clearFilters() {
this.loadItems();
this.id = null;
this.number = null;
},
addComputerInCabinet(cabinetId) {
let computerId = document.getElementById('computers').value;
let response = axios.post(`http://localhost:8080/api/cabinet/${cabinetId}/computer?computerId=${computerId}`);
console.log(response);
},
itemsComps(computerIds) {
let result = [];
if (typeof computerIds === 'undefined') {
return;
}
this.computers.forEach(computer => {
for (let i = 0; i < computerIds.length; i++) {
if (computer.id === computerIds[i]) {
for (let j = 0; j < this.monitors.length; j++) {
if (computer.monitorId === this.monitors[j].id) {
computer._monitor = this.monitors[j];
}
}
result.push(computer);
}
}
});
return result;
}
}
}
</script>
<template>
<div class="input-group mb-3">
<input type="text" class="form-control" id="numberFilterInput" placeholder="Номер кабинета" required v-model="number">
<button class="btn btn-primary" type="button" id="report-button"
@click.prevent="filter">Сформировать</button>
<button class="btn btn-outline-secondary" type="button" id="report-button"
@click.prevent="clearFilters">Очистить</button>
</div>
<ToolBar
@add="showAddModal"
@edit="showEditModal"
@remove="removeSelectedItems">
</ToolBar>
<DataTable
:headers="this.headers"
:items="this.items"
:selectedItems="this.selectedItems"
@dblclick="showEditModalDblClick">
</DataTable>
<Modal
:header="this.modal.header"
:confirm="this.modal.confirm"
v-model:visible="this.modalShow"
@done="saveItem">
<div class="mb-3">
<label for="number" class="form-label">Номер кабинета</label>
<input type="text" class="form-control" id="number" required v-model="data.number">
</div>
<DataTable
:headers="this.headersComps"
:items="itemsComps(data.computerIds)"
:selectedItems="this.selectedItemsComps">
</DataTable>
<div class="mb-3">
<label for="computers" class="form-label">Добавить компьютер</label>
<select class="form-select" id="computers" required>
<option disabled value="">Выберите компьютер</option>
<option v-for="computer in this.computers"
:value="computer.id">
{{ computer.modelName }}
</option>
</select>
</div>
<button class="btn btn-outline-secondary" type="button" id="addComputerButton"
@click.prevent="addComputerInCabinet(data.id)">Добавить</button>
</Modal>
</template>

View File

@ -0,0 +1,23 @@
<script>
export default {
data() {
return {
catalogs: [
{ name: 'orders', label: 'Заказы' },
// { name: 'students', label: 'Студенты' },
// { name: 'disciplines', label: 'Дисциплины' }
]
}
}
}
</script>
<template>
<div class="list-group">
<router-link v-for="catalog in this.catalogs"
:to="'/catalogs/' + catalog.name"
class="list-group-item list-group-item-action">
{{ catalog.label }}
</router-link>
</div>
</template>

View File

@ -0,0 +1,166 @@
<script>
import CatalogMixins from '../mixins/CatalogMixins.js';
import Cabinet from "../models/Cabinet";
import Computer from '../models/Computer';
import Monitor from '../models/Monitor';
import DataService from '../services/DataService';
export default {
mixins: [
CatalogMixins
],
data() {
return {
getAllUrl: 'computer/',
dataUrl: 'computer',
transformer: (data) => new Computer(data),
headers: [
{ name: 'modelName', label: 'Модель' },
{ name: 'serialNum', label: 'Серийный номер' },
{ name: 'monitorName', label: 'Модель монитора' },
{ name: 'cabinetNum', label: 'Номер кабинета' }
],
dataFilterUrl: 'computer/filter?',
cabinetUrl: 'cabinet/',
cabinets: [],
monitorUrl: 'monitor/',
monitors: []
}
},
beforeCreate() {
if (localStorage.getItem("token") == null) {
this.$router.push("/login");
}
},
created() {
DataService.readAll(this.cabinetUrl, (data) => new Cabinet(data))
.then(data => {
this.cabinets = data;
});
DataService.readAll(this.monitorUrl, (data) => new Monitor(data))
.then(data => {
this.monitors = data;
});
},
methods: {
filter() {
let urlParams = ""
if (document.getElementById('modelNameFilterInput').value !== "") {
if (urlParams !== "") {
urlParams += "&";
}
urlParams += "modelName=" + this.modelName;
}
if (document.getElementById('serialNumberFilterInput').value !== "") {
if (urlParams !== "") {
urlParams += "&";
}
urlParams += "serialNum=" + this.serialNumber;
}
if (document.getElementById('monitorFilterSelect').value !== "") {
if (urlParams !== "") {
urlParams += "&";
}
urlParams += "monitorId=" + this.monitorId;
}
if (document.getElementById('cabinetFilterSelect').value !== "") {
if (urlParams !== "") {
urlParams += "&";
}
urlParams += "cabinetId=" + this.cabinetId;
}
DataService.readAll(this.dataFilterUrl + urlParams, (data) => new Computer(data))
.then(data => {
this.items = data;
});
},
clearFilters() {
this.loadItems();
this.id = null;
this.modelName = null;
this.serialNumber = null;
this.monitorId = null;
this.cabinetId = null;
},
itemsComps(computers) {
if (typeof computers === 'undefined') {
return;
}
computers.forEach(computer => {
this.monitors.forEach(monitor => {
if (computer.monitorId === monitor.id) {
computer.monitor = monitor;
}
});
this.cabinets.forEach(cabinet => {
cabinet.computerIds.forEach(computerId => {
if (computer.id === computerId) {
computer.cabinet = cabinet;
}
});
});
});
return computers;
}
}
}
</script>
<template>
<div class="input-group mb-3">
<input type="text" class="form-control" id="modelNameFilterInput" placeholder="Модель" required v-model="modelName">
<input type="text" class="form-control" id="serialNumberFilterInput" placeholder="Серийный номер" required v-model="serialNumber">
<select class="form-select" id="monitorFilterSelect" v-model="monitorId">
<option disabled value="" selected>Выберите монитор</option>
<option v-for="monitor in monitors" :value="monitor.id">{{ monitor.modelName }}</option>
</select>
<select class="form-select" id="cabinetFilterSelect" v-model="cabinetId">
<option disabled value="" selected>Выберите номер кабинета</option>
<option v-for="cabinet in cabinets" :value="cabinet.id">{{ cabinet.number }}</option>
</select>
<button class="btn btn-primary" type="button" id="report-button"
@click.prevent="filter">Сформировать</button>
<button class="btn btn-outline-secondary" type="button" id="report-button"
@click.prevent="clearFilters">Очистить</button>
</div>
<ToolBar
@add="showAddModal"
@edit="showEditModal"
@remove="removeSelectedItems">
</ToolBar>
<DataTable
:headers="this.headers"
:items="itemsComps(this.items)"
:selectedItems="this.selectedItems"
@dblclick="showEditModalDblClick">
</DataTable>
<Modal
:header="this.modal.header"
:confirm="this.modal.confirm"
v-model:visible="this.modalShow"
@done="saveItem">
<div class="mb-3">
<label for="model" class="form-label">Модель</label>
<input type="text" class="form-control" id="model" required v-model="data.modelName">
</div>
<div class="mb-3">
<label for="serialNum" class="form-label">Серийный номер</label>
<input type="text" class="form-control" id="serialNum" required v-model="data.serialNum">
</div>
<div class="mb-3">
<label for="monitor" class="form-label">Монитор</label>
<select class="form-select" id="monitor" v-model="data.monitorId">
<option disabled value="">Выберите монитор</option>
<option v-for="monitor in this.monitors"
:value="monitor.id"
:selected="data.monitorId && monitor.id === data.monitorId">
{{ monitor.modelName }}
</option>
</select>
</div>
</Modal>
</template>

View File

@ -0,0 +1,70 @@
<script>
export default {
props: {
headers: Array,
items: Array,
selectedItems: Array
},
emits: {
dblclick: null
},
methods: {
rowClick(id) {
if (this.isSelected(id)) {
var index = this.selectedItems.indexOf(id);
if (index !== -1) {
this.selectedItems.splice(index, 1);
}
} else {
this.selectedItems.push(id);
}
},
rowDblClick(id) {
this.$emit('dblclick', id);
},
isSelected(id) {
return this.selectedItems.includes(id);
},
dataConvert(data) {
return data;
}
}
}
</script>
<template>
<table class="table table-hover">
<thead>
<tr>
<th scope="col">#</th>
<th v-for="header in this.headers"
:id="header.name"
scope="col">{{ header.label }}</th>
</tr>
</thead>
<tbody>
<tr v-for="(item, index) in this.items"
@click="rowClick(item.id)"
@dblclick="rowDblClick(item.id)"
:class="{selected: isSelected(item.id)}">
<th scope="row">{{ index + 1 }}</th>
<td v-for="header in this.headers">
{{ dataConvert(item[header.name]) }}
</td>
</tr>
</tbody>
</table>
</template>
<style scoped>
tbody tr:hover {
cursor: pointer;
}
tr.selected {
background-color: #0d6efd;
opacity: 80%;
}
tbody tr {
user-select: none;
}
</style>

View File

@ -0,0 +1,40 @@
<script>
export default {
methods: {
getRoutes() {
return this.$router.options.routes.filter(route => route.meta?.hasOwnProperty('label'));
},
logout() {
localStorage.clear();
this.$router.push('/login');
}
}
}
</script>
<template>
<nav class="navbar navbar-expand-lg bg-light">
<div class="container-fluid">
<a class="navbar-brand" href="/">
<i class="fa-solid fa-book"></i>
Рабочее место оператора пункта выдачи заказов
</a>
<button class="navbar-toggler" type="button" data-bs-toggle="collapse" data-bs-target="#navbarNav"
aria-controls="navbarNav" aria-expanded="false" aria-label="Toggle navigation">
<span class="navbar-toggler-icon"></span>
</button>
<div class="collapse navbar-collapse" id="navbarNav">
<ul class="navbar-nav">
<li class="nav-item"
v-for="route in this.getRoutes()">
<router-link class="nav-link" :to="route.path">{{ route.meta.label }}</router-link>
</li>
</ul>
</div>
<button class="btn btn-danger" @click.prevent="logout">Выход</button>
</div>
</nav>
</template>
<style scoped>
</style>

View File

@ -0,0 +1,96 @@
<script>
export default {
methods: {
getUserInfo () {
if (localStorage.getItem("token")) {
this.loginButton.classList.add("visually-hidden");
this.logoutButton.classList.remove("visually-hidden");
this.userSpan.innerText = localStorage.getItem("user");
} else {
this.loginButton.classList.remove("visually-hidden");
this.logoutButton.classList.add("visually-hidden");
this.userSpan.innerText = "";
localStorage.removeItem("user");
}
},
async login (login, password) {
const requestParams = {
method: "POST",
headers: {
"Content-Type": "application/json",
},
body: JSON.stringify({login: login, password: password}),
};
const response = await fetch(this.hostURL + "/jwt/login", requestParams);
const result = await response.text();
if (response.status === 200) {
localStorage.setItem("token", result);
localStorage.setItem("user", login);
this.$router.push("/cabinets");
} else {
localStorage.removeItem("token");
localStorage.removeItem("user");
alert(result);
}
},
loginForm () {
this.login(this.loginInput.value, this.passwordInput.value).then(() => {
this.loginInput.value = "";
this.passwordInput.value = "";
this.getUserInfo();
});
},
logoutForm () {
localStorage.removeItem("token");
localStorage.removeItem("user");
this.getUserInfo();
},
toSignup() {
this.$router.push("/signup");
}
},
data() {
return {
hostURL: "http://localhost:8080",
loginInput: undefined,
passwordInput: undefined,
loginButton: undefined,
logoutButton: undefined,
userSpan: undefined
}
},
mounted() {
this.loginInput = document.getElementById("login");
this.passwordInput = document.getElementById("password");
this.loginButton = document.getElementById("loginBtn");
this.logoutButton = document.getElementById("logoutBtn");
this.userSpan = document.getElementById("user");
this.getUserInfo();
}
}
</script>
<template>
<form id="loginForm" onsubmit="return false">
<div class="row mt-3">
<div class="col-sm-4">
<label for="login" class="form-label visually-hidden">Login</label>
<input type="text" class="form-control" id="login" required placeholder="Логин">
</div>
<div class="col-sm-4 mt-3 mt-sm-0">
<label for="password" class="form-label visually-hidden">Password</label>
<input type="password" class="form-control" id="password" required placeholder="Пароль">
</div>
<div class="d-grid col-sm-2 mx-auto mt-3 mt-sm-0">
<button id="loginBtn" type="submit" class="btn btn-success" @click.prevent="loginForm">Войти</button>
<button id="logoutBtn" type="button" class="btn btn-danger visually-hidden" @click.prevent="logoutForm">Выйти</button>
</div>
<div class="d-grid col-sm-2 mx-auto mt-3 mt-sm-0">
<span id="user" class="align-middle"></span>
</div>
</div>
</form>
<div class="mt-3">
<button class="btn btn-outline-secondary" @click.prevent="toSignup">Регистрация</button>
</div>
</template>

View File

@ -0,0 +1,67 @@
<script>
export default {
props: {
header: String,
confirm: String,
visible: Boolean
},
emits: {
done: null,
'update:visible': (value) => {
if (typeof value !== 'boolean') {
throw 'Value is not a boolean';
}
return true;
}
},
methods: {
hide() {
this.$emit('update:visible', false);
},
done() {
if (this.$refs.form.checkValidity()) {
this.$emit('done');
this.hide();
} else {
this.$refs.form.reportValidity();
}
}
}
}
</script>
<template>
<div class="modal fade" tabindex="-1" aria-hidden="true"
:class="{ 'modal-show': this.visible, 'show': this.visible }">
<div class="modal-dialog">
<div class="modal-content">
<div class="modal-header">
<h1 class="modal-title fs-5" id="exampleModalLabel">{{ header }}</h1>
<button type="button" class="btn-close" aria-label="Close"
@click.prevent="hide"></button>
</div>
<div class="modal-body">
<form @submit.prevent="done" ref="form">
<slot></slot>
</form>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-secondary"
@click.prevent="hide">Закрыть</button>
<button type="button" class="btn btn-primary"
@click.prevent="done">{{ confirm }}</button>
</div>
</div>
</div>
</div>
</template>
<style scoped>
.modal-show {
display: block;
}
.modal-content {
width: max-content;
}
</style>

View File

@ -0,0 +1,75 @@
<script>
import CatalogMixins from '../mixins/CatalogMixins.js';
import Monitor from '../models/Monitor';
import DataService from '../services/DataService';
export default {
mixins: [
CatalogMixins
],
data() {
return {
getAllUrl: 'monitor/',
dataUrl: 'monitor',
transformer: (data) => new Monitor(data),
headers: [
{ name: 'modelName', label: 'Модель' }
],
dataFilterUrl: 'monitor/filter?'
}
},
methods: {
filter() {
let urlParams = ""
if (document.getElementById('modelNameFilterInput').value !== "") {
urlParams += "modelName=" + this.modelName;
}
DataService.readAll(this.dataFilterUrl + urlParams, (data) => new Monitor(data))
.then(data => {
this.items = data;
});
},
clearFilters() {
this.loadItems();
this.id = null;
this.modelName = null;
}
},
beforeCreate() {
if (localStorage.getItem("token") == null) {
this.$router.push("/login");
}
}
}
</script>
<template>
<div class="input-group mb-3">
<input type="text" class="form-control" id="modelNameFilterInput" placeholder="Модель" required v-model="modelName">
<button class="btn btn-primary" type="button" id="report-button"
@click.prevent="filter">Сформировать</button>
<button class="btn btn-outline-secondary" type="button" id="report-button"
@click.prevent="clearFilters">Очистить</button>
</div>
<ToolBar
@add="showAddModal"
@edit="showEditModal"
@remove="removeSelectedItems">
</ToolBar>
<DataTable
:headers="this.headers"
:items="this.items"
:selectedItems="this.selectedItems"
@dblclick="showEditModalDblClick">
</DataTable>
<Modal
:header="this.modal.header"
:confirm="this.modal.confirm"
v-model:visible="this.modalShow"
@done="saveItem">
<div class="mb-3">
<label for="model" class="form-label">Модель</label>
<input type="text" class="form-control" id="model" required v-model="data.modelName">
</div>
</Modal>
</template>

View File

@ -0,0 +1,51 @@
<script>
import axios from "axios";
export default {
data() {
return {
data: []
}
},
methods: {
async createUser() {
const response = await axios.post("http://localhost:8080/signup", this.toJSON(this.data));
if (response.data !== "error") {
this.$router.push("/login");
} else {
document.getElementById('error').value = "Error!";
}
},
toJSON(data) {
const jsonObj = {};
const fields = Object.getOwnPropertyNames(data);
for (const field of fields) {
if (data[field] === undefined) {
continue;
}
jsonObj[field] = data[field];
}
return jsonObj;
}
}
}
</script>
<template>
<div class="mb-3">
<input type="text" name="login" class="form-control"
placeholder="Логин" required autofocus maxlength="64" v-model="data.login"/>
</div>
<div class="mb-3">
<input type="password" name="password" class="form-control"
placeholder="Пароль" required minlength="6" maxlength="64" v-model="data.password"/>
</div>
<div class="mb-3">
<input type="password" name="passwordConfirm" class="form-control"
placeholder="Пароль (подтверждение)" required minlength="6" maxlength="64" v-model="data.passwordConfirm"/>
</div>
<div class="mb-3">
<button type="submit" class="btn btn-success button-fixed" @click.prevent="createUser">Создать</button>
<a class="btn btn-primary button-fixed" href="/login">Назад</a>
</div>
<p id="error"></p>
</template>

View File

@ -0,0 +1,46 @@
<script>
export default {
props: {
},
emits: {
add: null,
edit: null,
remove: null
},
methods: {
add() {
this.$emit('add');
},
edit() {
this.$emit('edit');
},
remove() {
this.$emit('remove');
}
}
}
</script>
<template>
<div class="btn-group mt-2" role="group">
<button type="button" class="btn btn-success"
@click.prevent="add">
Добавить
</button>
<button type="button" class="btn btn-warning"
@click.prevent="edit">
Изменить
</button>
<button type="button" class="btn btn-danger"
@click.prevent="remove">
Удалить
</button>
</div>
</template>
<style scoped>
.btn {
min-width: 140px;
}
</style>

View File

@ -0,0 +1,45 @@
<script>
import CatalogMixins from '../mixins/CatalogMixins.js';
import User from '../models/User.js';
export default {
mixins: [
CatalogMixins
],
data() {
return {
getAllUrl: 'user',
dataUrl: 'user',
transformer: (data) => new User(data),
headers: [
{ name: 'id', label: 'ID' },
{ name: 'login', label: 'Логин' },
{ name: 'role', label: 'Роль' }
],
ifAdmin: Boolean
}
},
beforeCreate() {
if (localStorage.getItem("token") == null) {
this.$router.push("/login");
}
},
created() {
this.ifAdmin = localStorage.getItem("user") === "admin";
}
}
</script>
<template>
<div v-if="ifAdmin">
<DataTable
:headers="this.headers"
:items="this.items"
:selectedItems="this.selectedItems"
@dblclick="showEditModalDblClick">
</DataTable>
</div>
<div v-else>
<h2>Эта страница доступна только администраторам!</h2>
</div>
</template>

27
frontend/src/main.js Normal file
View File

@ -0,0 +1,27 @@
import {createApp} from 'vue'
import {createRouter, createWebHistory} from 'vue-router'
import './style.css'
import App from './App.vue'
import Cabinets from './components/Cabinets.vue'
import Computers from './components/Computers.vue'
import Monitors from './components/Monitors.vue'
import Login from "./components/Login.vue";
import Signup from "@/components/Signup.vue";
import Users from "@/components/Users.vue";
const routes = [
{ path: '/', redirect: '/cabinets' },
{ path: '/cabinets', component: Cabinets, meta: { label: 'Кабинеты' } },
{ path: '/computers', component: Computers, meta: { label: 'Компьютеры' } },
{ path: '/monitors', component: Monitors, meta: { label: 'Мониторы' } },
{ path: '/users', component: Users, meta: { label: 'Пользователи' } },
{ path: '/login', component: Login},
{ path: '/signup', component: Signup}
]
const router = createRouter({
history: createWebHistory(),
linkActiveClass: 'active',
routes
})
createApp(App).use(router).mount('#app')

View File

@ -0,0 +1,102 @@
import ToolBar from '../components/ToolBar.vue';
import DataTable from '../components/DataTable.vue';
import Modal from '../components/Modal.vue';
import DataService from '../services/DataService';
const CatalogMixin = {
components: {
ToolBar, DataTable, Modal
},
data() {
return {
getAllUrl: undefined,
dataUrl: undefined,
transformer: undefined,
headers: [],
items: [],
selectedItems: [],
modal: {
header: undefined,
confirm: undefined,
},
modalShow: false,
data: undefined,
isEdit: false
}
},
created() {
this.loadItems();
},
methods: {
loadItems() {
this.getItems();
this.data = this.transformer();
},
getItems() {
DataService.readAll(this.getAllUrl, this.transformer)
.then(data => {
this.items = data;
});
},
showAddModal() {
this.isEdit = false;
this.data = this.transformer();
this.modal.header = 'Добавление элемента';
this.modal.confirm = 'Добавить';
this.modalShow = true;
},
showEditModal() {
if (this.selectedItems.length === 0) {
return;
}
this.showEditModalDblClick(this.selectedItems[0]);
},
showEditModalDblClick(editId) {
DataService.read(this.dataUrl + "/" + editId, this.transformer)
.then(data => {
this.data = data;
this.isEdit = true;
this.modal.header = 'Редактирование элемента';
this.modal.confirm = 'Сохранить';
this.modalShow = true;
});
},
saveItem() {
if (!this.isEdit) {
DataService.create(this.dataUrl + "/", this.data)
.then(() => {
this.getItems();
});
} else {
DataService.update(this.dataUrl + "/" + this.data.id, this.data)
.then(() => {
this.getItems();
});
}
},
removeSelectedItems() {
if (this.selectedItems.length === 0) {
return;
}
if (confirm('Удалить выбранные элементы?')) {
const promises = [];
const self = this;
this.selectedItems.forEach(item => {
promises.push(DataService.delete(this.dataUrl + "/" + item));
});
Promise.all(promises).then((results) => {
results.forEach(function (id) {
const index = self.selectedItems.indexOf(id);
if (index === - 1) {
return;
}
self.selectedItems.splice(index, 1);
});
this.getItems();
});
}
}
}
}
export default CatalogMixin;

View File

@ -0,0 +1,26 @@
export default class Cabinet {
constructor(data) {
this._id = data?.id;
this._number = data?.number;
this._computerIds = data?.computerIds;
}
get id() {
return this._id;
}
get number() {
return this._number;
}
set number(value) {
if (typeof value !== 'string' || value === null || value.length == 0) {
throw 'New number value ' + value + ' is not a string or empty';
}
this._number = value;
}
get computerIds() {
return this._computerIds;
}
}

View File

@ -0,0 +1,62 @@
export default class Computer {
constructor(data) {
this._id = data?.id;
this._modelName = data?.modelName;
this._serialNum = data?.serialNum;
this._monitor = data?.monitor;
this._monitorId = data?.monitorId;
this._cabinet = data?.cabinet;
}
get id() {
return this._id;
}
get modelName() {
return this._modelName;
}
set modelName(value) {
this._modelName = value;
}
get serialNum() {
return this._serialNum;
}
set serialNum(value) {
this._serialNum = value;
}
get monitorId() {
return this._monitorId;
}
set monitorId(data) {
this._monitorId = data;
}
get monitor() {
return this._monitor;
}
set monitor(data) {
this._monitor = data;
}
get monitorName() {
return this._monitor?.modelName;
}
get cabinet() {
return this._cabinet;
}
set cabinet(data) {
this._cabinet = data;
}
get cabinetNum() {
return this._cabinet?.number;
}
}

View File

@ -0,0 +1,21 @@
export default class Monitor {
constructor(data) {
this._id = data?.id;
this._modelName = data?.modelName;
}
get id() {
return this._id;
}
get modelName() {
return this._modelName;
}
set modelName(value) {
if (typeof value !== 'string' || value === null || value.length == 0) {
throw 'New model name value ' + value + ' is not a string or empty';
}
this._modelName = value;
}
}

View File

@ -0,0 +1,33 @@
export default class Monitor {
constructor(data) {
this._id = data?.id;
this._login = data?.login;
this._role = data?.role;
}
get id() {
return this._id;
}
get login() {
return this._login;
}
set login(value) {
if (typeof value !== 'string' || value === null || value.length == 0) {
throw 'New model name value ' + value + ' is not a string or empty';
}
this._login = value;
}
get role() {
return this._role;
}
set role(value) {
if (typeof value !== 'string' || value === null || value.length == 0) {
throw 'New model name value ' + value + ' is not a string or empty';
}
this._role = value;
}
}

View File

@ -0,0 +1,62 @@
import axios from 'axios';
function toJSON(data) {
const jsonObj = {};
const fields = Object.getOwnPropertyNames(data);
for (const field of fields) {
if (data[field] === undefined) {
continue;
}
jsonObj[field.substring(1)] = data[field];
}
return jsonObj;
}
export default class DataService {
static dataUrlPrefix = 'http://localhost:8080/api/1.0/';
static async readAll(url, transformer) {
const response = (await axios.create({
headers: {
'Authorization': 'Bearer ' + localStorage.getItem("token")
}
}).get(this.dataUrlPrefix + url));
return response.data.map(item => transformer(item));
}
static async read(url, transformer) {
const response = await axios.create({
headers: {
'Authorization': 'Bearer ' + localStorage.getItem("token")
}
}).get(this.dataUrlPrefix + url);
return transformer(response.data);
}
static async create(url, data) {
const response = await axios.create({
headers: {
'Authorization': 'Bearer ' + localStorage.getItem("token")
}
}).post(this.dataUrlPrefix + url, toJSON(data));
return true;
}
static async update(url, data) {
const response = await axios.create({
headers: {
'Authorization': 'Bearer ' + localStorage.getItem("token")
}
}).put(this.dataUrlPrefix + url, toJSON(data));
return true;
}
static async delete(url) {
const response = await axios.create({
headers: {
'Authorization': 'Bearer ' + localStorage.getItem("token")
}
}).delete(this.dataUrlPrefix + url);
return response.data.id;
}
}

0
frontend/src/style.css Normal file
View File

15
frontend/vite.config.js Normal file
View File

@ -0,0 +1,15 @@
import {fileURLToPath, URL} from 'node:url'
import {defineConfig} from 'vite'
import vue from '@vitejs/plugin-vue'
import vueJsx from '@vitejs/plugin-vue-jsx'
// https://vitejs.dev/config/
export default defineConfig({
plugins: [vue(), vueJsx()],
resolve: {
alias: {
'@': fileURLToPath(new URL('./src', import.meta.url))
}
}
})

View File

@ -1,13 +0,0 @@
package com.kalyshev.yan;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
@RestController
public class LowercaseController {
@GetMapping("/lowercase")
public String lowercase(@RequestParam(value = "value", defaultValue = "None") String value) {
return value.toLowerCase();
}
}

View File

@ -1,15 +0,0 @@
package com.kalyshev.yan;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
@RestController
public class ReplaceController {
@GetMapping("/replace")
public String replace(@RequestParam(value = "value", defaultValue = "None") String value,
@RequestParam(value = "old", defaultValue = "") char oldChar,
@RequestParam(value = "new", defaultValue = "") char newChar) {
return value.replace(oldChar, newChar);
}
}

View File

@ -1,20 +0,0 @@
package com.kalyshev.yan;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
@RestController
public class SplitController {
@GetMapping("/split")
public String split(@RequestParam(value = "value", defaultValue = "None") String value,
@RequestParam(value = "splitBy", defaultValue = " ") String splitBy) {
String[] temp = value.split(splitBy);
String res = "";
for (int i = 0; i < temp.length; i++) {
res += temp[i];
res += "; ";
}
return res;
}
}

View File

@ -1,13 +0,0 @@
package com.kalyshev.yan;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
@RestController
public class UppercaseController {
@GetMapping("/uppercase")
public String uppercase(@RequestParam(value = "value", defaultValue = "None") String value) {
return value.toUpperCase();
}
}

View File

@ -1,13 +0,0 @@
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.WebMvcConfigurer;
@Configuration
public class WebConfiguration implements WebMvcConfigurer {
@Override
public void addCorsMappings(CorsRegistry registry) {
registry.addMapping("/**").allowedMethods("*");
}
}

View File

@ -2,7 +2,6 @@ package com.kalyshev.yan;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.web.bind.annotation.RestController;
@SpringBootApplication
public class YanApplication {

View File

@ -0,0 +1,64 @@
package com.kalyshev.yan.cabinet.controller;
import com.kalyshev.yan.cabinet.service.CabinetService;
import com.kalyshev.yan.computer.controller.ComputerDto;
import com.kalyshev.yan.configuration.OpenAPI30Configuration;
import org.springframework.web.bind.annotation.*;
import javax.validation.Valid;
import java.util.List;
@RestController
@RequestMapping(OpenAPI30Configuration.API_PREFIX + "/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<CabinetDto> getCabinets() {
return cabinetService.findAllCabinets().stream()
.map(CabinetDto::new)
.toList();
}
@GetMapping("/{id}/computers")
public List<ComputerDto> getCabinetComputers(@PathVariable Long id) {
return cabinetService.listComputersFromCabinet(id).stream()
.map(ComputerDto::new)
.toList();
}
@GetMapping("/filter")
public List<CabinetDto> 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);
}
}

View File

@ -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<Long> 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<Computer> 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<Long> getComputerIds() { return this.computerIds; }
public void setComputerIds(List<Long> computerIds) { this.computerIds = computerIds; }
}

View File

@ -0,0 +1,71 @@
package com.kalyshev.yan.cabinet.model;
import com.kalyshev.yan.computer.model.Computer;
import javax.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<Computer> 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<Computer> 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 + '\'' +
'}';
}
}

View File

@ -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));
}
}

View File

@ -0,0 +1,14 @@
package com.kalyshev.yan.cabinet.repository;
import com.kalyshev.yan.cabinet.model.Cabinet;
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<Cabinet, Long> {
@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<Cabinet> findFilteredCabinets(@Param("id") Long id,
@Param("number") String number);
}

View File

@ -0,0 +1,102 @@
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.List;
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> cabinet = cabinetRepository.findById(id);
return cabinet.orElseThrow(() -> new CabinetNotFoundException(id));
}
@Transactional(readOnly = true)
public List<Cabinet> findFilteredCabinets(Long id, String number) {
return cabinetRepository.findFilteredCabinets(id, number);
}
@Transactional(readOnly = true)
public List<Cabinet> 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<Computer> listComputersFromCabinet(Long id) {
if (id == null) {
throw new IllegalArgumentException("Cabinet id is null or empty");
}
return findCabinet(id).getComputers();
}
@Transactional
public void addComputerToCabinet(Long computerId, Long cabinetId) {
if (computerId == null) {
throw new IllegalArgumentException("Computer id is null or empty");
}
if (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 (computerId == null) {
throw new IllegalArgumentException("Computer id is null or empty");
}
if (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);
}
}

View File

@ -0,0 +1,56 @@
package com.kalyshev.yan.computer.controller;
import com.kalyshev.yan.computer.service.ComputerService;
import com.kalyshev.yan.configuration.OpenAPI30Configuration;
import com.kalyshev.yan.monitor.controller.MonitorDto;
import org.springframework.web.bind.annotation.*;
import javax.validation.Valid;
import java.util.List;
@RestController
@RequestMapping(OpenAPI30Configuration.API_PREFIX + "/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<ComputerDto> getComputers() {
return computerService.findAllComputers().stream()
.map(ComputerDto::new)
.toList();
}
@GetMapping("/filter")
public List<ComputerDto> 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));
}
}

View File

@ -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; }
}

View File

@ -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 javax.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 + '\'' +
'}';
}
}

View File

@ -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));
}
}

View File

@ -0,0 +1,32 @@
package com.kalyshev.yan.computer.repository;
import com.kalyshev.yan.computer.model.Computer;
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.List;
public interface ComputerRepository extends JpaRepository<Computer, Long> {
@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<Computer> 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<Long> computerIds);
}

View File

@ -0,0 +1,136 @@
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 org.springframework.lang.Nullable;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;
import java.util.List;
import java.util.Optional;
@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> computer = computerRepository.findById(id);
return computer.orElseThrow(() -> new ComputerNotFoundException(id));
}
@Transactional(readOnly = true)
public List<Computer> findAllComputers() {
return computerRepository.findAll();
}
@Transactional(readOnly = true)
public List<Computer> 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<Computer> computers = findAllComputers();
for (Computer computer : computers) {
deleteComputer(computer.getId());
}
}
@Transactional
public Monitor setMonitor(Long monitorId, Long computerId) {
if (computerId == null) {
throw new IllegalArgumentException("Computer id is null or empty");
}
if (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<Computer> 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();
}
}

View File

@ -0,0 +1,27 @@
package com.kalyshev.yan.configuration;
import com.kalyshev.yan.configuration.jwt.JwtFilter;
import io.swagger.v3.oas.models.Components;
import io.swagger.v3.oas.models.OpenAPI;
import io.swagger.v3.oas.models.security.SecurityRequirement;
import io.swagger.v3.oas.models.security.SecurityScheme;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
@Configuration
public class OpenAPI30Configuration {
public static final String API_PREFIX = "/api/1.0";
@Bean
public OpenAPI customizeOpenAPI() {
final String securitySchemeName = JwtFilter.TOKEN_BEGIN_STR;
return new OpenAPI()
.addSecurityItem(new SecurityRequirement()
.addList(securitySchemeName))
.components(new Components()
.addSecuritySchemes(securitySchemeName, new SecurityScheme()
.name(securitySchemeName)
.type(SecurityScheme.Type.HTTP)
.scheme("bearer")
.bearerFormat("JWT")));
}
}

View File

@ -0,0 +1,14 @@
package com.kalyshev.yan.configuration;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;
@Configuration
public class PasswordEncoderConfiguration {
@Bean
public PasswordEncoder passwordEncoder() {
return new BCryptPasswordEncoder();
}
}

View File

@ -0,0 +1,73 @@
package com.kalyshev.yan.configuration;
import com.kalyshev.yan.configuration.jwt.JwtFilter;
import com.kalyshev.yan.user.controller.UserController;
import com.kalyshev.yan.user.controller.UserSignupController;
import com.kalyshev.yan.user.model.UserRole;
import com.kalyshev.yan.user.service.UserService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.HttpMethod;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.method.configuration.EnableMethodSecurity;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.builders.WebSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.config.http.SessionCreationPolicy;
import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter;
@Configuration
@EnableWebSecurity
@EnableMethodSecurity(securedEnabled = true)
public class SecurityConfiguration extends WebSecurityConfigurerAdapter {
private final Logger log = LoggerFactory.getLogger(SecurityConfiguration.class);
public static final String SPA_URL_MASK = "/{path:[^\\.]*}";
private final UserService userService;
private final JwtFilter jwtFilter;
public SecurityConfiguration(UserService userService) {
this.userService = userService;
this.jwtFilter = new JwtFilter(userService);
createAdminOnStartup();
}
private void createAdminOnStartup() {
final String admin = "admin";
if (userService.findByLogin(admin) == null) {
log.info("Admin user successfully created");
userService.createUser(admin, admin, admin, UserRole.ADMIN);
}
}
@Override
protected void configure(HttpSecurity http) throws Exception {
log.info("Creating security configuration");
http.cors()
.and()
.csrf().disable()
.sessionManagement().sessionCreationPolicy(SessionCreationPolicy.STATELESS)
.and()
.authorizeRequests()
.antMatchers("/", SPA_URL_MASK).permitAll()
.antMatchers(HttpMethod.POST, UserController.URL_LOGIN).permitAll()
.antMatchers(HttpMethod.POST, UserSignupController.URL_LOGIN).permitAll()
.anyRequest()
.authenticated()
.and()
.addFilterBefore(jwtFilter, UsernamePasswordAuthenticationFilter.class)
.anonymous();
}
@Override
protected void configure(AuthenticationManagerBuilder builder) throws Exception {
builder.userDetailsService(userService);
}
@Override
public void configure(WebSecurity web) {
web.ignoring()
.antMatchers(HttpMethod.OPTIONS, "/**")
.antMatchers("/**/*.{js,html,css,png}")
.antMatchers("/swagger-ui/index.html")
.antMatchers("/webjars/**")
.antMatchers("/swagger-resources/**")
.antMatchers("/v3/api-docs/**");
}
}

View File

@ -0,0 +1,28 @@
package com.kalyshev.yan.configuration;
import org.springframework.boot.web.server.ErrorPage;
import org.springframework.boot.web.server.WebServerFactoryCustomizer;
import org.springframework.boot.web.servlet.server.ConfigurableServletWebServerFactory;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.HttpStatus;
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
class WebConfiguration implements WebMvcConfigurer {
@Override
public void addViewControllers(ViewControllerRegistry registry) {
registry.addViewController(SecurityConfiguration.SPA_URL_MASK).setViewName("forward:/");
registry.addViewController("/notFound").setViewName("forward:/");
}
@Bean
public WebServerFactoryCustomizer<ConfigurableServletWebServerFactory> containerCustomizer() {
return container -> container.addErrorPages(new ErrorPage(HttpStatus.NOT_FOUND, "/notFound"));
}
@Override
public void addCorsMappings(CorsRegistry registry) {
registry.addMapping("/**").allowedMethods("*");
}
}

View File

@ -0,0 +1,10 @@
package com.kalyshev.yan.configuration.jwt;
public class JwtException extends RuntimeException {
public JwtException(Throwable throwable) {
super(throwable);
}
public JwtException(String message) {
super(message);
}
}

View File

@ -0,0 +1,67 @@
package com.kalyshev.yan.configuration.jwt;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.kalyshev.yan.user.service.UserService;
import org.springframework.http.MediaType;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.util.StringUtils;
import org.springframework.web.filter.GenericFilterBean;
import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
public class JwtFilter extends GenericFilterBean {
private static final String AUTHORIZATION = "Authorization";
public static final String TOKEN_BEGIN_STR = "Bearer ";
private final UserService userService;
public JwtFilter(UserService userService) {
this.userService = userService;
}
private String getTokenFromRequest(HttpServletRequest request) {
String bearer = request.getHeader(AUTHORIZATION);
if (StringUtils.hasText(bearer) && bearer.startsWith(TOKEN_BEGIN_STR)) {
return bearer.substring(TOKEN_BEGIN_STR.length());
}
return null;
}
private void raiseException(ServletResponse response, int status, String message) throws IOException {
if (response instanceof final HttpServletResponse httpResponse) {
httpResponse.setContentType(MediaType.APPLICATION_JSON_VALUE);
httpResponse.setStatus(status);
final byte[] body = new ObjectMapper().writeValueAsBytes(message);
response.getOutputStream().write(body);
}
}
@Override
public void doFilter(ServletRequest request,
ServletResponse response,
FilterChain chain) throws IOException, ServletException {
if (request instanceof final HttpServletRequest httpRequest) {
final String token = getTokenFromRequest(httpRequest);
if (StringUtils.hasText(token)) {
try {
final UserDetails user = userService.loadUserByToken(token);
final UsernamePasswordAuthenticationToken auth =
new UsernamePasswordAuthenticationToken(user, null, user.getAuthorities());
SecurityContextHolder.getContext().setAuthentication(auth);
} catch (JwtException e) {
raiseException(response, HttpServletResponse.SC_UNAUTHORIZED, e.getMessage());
return;
} catch (Exception e) {
e.printStackTrace();
raiseException(response, HttpServletResponse.SC_INTERNAL_SERVER_ERROR,
String.format("Internal error: %s", e.getMessage()));
return;
}
}
}
chain.doFilter(request, response);
}
}

View File

@ -0,0 +1,27 @@
package com.kalyshev.yan.configuration.jwt;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.annotation.Configuration;
@Configuration
@ConfigurationProperties(prefix = "jwt", ignoreInvalidFields = true)
public class JwtProperties {
private String devToken = "";
private Boolean isDev = true;
public String getDevToken() {
return devToken;
}
public void setDevToken(String devToken) {
this.devToken = devToken;
}
public Boolean isDev() {
return isDev;
}
public void setDev(Boolean dev) {
isDev = dev;
}
}

View File

@ -0,0 +1,99 @@
package com.kalyshev.yan.configuration.jwt;
import com.auth0.jwt.JWT;
import com.auth0.jwt.algorithms.Algorithm;
import com.auth0.jwt.exceptions.JWTVerificationException;
import com.auth0.jwt.interfaces.DecodedJWT;
import com.auth0.jwt.interfaces.JWTVerifier;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
import java.nio.charset.StandardCharsets;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.time.LocalDate;
import java.time.ZoneId;
import java.util.Date;
import java.util.Optional;
import java.util.UUID;
@Component
public class JwtProvider {
private final static Logger LOG = LoggerFactory.getLogger(JwtProvider.class);
private final static byte[] HEX_ARRAY = "0123456789ABCDEF".getBytes(StandardCharsets.US_ASCII);
private final static String ISSUER = "auth0";
private final Algorithm algorithm;
private final JWTVerifier verifier;
public JwtProvider(JwtProperties jwtProperties) {
if (!jwtProperties.isDev()) {
LOG.info("Generate new JWT key for prod");
try {
final MessageDigest salt = MessageDigest.getInstance("SHA-256");
salt.update(UUID.randomUUID().toString().getBytes(StandardCharsets.UTF_8));
LOG.info("Use generated JWT key for prod \n{}", bytesToHex(salt.digest()));
algorithm = Algorithm.HMAC256(bytesToHex(salt.digest()));
} catch (NoSuchAlgorithmException e) {
throw new JwtException(e);
}
} else {
LOG.info("Use default JWT key for dev \n{}", jwtProperties.getDevToken());
algorithm = Algorithm.HMAC256(jwtProperties.getDevToken());
}
verifier = JWT.require(algorithm)
.withIssuer(ISSUER)
.build();
}
private static String bytesToHex(byte[] bytes) {
byte[] hexChars = new byte[bytes.length * 2];
for (int j = 0; j < bytes.length; j++) {
int v = bytes[j] & 0xFF;
hexChars[j * 2] = HEX_ARRAY[v >>> 4];
hexChars[j * 2 + 1] = HEX_ARRAY[v & 0x0F];
}
return new String(hexChars, StandardCharsets.UTF_8);
}
public String generateToken(String login) {
final Date issueDate = Date.from(LocalDate.now()
.atStartOfDay(ZoneId.systemDefault())
.toInstant());
final Date expireDate = Date.from(LocalDate.now()
.plusDays(15)
.atStartOfDay(ZoneId.systemDefault())
.toInstant());
return JWT.create()
.withIssuer(ISSUER)
.withIssuedAt(issueDate)
.withExpiresAt(expireDate)
.withSubject(login)
.sign(algorithm);
}
private DecodedJWT validateToken(String token) {
try {
return verifier.verify(token);
} catch (JWTVerificationException e) {
throw new JwtException(String.format("Token verification error: %s", e.getMessage()));
}
}
public boolean isTokenValid(String token) {
if (!StringUtils.hasText(token)) {
return false;
}
try {
validateToken(token);
return true;
} catch (JwtException e) {
LOG.error(e.getMessage());
return false;
}
}
public Optional<String> getLoginFromToken(String token) {
try {
return Optional.ofNullable(validateToken(token).getSubject());
} catch (JwtException e) {
LOG.error(e.getMessage());
return Optional.empty();
}
}
}

View File

@ -0,0 +1,51 @@
package com.kalyshev.yan.monitor.controller;
import com.kalyshev.yan.computer.service.ComputerService;
import com.kalyshev.yan.configuration.OpenAPI30Configuration;
import com.kalyshev.yan.monitor.service.MonitorService;
import org.springframework.web.bind.annotation.*;
import javax.validation.Valid;
import java.util.List;
@RestController
@RequestMapping(OpenAPI30Configuration.API_PREFIX + "/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<MonitorDto> getMonitors() {
return monitorService.findAllMonitors().stream()
.map(MonitorDto::new)
.toList();
}
@GetMapping("/filter")
public List<MonitorDto> 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));
}
}

View File

@ -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;
}
}

View File

@ -0,0 +1,50 @@
package com.kalyshev.yan.monitor.model;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
import javax.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 + '\'' +
'}';
}
}

View File

@ -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));
}
}

View File

@ -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<Monitor, Long> {
@Query(value = "select * from Monitor where (\"ID\" = :id or :id is Null) and " +
"(\"MODEL_NAME\" = :modelName or :modelName is Null)", nativeQuery = true)
public List<Monitor> findFilteredMonitors(@Param("id") Long id,
@Param("modelName") String modelName);
}

View File

@ -0,0 +1,61 @@
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.List;
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> monitor = monitorRepository.findById(id);
return monitor.orElseThrow(() -> new MonitorNotFoundException(id));
}
@Transactional(readOnly = true)
public List<Monitor> findAllMonitors() {
return monitorRepository.findAll();
}
@Transactional(readOnly = true)
public List<Monitor> 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(); }
}

View File

@ -0,0 +1,29 @@
package com.kalyshev.yan.user.controller;
import com.kalyshev.yan.configuration.OpenAPI30Configuration;
import com.kalyshev.yan.user.model.User;
import com.kalyshev.yan.user.service.UserService;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RestController;
import javax.validation.Valid;
import java.util.List;
@RestController
public class UserController {
public static final String URL_LOGIN = "/jwt/login";
private final UserService userService;
public UserController(UserService userService) {
this.userService = userService;
}
@GetMapping(OpenAPI30Configuration.API_PREFIX + "/user")
public List<User> getUsers() {
return userService.findAllUsers();
}
@PostMapping(URL_LOGIN)
public String login(@RequestBody @Valid UserDto userDto) {
return userService.loginAndGetToken(userDto);
}
}

View File

@ -0,0 +1,24 @@
package com.kalyshev.yan.user.controller;
import com.kalyshev.yan.user.model.User;
import javax.validation.constraints.NotEmpty;
public class UserDto {
@NotEmpty
private String login;
@NotEmpty
private String password;
public UserDto() {}
UserDto(User user) {
login = user.getLogin();
password = user.getPassword();
}
public String getLogin() {
return login;
}
public String getPassword() {
return password;
}
}

View File

@ -0,0 +1,31 @@
package com.kalyshev.yan.user.controller;
import com.kalyshev.yan.user.model.User;
import com.kalyshev.yan.user.service.UserService;
import com.kalyshev.yan.util.validation.ValidationException;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RestController;
import javax.validation.Valid;
@Controller
@RestController
public class UserSignupController {
public static final String URL_LOGIN = "/signup";
private final UserService userService;
public UserSignupController(UserService userService) {
this.userService = userService;
}
@PostMapping(URL_LOGIN)
public String signup(@RequestBody @Valid UserSignupDto userSignupDto) {
try {
final User user = userService.createUser(
userSignupDto.getLogin(), userSignupDto.getPassword(), userSignupDto.getPasswordConfirm());
return user.getLogin();
} catch (ValidationException e) {
return "error";
}
}
}

View File

@ -0,0 +1,34 @@
package com.kalyshev.yan.user.controller;
import javax.validation.constraints.NotBlank;
import javax.validation.constraints.Size;
public class UserSignupDto {
@NotBlank
@Size(min = 3, max = 64)
private String login;
@NotBlank
@Size(min = 6, max = 64)
private String password;
@NotBlank
@Size(min = 6, max = 64)
private String passwordConfirm;
public String getLogin() {
return login;
}
public void setLogin(String login) {
this.login = login;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
public String getPasswordConfirm() {
return passwordConfirm;
}
public void setPasswordConfirm(String passwordConfirm) {
this.passwordConfirm = passwordConfirm;
}
}

View File

@ -0,0 +1,71 @@
package com.kalyshev.yan.user.model;
import javax.persistence.*;
import javax.validation.constraints.NotBlank;
import javax.validation.constraints.Size;
import java.util.Objects;
@Entity
@Table(name = "users")
public class User {
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
private Long id;
@Column(nullable = false, unique = true, length = 64)
@NotBlank
@Size(min = 3, max = 64)
private String login;
@Column(nullable = false, length = 64)
@NotBlank
@Size(min = 6, max = 64)
private String password;
private UserRole role;
public User() {
}
public User(String login, String password) {
this(login, password, UserRole.USER);
}
public User(String login, String password, UserRole role) {
this.login = login;
this.password = password;
this.role = role;
}
public Long getId() {
return id;
}
public String getLogin() {
return login;
}
public void setLogin(String login) {
this.login = login;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
public UserRole getRole() {
return role;
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
User user = (User) o;
return Objects.equals(id, user.id);
}
@Override
public int hashCode() {
return Objects.hash(id);
}
@Override
public String toString() {
return "User{" +
"id=" + id +
", login='" + login + '\'' +
", password='" + password + '\'' +
'}';
}
}

View File

@ -0,0 +1,17 @@
package com.kalyshev.yan.user.model;
import org.springframework.security.core.GrantedAuthority;
public enum UserRole implements GrantedAuthority {
ADMIN,
USER;
private static final String PREFIX = "ROLE_";
@Override
public String getAuthority() {
return PREFIX + this.name();
}
public static final class AsString {
public static final String ADMIN = PREFIX + "ADMIN";
public static final String USER = PREFIX + "USER";
}
}

View File

@ -0,0 +1,7 @@
package com.kalyshev.yan.user.repository;
public class UserExistsException extends RuntimeException {
public UserExistsException(String login) {
super(String.format("User '%s' already exists", login));
}
}

View File

@ -0,0 +1,7 @@
package com.kalyshev.yan.user.repository;
public class UserNotFoundException extends RuntimeException {
public UserNotFoundException(String login) {
super(String.format("User not found '%s'", login));
}
}

View File

@ -0,0 +1,9 @@
package com.kalyshev.yan.user.repository;
import com.kalyshev.yan.user.model.User;
import org.springframework.data.jpa.repository.JpaRepository;
public interface UserRepository extends JpaRepository<User, Long> {
User findOneByLoginIgnoreCase(String login);
}

View File

@ -0,0 +1,92 @@
package com.kalyshev.yan.user.service;
import com.kalyshev.yan.configuration.jwt.JwtException;
import com.kalyshev.yan.configuration.jwt.JwtProvider;
import com.kalyshev.yan.monitor.controller.MonitorDto;
import com.kalyshev.yan.user.controller.UserDto;
import com.kalyshev.yan.user.model.User;
import com.kalyshev.yan.user.model.UserRole;
import com.kalyshev.yan.user.repository.UserExistsException;
import com.kalyshev.yan.user.repository.UserNotFoundException;
import com.kalyshev.yan.user.repository.UserRepository;
import com.kalyshev.yan.util.validation.ValidationException;
import com.kalyshev.yan.util.validation.ValidatorUtil;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Sort;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Service;
import java.util.Collections;
import java.util.List;
import java.util.Objects;
@Service
public class UserService implements UserDetailsService {
private final UserRepository userRepository;
private final PasswordEncoder passwordEncoder;
private final ValidatorUtil validatorUtil;
private final JwtProvider jwtProvider;
public UserService(UserRepository userRepository,
PasswordEncoder passwordEncoder,
ValidatorUtil validatorUtil,
JwtProvider jwtProvider) {
this.userRepository = userRepository;
this.passwordEncoder = passwordEncoder;
this.validatorUtil = validatorUtil;
this.jwtProvider = jwtProvider;
}
public Page<User> findAllPages(int page, int size) {
return userRepository.findAll(PageRequest.of(page - 1, size, Sort.by("id").ascending()));
}
public List<User> findAllUsers() {
return userRepository.findAll();
}
public User findByLogin(String login) {
return userRepository.findOneByLoginIgnoreCase(login);
}
public User createUser(String login, String password, String passwordConfirm) {
return createUser(login, password, passwordConfirm, UserRole.USER);
}
public User createUser(String login, String password, String passwordConfirm, UserRole role) {
if (findByLogin(login) != null) {
throw new UserExistsException(login);
}
final User user = new User(login, passwordEncoder.encode(password), role);
validatorUtil.validate(user);
if (!Objects.equals(password, passwordConfirm)) {
throw new ValidationException("Passwords not equals");
}
return userRepository.save(user);
}
public String loginAndGetToken(UserDto userDto) {
final User user = findByLogin(userDto.getLogin());
if (user == null) {
throw new UserNotFoundException(userDto.getLogin());
}
if (!passwordEncoder.matches(userDto.getPassword(), user.getPassword())) {
throw new UserNotFoundException(user.getLogin());
}
return jwtProvider.generateToken(user.getLogin());
}
public UserDetails loadUserByToken(String token) throws UsernameNotFoundException {
if (!jwtProvider.isTokenValid(token)) {
throw new JwtException("Bad token");
}
final String userLogin = jwtProvider.getLoginFromToken(token)
.orElseThrow(() -> new JwtException("Token is not contain Login"));
return loadUserByUsername(userLogin);
}
@Override
public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
final User userEntity = findByLogin(username);
if (userEntity == null) {
throw new UsernameNotFoundException(username);
}
return new org.springframework.security.core.userdetails.User(
userEntity.getLogin(), userEntity.getPassword(), Collections.singleton(userEntity.getRole()));
}
}

View File

@ -0,0 +1,40 @@
package com.kalyshev.yan.util.error;
import com.kalyshev.yan.cabinet.repository.CabinetNotFoundException;
import com.kalyshev.yan.computer.repository.ComputerNotFoundException;
import com.kalyshev.yan.monitor.repository.MonitorNotFoundException;
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 java.util.stream.Collectors;
@ControllerAdvice
public class AdviceController {
@ExceptionHandler({
MonitorNotFoundException.class,
ComputerNotFoundException.class,
CabinetNotFoundException.class,
ValidationException.class
})
public ResponseEntity<Object> handleException(Throwable e) {
return new ResponseEntity<>(e.getMessage(), HttpStatus.BAD_REQUEST);
}
@ExceptionHandler(MethodArgumentNotValidException.class)
public ResponseEntity<Object> 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<Object> handleUnknownException(Throwable e) {
e.printStackTrace();
return new ResponseEntity<>(e.getMessage(), HttpStatus.INTERNAL_SERVER_ERROR);
}
}

View File

@ -0,0 +1,12 @@
package com.kalyshev.yan.util.validation;
import java.util.Set;
public class ValidationException extends RuntimeException {
public ValidationException(String message) {
super(message);
}
public ValidationException(Set<String> errors) {
super(String.join("\n", errors));
}
}

View File

@ -0,0 +1,28 @@
package com.kalyshev.yan.util.validation;
import org.springframework.stereotype.Component;
import javax.validation.ConstraintViolation;
import javax.validation.Validation;
import javax.validation.Validator;
import javax.validation.ValidatorFactory;
import java.util.Set;
import java.util.stream.Collectors;
@Component
public class ValidatorUtil {
private final Validator validator;
public ValidatorUtil() {
try (ValidatorFactory factory = Validation.buildDefaultValidatorFactory()) {
this.validator = factory.getValidator();
}
}
public <T> void validate(T object) {
final Set<ConstraintViolation<T>> errors = validator.validate(object);
if (!errors.isEmpty()) {
throw new ValidationException(errors.stream()
.map(ConstraintViolation::getMessage)
.collect(Collectors.toSet()));
}
}
}

View File

@ -1 +1,13 @@
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
jwt.dev-token=my-secret-jwt
jwt.dev=true

View File

@ -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<Cabinet> cabinets = cabinetService.findAllCabinets();
log.info(cabinets.toString());
Assertions.assertEquals(cabinets.size(), 2);
}
@Test
void testComputerReadAllEmpty() {
cabinetService.deleteAllCabinets();
final List<Cabinet> cabinets = cabinetService.findAllCabinets();
log.info(cabinets.toString());
Assertions.assertEquals(cabinets.size(), 0);
}
}

View File

@ -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());
}
}

View File

@ -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<Computer> computers = computerService.findAllComputers();
log.info(computers.toString());
Assertions.assertEquals(computers.size(), 2);
}
@Test
void testComputerReadAllEmpty() {
computerService.deleteAllComputers();
final List<Computer> computers = computerService.findAllComputers();
log.info(computers.toString());
Assertions.assertEquals(computers.size(), 0);
}
}

View File

@ -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<Monitor> monitors = monitorService.findAllMonitors();
log.info(monitors.toString());
Assertions.assertEquals(monitors.size(), 2);
}
@Test
void testMonitorReadAllEmpty() {
computerService.deleteAllMonitorsWithRelations();
final List<Monitor> 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);
}
}

View File

@ -1,13 +0,0 @@
package com.kalyshev.yan;
import org.junit.jupiter.api.Test;
import org.springframework.boot.test.context.SpringBootTest;
@SpringBootTest
class YanApplicationTests {
@Test
void contextLoads() {
}
}

View File

@ -0,0 +1,6 @@
spring.datasource.url=jdbc:h2:mem:testdb
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=create-drop