Compare commits

...

No commits in common. "main" and "Lab3" have entirely different histories.
main ... Lab3

50 changed files with 2686 additions and 124 deletions

153
.gitignore vendored
View File

@ -1,128 +1,37 @@
# ---> JetBrains HELP.md
# Covers JetBrains IDEs: IntelliJ, RubyMine, PhpStorm, AppCode, PyCharm, CLion, Android Studio, WebStorm and Rider
# Reference: https://intellij-support.jetbrains.com/hc/en-us/articles/206544839
# User-specific stuff
.idea/**/workspace.xml
.idea/**/tasks.xml
.idea/**/usage.statistics.xml
.idea/**/dictionaries
.idea/**/shelf
# AWS User-specific
.idea/**/aws.xml
# Generated files
.idea/**/contentModel.xml
# Sensitive or high-churn files
.idea/**/dataSources/
.idea/**/dataSources.ids
.idea/**/dataSources.local.xml
.idea/**/sqlDataSources.xml
.idea/**/dynamic.xml
.idea/**/uiDesigner.xml
.idea/**/dbnavigator.xml
# Gradle
.idea/**/gradle.xml
.idea/**/libraries
# Gradle and Maven with auto-import
# When using Gradle or Maven with auto-import, you should exclude module files,
# since they will be recreated, and may cause churn. Uncomment if using
# auto-import.
# .idea/artifacts
# .idea/compiler.xml
# .idea/jarRepositories.xml
# .idea/modules.xml
# .idea/*.iml
# .idea/modules
# *.iml
# *.ipr
# CMake
cmake-build-*/
# Mongo Explorer plugin
.idea/**/mongoSettings.xml
# File-based project format
*.iws
# IntelliJ
out/
# mpeltonen/sbt-idea plugin
.idea_modules/
# JIRA plugin
atlassian-ide-plugin.xml
# Cursive Clojure plugin
.idea/replstate.xml
# SonarLint plugin
.idea/sonarlint/
# Crashlytics plugin (for Android Studio and IntelliJ)
com_crashlytics_export_strings.xml
crashlytics.properties
crashlytics-build.properties
fabric.properties
# Editor-based Rest Client
.idea/httpRequests
# Android studio 3.1+ serialized cache file
.idea/caches/build_file_checksums.ser
# ---> Gradle
.gradle .gradle
**/build/ build/
!src/**/build/ !gradle/wrapper/gradle-wrapper.jar
!**/src/main/**/build/
!**/src/test/**/build/
# Ignore Gradle GUI config ### STS ###
gradle-app.setting .apt_generated
# Avoid ignoring Gradle wrapper jar file (.jar files are usually ignored)
!gradle-wrapper.jar
# Avoid ignore Gradle wrappper properties
!gradle-wrapper.properties
# Cache of project
.gradletasknamecache
# Eclipse Gradle plugin generated files
# Eclipse Core
.project
# JDT-specific (Eclipse Java Development Tools)
.classpath .classpath
.factorypath
.project
.settings
.springBeans
.sts4-cache
bin/
!**/src/main/**/bin/
!**/src/test/**/bin/
# ---> Java ### IntelliJ IDEA ###
# Compiled class file .idea
*.class *.iws
*.iml
*.ipr
out/
!**/src/main/**/out/
!**/src/test/**/out/
# Log file ### NetBeans ###
*.log /nbproject/private/
/nbbuild/
# BlueJ files /dist/
*.ctxt /nbdist/
/.nb-gradle/
# Mobile Tools for Java (J2ME)
.mtj.tmp/
# Package Files #
*.jar
*.war
*.nar
*.ear
*.zip
*.tar.gz
*.rar
# virtual machine crash logs, see http://www.java.com/en/download/help/error_hotspot.xml
hs_err_pid*
replay_pid*
### VS Code ###
.vscode/

View File

@ -1,2 +0,0 @@
# PIbd-23_Yashin_A_IP_2

43
build.gradle Normal file
View File

@ -0,0 +1,43 @@
plugins {
id 'java'
id 'org.springframework.boot' version '3.2.2'
id 'io.spring.dependency-management' version '1.1.4'
}
group = 'IP_2'
version = '0.0.1-SNAPSHOT'
defaultTasks 'bootRun'
jar {
enabled = false
}
bootJar {
archiveFileName = String.format('%s-%s.jar', rootProject.name, version)
}
assert System.properties['java.specification.version'] == '17' || '21'
java {
sourceCompatibility = '17'
}
repositories {
mavenCentral()
}
dependencies {
implementation 'org.springframework.boot:spring-boot-starter-web'
implementation 'org.springdoc:springdoc-openapi-starter-webmvc-ui:2.3.0'
implementation 'org.modelmapper:modelmapper:3.2.0'
implementation 'org.springframework.boot:spring-boot-starter-data-jpa'
implementation 'com.h2database:h2:2.2.224'
developmentOnly 'org.springframework.boot:spring-boot-devtools'
testImplementation 'org.springframework.boot:spring-boot-starter-test'
}
tasks.named('test') {
useJUnitPlatform()
}

BIN
data.mv.db Normal file

Binary file not shown.

449
data.trace.db Normal file
View File

@ -0,0 +1,449 @@
2024-04-18 18:25:59.368842+04:00 jdbc[13]: exception
org.h2.jdbc.JdbcSQLSyntaxErrorException: Таблица "USERSREVIEWS" не найдена
Table "USERSREVIEWS" not found; SQL statement:
SELECT * FROM USERSREVIEWS [42102-224]
2024-04-18 18:26:39.326881+04:00 jdbc[13]: exception
org.h2.jdbc.JdbcSQLSyntaxErrorException: Столбец "USERS.USER_ID" не найден
Column "USERS.USER_ID" not found; SQL statement:
SELECT * FROM reviews join users on users.user_id [42122-224]
at org.h2.message.DbException.getJdbcSQLException(DbException.java:514)
at org.h2.message.DbException.getJdbcSQLException(DbException.java:489)
at org.h2.message.DbException.get(DbException.java:223)
at org.h2.message.DbException.get(DbException.java:199)
at org.h2.expression.ExpressionColumn.getColumnException(ExpressionColumn.java:244)
at org.h2.expression.ExpressionColumn.optimizeOther(ExpressionColumn.java:226)
at org.h2.expression.ExpressionColumn.optimize(ExpressionColumn.java:213)
at org.h2.expression.Expression.optimizeCondition(Expression.java:148)
at org.h2.command.query.Select.prepareExpressions(Select.java:1177)
at org.h2.command.query.Query.prepare(Query.java:218)
at org.h2.command.Parser.prepareCommand(Parser.java:489)
at org.h2.engine.SessionLocal.prepareLocal(SessionLocal.java:639)
at org.h2.engine.SessionLocal.prepareCommand(SessionLocal.java:559)
at org.h2.jdbc.JdbcConnection.prepareCommand(JdbcConnection.java:1166)
at org.h2.jdbc.JdbcStatement.executeInternal(JdbcStatement.java:245)
at org.h2.jdbc.JdbcStatement.execute(JdbcStatement.java:231)
at org.h2.server.web.WebApp.getResult(WebApp.java:1345)
at org.h2.server.web.WebApp.query(WebApp.java:1143)
at org.h2.server.web.WebApp.query(WebApp.java:1119)
at org.h2.server.web.WebApp.process(WebApp.java:245)
at org.h2.server.web.WebApp.processRequest(WebApp.java:177)
at org.h2.server.web.JakartaWebServlet.doGet(JakartaWebServlet.java:129)
at org.h2.server.web.JakartaWebServlet.doPost(JakartaWebServlet.java:166)
at jakarta.servlet.http.HttpServlet.service(HttpServlet.java:590)
at jakarta.servlet.http.HttpServlet.service(HttpServlet.java:658)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:205)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:149)
at org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:51)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:174)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:149)
at org.springframework.web.filter.RequestContextFilter.doFilterInternal(RequestContextFilter.java:100)
at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:116)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:174)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:149)
at org.springframework.web.filter.FormContentFilter.doFilterInternal(FormContentFilter.java:93)
at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:116)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:174)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:149)
at org.springframework.web.filter.CharacterEncodingFilter.doFilterInternal(CharacterEncodingFilter.java:201)
at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:116)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:174)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:149)
at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:167)
at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:90)
at org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:482)
at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:115)
at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:93)
at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:74)
at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:340)
at org.apache.coyote.http11.Http11Processor.service(Http11Processor.java:391)
at org.apache.coyote.AbstractProcessorLight.process(AbstractProcessorLight.java:63)
at org.apache.coyote.AbstractProtocol$ConnectionHandler.process(AbstractProtocol.java:896)
at org.apache.tomcat.util.net.NioEndpoint$SocketProcessor.doRun(NioEndpoint.java:1744)
at org.apache.tomcat.util.net.SocketProcessorBase.run(SocketProcessorBase.java:52)
at org.apache.tomcat.util.threads.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1191)
at org.apache.tomcat.util.threads.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:659)
at org.apache.tomcat.util.threads.TaskThread$WrappingRunnable.run(TaskThread.java:61)
at java.base/java.lang.Thread.run(Thread.java:1583)
2024-04-18 18:31:18.587415+04:00 jdbc[13]: exception
org.h2.jdbc.JdbcSQLSyntaxErrorException: Столбец "R.USERS_ID" не найден
Column "R.USERS_ID" not found; SQL statement:
SELECT u.login as login, count(*) as count FROM reviews r join users u on u.id = r.users_id [42122-224]
at org.h2.message.DbException.getJdbcSQLException(DbException.java:514)
at org.h2.message.DbException.getJdbcSQLException(DbException.java:489)
at org.h2.message.DbException.get(DbException.java:223)
at org.h2.message.DbException.get(DbException.java:199)
at org.h2.expression.ExpressionColumn.getColumnException(ExpressionColumn.java:244)
at org.h2.expression.ExpressionColumn.optimizeOther(ExpressionColumn.java:226)
at org.h2.expression.ExpressionColumn.optimize(ExpressionColumn.java:213)
at org.h2.expression.condition.Comparison.optimize(Comparison.java:148)
at org.h2.expression.Expression.optimizeCondition(Expression.java:148)
at org.h2.command.query.Select.prepareExpressions(Select.java:1177)
at org.h2.command.query.Query.prepare(Query.java:218)
at org.h2.command.Parser.prepareCommand(Parser.java:489)
at org.h2.engine.SessionLocal.prepareLocal(SessionLocal.java:639)
at org.h2.engine.SessionLocal.prepareCommand(SessionLocal.java:559)
at org.h2.jdbc.JdbcConnection.prepareCommand(JdbcConnection.java:1166)
at org.h2.jdbc.JdbcStatement.executeInternal(JdbcStatement.java:245)
at org.h2.jdbc.JdbcStatement.execute(JdbcStatement.java:231)
at org.h2.server.web.WebApp.getResult(WebApp.java:1345)
at org.h2.server.web.WebApp.query(WebApp.java:1143)
at org.h2.server.web.WebApp.query(WebApp.java:1119)
at org.h2.server.web.WebApp.process(WebApp.java:245)
at org.h2.server.web.WebApp.processRequest(WebApp.java:177)
at org.h2.server.web.JakartaWebServlet.doGet(JakartaWebServlet.java:129)
at org.h2.server.web.JakartaWebServlet.doPost(JakartaWebServlet.java:166)
at jakarta.servlet.http.HttpServlet.service(HttpServlet.java:590)
at jakarta.servlet.http.HttpServlet.service(HttpServlet.java:658)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:205)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:149)
at org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:51)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:174)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:149)
at org.springframework.web.filter.RequestContextFilter.doFilterInternal(RequestContextFilter.java:100)
at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:116)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:174)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:149)
at org.springframework.web.filter.FormContentFilter.doFilterInternal(FormContentFilter.java:93)
at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:116)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:174)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:149)
at org.springframework.web.filter.CharacterEncodingFilter.doFilterInternal(CharacterEncodingFilter.java:201)
at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:116)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:174)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:149)
at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:167)
at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:90)
at org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:482)
at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:115)
at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:93)
at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:74)
at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:340)
at org.apache.coyote.http11.Http11Processor.service(Http11Processor.java:391)
at org.apache.coyote.AbstractProcessorLight.process(AbstractProcessorLight.java:63)
at org.apache.coyote.AbstractProtocol$ConnectionHandler.process(AbstractProtocol.java:896)
at org.apache.tomcat.util.net.NioEndpoint$SocketProcessor.doRun(NioEndpoint.java:1744)
at org.apache.tomcat.util.net.SocketProcessorBase.run(SocketProcessorBase.java:52)
at org.apache.tomcat.util.threads.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1191)
at org.apache.tomcat.util.threads.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:659)
at org.apache.tomcat.util.threads.TaskThread$WrappingRunnable.run(TaskThread.java:61)
at java.base/java.lang.Thread.run(Thread.java:1583)
2024-04-18 18:31:26.826213+04:00 jdbc[13]: exception
org.h2.jdbc.JdbcSQLSyntaxErrorException: Столбец "U.LOGIN" должен быть в предложении GROUP BY
Column "U.LOGIN" must be in the GROUP BY list; SQL statement:
SELECT u.login as login, count(*) as count FROM reviews r join users u on u.id = r.user_id [90016-224]
at org.h2.message.DbException.getJdbcSQLException(DbException.java:644)
at org.h2.message.DbException.getJdbcSQLException(DbException.java:489)
at org.h2.message.DbException.get(DbException.java:223)
at org.h2.message.DbException.get(DbException.java:199)
at org.h2.expression.ExpressionColumn.updateAggregate(ExpressionColumn.java:266)
at org.h2.expression.Alias.updateAggregate(Alias.java:74)
at org.h2.command.query.Select.updateAgg(Select.java:539)
at org.h2.command.query.Select.gatherGroup(Select.java:522)
at org.h2.command.query.Select.queryGroup(Select.java:488)
at org.h2.command.query.Select.queryWithoutCache(Select.java:828)
at org.h2.command.query.Query.queryWithoutCacheLazyCheck(Query.java:197)
at org.h2.command.query.Query.query(Query.java:520)
at org.h2.command.query.Query.query(Query.java:483)
at org.h2.command.CommandContainer.query(CommandContainer.java:252)
at org.h2.command.Command.executeQuery(Command.java:192)
at org.h2.jdbc.JdbcStatement.executeInternal(JdbcStatement.java:257)
at org.h2.jdbc.JdbcStatement.execute(JdbcStatement.java:231)
at org.h2.server.web.WebApp.getResult(WebApp.java:1345)
at org.h2.server.web.WebApp.query(WebApp.java:1143)
at org.h2.server.web.WebApp.query(WebApp.java:1119)
at org.h2.server.web.WebApp.process(WebApp.java:245)
at org.h2.server.web.WebApp.processRequest(WebApp.java:177)
at org.h2.server.web.JakartaWebServlet.doGet(JakartaWebServlet.java:129)
at org.h2.server.web.JakartaWebServlet.doPost(JakartaWebServlet.java:166)
at jakarta.servlet.http.HttpServlet.service(HttpServlet.java:590)
at jakarta.servlet.http.HttpServlet.service(HttpServlet.java:658)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:205)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:149)
at org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:51)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:174)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:149)
at org.springframework.web.filter.RequestContextFilter.doFilterInternal(RequestContextFilter.java:100)
at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:116)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:174)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:149)
at org.springframework.web.filter.FormContentFilter.doFilterInternal(FormContentFilter.java:93)
at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:116)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:174)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:149)
at org.springframework.web.filter.CharacterEncodingFilter.doFilterInternal(CharacterEncodingFilter.java:201)
at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:116)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:174)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:149)
at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:167)
at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:90)
at org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:482)
at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:115)
at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:93)
at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:74)
at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:340)
at org.apache.coyote.http11.Http11Processor.service(Http11Processor.java:391)
at org.apache.coyote.AbstractProcessorLight.process(AbstractProcessorLight.java:63)
at org.apache.coyote.AbstractProtocol$ConnectionHandler.process(AbstractProtocol.java:896)
at org.apache.tomcat.util.net.NioEndpoint$SocketProcessor.doRun(NioEndpoint.java:1744)
at org.apache.tomcat.util.net.SocketProcessorBase.run(SocketProcessorBase.java:52)
at org.apache.tomcat.util.threads.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1191)
at org.apache.tomcat.util.threads.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:659)
at org.apache.tomcat.util.threads.TaskThread$WrappingRunnable.run(TaskThread.java:61)
at java.base/java.lang.Thread.run(Thread.java:1583)
2024-04-18 18:31:28.088309+04:00 jdbc[13]: exception
org.h2.jdbc.JdbcSQLSyntaxErrorException: Столбец "U.LOGIN" должен быть в предложении GROUP BY
Column "U.LOGIN" must be in the GROUP BY list; SQL statement:
SELECT u.login as login, count(*) as count FROM reviews r join users u on u.id = r.user_id [90016-224]
at org.h2.message.DbException.getJdbcSQLException(DbException.java:644)
at org.h2.message.DbException.getJdbcSQLException(DbException.java:489)
at org.h2.message.DbException.get(DbException.java:223)
at org.h2.message.DbException.get(DbException.java:199)
at org.h2.expression.ExpressionColumn.updateAggregate(ExpressionColumn.java:266)
at org.h2.expression.Alias.updateAggregate(Alias.java:74)
at org.h2.command.query.Select.updateAgg(Select.java:539)
at org.h2.command.query.Select.gatherGroup(Select.java:522)
at org.h2.command.query.Select.queryGroup(Select.java:488)
at org.h2.command.query.Select.queryWithoutCache(Select.java:828)
at org.h2.command.query.Query.queryWithoutCacheLazyCheck(Query.java:197)
at org.h2.command.query.Query.query(Query.java:520)
at org.h2.command.query.Query.query(Query.java:483)
at org.h2.command.CommandContainer.query(CommandContainer.java:252)
at org.h2.command.Command.executeQuery(Command.java:192)
at org.h2.jdbc.JdbcStatement.executeInternal(JdbcStatement.java:257)
at org.h2.jdbc.JdbcStatement.execute(JdbcStatement.java:231)
at org.h2.server.web.WebApp.getResult(WebApp.java:1345)
at org.h2.server.web.WebApp.query(WebApp.java:1143)
at org.h2.server.web.WebApp.query(WebApp.java:1119)
at org.h2.server.web.WebApp.process(WebApp.java:245)
at org.h2.server.web.WebApp.processRequest(WebApp.java:177)
at org.h2.server.web.JakartaWebServlet.doGet(JakartaWebServlet.java:129)
at org.h2.server.web.JakartaWebServlet.doPost(JakartaWebServlet.java:166)
at jakarta.servlet.http.HttpServlet.service(HttpServlet.java:590)
at jakarta.servlet.http.HttpServlet.service(HttpServlet.java:658)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:205)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:149)
at org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:51)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:174)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:149)
at org.springframework.web.filter.RequestContextFilter.doFilterInternal(RequestContextFilter.java:100)
at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:116)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:174)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:149)
at org.springframework.web.filter.FormContentFilter.doFilterInternal(FormContentFilter.java:93)
at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:116)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:174)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:149)
at org.springframework.web.filter.CharacterEncodingFilter.doFilterInternal(CharacterEncodingFilter.java:201)
at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:116)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:174)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:149)
at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:167)
at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:90)
at org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:482)
at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:115)
at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:93)
at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:74)
at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:340)
at org.apache.coyote.http11.Http11Processor.service(Http11Processor.java:391)
at org.apache.coyote.AbstractProcessorLight.process(AbstractProcessorLight.java:63)
at org.apache.coyote.AbstractProtocol$ConnectionHandler.process(AbstractProtocol.java:896)
at org.apache.tomcat.util.net.NioEndpoint$SocketProcessor.doRun(NioEndpoint.java:1744)
at org.apache.tomcat.util.net.SocketProcessorBase.run(SocketProcessorBase.java:52)
at org.apache.tomcat.util.threads.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1191)
at org.apache.tomcat.util.threads.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:659)
at org.apache.tomcat.util.threads.TaskThread$WrappingRunnable.run(TaskThread.java:61)
at java.base/java.lang.Thread.run(Thread.java:1583)
2024-04-18 18:35:53.107821+04:00 jdbc[13]: exception
org.h2.jdbc.JdbcSQLSyntaxErrorException: Синтаксическая ошибка в выражении SQL "SELECT u.login as login, count(*) as count FROM reviews r join users u on u.id = r.user_id group by login order by count [*]dsc"
Syntax error in SQL statement "SELECT u.login as login, count(*) as count FROM reviews r join users u on u.id = r.user_id group by login order by count [*]dsc"; SQL statement:
SELECT u.login as login, count(*) as count FROM reviews r join users u on u.id = r.user_id group by login order by count dsc [42000-224]
2024-04-18 18:36:21.300704+04:00 jdbc[13]: exception
org.h2.jdbc.JdbcSQLSyntaxErrorException: Синтаксическая ошибка в выражении SQL "SELECT u.login as login, count(*) as count FROM reviews r join users u on u.id = r.user_id group by login order by count [*]DSC"
Syntax error in SQL statement "SELECT u.login as login, count(*) as count FROM reviews r join users u on u.id = r.user_id group by login order by count [*]DSC"; SQL statement:
SELECT u.login as login, count(*) as count FROM reviews r join users u on u.id = r.user_id group by login order by count DSC [42000-224]
2024-04-18 18:36:41.364562+04:00 jdbc[13]: exception
org.h2.jdbc.JdbcSQLSyntaxErrorException: Синтаксическая ошибка в выражении SQL "SELECT u.login as login, count(*) as count FROM reviews r join users u on u.id = r.user_id group by login order by count [*]DES"
Syntax error in SQL statement "SELECT u.login as login, count(*) as count FROM reviews r join users u on u.id = r.user_id group by login order by count [*]DES"; SQL statement:
SELECT u.login as login, count(*) as count FROM reviews r join users u on u.id = r.user_id group by login order by count DES [42000-224]
2024-04-18 18:41:46.400938+04:00 database: wrong user or password; user: "SA"
org.h2.message.DbException: Неверное имя пользователя или пароль
Wrong user name or password [28000-224]
at org.h2.message.DbException.get(DbException.java:223)
at org.h2.message.DbException.get(DbException.java:199)
at org.h2.message.DbException.get(DbException.java:188)
at org.h2.engine.Engine.openSession(Engine.java:154)
at org.h2.engine.Engine.openSession(Engine.java:222)
at org.h2.engine.Engine.createSession(Engine.java:201)
at org.h2.engine.SessionRemote.connectEmbeddedOrServer(SessionRemote.java:343)
at org.h2.jdbc.JdbcConnection.<init>(JdbcConnection.java:125)
at org.h2.util.JdbcUtils.getConnection(JdbcUtils.java:288)
at org.h2.server.web.WebServer.getConnection(WebServer.java:811)
at org.h2.server.web.WebApp.login(WebApp.java:1039)
at org.h2.server.web.WebApp.process(WebApp.java:227)
at org.h2.server.web.WebApp.processRequest(WebApp.java:177)
at org.h2.server.web.JakartaWebServlet.doGet(JakartaWebServlet.java:129)
at org.h2.server.web.JakartaWebServlet.doPost(JakartaWebServlet.java:166)
at jakarta.servlet.http.HttpServlet.service(HttpServlet.java:590)
at jakarta.servlet.http.HttpServlet.service(HttpServlet.java:658)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:205)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:149)
at org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:51)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:174)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:149)
at org.springframework.web.filter.RequestContextFilter.doFilterInternal(RequestContextFilter.java:100)
at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:116)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:174)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:149)
at org.springframework.web.filter.FormContentFilter.doFilterInternal(FormContentFilter.java:93)
at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:116)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:174)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:149)
at org.springframework.web.filter.CharacterEncodingFilter.doFilterInternal(CharacterEncodingFilter.java:201)
at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:116)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:174)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:149)
at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:167)
at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:90)
at org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:482)
at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:115)
at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:93)
at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:74)
at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:340)
at org.apache.coyote.http11.Http11Processor.service(Http11Processor.java:391)
at org.apache.coyote.AbstractProcessorLight.process(AbstractProcessorLight.java:63)
at org.apache.coyote.AbstractProtocol$ConnectionHandler.process(AbstractProtocol.java:896)
at org.apache.tomcat.util.net.NioEndpoint$SocketProcessor.doRun(NioEndpoint.java:1744)
at org.apache.tomcat.util.net.SocketProcessorBase.run(SocketProcessorBase.java:52)
at org.apache.tomcat.util.threads.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1191)
at org.apache.tomcat.util.threads.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:659)
at org.apache.tomcat.util.threads.TaskThread$WrappingRunnable.run(TaskThread.java:61)
at java.base/java.lang.Thread.run(Thread.java:1583)
Caused by: org.h2.jdbc.JdbcSQLInvalidAuthorizationSpecException: Неверное имя пользователя или пароль
Wrong user name or password [28000-224]
at org.h2.message.DbException.getJdbcSQLException(DbException.java:522)
at org.h2.message.DbException.getJdbcSQLException(DbException.java:489)
... 50 more
2024-04-18 18:42:06.702323+04:00 jdbc[13]: exception
org.h2.jdbc.JdbcSQLSyntaxErrorException: Столбец "U" не найден
Column "U" not found; SQL statement:
SELECT u as login, count(*) as count FROM reviews r join users u on u.id = r.user_id group by login [42122-224]
at org.h2.message.DbException.getJdbcSQLException(DbException.java:514)
at org.h2.message.DbException.getJdbcSQLException(DbException.java:489)
at org.h2.message.DbException.get(DbException.java:223)
at org.h2.message.DbException.get(DbException.java:199)
at org.h2.expression.ExpressionColumn.getColumnException(ExpressionColumn.java:244)
at org.h2.expression.ExpressionColumn.optimizeOther(ExpressionColumn.java:226)
at org.h2.expression.ExpressionColumn.optimize(ExpressionColumn.java:213)
at org.h2.expression.Alias.optimize(Alias.java:52)
at org.h2.command.query.Select.prepareExpressions(Select.java:1170)
at org.h2.command.query.Query.prepare(Query.java:218)
at org.h2.command.Parser.prepareCommand(Parser.java:489)
at org.h2.engine.SessionLocal.prepareLocal(SessionLocal.java:639)
at org.h2.engine.SessionLocal.prepareCommand(SessionLocal.java:559)
at org.h2.jdbc.JdbcConnection.prepareCommand(JdbcConnection.java:1166)
at org.h2.jdbc.JdbcStatement.executeInternal(JdbcStatement.java:245)
at org.h2.jdbc.JdbcStatement.execute(JdbcStatement.java:231)
at org.h2.server.web.WebApp.getResult(WebApp.java:1345)
at org.h2.server.web.WebApp.query(WebApp.java:1143)
at org.h2.server.web.WebApp.query(WebApp.java:1119)
at org.h2.server.web.WebApp.process(WebApp.java:245)
at org.h2.server.web.WebApp.processRequest(WebApp.java:177)
at org.h2.server.web.JakartaWebServlet.doGet(JakartaWebServlet.java:129)
at org.h2.server.web.JakartaWebServlet.doPost(JakartaWebServlet.java:166)
at jakarta.servlet.http.HttpServlet.service(HttpServlet.java:590)
at jakarta.servlet.http.HttpServlet.service(HttpServlet.java:658)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:205)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:149)
at org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:51)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:174)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:149)
at org.springframework.web.filter.RequestContextFilter.doFilterInternal(RequestContextFilter.java:100)
at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:116)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:174)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:149)
at org.springframework.web.filter.FormContentFilter.doFilterInternal(FormContentFilter.java:93)
at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:116)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:174)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:149)
at org.springframework.web.filter.CharacterEncodingFilter.doFilterInternal(CharacterEncodingFilter.java:201)
at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:116)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:174)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:149)
at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:167)
at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:90)
at org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:482)
at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:115)
at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:93)
at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:74)
at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:340)
at org.apache.coyote.http11.Http11Processor.service(Http11Processor.java:391)
at org.apache.coyote.AbstractProcessorLight.process(AbstractProcessorLight.java:63)
at org.apache.coyote.AbstractProtocol$ConnectionHandler.process(AbstractProtocol.java:896)
at org.apache.tomcat.util.net.NioEndpoint$SocketProcessor.doRun(NioEndpoint.java:1744)
at org.apache.tomcat.util.net.SocketProcessorBase.run(SocketProcessorBase.java:52)
at org.apache.tomcat.util.threads.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1191)
at org.apache.tomcat.util.threads.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:659)
at org.apache.tomcat.util.threads.TaskThread$WrappingRunnable.run(TaskThread.java:61)
at java.base/java.lang.Thread.run(Thread.java:1583)
2024-04-18 18:43:02.191025+04:00 jdbc[13]: exception
org.h2.jdbc.JdbcSQLSyntaxErrorException: Столбец "U" не найден
Column "U" not found; SQL statement:
SELECT u as login, count(*) as count FROM reviews r join users u on u.id = r.user_id group by login [42122-224]
at org.h2.message.DbException.getJdbcSQLException(DbException.java:514)
at org.h2.message.DbException.getJdbcSQLException(DbException.java:489)
at org.h2.message.DbException.get(DbException.java:223)
at org.h2.message.DbException.get(DbException.java:199)
at org.h2.expression.ExpressionColumn.getColumnException(ExpressionColumn.java:244)
at org.h2.expression.ExpressionColumn.optimizeOther(ExpressionColumn.java:226)
at org.h2.expression.ExpressionColumn.optimize(ExpressionColumn.java:213)
at org.h2.expression.Alias.optimize(Alias.java:52)
at org.h2.command.query.Select.prepareExpressions(Select.java:1170)
at org.h2.command.query.Query.prepare(Query.java:218)
at org.h2.command.Parser.prepareCommand(Parser.java:489)
at org.h2.engine.SessionLocal.prepareLocal(SessionLocal.java:639)
at org.h2.engine.SessionLocal.prepareCommand(SessionLocal.java:559)
at org.h2.jdbc.JdbcConnection.prepareCommand(JdbcConnection.java:1166)
at org.h2.jdbc.JdbcStatement.executeInternal(JdbcStatement.java:245)
at org.h2.jdbc.JdbcStatement.execute(JdbcStatement.java:231)
at org.h2.server.web.WebApp.getResult(WebApp.java:1345)
at org.h2.server.web.WebApp.query(WebApp.java:1143)
at org.h2.server.web.WebApp.query(WebApp.java:1119)
at org.h2.server.web.WebApp.process(WebApp.java:245)
at org.h2.server.web.WebApp.processRequest(WebApp.java:177)
at org.h2.server.web.JakartaWebServlet.doGet(JakartaWebServlet.java:129)
at org.h2.server.web.JakartaWebServlet.doPost(JakartaWebServlet.java:166)
at jakarta.servlet.http.HttpServlet.service(HttpServlet.java:590)
at jakarta.servlet.http.HttpServlet.service(HttpServlet.java:658)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:205)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:149)
at org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:51)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:174)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:149)
at org.springframework.web.filter.RequestContextFilter.doFilterInternal(RequestContextFilter.java:100)
at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:116)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:174)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:149)
at org.springframework.web.filter.FormContentFilter.doFilterInternal(FormContentFilter.java:93)
at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:116)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:174)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:149)
at org.springframework.web.filter.CharacterEncodingFilter.doFilterInternal(CharacterEncodingFilter.java:201)
at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:116)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:174)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:149)
at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:167)
at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:90)
at org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:482)
at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:115)
at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:93)
at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:74)
at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:340)
at org.apache.coyote.http11.Http11Processor.service(Http11Processor.java:391)
at org.apache.coyote.AbstractProcessorLight.process(AbstractProcessorLight.java:63)
at org.apache.coyote.AbstractProtocol$ConnectionHandler.process(AbstractProtocol.java:896)
at org.apache.tomcat.util.net.NioEndpoint$SocketProcessor.doRun(NioEndpoint.java:1744)
at org.apache.tomcat.util.net.SocketProcessorBase.run(SocketProcessorBase.java:52)
at org.apache.tomcat.util.threads.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1191)
at org.apache.tomcat.util.threads.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:659)
at org.apache.tomcat.util.threads.TaskThread$WrappingRunnable.run(TaskThread.java:61)
at java.base/java.lang.Thread.run(Thread.java:1583)

BIN
gradle/wrapper/gradle-wrapper.jar vendored Normal file

Binary file not shown.

View File

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

248
gradlew vendored Normal file
View File

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

92
gradlew.bat vendored Normal file
View File

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

61
index.html Normal file
View File

@ -0,0 +1,61 @@
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
</head>
<body>
<p id="out">Push the button</p>
<input id="name"/>
<br/>
<button onclick="get()">Get</button>
<br/>
<button onclick="getTest()">Get Test</button>
<br/>
<button onclick="post()">Post</button>
<br/>
<button onclick="put()">Put</button>
</body>
<script>
const url = "http://localhost:8080/api";
const out = document.getElementById("out");
const name = document.getElementById("name");
const get = async () => {
const res = await fetch(`${url}?name=${name.value}`);
const text = await res.text();
out.innerText = text;
}
const getTest = async () => {
const res = await fetch(`${url}/test`);
const text = await res.text();
out.innerText = text;
}
const post = async () => {
if (!name.value) {
alert("Name is required");
return;
}
const res = await fetch(url, {
method: 'post',
headers: {'Content-Type': 'application/json'},
body: name.value
});
const text = await res.text();
out.innerText = text;
}
const put = async () => {
if (!name.value) {
alert("Name is required");
return;
}
const res = await fetch(`${url}/${name.value}`, {
method: 'put',
headers: {'Content-Type': 'application/json'},
body: name.value
});
const text = await res.text();
out.innerText = text;
}
</script>
</html>

6
package-lock.json generated Normal file
View File

@ -0,0 +1,6 @@
{
"name": "Lab1",
"lockfileVersion": 3,
"requires": true,
"packages": {}
}

1
settings.gradle Normal file
View File

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

View File

@ -0,0 +1,76 @@
package ip_2.lab1;
import ip_2.lab1.items.model.ItemEntity;
import ip_2.lab1.items.service.ItemService;
import ip_2.lab1.reviews.model.ReviewEntity;
import ip_2.lab1.reviews.service.ReviewService;
import ip_2.lab1.types.model.TypeEntity;
import ip_2.lab1.types.service.TypeService;
import ip_2.lab1.users.model.UserEntity;
import ip_2.lab1.users.service.UserService;
import org.h2.engine.User;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.boot.CommandLineRunner;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import java.util.Objects;
@SpringBootApplication
public class Lab1Application implements CommandLineRunner {
private final Logger log = LoggerFactory.getLogger(Lab1Application.class);
private final TypeService typeService;
private final ItemService itemService;
private final UserService userService;
private final ReviewService reviewService;
public Lab1Application(TypeService typeService, ItemService itemService, UserService userService, ReviewService reviewService) {
this.typeService = typeService;
this.itemService = itemService;
this.userService = userService;
this.reviewService = reviewService;
}
public static void main(String[] args) {
SpringApplication.run(Lab1Application.class, args);
}
@Override
public void run(String... args) throws Exception {
if (args.length > 0 && Objects.equals("--populate", args[0])) {
log.info("Create default types values");
final var type1 = typeService.create(new TypeEntity("Асфальт", 2000));
final var type2 = typeService.create(new TypeEntity("Грунт", 3000));
final var type3 = typeService.create(new TypeEntity("Асфальт + грунт", 3500));
log.info("Create items");
final var item1 = itemService.create(new ItemEntity(type1, 1700, 5));
final var item2 = itemService.create(new ItemEntity(type2, 2700, 5));
final var item3 = itemService.create(new ItemEntity(type3, 3200, 5));
log.info("Create users");
final var user1 = userService.create(new UserEntity("Artyom", "1234"));
final var user2 = userService.create(new UserEntity("Niyaz", "1234"));
final var user3 = userService.create(new UserEntity("Rostik", "1234"));
final var user4 = userService.create(new UserEntity("Artur", "1234"));
final var user5 = userService.create(new UserEntity("Andrey", "1234"));
final var user6 = userService.create(new UserEntity("Alionchik", "1234"));
log.info("Create reviews");
final var review1 = reviewService.create(new ReviewEntity(user1, "Кайфарики"));
final var review2 = reviewService.create(new ReviewEntity(user2, "Кайфарики кайфецкие"));
final var review3 = reviewService.create(new ReviewEntity(user3, "Кайфарики турецкие"));
final var review4 = reviewService.create(new ReviewEntity(user3, "Кайфарики масдавские"));
final var review5 = reviewService.create(new ReviewEntity(user4, "Кайфарики минские"));
final var review7 = reviewService.create(new ReviewEntity(user4, "Кайфарики грузинские"));
final var review8 = reviewService.create(new ReviewEntity(user5, "Кайфарики японские"));
final var review9 = reviewService.create(new ReviewEntity(user6, "Кайфарики македонские"));
log.info("Creation finished");
}
}
}

View File

@ -0,0 +1,97 @@
package ip_2.lab1.core.api;
import java.util.ArrayList;
import java.util.List;
public class PageDto<D> {
private List<D> items = new ArrayList<>();
private int itemsCount;
private int currentPage;
private int currentSize;
private int totalPages;
private long totalItems;
private boolean isFirst;
private boolean isLast;
private boolean hasNext;
private boolean hasPrevious;
public List<D> getItems() {
return items;
}
public void setItems(List<D> items) {
this.items = items;
}
public int getItemsCount() {
return itemsCount;
}
public void setItemsCount(int itemsCount) {
this.itemsCount = itemsCount;
}
public int getCurrentPage() {
return currentPage;
}
public void setCurrentPage(int currentPage) {
this.currentPage = currentPage;
}
public int getCurrentSize() {
return currentSize;
}
public void setCurrentSize(int currentSize) {
this.currentSize = currentSize;
}
public int getTotalPages() {
return totalPages;
}
public void setTotalPages(int totalPages) {
this.totalPages = totalPages;
}
public long getTotalItems() {
return totalItems;
}
public void setTotalItems(long totalItems) {
this.totalItems = totalItems;
}
public boolean isFirst() {
return isFirst;
}
public void setFirst(boolean isFirst) {
this.isFirst = isFirst;
}
public boolean isLast() {
return isLast;
}
public void setLast(boolean isLast) {
this.isLast = isLast;
}
public boolean isHasNext() {
return hasNext;
}
public void setHasNext(boolean hasNext) {
this.hasNext = hasNext;
}
public boolean isHasPrevious() {
return hasPrevious;
}
public void setHasPrevious(boolean hasPrevious) {
this.hasPrevious = hasPrevious;
}
}

View File

@ -0,0 +1,25 @@
package ip_2.lab1.core.api;
import org.springframework.data.domain.Page;
import java.util.function.Function;
public class PageDtoMapper {
private PageDtoMapper() {
}
public static <D, E> PageDto<D> toDto(Page<E> page, Function<E, D> mapper) {
final PageDto<D> dto = new PageDto<>();
dto.setItems(page.getContent().stream().map(mapper::apply).toList());
dto.setItemsCount(page.getNumberOfElements());
dto.setCurrentPage(page.getNumber());
dto.setCurrentSize(page.getSize());
dto.setTotalPages(page.getTotalPages());
dto.setTotalItems(page.getTotalElements());
dto.setFirst(page.isFirst());
dto.setLast(page.isLast());
dto.setHasNext(page.hasNext());
dto.setHasPrevious(page.hasPrevious());
return dto;
}
}

View File

@ -0,0 +1,10 @@
package ip_2.lab1.core.configuration;
public class Constants {
public static final String SEQUENCE_NAME = "hibernate_sequence";
public static final String API_URL = "/api/1.0";
private Constants(){
}
}

View File

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

View File

@ -0,0 +1,14 @@
package ip_2.lab1.core.configuration;
import jakarta.validation.constraints.NotNull;
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(@NotNull CorsRegistry registry) {
registry.addMapping("/**").allowedMethods("GET", "POST", "PUT", "DELETE");
}
}

View File

@ -0,0 +1,7 @@
package ip_2.lab1.core.error;
public class NotFoundException extends RuntimeException{
public <T> NotFoundException(Class<T> clazz, Long id) {
super(String.format("%s with id [%s] is not found or not exists", clazz.getSimpleName(), id));
}
}

View File

@ -0,0 +1,24 @@
package ip_2.lab1.core.model;
import com.fasterxml.jackson.databind.ser.Serializers;
import ip_2.lab1.core.configuration.Constants;
import jakarta.persistence.*;
@MappedSuperclass
public abstract class BaseEntity {
@Id
@GeneratedValue(strategy = GenerationType.SEQUENCE, generator = Constants.SEQUENCE_NAME)
@SequenceGenerator(name = Constants.SEQUENCE_NAME, sequenceName = Constants.SEQUENCE_NAME, allocationSize = 1)
protected Long id;
protected BaseEntity(){
}
public Long getId(){
return id;
}
public void setId(Long id){
this.id = id;
}
}

View File

@ -0,0 +1,77 @@
package ip_2.lab1.items.api;
import ip_2.lab1.core.configuration.Constants;
import ip_2.lab1.items.model.ItemEntity;
import ip_2.lab1.items.model.ItemGrouped;
import ip_2.lab1.items.service.ItemService;
import ip_2.lab1.types.service.TypeService;
import jakarta.validation.Valid;
import org.modelmapper.ModelMapper;
import org.springframework.web.bind.annotation.*;
import org.yaml.snakeyaml.nodes.CollectionNode;
import java.util.List;
@RestController
@RequestMapping(Constants.API_URL + "/item")
public class ItemController {
private final TypeService typeService;
private final ItemService itemService;
private final ModelMapper modelMapper;
public ItemController(TypeService typeService, ItemService itemService, ModelMapper modelMapper) {
this.itemService = itemService;
this.typeService = typeService;
this.modelMapper = modelMapper;
}
private ItemDto toDto(ItemEntity entity) {
final ItemDto dto = modelMapper.map(entity, ItemDto.class);
double ben = (entity.getType().getBasePrice() - entity.getPrice()) * entity.getCount();
dto.setBenefit(ben);
return dto;
}
private ItemEntity toEntity(ItemDto dto) {
final ItemEntity entity = modelMapper.map(dto, ItemEntity.class);
entity.setType(typeService.get(dto.getTypeId()));
return entity;
}
private ItemGroupedDto toGroupedDto(ItemGrouped entity) {
return modelMapper.map(entity, ItemGroupedDto.class);
}
@GetMapping
public List<ItemDto> getAll(@RequestParam(name = "typeId", defaultValue = "0") Long typeId) {
return itemService.getAll(typeId).stream().map(this::toDto).toList();
}
@GetMapping("/{id}")
public ItemDto get(@PathVariable(name = "id") Long id) {
return toDto(itemService.get(id));
}
@PostMapping
public ItemDto create(
@RequestBody ItemDto dto) {
return toDto(itemService.create( toEntity(dto)));
}
@PutMapping("/{id}")
public ItemDto update(@PathVariable(name = "id") Long id, @RequestBody ItemDto dto) {
return toDto(itemService.update(id, toEntity(dto)));
}
@DeleteMapping("/{id}")
public ItemDto delete(@PathVariable(name = "id") Long id) {
return toDto(itemService.delete(id));
}
@GetMapping("/total")
public List<ItemGroupedDto> getTotalPrice() {
return itemService.getTotal().stream()
.map(this::toGroupedDto)
.toList();
}
}

View File

@ -0,0 +1,71 @@
package ip_2.lab1.items.api;
import com.fasterxml.jackson.annotation.JsonProperty;
import ip_2.lab1.types.repository.TypeRepository;
import ip_2.lab1.types.service.TypeService;
import jakarta.validation.constraints.Min;
import jakarta.validation.constraints.NotNull;
import java.util.Objects;
public class ItemDto {
@JsonProperty(access = JsonProperty.Access.READ_ONLY)
private Long id;
@NotNull
@Min(1)
private Long typeId;
@NotNull
@Min(1)
private Double price;
@NotNull
@Min(1)
private Integer count;
private Double benefit;
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public Long getTypeId() {
return typeId;
}
public void setTypeId(Long typeId) {
this.typeId = typeId;
}
public Double getPrice() {
return price;
}
public void setPrice(Double price) {
this.price = price;
}
public Integer getCount() {
return count;
}
public void setCount(Integer count) {
this.count = count;
}
@JsonProperty(access = JsonProperty.Access.READ_ONLY)
public Double getSum() {
return price * count;
}
@JsonProperty(access = JsonProperty.Access.READ_ONLY)
public Double getBenefit() {
return benefit;
}
public void setBenefit(double benefit) {
this.benefit = benefit;
}
}

View File

@ -0,0 +1,22 @@
package ip_2.lab1.items.api;
public class ItemGroupedDto {
private Long typeId;
private Integer totalPrice;
public Long getTypeId() {
return typeId;
}
public void setTypeId(Long typeId) {
this.typeId = typeId;
}
public Integer getTotalPrice() {
return totalPrice;
}
public void setTotalPrice(Integer totalPrice) {
this.totalPrice = totalPrice;
}
}

View File

@ -0,0 +1,66 @@
package ip_2.lab1.items.model;
import io.swagger.v3.oas.models.security.SecurityScheme;
import ip_2.lab1.core.model.BaseEntity;
import ip_2.lab1.types.model.TypeEntity;
import jakarta.persistence.*;
import java.util.Objects;
@Entity
@Table(name = "items")
public class ItemEntity extends BaseEntity {
@ManyToOne
@JoinColumn(name = "typeId", nullable = false)
private TypeEntity type;
@Column(nullable = false)
private Integer price;
@Column(nullable = false)
private Integer count;
public ItemEntity() {
}
public ItemEntity(TypeEntity type, Integer price, Integer count) {
this.type = type;
this.price = price;
this.count = count;
}
public TypeEntity getType() {
return type;
}
public void setType(TypeEntity type) {
this.type = type;
}
public Integer getPrice() {
return price;
}
public void setPrice(Integer price) {
this.price = price;
}
public Integer getCount() {
return count;
}
public void setCount(Integer count) {
this.count = count;
}
@Override
public int hashCode() { return Objects.hash(id, type, price, count); }
@Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null || getClass() != obj.getClass())
return false;
final ItemEntity other = (ItemEntity) obj;
return Objects.equals(other.getId(), id)
&& Objects.equals(other.getType(), type)
&& Objects.equals(other.getPrice(), price)
&& Objects.equals(other.getCount(), count);
}
}

View File

@ -0,0 +1,8 @@
package ip_2.lab1.items.model;
import ip_2.lab1.types.model.TypeEntity;
public interface ItemGrouped {
TypeEntity getType();
int getTotalPrice();
}

View File

@ -0,0 +1,17 @@
package ip_2.lab1.items.repository;
import ip_2.lab1.items.model.ItemEntity;
import ip_2.lab1.items.model.ItemGrouped;
import org.springframework.data.jpa.repository.Query;
import org.springframework.data.repository.CrudRepository;
import java.util.List;
public interface ItemRepository extends CrudRepository<ItemEntity, Long> {
List<ItemEntity> findByTypeId(long typeId);
void deleteAllByTypeId(Long typeId);
@Query("select t as type, coalesce(sum(i.price * i.count), 0) as totalPrice "
+ "from TypeEntity t left join ItemEntity i on i.type = t "
+ "group by t order by t.id")
List<ItemGrouped> getItemsTotalByType();
}

View File

@ -0,0 +1,68 @@
package ip_2.lab1.items.service;
import ip_2.lab1.core.error.NotFoundException;
import ip_2.lab1.items.model.ItemEntity;
import ip_2.lab1.items.model.ItemGrouped;
import ip_2.lab1.items.repository.ItemRepository;
import ip_2.lab1.types.model.TypeEntity;
import ip_2.lab1.types.service.TypeService;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import java.util.List;
import java.util.Objects;
import java.util.Optional;
import java.util.stream.StreamSupport;
@Service
public class ItemService {
private final ItemRepository repository;
public ItemService(ItemRepository repository) {
this.repository = repository;
}
@Transactional(readOnly = true)
public List<ItemEntity> getAll(long typeId) {
if (typeId <= 0L) {
return StreamSupport.stream(repository.findAll().spliterator(), false).toList();
} else {
return repository.findByTypeId(typeId);
}
}
@Transactional(readOnly = true)
public ItemEntity get(long id) {
return repository.findById(id)
.orElseThrow(() -> new NotFoundException(ItemEntity.class, id));
}
@Transactional
public ItemEntity create(ItemEntity entity) {
if (entity == null) {
throw new IllegalArgumentException("Entity is null");
}
return repository.save(entity);
}
@Transactional
public ItemEntity update(long id, ItemEntity entity) {
final ItemEntity existsEntity = get(id);
existsEntity.setType(entity.getType());
existsEntity.setPrice(entity.getPrice());
existsEntity.setCount(entity.getCount());
return repository.save(existsEntity);
}
@Transactional
public ItemEntity delete(long id) {
final ItemEntity existsEntity = get(id);
repository.delete(existsEntity);
return existsEntity;
}
@Transactional(readOnly = true)
public List<ItemGrouped> getTotal() {
return repository.getItemsTotalByType();
}
}

View File

@ -0,0 +1,82 @@
package ip_2.lab1.reviews.api;
import ip_2.lab1.core.api.PageDto;
import ip_2.lab1.core.api.PageDtoMapper;
import ip_2.lab1.core.configuration.Constants;
import ip_2.lab1.items.api.ItemGroupedDto;
import ip_2.lab1.items.model.ItemGrouped;
import ip_2.lab1.reviews.model.ReviewEntity;
import ip_2.lab1.reviews.model.ReviewGrouped;
import ip_2.lab1.reviews.repository.ReviewRepository;
import ip_2.lab1.reviews.service.ReviewService;
import ip_2.lab1.users.service.UserService;
import jakarta.validation.constraints.Max;
import jakarta.validation.constraints.Min;
import org.modelmapper.ModelMapper;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.jaxb.SpringDataJaxb;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;
import java.util.List;
import java.util.stream.StreamSupport;
@RestController
@RequestMapping(Constants.API_URL + "/review")
public class ReviewController {
private final UserService userService;
private final ReviewService reviewService;
private final ReviewRepository reviewRepository;
private final ModelMapper modelMapper;
public ReviewController(UserService userService, ReviewService reviewService, ReviewRepository reviewRepository, ModelMapper modelMapper) {
this.userService = userService;
this.reviewService = reviewService;
this.reviewRepository = reviewRepository;
this.modelMapper = modelMapper;
}
private ReviewDto toDto(ReviewEntity entity) {
return modelMapper.map(entity, ReviewDto.class);
}
private ReviewEntity toEntity(ReviewDto dto) {
final ReviewEntity entity = modelMapper.map(dto, ReviewEntity.class);
entity.setUser(userService.getForReviewCreate(dto.getUserId()));
return entity;
}
private ReviewGroupedDto toGroupedDto(ReviewGrouped entity) {
return modelMapper.map(entity, ReviewGroupedDto.class);
}
@GetMapping
public PageDto<ReviewDto> getAll(@RequestParam(name = "userId", defaultValue = "0") Long userId,
@RequestParam(name = "page", defaultValue = "0") Integer page,
@RequestParam(name = "size", defaultValue = "20") Integer size) {
return PageDtoMapper.toDto(reviewService.getAll(userId, page, size), this::toDto);
}
@GetMapping("/{id}")
public ReviewDto get(@PathVariable(name = "id") Long id) {
return toDto(reviewService.get(id));
}
@PostMapping
public ReviewDto create(@RequestBody ReviewDto dto) {
return toDto(reviewService.create(toEntity(dto)));
}
@PutMapping("/{id}")
public ReviewDto update(@PathVariable(name = "id") Long id, @RequestBody ReviewDto dto) {
return toDto(reviewService.update(id, toEntity(dto)));
}
@DeleteMapping("/{id}")
public ReviewDto delete(@PathVariable(name = "id") Long id) {
return toDto(reviewService.delete(id));
}
@GetMapping("/count")
public List<ReviewGroupedDto> getReviewCount() {
return reviewService.getCount(0, 5).stream().map(this::toGroupedDto).toList();
}
}

View File

@ -0,0 +1,35 @@
package ip_2.lab1.reviews.api;
import com.fasterxml.jackson.annotation.JsonProperty;
import jakarta.validation.constraints.Min;
import jakarta.validation.constraints.NotBlank;
import jakarta.validation.constraints.NotNull;
import jakarta.validation.constraints.Size;
public class ReviewDto {
@JsonProperty(access = JsonProperty.Access.READ_ONLY)
private Long id;
@NotNull
@Min(1)
private Long userId;
@NotBlank
@Size(min = 3, max = 300)
private String text;
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public Long getUserId() {
return userId;
}
public void setUserId(Long userId) {
this.userId = userId;
}
public String getText() { return text; }
public void setText(String text) { this.text = text; }
}

View File

@ -0,0 +1,22 @@
package ip_2.lab1.reviews.api;
public class ReviewGroupedDto {
private String userLogin;
private Integer count;
public Integer getCount() {
return count;
}
public void setCount(Integer count) {
this.count = count;
}
public String getUserLogin() {
return userLogin;
}
public void setUserLogin(String userLogin) {
this.userLogin = userLogin;
}
}

View File

@ -0,0 +1,57 @@
package ip_2.lab1.reviews.model;
import ip_2.lab1.core.model.BaseEntity;
import ip_2.lab1.types.model.TypeEntity;
import ip_2.lab1.users.model.UserEntity;
import jakarta.persistence.*;
import org.h2.engine.User;
import org.hibernate.annotations.Cascade;
import java.util.Objects;
@Entity
@Table(name = "reviews")
public class ReviewEntity extends BaseEntity {
@ManyToOne
@JoinColumn(name = "userId", nullable = false)
private UserEntity user;
@Column(nullable = false, length = 300)
private String text;
public ReviewEntity() {
}
public ReviewEntity(UserEntity user, String text) {
this.user = user;
this.text = text;
}
public UserEntity getUser() { return user;}
public void setUser(UserEntity user) {
this.user = user;
if(!user.getReviews().contains(this))
user.addReview(this);
}
public String getText() {
return text;
}
public void setText(String text) {
this.text = text;
}
@Override
public int hashCode() {
return Objects.hash(id, user, text);
}
@Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null || getClass() != obj.getClass())
return false;
final ReviewEntity other = (ReviewEntity) obj;
return Objects.equals(other.getId(), id) && Objects.equals(other.getUser().getId(), user.getId())
&& Objects.equals(other.getText(), text);
}
}

View File

@ -0,0 +1,8 @@
package ip_2.lab1.reviews.model;
import ip_2.lab1.users.model.UserEntity;
public interface ReviewGrouped {
UserEntity getUser();
Integer getCount();
}

View File

@ -0,0 +1,22 @@
package ip_2.lab1.reviews.repository;
import ip_2.lab1.reviews.model.ReviewEntity;
import ip_2.lab1.reviews.model.ReviewGrouped;
import ip_2.lab1.users.model.UserEntity;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.data.jpa.repository.Query;
import org.springframework.data.repository.CrudRepository;
import org.springframework.data.repository.PagingAndSortingRepository;
import java.util.List;
public interface ReviewRepository extends CrudRepository<ReviewEntity, Long>, PagingAndSortingRepository<ReviewEntity, Long> {
Page<ReviewEntity> findByUserId(Long userId, Pageable pageable);
List<ReviewEntity> findByUserId(Long userId);
void deleteAllByUserId(Long userId);
@Query("SELECT u as user, count(*) as count FROM ReviewEntity r join UserEntity u on u = r.user group by user order by count DESC ")
Page<ReviewGrouped> getReviewCountByUsers(Pageable pageable);
}

View File

@ -0,0 +1,86 @@
package ip_2.lab1.reviews.service;
import ip_2.lab1.core.error.NotFoundException;
import ip_2.lab1.items.model.ItemGrouped;
import ip_2.lab1.reviews.model.ReviewEntity;
import ip_2.lab1.reviews.model.ReviewGrouped;
import ip_2.lab1.reviews.repository.ReviewRepository;
import ip_2.lab1.types.model.TypeEntity;
import ip_2.lab1.types.repository.TypeRepository;
import ip_2.lab1.users.model.UserEntity;
import ip_2.lab1.users.service.UserService;
import jakarta.validation.constraints.Max;
import jakarta.validation.constraints.Min;
import org.antlr.v4.runtime.atn.SemanticContext;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.RequestParam;
import java.util.List;
import java.util.Optional;
import java.util.stream.StreamSupport;
@Service
public class ReviewService {
private final ReviewRepository repository;
private final UserService userService;
public ReviewService(ReviewRepository repository, UserService userService) {
this.repository = repository;
this.userService = userService;
}
@Transactional(readOnly = true)
public List<ReviewEntity> getAll(long userId) {
if (userId <= 0L)
return StreamSupport.stream(repository.findAll().spliterator(), false).toList();
userService.get(userId);
return repository.findByUserId(userId);
}
@Transactional(readOnly = true)
public Page<ReviewEntity> getAll(long userId, Integer offset, Integer limit) {
if (userId <= 0L)
return repository.findAll(PageRequest.of(offset, limit));
userService.get(userId);
return repository.findByUserId(userId, PageRequest.of(offset, limit));
}
@Transactional(readOnly = true)
public ReviewEntity get(Long id) {
return repository.findById(id).orElseThrow(() -> new NotFoundException(ReviewEntity.class, id));
}
@Transactional
public ReviewEntity create(ReviewEntity entity) {
if (entity == null) {
throw new IllegalArgumentException("Entity is null");
}
final UserEntity existUser = userService.get(entity.getUser().getId());
entity.setUser(existUser);
return repository.save(entity);
}
@Transactional
public ReviewEntity update(long id, ReviewEntity entity) {
final ReviewEntity existsEntity = get(id);
userService.get(entity.getUser().getId());
existsEntity.setUser(entity.getUser());
existsEntity.setText(entity.getText());
return repository.save(existsEntity);
}
@Transactional
public ReviewEntity delete(long id) {
final ReviewEntity existsEntity = get(id);
repository.delete(existsEntity);
return existsEntity;
}
@Transactional(readOnly = true)
public Page<ReviewGrouped> getCount(int offset, int limit) {
return repository.getReviewCountByUsers(PageRequest.of(offset, limit));
}
}

View File

@ -0,0 +1,53 @@
package ip_2.lab1.types.api;
import ip_2.lab1.core.configuration.Constants;
import ip_2.lab1.types.model.TypeEntity;
import ip_2.lab1.types.service.TypeService;
import org.modelmapper.ModelMapper;
import org.springframework.web.bind.annotation.*;
import java.util.List;
@RestController
@RequestMapping(Constants.API_URL + "/type")
public class TypeController {
private final TypeService typeService;
private final ModelMapper modelMapper;
public TypeController(TypeService typeService, ModelMapper modelMapper) {
this.typeService = typeService;
this.modelMapper = modelMapper;
}
private TypeDto toDto(TypeEntity entity) {
return modelMapper.map(entity, TypeDto.class);
}
private TypeEntity toEntity(TypeDto dto) {
return modelMapper.map(dto, TypeEntity.class);
}
@GetMapping
public List<TypeDto> getAll() {
return typeService.getAll().stream().map(this::toDto).toList();
}
@GetMapping("/{id}")
public TypeDto get(@PathVariable(name = "id") Long id) {
return toDto(typeService.get(id));
}
@PostMapping
public TypeDto create(@RequestBody TypeDto dto) {
return toDto(typeService.create(toEntity(dto)));
}
@PutMapping("/{id}")
public TypeDto update(@PathVariable(name = "id") Long id, @RequestBody TypeDto dto) {
return toDto(typeService.update(id, toEntity(dto)));
}
@DeleteMapping("/{id}")
public TypeDto delete(@PathVariable(name = "id") Long id) {
return toDto(typeService.delete(id));
}
}

View File

@ -0,0 +1,34 @@
package ip_2.lab1.types.api;
import com.fasterxml.jackson.annotation.JsonProperty;
import io.swagger.v3.oas.models.security.SecurityScheme;
import jakarta.validation.constraints.*;
public class TypeDto {
@JsonProperty(access = JsonProperty.Access.READ_ONLY)
private Long id;
@NotBlank
@Size(min = 3, max = 30)
private String name;
@NotNull
@Min(1)
@Size(min = 1, max = 10)
private Integer basePrice;
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public Integer getBasePrice() { return basePrice; }
public void setBasePrice(Integer basePrice) { this.basePrice = basePrice; }
}

View File

@ -0,0 +1,56 @@
package ip_2.lab1.types.model;
import ip_2.lab1.core.model.BaseEntity;
import ip_2.lab1.items.model.ItemEntity;
import jakarta.persistence.*;
import java.lang.reflect.Type;
import java.util.HashSet;
import java.util.Objects;
import java.util.Set;
@Entity
@Table(name = "types")
public class TypeEntity extends BaseEntity {
@Column(nullable = false, unique = true, length = 30)
private String name;
@Column(nullable = false, length = 10)
private Integer basePrice;
public TypeEntity() {
}
public TypeEntity(String name, Integer basePrice) {
this.name = name;
this.basePrice = basePrice;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getBasePrice() {
return basePrice;
}
public void setBasePrice(int basePrice) {
this.basePrice = basePrice;
}
@Override
public int hashCode() {
return Objects.hash(id, name, basePrice);
}
@Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null || getClass() != obj.getClass())
return false;
final TypeEntity other = (TypeEntity) obj;
return Objects.equals(other.getId(), id) && Objects.equals(other.getName(), name)
&& Objects.equals(other.getBasePrice(), basePrice);
}
}

View File

@ -0,0 +1,11 @@
package ip_2.lab1.types.repository;
import ip_2.lab1.types.model.TypeEntity;
import org.springframework.data.repository.CrudRepository;
import java.util.Map;
import java.util.Optional;
public interface TypeRepository extends CrudRepository<TypeEntity, Long> {
Optional<TypeEntity> findByNameIgnoreCase(String name);
}

View File

@ -0,0 +1,64 @@
package ip_2.lab1.types.service;
import ip_2.lab1.core.error.NotFoundException;
import ip_2.lab1.items.repository.ItemRepository;
import ip_2.lab1.types.model.TypeEntity;
import ip_2.lab1.types.repository.TypeRepository;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import java.lang.reflect.Type;
import java.util.List;
import java.util.Optional;
import java.util.stream.StreamSupport;
@Service
public class TypeService {
private final TypeRepository repository;
private final ItemRepository itemRepository;
public TypeService(TypeRepository repository, ItemRepository itemRepository) {
this.repository = repository;
this.itemRepository = itemRepository;
}
private void checkName(String name) {
if (repository.findByNameIgnoreCase(name).isPresent()) {
throw new IllegalArgumentException(
String.format("Type with name %s is already exists", name));
}
}
@Transactional(readOnly = true)
public List<TypeEntity> getAll() {
return StreamSupport.stream(repository.findAll().spliterator(), false).toList();
}
@Transactional(readOnly = true)
public TypeEntity get(Long id) {
return repository.findById(id)
.orElseThrow(() -> new NotFoundException(TypeEntity.class, id)); }
@Transactional
public TypeEntity create(TypeEntity entity) {
if (entity == null) {
throw new IllegalArgumentException("Entity is null");
}
checkName(entity.getName());
return repository.save(entity); }
@Transactional
public TypeEntity update(Long id, TypeEntity entity) {
final TypeEntity existsEntity = get(id);
existsEntity.setName(entity.getName());
existsEntity.setBasePrice(entity.getBasePrice());
return repository.save(existsEntity);
}
public TypeEntity delete(Long id) {
final TypeEntity existsEntity = get(id);
itemRepository.deleteAllByTypeId(id);
repository.delete(existsEntity);
return existsEntity;
}
}

View File

@ -0,0 +1,48 @@
package ip_2.lab1.users.api;
import ip_2.lab1.core.configuration.Constants;
import ip_2.lab1.users.model.UserEntity;
import ip_2.lab1.users.service.UserService;
import org.modelmapper.ModelMapper;
import org.springframework.web.bind.annotation.*;
import java.util.List;
@RestController
@RequestMapping(Constants.API_URL + "/user")
public class UserController {
private final UserService userService;
private final ModelMapper modelMapper;
public UserController(UserService userService, ModelMapper modelMapper){
this.userService = userService;
this.modelMapper = modelMapper;
}
private UserDto toDto(UserEntity entity){ return modelMapper.map(entity, UserDto.class);}
private UserEntity toEntity(UserDto dto){ return modelMapper.map(dto, UserEntity.class);}
@GetMapping
public List<UserDto> getAll(){ return userService.getAll().stream().map(this::toDto).toList();}
@GetMapping("/{id}")
public UserDto get(@PathVariable(name = "id") Long id){ return toDto(userService.get(id));}
@PostMapping()
public UserDto create(@RequestBody UserDto dto){ return toDto(userService.create(toEntity(dto)));}
@PutMapping("/{id}")
public UserDto update(@PathVariable(name = "id") Long id, @RequestBody UserDto dto){
return toDto(userService.update(id, toEntity(dto)));
}
@PutMapping("/updatePassword/{id}")
public UserDto updatePassword(@PathVariable(name = "id") Long id, @RequestParam String password){
return toDto(userService.updatePassword(id, password));
}
@DeleteMapping("/{id}")
public UserDto delete(@PathVariable(name = "id") Long id){
return toDto(userService.delete(id));
}
}

View File

@ -0,0 +1,41 @@
package ip_2.lab1.users.api;
import com.fasterxml.jackson.annotation.JsonProperty;
import ip_2.lab1.reviews.model.ReviewEntity;
import jakarta.validation.constraints.NotBlank;
import jakarta.validation.constraints.Size;
import java.util.List;
import java.util.Set;
public class UserDto {
@JsonProperty(access = JsonProperty.Access.READ_ONLY)
private Long id;
@NotBlank
@Size(min = 3, max = 30)
private String login;
@NotBlank
@Size(min = 4, max = 30)
private String password;
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = 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;
}
}

View File

@ -0,0 +1,68 @@
package ip_2.lab1.users.model;
import ip_2.lab1.core.model.BaseEntity;
import ip_2.lab1.reviews.model.ReviewEntity;
import ip_2.lab1.types.model.TypeEntity;
import jakarta.persistence.*;
import org.h2.engine.User;
import java.util.HashSet;
import java.util.Objects;
import java.util.Set;
@Entity
@Table(name = "users")
public class UserEntity extends BaseEntity {
@OneToMany(mappedBy = "user", cascade = CascadeType.ALL)
@OrderBy("id ASC")
private final Set<ReviewEntity> reviews = new HashSet<>();
@Column(nullable = false, unique = true, length = 30)
private String login;
@Column(nullable = false, length = 30)
private String password;
public UserEntity() {
}
public UserEntity (String login, String password){
this.login = login;
this.password = password;
}
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 Set<ReviewEntity> getReviews() {
return reviews;
}
public void addReview(ReviewEntity review) {
if (review.getUser() != this) {
review.setUser(this);
}
reviews.add(review);
}
@Override
public int hashCode() {
return Objects.hash(id, login, password);
}
@Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null || getClass() != obj.getClass())
return false;
final UserEntity other = (UserEntity) obj;
return Objects.equals(other.getId(), id) && Objects.equals(other.getLogin(), login)
&& Objects.equals(other.getPassword(), password);
}
}

View File

@ -0,0 +1,14 @@
package ip_2.lab1.users.repository;
import ip_2.lab1.users.model.UserEntity;
import org.springframework.data.jpa.repository.Query;
import org.springframework.data.repository.CrudRepository;
import java.util.Optional;
public interface UserRepository extends CrudRepository<UserEntity, Long> {
Optional<UserEntity> findByLoginIgnoreCase(String login);
@Query("select u from UserEntity u join fetch u.reviews where u.id = ?1")
Optional<UserEntity> findByIdForReviewCreate(Long id);
}

View File

@ -0,0 +1,89 @@
package ip_2.lab1.users.service;
import ip_2.lab1.core.error.NotFoundException;
import ip_2.lab1.reviews.model.ReviewEntity;
import ip_2.lab1.reviews.repository.ReviewRepository;
import ip_2.lab1.users.model.UserEntity;
import ip_2.lab1.users.repository.UserRepository;
import org.springframework.data.domain.Page;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import java.util.List;
import java.util.stream.StreamSupport;
@Service
public class UserService {
private final UserRepository repository;
private final ReviewRepository reviewRepository;
public UserService(UserRepository repository, ReviewRepository reviewRepository){
this.repository = repository;
this.reviewRepository = reviewRepository;
}
private void checkLogin(String login) {
if (repository.findByLoginIgnoreCase(login).isPresent()) {
throw new IllegalArgumentException(
String.format("User with login %s is already exists", login));
}
}
@Transactional(readOnly = true)
public List<UserEntity> getAll(){
return StreamSupport.stream(repository.findAll().spliterator(), false).toList();
}
@Transactional(readOnly = true)
public UserEntity get(Long id){
return repository.findById(id)
.orElseThrow(() -> new NotFoundException(UserEntity.class, id));
}
@Transactional(readOnly = true)
public UserEntity getForReviewCreate(Long id){
return repository.findByIdForReviewCreate(id)
.orElseThrow(() -> new NotFoundException(UserEntity.class, id));
}
@Transactional
public UserEntity create(UserEntity entity){
if (entity == null){
throw new IllegalArgumentException("Entity is null");
}
checkLogin(entity.getLogin());
return repository.save(entity);
}
@Transactional
public UserEntity update(Long id, UserEntity entity){
if (entity == null)
throw new IllegalArgumentException("Entity is null");
final UserEntity existsEntity = get(id);
existsEntity.setLogin(entity.getLogin());
return repository.save(existsEntity);
}
@Transactional
public UserEntity updatePassword(Long id, String password){
if (password == null)
throw new IllegalArgumentException("Password is null");
final UserEntity existsEntity = get(id);
if (password.equals(existsEntity.getPassword()))
throw new IllegalArgumentException("It is existing password");
if (password.contains("1234"))
throw new IllegalArgumentException("Password could not contains numeric sequences");
if(password.length() > 30 || password.length() < 4)
throw new IllegalArgumentException("Password`s length must be in range 4 and 30 characters");
existsEntity.setPassword(password);
return repository.save(existsEntity);
}
@Transactional
public UserEntity delete(Long id){
final UserEntity existsEntity = get(id);
reviewRepository.deleteAllByUserId(id);
repository.deleteById(id);
return existsEntity;
}
}

View File

@ -0,0 +1,20 @@
# Server
spring.main.banner-mode=off
server.port=8080
# Logger settings
# Available levels are: TRACE, DEBUG, INFO, WARN, ERROR, FATAL, OFF
logging.level.com.example.demo=DEBUG
# JPA Settings
spring.datasource.url=jdbc:h2:file:./data
spring.datasource.username=sa
spring.datasource.password=password
spring.datasource.driver-class-name=org.h2.Driver
spring.jpa.hibernate.ddl-auto=create
spring.jpa.open-in-view=false
# spring.jpa.show-sql=true
# spring.jpa.properties.hibernate.format_sql=true
# H2 console
spring.h2.console.enabled=true

View File

@ -0,0 +1,88 @@
package ip_2.lab1;
import ip_2.lab1.core.error.NotFoundException;
import ip_2.lab1.items.model.ItemEntity;
import ip_2.lab1.items.service.ItemService;
import ip_2.lab1.types.model.TypeEntity;
import ip_2.lab1.types.service.TypeService;
import org.junit.jupiter.api.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.dao.DataIntegrityViolationException;
@SpringBootTest
@TestMethodOrder(MethodOrderer.OrderAnnotation.class)
public class ItemServiceTest {
@Autowired
private ItemService itemService;
@Autowired
private TypeService typeService;
private TypeEntity type;
private ItemEntity item;
private ItemEntity item2;
private ItemEntity item3;
@BeforeEach
void createData(){
removeData();
type = typeService.create(new TypeEntity("Asfalt", 1000));
item = itemService.create(new ItemEntity(type, 900, 10));
item2 = itemService.create(new ItemEntity(type, 800, 5));
item3 = itemService.create(new ItemEntity(type, 700, 100));
}
@AfterEach
void removeData(){
itemService.getAll(0L).forEach(item -> itemService.delete(item.getId()));
typeService.getAll().forEach(type -> typeService.delete(type.getId()));
}
@Test
void getTest() {
Assertions.assertThrows(NotFoundException.class, () -> itemService.get(0L));
}
@Test
void createTest() {
Assertions.assertEquals(3, itemService.getAll(0L).size());
Assertions.assertEquals(item, itemService.get(item.getId()));
}
@Test
void createNullableTest() {
final ItemEntity NullableItem = new ItemEntity(null, null, null);
Assertions.assertThrows(DataIntegrityViolationException.class, () -> itemService.create(NullableItem));
}
@Test
void updateTest() {
final int testPrice = 1800;
final int testCount = 20;
final TypeEntity type1 = typeService.create(new TypeEntity("Grunt", 2000));
final TypeEntity oldType = item.getType();
final int oldPrice = item.getPrice();
final int oldCount = item.getCount();
final ItemEntity newEntity = itemService.update(item.getId(), new ItemEntity(type1, testPrice, testCount));
Assertions.assertEquals(3, itemService.getAll(0L).size());
Assertions.assertEquals(newEntity, itemService.get(item.getId()));
Assertions.assertEquals(type1, newEntity.getType());
Assertions.assertEquals(testPrice, newEntity.getPrice());
Assertions.assertEquals(testCount, newEntity.getCount());
Assertions.assertNotEquals(oldType, newEntity.getType());
Assertions.assertNotEquals(oldPrice, newEntity.getPrice());
Assertions.assertNotEquals(oldCount, newEntity.getCount());
}
@Test
void deleteTest() {
itemService.delete(item3.getId());
Assertions.assertEquals(2, itemService.getAll(0L).size());
final ItemEntity last = itemService.get(item2.getId());
Assertions.assertEquals(item2.getId(), last.getId());
}
}

View File

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

View File

@ -0,0 +1,74 @@
package ip_2.lab1;
import ip_2.lab1.core.error.NotFoundException;
import ip_2.lab1.reviews.model.ReviewEntity;
import ip_2.lab1.reviews.service.ReviewService;
import ip_2.lab1.users.model.UserEntity;
import ip_2.lab1.users.service.UserService;
import org.junit.jupiter.api.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
@SpringBootTest
@TestMethodOrder(MethodOrderer.OrderAnnotation.class)
public class ReviewServiceTest {
@Autowired
private ReviewService reviewService;
@Autowired
private UserService userService;
private UserEntity user;
private ReviewEntity review;
private ReviewEntity review2;
private ReviewEntity review3;
@BeforeEach
void createData(){
removeData();
user = userService.create(new UserEntity("Artyom", "1234"));
review = reviewService.create(new ReviewEntity(user, "Good"));
review2 = reviewService.create(new ReviewEntity(user, "Super good"));
review3 = reviewService.create(new ReviewEntity(user, "Not bad"));
}
@AfterEach
void removeData(){
reviewService.getAll(0L).forEach(review -> reviewService.delete(review.getId()));
userService.getAll().forEach(user -> userService.delete(user.getId()));
}
@Test
void getTest() {
Assertions.assertThrows(NotFoundException.class, () -> reviewService.get(0L));
}
@Test
void createTest() {
Assertions.assertEquals(3, reviewService.getAll(0L).size());
Assertions.assertEquals(review, reviewService.get(review.getId()));
}
@Test
void updateTest() {
final String text = "test";
final UserEntity user1 = userService.create(new UserEntity("Niyaz", "1234"));
final UserEntity oldUser = review.getUser();
final String oldText = review.getText();
final ReviewEntity newEntity = reviewService.update(review.getId(), new ReviewEntity(user1, text));
Assertions.assertEquals(3, reviewService.getAll(0L).size());
Assertions.assertEquals(newEntity, reviewService.get(review.getId()));
Assertions.assertEquals(user1, newEntity.getUser());
Assertions.assertEquals(text, newEntity.getText());
Assertions.assertNotEquals(oldUser, newEntity.getUser());
Assertions.assertNotEquals(oldText, newEntity.getText());
}
@Test
void deleteTest() {
reviewService.delete(review3.getId());
Assertions.assertEquals(2, reviewService.getAll(0L).size());
final ReviewEntity last = reviewService.get(review2.getId());
Assertions.assertEquals(review2.getId(), last.getId());
}
}

View File

@ -0,0 +1,81 @@
package ip_2.lab1;
import ip_2.lab1.types.service.TypeService;
import ip_2.lab1.core.error.NotFoundException;
import ip_2.lab1.types.model.TypeEntity;
import org.junit.jupiter.api.*;
import org.junit.jupiter.api.MethodOrderer.OrderAnnotation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.dao.DataIntegrityViolationException;
@SpringBootTest
@TestMethodOrder(OrderAnnotation.class)
class TypeServiceTests {
@Autowired
private TypeService typeService;
private TypeEntity type;
@BeforeEach
void createData() {
removeData();
type = typeService.create(new TypeEntity("Asfalt", 2000));
typeService.create(new TypeEntity("Grunt", 3000));
typeService.create(new TypeEntity("Asfalt + Grunt", 3500));
}
@AfterEach
void removeData() {
typeService.getAll().forEach(item -> typeService.delete(item.getId()));
}
@Test
void getTest() {
Assertions.assertThrows(NotFoundException.class, () -> typeService.get(0L));
}
@Test
void createTest() {
Assertions.assertEquals(3, typeService.getAll().size());
Assertions.assertEquals(type, typeService.get(type.getId()));
}
@Test
void createNotUniqueTest() {
final TypeEntity nonUniqueType = new TypeEntity("Asfalt", 2000);
Assertions.assertThrows(IllegalArgumentException.class, () -> typeService.create(nonUniqueType));
}
@Test
void createNullableTest() {
final TypeEntity nullableType = new TypeEntity(null, null);
Assertions.assertThrows(DataIntegrityViolationException.class, () -> typeService.create(nullableType));
}
@Test
void updateTest() {
final String test = "TEST";
final Integer testPrice = 1000;
final String oldName = type.getName();
final Integer oldPrice = type.getBasePrice();
final TypeEntity newEntity = typeService.update(type.getId(), new TypeEntity(test, testPrice));
Assertions.assertEquals(3, typeService.getAll().size());
Assertions.assertEquals(newEntity, typeService.get(type.getId()));
Assertions.assertEquals(test, newEntity.getName());
Assertions.assertEquals(testPrice, newEntity.getBasePrice());
Assertions.assertNotEquals(oldName, newEntity.getName());
Assertions.assertNotEquals(oldPrice, newEntity.getBasePrice());
}
@Test
void deleteTest() {
typeService.delete(type.getId());
Assertions.assertEquals(2, typeService.getAll().size());
final TypeEntity newEntity = typeService.create(new TypeEntity(type.getName(), type.getBasePrice()));
Assertions.assertEquals(3, typeService.getAll().size());
Assertions.assertNotEquals(type.getId(), newEntity.getId());
}
}

View File

@ -0,0 +1,87 @@
package ip_2.lab1;
import ip_2.lab1.core.error.NotFoundException;
import ip_2.lab1.users.model.UserEntity;
import ip_2.lab1.users.service.UserService;
import org.junit.jupiter.api.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.dao.DataIntegrityViolationException;
@SpringBootTest
@TestMethodOrder(MethodOrderer.OrderAnnotation.class)
public class UserServiceTest {
@Autowired
private UserService userService;
private UserEntity entity;
@BeforeEach
void createData() {
removeData();
entity = userService.create(new UserEntity("Artyom", "1234"));
userService.create(new UserEntity("Niyaz", "1234"));
userService.create(new UserEntity("Rostik", "1234"));
}
@AfterEach
void removeData() {
userService.getAll().forEach(item -> userService.delete(item.getId()));
}
@Test
void getTest() {
Assertions.assertThrows(NotFoundException.class, () -> userService.get(0L));
}
@Test
void createTest() {
Assertions.assertEquals(3, userService.getAll().size());
Assertions.assertEquals(entity, userService.get(entity.getId()));
}
@Test
void createNotUniqueTest() {
final UserEntity nonUniqueEntity = new UserEntity("Artyom", "1234");
Assertions.assertThrows(IllegalArgumentException.class, () -> userService.create(nonUniqueEntity));
}
@Test
void createNullableTest() {
final UserEntity nullableEntity = new UserEntity(null, null);
Assertions.assertThrows(DataIntegrityViolationException.class, () -> userService.create(nullableEntity));
}
@Test
void updateTest() {
final String login = "TEST";
final String oldLogin = entity.getLogin();
final String oldPassword = entity.getPassword();
final UserEntity newEntity = userService.update(entity.getId(), new UserEntity(login, null));
Assertions.assertEquals(3, userService.getAll().size());
Assertions.assertEquals(newEntity, userService.get(entity.getId()));
Assertions.assertEquals(login, newEntity.getLogin());
Assertions.assertNotEquals(oldLogin, newEntity.getLogin());
}
@Test
void updatePasswordTest(){
final String password = "TEST";
final String oldPassword = entity.getPassword();
final UserEntity newEntity = userService.updatePassword(entity.getId(), password);
Assertions.assertEquals(newEntity, userService.get(entity.getId()));
Assertions.assertEquals(password, newEntity.getPassword());
Assertions.assertNotEquals(oldPassword, newEntity.getPassword());
}
@Test
void deleteTest() {
userService.delete(entity.getId());
Assertions.assertEquals(2, userService.getAll().size());
final UserEntity newEntity = userService.create(new UserEntity(entity.getLogin(), entity.getPassword()));
Assertions.assertEquals(3, userService.getAll().size());
Assertions.assertNotEquals(entity.getId(), newEntity.getId());
}
}