Ничего не работает

This commit is contained in:
dasha 2023-03-27 03:45:44 +04:00
parent e6af154d0a
commit 82dcfd163c
40 changed files with 5787 additions and 654 deletions

View File

@ -12,7 +12,13 @@ repositories {
mavenCentral()
}
jar {
enabled = false
}
dependencies {
implementation(project(':front'))
implementation 'org.springframework.boot:spring-boot-starter-web'
implementation 'com.h2database:h2:2.1.210'
implementation 'org.springframework.boot:spring-boot-starter-validation'
@ -20,6 +26,8 @@ dependencies {
implementation 'org.springframework.boot:spring-boot-starter-data-jpa'
testImplementation 'org.springframework.boot:spring-boot-starter-test'
implementation 'org.hibernate.validator:hibernate-validator'
implementation 'org.springdoc:springdoc-openapi-ui:1.6.5'
}
tasks.named('test') {

Binary file not shown.

248
data.trace.db Normal file
View File

@ -0,0 +1,248 @@
2023-03-27 03:39:27 jdbc[13]: exception
org.h2.jdbc.JdbcSQLSyntaxErrorException: Столбец "2022-03-27" не найден
Column "2022-03-27" not found; SQL statement:
insert into tab_order values (
1, "2022-03-27", 1
) [42122-210]
at org.h2.message.DbException.getJdbcSQLException(DbException.java:521)
at org.h2.message.DbException.getJdbcSQLException(DbException.java:496)
at org.h2.message.DbException.get(DbException.java:227)
at org.h2.message.DbException.get(DbException.java:203)
at org.h2.expression.ExpressionColumn.getColumnException(ExpressionColumn.java:248)
at org.h2.expression.ExpressionColumn.optimizeOther(ExpressionColumn.java:230)
at org.h2.expression.ExpressionColumn.optimize(ExpressionColumn.java:213)
at org.h2.command.dml.Insert.prepare(Insert.java:300)
at org.h2.command.Parser.prepareCommand(Parser.java:557)
at org.h2.engine.SessionLocal.prepareLocal(SessionLocal.java:615)
at org.h2.engine.SessionLocal.prepareCommand(SessionLocal.java:553)
at org.h2.jdbc.JdbcConnection.prepareCommand(JdbcConnection.java:1116)
at org.h2.jdbc.JdbcStatement.executeInternal(JdbcStatement.java:237)
at org.h2.jdbc.JdbcStatement.execute(JdbcStatement.java:223)
at org.h2.server.web.WebApp.getResult(WebApp.java:1339)
at org.h2.server.web.WebApp.query(WebApp.java:1137)
at org.h2.server.web.WebApp.query(WebApp.java:1113)
at org.h2.server.web.WebApp.process(WebApp.java:244)
at org.h2.server.web.WebApp.processRequest(WebApp.java:176)
at org.h2.server.web.JakartaWebServlet.doGet(JakartaWebServlet.java:129)
at org.h2.server.web.JakartaWebServlet.doPost(JakartaWebServlet.java:166)
at jakarta.servlet.http.HttpServlet.service(HttpServlet.java:731)
at jakarta.servlet.http.HttpServlet.service(HttpServlet.java:814)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:223)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:158)
at org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:53)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:185)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:158)
at org.springframework.web.filter.RequestContextFilter.doFilterInternal(RequestContextFilter.java:100)
at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:116)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:185)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:158)
at org.springframework.web.filter.FormContentFilter.doFilterInternal(FormContentFilter.java:93)
at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:116)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:185)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:158)
at org.springframework.web.filter.CharacterEncodingFilter.doFilterInternal(CharacterEncodingFilter.java:201)
at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:116)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:185)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:158)
at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:177)
at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:97)
at org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:542)
at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:119)
at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:92)
at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:78)
at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:357)
at org.apache.coyote.http11.Http11Processor.service(Http11Processor.java:400)
at org.apache.coyote.AbstractProcessorLight.process(AbstractProcessorLight.java:65)
at org.apache.coyote.AbstractProtocol$ConnectionHandler.process(AbstractProtocol.java:859)
at org.apache.tomcat.util.net.NioEndpoint$SocketProcessor.doRun(NioEndpoint.java:1734)
at org.apache.tomcat.util.net.SocketProcessorBase.run(SocketProcessorBase.java:52)
at org.apache.tomcat.util.threads.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1191)
at org.apache.tomcat.util.threads.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:659)
at org.apache.tomcat.util.threads.TaskThread$WrappingRunnable.run(TaskThread.java:61)
at java.base/java.lang.Thread.run(Thread.java:833)
2023-03-27 03:40:48 jdbc[13]: exception
org.h2.jdbc.JdbcSQLSyntaxErrorException: Столбец "27-03-2022" не найден
Column "27-03-2022" not found; SQL statement:
insert into tab_order values (
1, "27-03-2022", 1
) [42122-210]
at org.h2.message.DbException.getJdbcSQLException(DbException.java:521)
at org.h2.message.DbException.getJdbcSQLException(DbException.java:496)
at org.h2.message.DbException.get(DbException.java:227)
at org.h2.message.DbException.get(DbException.java:203)
at org.h2.expression.ExpressionColumn.getColumnException(ExpressionColumn.java:248)
at org.h2.expression.ExpressionColumn.optimizeOther(ExpressionColumn.java:230)
at org.h2.expression.ExpressionColumn.optimize(ExpressionColumn.java:213)
at org.h2.command.dml.Insert.prepare(Insert.java:300)
at org.h2.command.Parser.prepareCommand(Parser.java:557)
at org.h2.engine.SessionLocal.prepareLocal(SessionLocal.java:615)
at org.h2.engine.SessionLocal.prepareCommand(SessionLocal.java:553)
at org.h2.jdbc.JdbcConnection.prepareCommand(JdbcConnection.java:1116)
at org.h2.jdbc.JdbcStatement.executeInternal(JdbcStatement.java:237)
at org.h2.jdbc.JdbcStatement.execute(JdbcStatement.java:223)
at org.h2.server.web.WebApp.getResult(WebApp.java:1339)
at org.h2.server.web.WebApp.query(WebApp.java:1137)
at org.h2.server.web.WebApp.query(WebApp.java:1113)
at org.h2.server.web.WebApp.process(WebApp.java:244)
at org.h2.server.web.WebApp.processRequest(WebApp.java:176)
at org.h2.server.web.JakartaWebServlet.doGet(JakartaWebServlet.java:129)
at org.h2.server.web.JakartaWebServlet.doPost(JakartaWebServlet.java:166)
at jakarta.servlet.http.HttpServlet.service(HttpServlet.java:731)
at jakarta.servlet.http.HttpServlet.service(HttpServlet.java:814)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:223)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:158)
at org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:53)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:185)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:158)
at org.springframework.web.filter.RequestContextFilter.doFilterInternal(RequestContextFilter.java:100)
at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:116)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:185)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:158)
at org.springframework.web.filter.FormContentFilter.doFilterInternal(FormContentFilter.java:93)
at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:116)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:185)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:158)
at org.springframework.web.filter.CharacterEncodingFilter.doFilterInternal(CharacterEncodingFilter.java:201)
at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:116)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:185)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:158)
at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:177)
at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:97)
at org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:542)
at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:119)
at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:92)
at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:78)
at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:357)
at org.apache.coyote.http11.Http11Processor.service(Http11Processor.java:400)
at org.apache.coyote.AbstractProcessorLight.process(AbstractProcessorLight.java:65)
at org.apache.coyote.AbstractProtocol$ConnectionHandler.process(AbstractProtocol.java:859)
at org.apache.tomcat.util.net.NioEndpoint$SocketProcessor.doRun(NioEndpoint.java:1734)
at org.apache.tomcat.util.net.SocketProcessorBase.run(SocketProcessorBase.java:52)
at org.apache.tomcat.util.threads.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1191)
at org.apache.tomcat.util.threads.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:659)
at org.apache.tomcat.util.threads.TaskThread$WrappingRunnable.run(TaskThread.java:61)
at java.base/java.lang.Thread.run(Thread.java:833)
2023-03-27 03:41:31 jdbc[13]: exception
org.h2.jdbc.JdbcSQLSyntaxErrorException: Столбец "'2022-12-31'" не найден
Column "'2022-12-31'" not found; SQL statement:
insert into tab_order values (
1, "'2022-12-31'", 1
) [42122-210]
at org.h2.message.DbException.getJdbcSQLException(DbException.java:521)
at org.h2.message.DbException.getJdbcSQLException(DbException.java:496)
at org.h2.message.DbException.get(DbException.java:227)
at org.h2.message.DbException.get(DbException.java:203)
at org.h2.expression.ExpressionColumn.getColumnException(ExpressionColumn.java:248)
at org.h2.expression.ExpressionColumn.optimizeOther(ExpressionColumn.java:230)
at org.h2.expression.ExpressionColumn.optimize(ExpressionColumn.java:213)
at org.h2.command.dml.Insert.prepare(Insert.java:300)
at org.h2.command.Parser.prepareCommand(Parser.java:557)
at org.h2.engine.SessionLocal.prepareLocal(SessionLocal.java:615)
at org.h2.engine.SessionLocal.prepareCommand(SessionLocal.java:553)
at org.h2.jdbc.JdbcConnection.prepareCommand(JdbcConnection.java:1116)
at org.h2.jdbc.JdbcStatement.executeInternal(JdbcStatement.java:237)
at org.h2.jdbc.JdbcStatement.execute(JdbcStatement.java:223)
at org.h2.server.web.WebApp.getResult(WebApp.java:1339)
at org.h2.server.web.WebApp.query(WebApp.java:1137)
at org.h2.server.web.WebApp.query(WebApp.java:1113)
at org.h2.server.web.WebApp.process(WebApp.java:244)
at org.h2.server.web.WebApp.processRequest(WebApp.java:176)
at org.h2.server.web.JakartaWebServlet.doGet(JakartaWebServlet.java:129)
at org.h2.server.web.JakartaWebServlet.doPost(JakartaWebServlet.java:166)
at jakarta.servlet.http.HttpServlet.service(HttpServlet.java:731)
at jakarta.servlet.http.HttpServlet.service(HttpServlet.java:814)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:223)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:158)
at org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:53)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:185)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:158)
at org.springframework.web.filter.RequestContextFilter.doFilterInternal(RequestContextFilter.java:100)
at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:116)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:185)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:158)
at org.springframework.web.filter.FormContentFilter.doFilterInternal(FormContentFilter.java:93)
at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:116)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:185)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:158)
at org.springframework.web.filter.CharacterEncodingFilter.doFilterInternal(CharacterEncodingFilter.java:201)
at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:116)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:185)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:158)
at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:177)
at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:97)
at org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:542)
at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:119)
at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:92)
at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:78)
at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:357)
at org.apache.coyote.http11.Http11Processor.service(Http11Processor.java:400)
at org.apache.coyote.AbstractProcessorLight.process(AbstractProcessorLight.java:65)
at org.apache.coyote.AbstractProtocol$ConnectionHandler.process(AbstractProtocol.java:859)
at org.apache.tomcat.util.net.NioEndpoint$SocketProcessor.doRun(NioEndpoint.java:1734)
at org.apache.tomcat.util.net.SocketProcessorBase.run(SocketProcessorBase.java:52)
at org.apache.tomcat.util.threads.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1191)
at org.apache.tomcat.util.threads.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:659)
at org.apache.tomcat.util.threads.TaskThread$WrappingRunnable.run(TaskThread.java:61)
at java.base/java.lang.Thread.run(Thread.java:833)
2023-03-27 03:42:20 jdbc[13]: exception
org.h2.jdbc.JdbcSQLSyntaxErrorException: Столбец "'2022-12-31'" не найден
Column "'2022-12-31'" not found; SQL statement:
insert into tab_order (id, date_of_purchase, customer_fk) values (
1, "'2022-12-31'", 1
) [42122-210]
at org.h2.message.DbException.getJdbcSQLException(DbException.java:521)
at org.h2.message.DbException.getJdbcSQLException(DbException.java:496)
at org.h2.message.DbException.get(DbException.java:227)
at org.h2.message.DbException.get(DbException.java:203)
at org.h2.expression.ExpressionColumn.getColumnException(ExpressionColumn.java:248)
at org.h2.expression.ExpressionColumn.optimizeOther(ExpressionColumn.java:230)
at org.h2.expression.ExpressionColumn.optimize(ExpressionColumn.java:213)
at org.h2.command.dml.Insert.prepare(Insert.java:300)
at org.h2.command.Parser.prepareCommand(Parser.java:557)
at org.h2.engine.SessionLocal.prepareLocal(SessionLocal.java:615)
at org.h2.engine.SessionLocal.prepareCommand(SessionLocal.java:553)
at org.h2.jdbc.JdbcConnection.prepareCommand(JdbcConnection.java:1116)
at org.h2.jdbc.JdbcStatement.executeInternal(JdbcStatement.java:237)
at org.h2.jdbc.JdbcStatement.execute(JdbcStatement.java:223)
at org.h2.server.web.WebApp.getResult(WebApp.java:1339)
at org.h2.server.web.WebApp.query(WebApp.java:1137)
at org.h2.server.web.WebApp.query(WebApp.java:1113)
at org.h2.server.web.WebApp.process(WebApp.java:244)
at org.h2.server.web.WebApp.processRequest(WebApp.java:176)
at org.h2.server.web.JakartaWebServlet.doGet(JakartaWebServlet.java:129)
at org.h2.server.web.JakartaWebServlet.doPost(JakartaWebServlet.java:166)
at jakarta.servlet.http.HttpServlet.service(HttpServlet.java:731)
at jakarta.servlet.http.HttpServlet.service(HttpServlet.java:814)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:223)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:158)
at org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:53)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:185)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:158)
at org.springframework.web.filter.RequestContextFilter.doFilterInternal(RequestContextFilter.java:100)
at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:116)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:185)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:158)
at org.springframework.web.filter.FormContentFilter.doFilterInternal(FormContentFilter.java:93)
at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:116)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:185)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:158)
at org.springframework.web.filter.CharacterEncodingFilter.doFilterInternal(CharacterEncodingFilter.java:201)
at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:116)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:185)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:158)
at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:177)
at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:97)
at org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:542)
at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:119)
at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:92)
at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:78)
at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:357)
at org.apache.coyote.http11.Http11Processor.service(Http11Processor.java:400)
at org.apache.coyote.AbstractProcessorLight.process(AbstractProcessorLight.java:65)
at org.apache.coyote.AbstractProtocol$ConnectionHandler.process(AbstractProtocol.java:859)
at org.apache.tomcat.util.net.NioEndpoint$SocketProcessor.doRun(NioEndpoint.java:1734)
at org.apache.tomcat.util.net.SocketProcessorBase.run(SocketProcessorBase.java:52)
at org.apache.tomcat.util.threads.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1191)
at org.apache.tomcat.util.threads.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:659)
at org.apache.tomcat.util.threads.TaskThread$WrappingRunnable.run(TaskThread.java:61)
at java.base/java.lang.Thread.run(Thread.java:833)

26
front/.gitignore vendored Normal file
View File

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

58
front/build.gradle Normal file
View File

@ -0,0 +1,58 @@
import com.github.gradle.node.util.PlatformHelper
import groovy.text.SimpleTemplateEngine
plugins {
id 'java'
id 'com.github.node-gradle.node' version '3.5.1'
id "de.undercouch.download" version '5.3.1'
}
node {
version = '18.15.0'
download = true
}
jar.dependsOn 'npmBuild'
clean.dependsOn 'npmClean'
nodeSetup.dependsOn 'downloadNode'
jar {
from 'dist'
into 'static'
final devHost = 'http://localhost:8080'
final prodHost = ''
filesMatching('index.html') {
filter { line -> line.replaceAll(devHost, prodHost) }
}
}
task downloadNode(type: Download) {
final helper = new PlatformHelper()
final templateData = [
"url" : node.distBaseUrl.get(),
"version": node.version.get(),
"os" : helper.osName,
"arch" : helper.osArch,
"ext" : helper.windows ? 'zip' : 'tar.gz'
]
final urlTemplate = '${url}/v${version}/node-v${version}-${os}-${arch}.${ext}'
final engine = new SimpleTemplateEngine()
final url = engine.createTemplate(urlTemplate).make(templateData).toString()
final String destDir = '.gradle/'
file(destDir).mkdirs()
src url
dest destDir
overwrite false
}
tasks.register('npmBuild', NpmTask) {
dependsOn npmInstall
args = ['run-script', 'build']
}
tasks.register('npmClean', NpmTask) {
dependsOn npmInstall
args = ['run-script', 'clean']
}

View File

@ -1,47 +0,0 @@
<!DOCTYPE html>
<html lang="ru">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1">
<script src="node_modules/bootstrap/dist/js/bootstrap.min.js"></script>
<link href="node_modules/bootstrap/dist/css/bootstrap.min.css" rel="stylesheet" />
<link href="node_modules/@fortawesome/fontawesome-free/css/all.min.css" rel="stylesheet" />
<title>Калькулятор</title>
</head>
<body>
<form class="mx-2 d-flex flex-column align-items-center text-center">
<div>
Первое число
<input id="first" class="form-control" type='number' value='0' />
</div>
<div>
Операция
<select class="form-select" id="operation">
<option value="1">+</option>
<option value="2">-</option>
<option value="3">*</option>
<option value="4">/</option>
</select>
</div>
<div>
Второе число
<input id="second" class="form-control" type='number' value='0' />
</div>
<div>
<button type="button" class="btn btn-primary my-2" id="calculate">Числа</button>
</div>
<div>
<button type="button" class="btn btn-primary mb-2" id="calculateStr">Строки</button>
</div>
<div>
Результат:
<p id="result"> </p>
</div>
</form>
</div>
<script src="script.js"></script>
</body>
</html>

4894
front/package-lock.json generated

File diff suppressed because it is too large Load Diff

View File

@ -1,16 +1,17 @@
{
"name": "int-prog",
"version": "1.0.0",
"main": "index.html",
"source": "src/index.html",
"scripts": {
"start": "http-server -p 3000 ./",
"test": "echo \"Error: no test specified\" && exit 1"
"start": "parcel --port 3000",
"build": "npm run clean && parcel build",
"clean": "rimraf dist"
},
"dependencies": {
"bootstrap": "5.2.1",
"@fortawesome/fontawesome-free": "6.2.0"
"bootstrap": "5.2.3"
},
"devDependencies": {
"http-server": "14.1.1"
"parcel": "2.8.3",
"rimraf": "4.4.0"
}
}

View File

@ -1,44 +0,0 @@
const calculateButton = document.getElementById("calculate");
const calculateStrButton = document.getElementById("calculateStr");
const first = document.getElementById("first");
const second = document.getElementById("second");
const select = document.getElementById("operation");
const result = document.getElementById("result");
calculateButton.onclick = function() {
calculate("num");
};
calculateStrButton.onclick = function() {
calculate("str");
};
function calculate(parametr) {
switch (parseInt(select.value)) {
case 1:
doSmth("plus", parametr)
break;
case 2:
doSmth("minus", parametr)
break;
case 3:
doSmth("mult", parametr)
break;
case 4:
doSmth("div", parametr)
break;
};
}
function checkNum(res) {
if (res.indexOf(".") != -1)
return parseInt(res)
else
return res
}
function doSmth(address, type) {
console.log("Тип " + type)
fetch(`http://localhost:8080/${address}?first=${first.value}&second=${second.value}&type=${type}`)
.then(response => response.text())
.then(res => result.innerHTML = checkNum(res));
}

74
front/src/index.html Normal file
View File

@ -0,0 +1,74 @@
<!doctype html>
<html lang="ru">
<head>
<meta charset="UTF-8">
<meta name="viewport"
content="width=device-width, user-scalable=no, initial-scale=1.0, maximum-scale=1.0, minimum-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>REST Client Example</title>
<script type="module" src="../node_modules/bootstrap/dist/js/bootstrap.min.js"></script>
<link href="../node_modules/bootstrap/dist/css/bootstrap.min.css" rel="stylesheet"/>
</head>
<body>
<header class="d-flex justify-content-center py-3">
<ul class="nav nav-pills">
<li class="nav-item"><a href="./index.html" class="nav-link active" aria-current="page">Customer</a></li>
<li class="nav-item"><a href="./ticket.html" class="nav-link">Ticket</a></li>
<li class="nav-item"><a href="./order.html" class="nav-link">Order</a></li>
</ul>
</header>
<div class="container">
<form id="form" novalidate>
<div class="row mt-3">
<div class="col-sm-6">
<label for="login" class="form-label">login</label>
<input type="text" class="form-control" id="login" required>
</div>
<div class="col-sm-6">
<label for="password" class="form-label">password</label>
<input type="password" class="form-control" id="password" required>
</div>
</div>
<div class="row mt-3">
<div class="d-grid col-sm-4 mx-auto">
<button type="submit" class="btn btn-success">Add</button>
</div>
<div class="d-grid col-sm-4 mx-auto mt-3 mt-sm-0">
<button id="testError" type="button" class="btn btn-danger">Test</button>
</div>
<div class="d-grid col-sm-4 mx-auto mt-3 mt-sm-0">
<button id="testNormal" type="button" class="btn btn-secondary">Test</button>
</div>
</div>
</form>
<div class="row mt-3">
<div class="col-sm-4">
<label for="id" class="form-label">id</label>
<input type="number" class="form-control" id="id" required>
</div>
</div>
<div class="row mt-3">
<div class="d-grid col-sm-2">
<button id="editBtn" class="btn btn-primary">Edit</button>
</div>
<div class="d-grid col-sm-2">
<button id="removeBtn" class="btn btn-danger">Remove</button>
</div>
</div>
<div class="row table-responsive">
<table class="table mt-3">
<thead>
<tr>
<th scope="col">#</th>
<th scope="col">Login</th>
<th scope="col">Password</th>
</tr>
</thead>
<tbody id="tbody">
</tbody>
</table>
</div>
</div>
</body>
<script src="script.js"></script>
</html>

63
front/src/order.html Normal file
View File

@ -0,0 +1,63 @@
<!doctype html>
<html lang="ru">
<head>
<meta charset="UTF-8">
<meta name="viewport"
content="width=device-width, user-scalable=no, initial-scale=1.0, maximum-scale=1.0, minimum-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>REST Client Example</title>
<script type="module" src="../node_modules/bootstrap/dist/js/bootstrap.min.js"></script>
<link href="../node_modules/bootstrap/dist/css/bootstrap.min.css" rel="stylesheet"/>
</head>
<body>
<header class="d-flex justify-content-center py-3">
<ul class="nav nav-pills">
<li class="nav-item"><a href="./index.html" class="nav-link" aria-current="page">Customer</a></li>
<li class="nav-item"><a href="./ticket.html" class="nav-link">Ticket</a></li>
<li class="nav-item"><a href="./order.html" class="nav-link active">Order</a></li>
</ul>
</header>
<div class="container">
<form id="form" novalidate>
<div class="row mt-3">
<div class="col-sm-6">
<label for="id" class="form-label">id</label>
<input type="number" class="form-control" id="id" required>
</div>
<div class="col-sm-6">
<label for="customer" class="form-label">customer id</label>
<input type="text" class="form-control" id="customer" required>
</div>
</div>
<div class="row mt-3">
<div class="d-grid col-sm-6">
<button id="removeBtn" class="btn btn-danger">Remove</button>
</div>
<div class="d-grid col-sm-6">
<button id="relateBtn" class="btn btn-primary">Relate</button>
</div>
</div>
<div class="row mt-3">
<div class="d-grid col-sm-6 mx-auto">
<button type="submit" class="btn btn-success">Add empty order</button>
</div>
</div>
</form>
<div class="row table-responsive">
<table class="table mt-3">
<thead>
<tr>
<th scope="col">#</th>
<th scope="col">Customer</th>
<th scope="col">Date Of Purchase</th>
<th scope="col">Tickets</th>
</tr>
</thead>
<tbody id="tbody">
</tbody>
</table>
</div>
</div>
</body>
<script src="order.js"></script>
</html>

75
front/src/order.js Normal file
View File

@ -0,0 +1,75 @@
"use strict";
window.addEventListener('DOMContentLoaded', function () {
const host = "http://localhost:8080";
const table = document.getElementById("tbody");
const form = document.getElementById("form");
const customerInput = document.getElementById("customer");
const idInput = document.getElementById("id");
const removeBtn = document.getElementById("removeBtn");
const getData = async function () {
table.innerHTML = "";
const response = await fetch(host + "/order");
const data = await response.json();
/*data.forEach(order => {
let temp = "<select>";
order.tickets.forEach(ticket => {
temp += `<option>${ticket.name + " " + ticket.price + " " + ticket.timestamp}</option>`
})
table.innerHTML +=
`<tr>
<th scope="row">${order.id}</th>
<td>${order.customer}</td>
<td>${order.dateOfPurchase}</td>
<td>${temp}</td>
</tr>`;
})*/
}
async function create() {
const requestParams = {
method: "POST",
headers: {
'Accept': 'application/json',
'Content-Type': 'application/json'
}
};
const response = await fetch(host + `/order/post?post=`, requestParams);
return await response.json();
}
async function remove(id) {
const requestParams = {
method: "DELETE",
};
const response = await fetch(host + `/order/${id}`, requestParams);
return await response.json();
}
async function editCustomer(id) {
const requestParams = {
method: "PUT",
headers: {
"Content-Type": "application/json",
}
};
const response = await fetch(host + `/order/${id}/updcustomer`, requestParams);
return await response.json();
}
form.addEventListener("submit", function (event) {
event.preventDefault();
create().then(() => {
getData();
});
});
removeBtn.addEventListener("click", function (event) {
event.preventDefault();
remove(idInput.value).then((result) => {
getData();
customerInput.value = "";
idInput.value = "";
});
});
getData();
});

114
front/src/script.js Normal file
View File

@ -0,0 +1,114 @@
"use strict";
window.addEventListener('DOMContentLoaded', function () {
const host = "http://localhost:8080";
const table = document.getElementById("tbody");
const form = document.getElementById("form");
const passwordInput = document.getElementById("password");
const loginInput = document.getElementById("login");
const idInput = document.getElementById("id");
const removeBtn = document.getElementById("removeBtn");
const editBtn = document.getElementById("editBtn");
const testErrorBtn = document.getElementById("testError");
const testNormalBtn = document.getElementById("testNormal");
const getData = async function () {
table.innerHTML = "";
const response = await fetch(host + "/customer");
const data = await response.json();
data.forEach(customer => {
table.innerHTML +=
`<tr>
<th scope="row">${customer.id}</th>
<td>${customer.login}</td>
<td>${customer.password}</td>
</tr>`;
})
}
const create = async function (login, password) {
const requestParams = {
method: "POST",
headers: {
"Content-Type": "application/json",
}
};
const response = await fetch(host + `/customer?login=${login}&password=${password}`, requestParams);
return await response.json();
}
async function remove(id) {
const requestParams = {
method: "DELETE",
};
const response = await fetch(host + `/customer/${id}`, requestParams);
return await response.json();
}
async function edit(id, login, password) {
const requestParams = {
method: "PUT",
headers: {
"Content-Type": "application/json",
}
};
const response = await fetch(host + `/customer/${id}?login=${login}&password=${password}`, requestParams);
return await response.json();
}
const test = async function (testObject) {
const requestParams = {
method: "POST",
headers: {
"Content-Type": "application/json",
},
body: JSON.stringify(testObject),
};
const response = await fetch(host + "/test", requestParams);
if (response.status === 200) {
const data = await response.json();
alert(`TestDto=[id=${data.id}, name=${data.name}, data=${data.data}]`);
}
if (response.status === 400) {
const data = await response.text();
alert(data);
}
}
form.addEventListener("submit", function (event) {
event.preventDefault();
create(loginInput.value, passwordInput.value).then((result) => {
getData();
loginInput.value = "";
passwordInput.value = "";
alert(`Customer[id=${result.id}, login=${result.login}, password=${result.password}]`);
});
});
testErrorBtn.addEventListener("click", function () {
test({});
});
testNormalBtn.addEventListener("click", function () {
test({id: 10, name: "test"});
});
removeBtn.addEventListener("click", function (event) {
event.preventDefault();
remove(idInput.value).then((result) => {
getData();
loginInput.value = "";
passwordInput.value = "";
idInput.value = "";
});
});
editBtn.addEventListener("click", function (event) {
event.preventDefault();
edit(idInput.value, loginInput.value, passwordInput.value).then((result) => {
getData();
loginInput.value = "";
passwordInput.value = "";
idInput.value = "";
});
});
getData();
});

74
front/src/ticket.html Normal file
View File

@ -0,0 +1,74 @@
<!doctype html>
<html lang="ru">
<head>
<meta charset="UTF-8">
<meta name="viewport"
content="width=device-width, user-scalable=no, initial-scale=1.0, maximum-scale=1.0, minimum-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>REST Client Example</title>
<script type="module" src="../node_modules/bootstrap/dist/js/bootstrap.min.js"></script>
<link href="../node_modules/bootstrap/dist/css/bootstrap.min.css" rel="stylesheet"/>
</head>
<body>
<header class="d-flex justify-content-center py-3">
<ul class="nav nav-pills">
<li class="nav-item"><a href="./index.html" class="nav-link" aria-current="page">Customer</a></li>
<li class="nav-item"><a href="./ticket.html" class="nav-link active">Ticket</a></li>
<li class="nav-item"><a href="./order.html" class="nav-link">Order</a></li>
</ul>
</header>
<div class="container">
<form id="form" novalidate>
<div class="row mt-3">
<div class="col-sm-4">
<label for="name" class="form-label">name</label>
<input type="text" class="form-control" id="name" required>
</div>
<div class="col-sm-4">
<label for="price" class="form-label">price</label>
<input type="number" step="0.01" class="form-control" id="price" required>
</div>
<div class="col-sm-4">
<label for="timestamp" class="form-label">timestamp</label>
<input type="datetime-local" class="form-control" id="timestamp" required>
</div>
</div>
<div class="row mt-3">
<div class="d-grid col-sm-4 mx-auto">
<button type="submit" class="btn btn-success">Add</button>
</div>
</div>
<div class="row mt-3">
<div class="col-sm-4">
<label for="id" class="form-label">id</label>
<input type="number" class="form-control" id="id" required>
</div>
</div>
<div class="row mt-3">
<div class="d-grid col-sm-2">
<button id="editBtn" class="btn btn-primary">Edit</button>
</div>
<div class="d-grid col-sm-2">
<button id="removeBtn" class="btn btn-danger">Remove</button>
</div>
</div>
</form>
<div class="row table-responsive">
<table class="table mt-3">
<thead>
<tr>
<th scope="col">#</th>
<th scope="col">Name</th>
<th scope="col">Price</th>
<th scope="col">Timestamp</th>
</tr>
</thead>
<tbody id="tbody">
</tbody>
</table>
</div>
</div>
</body>
<script src="ticket.js"></script>
</html>

89
front/src/ticket.js Normal file
View File

@ -0,0 +1,89 @@
"use strict";
window.addEventListener('DOMContentLoaded', function () {
const host = "http://localhost:8080";
const table = document.getElementById("tbody");
const form = document.getElementById("form");
const priceInput = document.getElementById("price");
const nameInput = document.getElementById("name");
const idInput = document.getElementById("id");
const removeBtn = document.getElementById("removeBtn");
const editBtn = document.getElementById("editBtn");
const timestampInput = document.getElementById("timestamp");
const getData = async function () {
table.innerHTML = "";
const response = await fetch(host + "/ticket");
const data = await response.json();
data.forEach(ticket => {
table.innerHTML +=
`<tr>
<th scope="row">${ticket.id}</th>
<td>${ticket.name}</td>
<td>${ticket.price}</td>
<td>${ticket.timestamp}</td>
</tr>`;
})
}
async function create(name, price, timestamp) {
const requestParams = {
method: "POST",
headers: {
"Content-Type": "application/json",
}
};
const response = await fetch(host + `/ticket?name=${name}&price=${price}&timestamp=${timestamp}`, requestParams);
return await response.json();
}
async function remove(id) {
const requestParams = {
method: "DELETE",
};
const response = await fetch(host + `/ticket/${id}`, requestParams);
return await response.json();
}
async function edit(id, name, price) {
const requestParams = {
method: "PUT",
headers: {
"Content-Type": "application/json",
}
};
const response = await fetch(host + `/ticket/${id}?name=${name}&price=${price}`, requestParams);
return await response.json();
}
form.addEventListener("submit", function (event) {
event.preventDefault();
create(nameInput.value, priceInput.value, timestampInput.value).then((result) => {
getData();
nameInput.value = "";
priceInput.value = "";
timestampInput.value = "";
//alert(`Ticket[id=${result.id}, name=${result.name}, price=${result.price}, timestamp=${result.timetamp}]`);
});
});
removeBtn.addEventListener("click", function (event) {
event.preventDefault();
remove(idInput.value).then((result) => {
getData();
nameInput.value = "";
priceInput.value = "";
timestampInput.value = "";
idInput.value = "";
});
});
editBtn.addEventListener("click", function (event) {
event.preventDefault();
edit(idInput.value, nameInput.value, priceInput.value).then((result) => {
getData();
nameInput.value = "";
priceInput.value = "";
idInput.value = "";
});
});
getData();
});

View File

@ -1 +1,2 @@
rootProject.name = 'app'
include 'front'

View File

@ -0,0 +1,46 @@
package com.labwork1.app.student.controller;
import com.labwork1.app.student.service.CustomerService;
import org.springframework.web.bind.annotation.*;
import java.util.List;
@RestController
@RequestMapping("/customer")
public class CustomerController {
private final CustomerService customerService;
public CustomerController(CustomerService customerService) {
this.customerService = customerService;
}
@GetMapping("/{id}")
public CustomerDto getCustomer(@PathVariable Long id) {
return new CustomerDto(customerService.findCustomer(id));
}
@GetMapping
public List<CustomerDto> getCustomers() {
return customerService.findAllCustomers().stream()
.map(CustomerDto::new)
.toList();
}
@PostMapping
public CustomerDto createCustomer(@RequestParam("login") String login,
@RequestParam("password") String password) {
return new CustomerDto(customerService.addCustomer(login, password));
}
@PutMapping("/{id}")
public CustomerDto updateCustomer(@PathVariable Long id,
@RequestParam("login") String login,
@RequestParam("password") String password) {
return new CustomerDto(customerService.updateCustomer(id, login, password));
}
@DeleteMapping("/{id}")
public CustomerDto deleteCustomer(@PathVariable Long id) {
return new CustomerDto(customerService.deleteCustomer(id));
}
}

View File

@ -0,0 +1,33 @@
package com.labwork1.app.student.controller;
import com.labwork1.app.student.model.Customer;
import com.labwork1.app.student.model.Order;
import java.util.List;
public class CustomerDto {
private final long id;
private final String login;
private final String password;
private final List<Order> orders;
public CustomerDto(Customer customer) {
this.id = customer.getId();
this.login = customer.getLogin();
this.password = customer.getPassword();
this.orders = customer.getOrders();
}
public long getId() {
return id;
}
public String getLogin() {
return login;
}
public String getPassword() {
return password;
}
public List<Order> getOrders() {
return orders;
}
}

View File

@ -0,0 +1,61 @@
package com.labwork1.app.student.controller;
import com.labwork1.app.student.model.Customer;
import com.labwork1.app.student.model.Order;
import com.labwork1.app.student.service.CustomerService;
import com.labwork1.app.student.service.OrderService;
import com.labwork1.app.student.service.TicketService;
import org.springframework.web.bind.annotation.*;
import java.util.List;
@RestController
@RequestMapping("/order")
public class OrderController {
private final OrderService orderService;
private final CustomerService customerService;
private final TicketService ticketService;
public OrderController(OrderService orderService,
CustomerService customerService, TicketService ticketService) {
this.orderService = orderService;
this.customerService = customerService;
this.ticketService = ticketService;
}
@GetMapping("/{id}")
public OrderDto getOrder(@PathVariable Long id) {
return new OrderDto(orderService.findOrder(id));
}
@GetMapping
public List<OrderDto> getOrders() {
return orderService.findAllOrders().stream()
.map(OrderDto::new)
.toList();
}
@PostMapping("/post")
public OrderDto createOrder(@RequestParam("post") String post) {
return new OrderDto(orderService.addOrder());
}
@PutMapping("/{id}/updcustomer")
public OrderDto updateOrderCustomer(@PathVariable Long id,
@RequestParam("customer") Long customer) {
return new OrderDto(orderService.addCustomer(id, customer));
}
@PutMapping("/{id}/updticket")
public OrderDto updateOrder(@PathVariable Long id,
@RequestParam("ticket") String ticket) {
return new OrderDto(orderService.addTicket(id,
ticketService.findTicket(Long.parseLong(ticket))));
}
@DeleteMapping("/{id}")
public OrderDto deleteOrder(@PathVariable Long id) {
return new OrderDto(orderService.deleteOrder(id));
}
}

View File

@ -0,0 +1,35 @@
package com.labwork1.app.student.controller;
import com.labwork1.app.student.model.Customer;
import com.labwork1.app.student.model.Order;
import java.sql.Date;
import java.util.List;
public class OrderDto {
private final long id;
private final Date dateOfPurchase;
private final Customer customer;
private final List<TicketDto> tickets;
public OrderDto(Order order) {
this.id = order.getId();
this.dateOfPurchase = order.getDateOfPurchase();
this.customer = order.getCustomer();
this.tickets = order.getTickets()
.stream()
.map(x -> new TicketDto(x)).toList();
}
public long getId() {
return id;
}
public Date getDateOfPurchase() {
return dateOfPurchase;
}
public Customer getCustomer() {
return customer;
}
public List<TicketDto> getTickets() {
return tickets;
}
}

View File

@ -0,0 +1,55 @@
package com.labwork1.app.student.controller;
import com.labwork1.app.student.service.TicketService;
import org.springframework.web.bind.annotation.*;
import java.sql.Timestamp;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
@RestController
@RequestMapping("/ticket")
public class TicketController {
private final TicketService ticketService;
public TicketController(TicketService ticketService) {
this.ticketService = ticketService;
}
@GetMapping("/{id}")
public TicketDto getTicket(@PathVariable Long id) {
return new TicketDto(ticketService.findTicket(id));
}
@GetMapping
public List<TicketDto> getTickets() {
return ticketService.findAllTickets().stream()
.map(TicketDto::new)
.toList();
}
@PostMapping
public TicketDto createTicket(@RequestParam("name") String name,
@RequestParam("price") String price,
@RequestParam("timestamp") String timestamp) throws ParseException {
SimpleDateFormat format = new SimpleDateFormat();
format.applyPattern("yyyy-MM-dd-HH:ss");
Date docDate = format.parse(timestamp.replace('T', '-'));
return new TicketDto(ticketService.addTicket(name, Double.parseDouble(price),
new Timestamp(docDate.getTime())));
}
@PutMapping("/{id}")
public TicketDto updateTicket(@PathVariable Long id,
@RequestParam("name") String name,
@RequestParam("price") String price) {
return new TicketDto(ticketService.updateTicket(id, name, Double.parseDouble(price)));
}
@DeleteMapping("/{id}")
public TicketDto deleteTicket(@PathVariable Long id) {
return new TicketDto(ticketService.deleteTicket(id));
}
}

View File

@ -0,0 +1,30 @@
package com.labwork1.app.student.controller;
import com.labwork1.app.student.model.Ticket;
import java.sql.Timestamp;
public class TicketDto {
private final long id;
private String name;
private Double price;
private Timestamp timestamp;
public TicketDto(Ticket ticket) {
this.id = ticket.getId();
this.name = ticket.getName();
this.price = ticket.getPrice();
this.timestamp = ticket.getTimestamp();
}
public long getId() {
return id;
}
public String getName() {
return name;
}
public Double getPrice() {
return price;
}
public Timestamp getTimestamp() {
return timestamp;
}
}

View File

@ -1,6 +1,7 @@
package com.labwork1.app.student.model;
import jakarta.persistence.*;
import jakarta.validation.constraints.NotBlank;
import java.util.ArrayList;
import java.util.List;
@ -11,9 +12,9 @@ public class Customer {
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
private Long id;
@Column
@NotBlank(message = "login can't be null or empty")
private String login;
@Column
@NotBlank(message = "password can't be null or empty")
private String password;
@OneToMany(fetch = FetchType.EAGER, mappedBy = "customer", cascade = CascadeType.REMOVE)
private List<Order> orders;

View File

@ -1,6 +1,8 @@
package com.labwork1.app.student.model;
import jakarta.persistence.*;
import jakarta.validation.constraints.NotBlank;
import jakarta.validation.constraints.NotNull;
import java.sql.Date;
import java.util.ArrayList;
@ -13,9 +15,10 @@ public class Order {
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
private Long id;
@Column
@NotNull(message = "dateOfPurchase can't be null or empty")
@Temporal(TemporalType.DATE)
private Date dateOfPurchase;
@NotNull(message = "customer can't be null or empty")
@ManyToOne(fetch = FetchType.EAGER)
@JoinColumn(name = "customer_fk")
private Customer customer;

View File

@ -1,6 +1,7 @@
package com.labwork1.app.student.model;
import jakarta.persistence.*;
import jakarta.validation.constraints.*;
import java.sql.Timestamp;
import java.util.List;
@ -11,11 +12,11 @@ public class Ticket {
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
private Long id;
@Column
@NotBlank(message = "name can't be null or empty")
private String name;
@Column
@NotNull(message = "price can't be null or empty")
private Double price;
@Column
@NotNull(message = "timestamp can't be null or empty")
@Temporal(TemporalType.TIMESTAMP)
private Timestamp timestamp;
@ManyToMany(fetch = FetchType.EAGER, mappedBy = "tickets")

View File

@ -0,0 +1,7 @@
package com.labwork1.app.student.repository;
import com.labwork1.app.student.model.Customer;
import org.springframework.data.jpa.repository.JpaRepository;
public interface CustomerRepository extends JpaRepository<Customer, Long> {
}

View File

@ -0,0 +1,7 @@
package com.labwork1.app.student.repository;
import com.labwork1.app.student.model.Order;
import org.springframework.data.jpa.repository.JpaRepository;
public interface OrderRepository extends JpaRepository<Order, Long> {
}

View File

@ -0,0 +1,7 @@
package com.labwork1.app.student.repository;
import com.labwork1.app.student.model.Ticket;
import org.springframework.data.jpa.repository.JpaRepository;
public interface TicketRepository extends JpaRepository<Ticket, Long> {
}

View File

@ -0,0 +1,7 @@
package com.labwork1.app.student.service;
public class CustomerNotFoundException extends RuntimeException {
public CustomerNotFoundException(Long id) {
super(String.format("Customer with id [%s] is not found", id));
}
}

View File

@ -1,66 +1,61 @@
package com.labwork1.app.student.service;
import com.labwork1.app.student.model.Customer;
import com.labwork1.app.student.repository.CustomerRepository;
import com.labwork1.app.util.validation.ValidatorUtil;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;
import jakarta.persistence.EntityManager;
import jakarta.persistence.EntityNotFoundException;
import jakarta.persistence.PersistenceContext;
import java.util.List;
import java.util.Optional;
@Service
public class CustomerService {
@PersistenceContext
private EntityManager em;
private final CustomerRepository customerRepository;
private final ValidatorUtil validatorUtil;
public CustomerService(CustomerRepository customerRepository,
ValidatorUtil validatorUtil) {
this.customerRepository = customerRepository;
this.validatorUtil = validatorUtil;
}
@Transactional
public Customer addCustomer(String login, String password) {
if (!StringUtils.hasText(login) || !StringUtils.hasText(password)) {
throw new IllegalArgumentException("Customer login/password is null or empty");
}
final Customer customer = new Customer(login, password);
em.persist(customer);
return customer;
validatorUtil.validate(customer);
return customerRepository.save(customer);
}
@Transactional(readOnly = true)
public Customer findCustomer(Long id) {
final Customer customer = em.find(Customer.class, id);
if (customer == null) {
throw new EntityNotFoundException(String.format("Customer with id [%s] is not found", id));
}
return customer;
final Optional<Customer> customer = customerRepository.findById(id);
return customer.orElseThrow(() -> new CustomerNotFoundException(id));
}
@Transactional(readOnly = true)
public List<Customer> findAllCustomers() {
return em.createQuery("select c from Customer c", Customer.class)
.getResultList();
return customerRepository.findAll();
}
@Transactional
public Customer updateCustomer(Long id, String login, String password) {
if (!StringUtils.hasText(login) || !StringUtils.hasText(password)) {
throw new IllegalArgumentException("Customer login/password is null or empty");
}
final Customer currentCustomer = findCustomer(id);
currentCustomer.setLogin(login);
currentCustomer.setPassword(password);
return em.merge(currentCustomer);
validatorUtil.validate(currentCustomer);
return customerRepository.save(currentCustomer);
}
@Transactional
public Customer deleteCustomer(Long id) {
final Customer currentCustomer = findCustomer(id);
em.remove(currentCustomer);
customerRepository.delete(currentCustomer);
return currentCustomer;
}
@Transactional
public void deleteAllCustomers() {
em.createQuery("delete from Customer").executeUpdate();
customerRepository.deleteAll();
}
}

View File

@ -0,0 +1,7 @@
package com.labwork1.app.student.service;
public class OrderNotFoundException extends RuntimeException {
public OrderNotFoundException(Long id) {
super(String.format("Order with id [%s] is not found", id));
}
}

View File

@ -3,78 +3,89 @@ package com.labwork1.app.student.service;
import com.labwork1.app.student.model.Customer;
import com.labwork1.app.student.model.Order;
import com.labwork1.app.student.model.Ticket;
import jakarta.persistence.EntityManager;
import jakarta.persistence.EntityNotFoundException;
import jakarta.persistence.PersistenceContext;
import com.labwork1.app.student.repository.CustomerRepository;
import com.labwork1.app.student.repository.OrderRepository;
import com.labwork1.app.student.repository.TicketRepository;
import com.labwork1.app.util.validation.ValidatorUtil;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import java.sql.Date;
import java.util.List;
import java.util.Optional;
@Service
public class OrderService {
@PersistenceContext
private EntityManager em;
private final OrderRepository orderRepository;
private final TicketRepository ticketRepository;
private final CustomerRepository customerRepository;
private final ValidatorUtil validatorUtil;
public OrderService(OrderRepository orderRepository,
TicketRepository ticketRepository,
CustomerRepository customerRepository,
ValidatorUtil validatorUtil) {
this.orderRepository = orderRepository;
this.ticketRepository = ticketRepository;
this.customerRepository = customerRepository;
this.validatorUtil = validatorUtil;
}
@Transactional
public Order addOrder(Customer customer) {
if (customer == null || em.find(Customer.class, customer.getId()) == null) {
throw new IllegalArgumentException("addOrder empty fields");
}
public Order addOrder() {
final Order order = new Order(new Date(System.currentTimeMillis()));
validatorUtil.validate(order);
return orderRepository.save(order);
}
@Transactional
public Order addCustomer(Long id, Long customer_id) {
final Order order = findOrder(id);
final Customer customer = customerRepository.findById(customer_id).get();
order.setCustomer(customer);
em.persist(order);
em.merge(customer);
validatorUtil.validate(order);
return order;
}
@Transactional
public Order addTicket(Long id, Ticket ticket) {
if (ticket == null) {
throw new IllegalArgumentException("addOrder empty fields");
}
final Order currentOrder = findOrder(id);
currentOrder.addTicket(ticket);
ticket.setOrder(currentOrder);
em.merge(ticket);
return em.merge(currentOrder);
validatorUtil.validate(currentOrder);
return orderRepository.save(currentOrder);
}
@Transactional(readOnly = true)
public Order findOrder(Long id) {
final Order order = em.find(Order.class, id);
if (order == null) {
throw new EntityNotFoundException(String.format("Order with id [%s] is not found", id));
}
return order;
final Optional<Order> order = orderRepository.findById(id);
return order.orElseThrow(() -> new OrderNotFoundException(id));
}
@Transactional(readOnly = true)
public List<Order> findAllOrders() {
return em.createQuery("select o from Order o", Order.class)
.getResultList();
return orderRepository.findAll();
}
@Transactional
public Order deleteOrder(Long id) {
final Order currentOrder = findOrder(id);
em.remove(currentOrder);
orderRepository.delete(currentOrder);
return currentOrder;
}
@Transactional
public Order deleteTicketInOrder(Long id, Ticket ticket) {
final Order currentOrder = findOrder(id);
final Ticket currentTicket = em.find(Ticket.class, ticket.getId());
currentOrder.getTickets().remove(currentTicket);
currentTicket.getOrders().remove(currentOrder);
em.merge(currentTicket);
return em.merge(currentOrder);
final Optional<Ticket> currentTicket = ticketRepository.findById(id);
currentTicket.ifPresent(x -> x.getOrders().remove(currentOrder));
orderRepository.findById(currentOrder.getId())
.ifPresent(x -> x.getTickets().remove(currentTicket));
return currentOrder;
}
@Transactional
public void deleteAllOrders() {
em.createQuery("delete from Order").executeUpdate();
orderRepository.deleteAll();
}
}

View File

@ -0,0 +1,7 @@
package com.labwork1.app.student.service;
public class TicketNotFoundException extends RuntimeException {
public TicketNotFoundException(Long id) {
super(String.format("Ticket with id [%s] is not found", id));
}
}

View File

@ -1,67 +1,62 @@
package com.labwork1.app.student.service;
import com.labwork1.app.student.model.Order;
import com.labwork1.app.student.model.Ticket;
import jakarta.persistence.EntityManager;
import jakarta.persistence.EntityNotFoundException;
import jakarta.persistence.PersistenceContext;
import com.labwork1.app.student.repository.TicketRepository;
import com.labwork1.app.util.validation.ValidatorUtil;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;
import java.sql.Timestamp;
import java.util.List;
import java.util.Optional;
@Service
public class TicketService {
@PersistenceContext
private EntityManager em;
private final TicketRepository ticketRepository;
private final ValidatorUtil validatorUtil;
public TicketService(TicketRepository ticketRepository,
ValidatorUtil validatorUtil) {
this.ticketRepository = ticketRepository;
this.validatorUtil = validatorUtil;
}
@Transactional
public Ticket addTicket(String name, Double price, Timestamp date) {
if (!StringUtils.hasText(name) || price <= 0 || date == null) {
throw new IllegalArgumentException("addTicket empty fields");
}
final Ticket ticket = new Ticket(name, price, date);
em.persist(ticket);
return ticket;
validatorUtil.validate(ticket);
return ticketRepository.save(ticket);
}
@Transactional(readOnly = true)
public Ticket findTicket(Long id) {
final Ticket ticket = em.find(Ticket.class, id);
if (ticket == null) {
throw new EntityNotFoundException(String.format("Ticket with id [%s] is not found", id));
}
return ticket;
final Optional<Ticket> ticket = ticketRepository.findById(id);
return ticket.orElseThrow(() -> new TicketNotFoundException(id));
}
@Transactional(readOnly = true)
public List<Ticket> findAllTickets() {
return em.createQuery("select t from Ticket t", Ticket.class)
.getResultList();
return ticketRepository.findAll();
}
@Transactional
public Ticket updateTicket(Long id, String name, Double price) {
if (!StringUtils.hasText(name) || price <= 0) {
throw new IllegalArgumentException("updateTicket empty fields");
}
final Ticket currentTicket = findTicket(id);
currentTicket.setName(name);
currentTicket.setPrice(price);
return em.merge(currentTicket);
validatorUtil.validate(currentTicket);
return ticketRepository.save(currentTicket);
}
@Transactional
public Ticket deleteTicket(Long id) {
final Ticket currentTicket = findTicket(id);
em.remove(currentTicket);
ticketRepository.delete(currentTicket);
return currentTicket;
}
@Transactional
public void deleteAllTickets() {
em.createQuery("delete from Ticket ").executeUpdate();
ticketRepository.deleteAll();
}
}

View File

@ -0,0 +1,17 @@
package com.labwork1.app.test.controller;
import com.labwork1.app.test.model.TestDto;
import jakarta.validation.Valid;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
@RestController
@RequestMapping("/test")
public class TestController {
@PostMapping
public TestDto testValidation(@RequestBody @Valid TestDto testDto) {
return testDto;
}
}

View File

@ -0,0 +1,31 @@
package com.labwork1.app.test.model;
import com.fasterxml.jackson.annotation.JsonIgnore;
import com.fasterxml.jackson.annotation.JsonProperty;
import jakarta.validation.constraints.NotBlank;
import jakarta.validation.constraints.NotNull;
public class TestDto {
@NotNull(message = "Id can't be null")
private Long id;
@NotBlank(message = "Name can't be null or empty")
private String name;
public Long getId() {
return id;
}
public String getName() {
return name;
}
@JsonProperty(access = JsonProperty.Access.READ_ONLY)
public String getData() {
return String.format("%s %s", id, name);
}
@JsonIgnore
public String getAnotherData() {
return "Test";
}
}

View File

@ -0,0 +1,42 @@
package com.labwork1.app.util.error;
import com.labwork1.app.student.service.CustomerNotFoundException;
import com.labwork1.app.student.service.OrderNotFoundException;
import com.labwork1.app.student.service.TicketNotFoundException;
import com.labwork1.app.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({
CustomerNotFoundException.class,
OrderNotFoundException.class,
TicketNotFoundException.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,9 @@
package com.labwork1.app.util.validation;
import java.util.Set;
public class ValidationException extends RuntimeException {
public ValidationException(Set<String> errors) {
super(String.join("\n", errors));
}
}

View File

@ -0,0 +1,30 @@
package com.labwork1.app.util.validation;
import jakarta.validation.ConstraintViolation;
import jakarta.validation.Validation;
import jakarta.validation.Validator;
import jakarta.validation.ValidatorFactory;
import org.springframework.stereotype.Component;
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

@ -27,7 +27,7 @@ public class JpaCustomerTests {
@Autowired
private OrderService orderService;
@Test
/* @Test
void testOrder() {
ticketService.deleteAllTickets();
orderService.deleteAllOrders();
@ -132,5 +132,5 @@ public class JpaCustomerTests {
Assertions.assertEquals(tickets2.size(), 0);
}
}*/
}