Compare commits

...

3 Commits
main ... lab3

Author SHA1 Message Date
K
f2f313b4f8 lab3 2024-05-10 15:16:24 +04:00
K
bbbb903b2e lab2 2024-05-09 11:25:46 +03:00
87105799eb Удалить 'README.md' 2024-04-25 14:45:45 +04:00
46 changed files with 2268 additions and 138 deletions

View File

@ -1,2 +0,0 @@
# Internet_Programming_PIbd-21_Putincev_D_M_Backend

View File

@ -1,12 +1,23 @@
plugins {
id 'java'
id 'org.springframework.boot' version '3.2.2'
id 'org.springframework.boot' version '3.2.5'
id 'io.spring.dependency-management' version '1.1.4'
}
group = 'com.example'
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'
}
@ -17,7 +28,12 @@ repositories {
dependencies {
implementation 'org.springframework.boot:spring-boot-starter-web'
implementation 'org.springframework.boot:spring-boot-starter-validation'
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'
testImplementation 'org.springframework.boot:spring-boot-starter-test'
}

BIN
data.mv.db Normal file

Binary file not shown.

153
data.trace.db Normal file
View File

@ -0,0 +1,153 @@
2024-05-10 15:01:13.422365+04:00 database: flush
org.h2.message.DbException: Внутренняя ошибка: "org.h2.mvstore.MVStoreException: The file is locked: C:/Users/K/source/ip/demo/data.mv.db [2.2.224/7]"
General error: "org.h2.mvstore.MVStoreException: The file is locked: C:/Users/K/source/ip/demo/data.mv.db [2.2.224/7]" [50000-224]
at org.h2.message.DbException.get(DbException.java:212)
at org.h2.message.DbException.convert(DbException.java:407)
at org.h2.mvstore.db.Store.lambda$new$0(Store.java:122)
at org.h2.mvstore.MVStore.handleException(MVStore.java:1546)
at org.h2.mvstore.MVStore.panic(MVStore.java:371)
at org.h2.mvstore.MVStore.<init>(MVStore.java:291)
at org.h2.mvstore.MVStore$Builder.open(MVStore.java:2035)
at org.h2.mvstore.db.Store.<init>(Store.java:133)
at org.h2.engine.Database.<init>(Database.java:326)
at org.h2.engine.Engine.openSession(Engine.java:92)
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.Driver.connect(Driver.java:59)
at com.zaxxer.hikari.util.DriverDataSource.getConnection(DriverDataSource.java:138)
at com.zaxxer.hikari.pool.PoolBase.newConnection(PoolBase.java:359)
at com.zaxxer.hikari.pool.PoolBase.newPoolEntry(PoolBase.java:201)
at com.zaxxer.hikari.pool.HikariPool.createPoolEntry(HikariPool.java:470)
at com.zaxxer.hikari.pool.HikariPool.checkFailFast(HikariPool.java:561)
at com.zaxxer.hikari.pool.HikariPool.<init>(HikariPool.java:100)
at com.zaxxer.hikari.HikariDataSource.getConnection(HikariDataSource.java:112)
at org.hibernate.engine.jdbc.connections.internal.DatasourceConnectionProviderImpl.getConnection(DatasourceConnectionProviderImpl.java:122)
at org.hibernate.engine.jdbc.env.internal.JdbcEnvironmentInitiator$ConnectionProviderJdbcConnectionAccess.obtainConnection(JdbcEnvironmentInitiator.java:428)
at org.hibernate.resource.transaction.backend.jdbc.internal.JdbcIsolationDelegate.delegateWork(JdbcIsolationDelegate.java:61)
at org.hibernate.engine.jdbc.env.internal.JdbcEnvironmentInitiator.getJdbcEnvironmentUsingJdbcMetadata(JdbcEnvironmentInitiator.java:276)
at org.hibernate.engine.jdbc.env.internal.JdbcEnvironmentInitiator.initiateService(JdbcEnvironmentInitiator.java:107)
at org.hibernate.engine.jdbc.env.internal.JdbcEnvironmentInitiator.initiateService(JdbcEnvironmentInitiator.java:68)
at org.hibernate.boot.registry.internal.StandardServiceRegistryImpl.initiateService(StandardServiceRegistryImpl.java:130)
at org.hibernate.service.internal.AbstractServiceRegistryImpl.createService(AbstractServiceRegistryImpl.java:263)
at org.hibernate.service.internal.AbstractServiceRegistryImpl.initializeService(AbstractServiceRegistryImpl.java:238)
at org.hibernate.service.internal.AbstractServiceRegistryImpl.getService(AbstractServiceRegistryImpl.java:215)
at org.hibernate.boot.model.relational.Database.<init>(Database.java:45)
at org.hibernate.boot.internal.InFlightMetadataCollectorImpl.getDatabase(InFlightMetadataCollectorImpl.java:223)
at org.hibernate.boot.internal.InFlightMetadataCollectorImpl.<init>(InFlightMetadataCollectorImpl.java:191)
at org.hibernate.boot.model.process.spi.MetadataBuildingProcess.complete(MetadataBuildingProcess.java:170)
at org.hibernate.jpa.boot.internal.EntityManagerFactoryBuilderImpl.metadata(EntityManagerFactoryBuilderImpl.java:1432)
at org.hibernate.jpa.boot.internal.EntityManagerFactoryBuilderImpl.build(EntityManagerFactoryBuilderImpl.java:1503)
at org.springframework.orm.jpa.vendor.SpringHibernateJpaPersistenceProvider.createContainerEntityManagerFactory(SpringHibernateJpaPersistenceProvider.java:75)
at org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean.createNativeEntityManagerFactory(LocalContainerEntityManagerFactoryBean.java:390)
at org.springframework.orm.jpa.AbstractEntityManagerFactoryBean.buildNativeEntityManagerFactory(AbstractEntityManagerFactoryBean.java:409)
at org.springframework.orm.jpa.AbstractEntityManagerFactoryBean.afterPropertiesSet(AbstractEntityManagerFactoryBean.java:396)
at org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean.afterPropertiesSet(LocalContainerEntityManagerFactoryBean.java:366)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.invokeInitMethods(AbstractAutowireCapableBeanFactory.java:1833)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.initializeBean(AbstractAutowireCapableBeanFactory.java:1782)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:600)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:522)
at org.springframework.beans.factory.support.AbstractBeanFactory.lambda$doGetBean$0(AbstractBeanFactory.java:326)
at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:234)
at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:324)
at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:200)
at org.springframework.context.support.AbstractApplicationContext.getBean(AbstractApplicationContext.java:1234)
at org.springframework.context.support.AbstractApplicationContext.finishBeanFactoryInitialization(AbstractApplicationContext.java:952)
at org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:624)
at org.springframework.boot.SpringApplication.refresh(SpringApplication.java:754)
at org.springframework.boot.SpringApplication.refreshContext(SpringApplication.java:456)
at org.springframework.boot.SpringApplication.run(SpringApplication.java:334)
at org.springframework.boot.test.context.SpringBootContextLoader.lambda$loadContext$3(SpringBootContextLoader.java:137)
at org.springframework.util.function.ThrowingSupplier.get(ThrowingSupplier.java:58)
at org.springframework.util.function.ThrowingSupplier.get(ThrowingSupplier.java:46)
at org.springframework.boot.SpringApplication.withHook(SpringApplication.java:1454)
at org.springframework.boot.test.context.SpringBootContextLoader$ContextLoaderHook.run(SpringBootContextLoader.java:553)
at org.springframework.boot.test.context.SpringBootContextLoader.loadContext(SpringBootContextLoader.java:137)
at org.springframework.boot.test.context.SpringBootContextLoader.loadContext(SpringBootContextLoader.java:108)
at org.springframework.test.context.cache.DefaultCacheAwareContextLoaderDelegate.loadContextInternal(DefaultCacheAwareContextLoaderDelegate.java:225)
at org.springframework.test.context.cache.DefaultCacheAwareContextLoaderDelegate.loadContext(DefaultCacheAwareContextLoaderDelegate.java:152)
at org.springframework.test.context.support.DefaultTestContext.getApplicationContext(DefaultTestContext.java:130)
at org.springframework.test.context.web.ServletTestExecutionListener.setUpRequestContextIfNecessary(ServletTestExecutionListener.java:191)
at org.springframework.test.context.web.ServletTestExecutionListener.prepareTestInstance(ServletTestExecutionListener.java:130)
at org.springframework.test.context.TestContextManager.prepareTestInstance(TestContextManager.java:260)
at org.springframework.test.context.junit.jupiter.SpringExtension.postProcessTestInstance(SpringExtension.java:163)
at org.junit.jupiter.engine.descriptor.ClassBasedTestDescriptor.lambda$invokeTestInstancePostProcessors$10(ClassBasedTestDescriptor.java:378)
at org.junit.jupiter.engine.descriptor.ClassBasedTestDescriptor.executeAndMaskThrowable(ClassBasedTestDescriptor.java:383)
at org.junit.jupiter.engine.descriptor.ClassBasedTestDescriptor.lambda$invokeTestInstancePostProcessors$11(ClassBasedTestDescriptor.java:378)
at java.base/java.util.stream.ReferencePipeline$3$1.accept(ReferencePipeline.java:197)
at java.base/java.util.stream.ReferencePipeline$2$1.accept(ReferencePipeline.java:179)
at java.base/java.util.ArrayList$ArrayListSpliterator.forEachRemaining(ArrayList.java:1708)
at java.base/java.util.stream.AbstractPipeline.copyInto(AbstractPipeline.java:509)
at java.base/java.util.stream.AbstractPipeline.wrapAndCopyInto(AbstractPipeline.java:499)
at java.base/java.util.stream.StreamSpliterators$WrappingSpliterator.forEachRemaining(StreamSpliterators.java:310)
at java.base/java.util.stream.Streams$ConcatSpliterator.forEachRemaining(Streams.java:735)
at java.base/java.util.stream.Streams$ConcatSpliterator.forEachRemaining(Streams.java:734)
at java.base/java.util.stream.ReferencePipeline$Head.forEach(ReferencePipeline.java:762)
at org.junit.jupiter.engine.descriptor.ClassBasedTestDescriptor.invokeTestInstancePostProcessors(ClassBasedTestDescriptor.java:377)
at org.junit.jupiter.engine.descriptor.ClassBasedTestDescriptor.lambda$instantiateAndPostProcessTestInstance$6(ClassBasedTestDescriptor.java:290)
at org.junit.platform.engine.support.hierarchical.ThrowableCollector.execute(ThrowableCollector.java:73)
at org.junit.jupiter.engine.descriptor.ClassBasedTestDescriptor.instantiateAndPostProcessTestInstance(ClassBasedTestDescriptor.java:289)
at org.junit.jupiter.engine.descriptor.ClassBasedTestDescriptor.lambda$testInstancesProvider$4(ClassBasedTestDescriptor.java:279)
at java.base/java.util.Optional.orElseGet(Optional.java:364)
at org.junit.jupiter.engine.descriptor.ClassBasedTestDescriptor.lambda$testInstancesProvider$5(ClassBasedTestDescriptor.java:278)
at org.junit.jupiter.engine.execution.TestInstancesProvider.getTestInstances(TestInstancesProvider.java:31)
at org.junit.jupiter.engine.descriptor.TestMethodTestDescriptor.lambda$prepare$0(TestMethodTestDescriptor.java:106)
at org.junit.platform.engine.support.hierarchical.ThrowableCollector.execute(ThrowableCollector.java:73)
at org.junit.jupiter.engine.descriptor.TestMethodTestDescriptor.prepare(TestMethodTestDescriptor.java:105)
at org.junit.jupiter.engine.descriptor.TestMethodTestDescriptor.prepare(TestMethodTestDescriptor.java:69)
at org.junit.platform.engine.support.hierarchical.NodeTestTask.lambda$prepare$2(NodeTestTask.java:123)
at org.junit.platform.engine.support.hierarchical.ThrowableCollector.execute(ThrowableCollector.java:73)
at org.junit.platform.engine.support.hierarchical.NodeTestTask.prepare(NodeTestTask.java:123)
at org.junit.platform.engine.support.hierarchical.NodeTestTask.execute(NodeTestTask.java:90)
at java.base/java.util.ArrayList.forEach(ArrayList.java:1596)
at org.junit.platform.engine.support.hierarchical.SameThreadHierarchicalTestExecutorService.invokeAll(SameThreadHierarchicalTestExecutorService.java:41)
at org.junit.platform.engine.support.hierarchical.NodeTestTask.lambda$executeRecursively$6(NodeTestTask.java:155)
at org.junit.platform.engine.support.hierarchical.ThrowableCollector.execute(ThrowableCollector.java:73)
at org.junit.platform.engine.support.hierarchical.NodeTestTask.lambda$executeRecursively$8(NodeTestTask.java:141)
at org.junit.platform.engine.support.hierarchical.Node.around(Node.java:137)
at org.junit.platform.engine.support.hierarchical.NodeTestTask.lambda$executeRecursively$9(NodeTestTask.java:139)
at org.junit.platform.engine.support.hierarchical.ThrowableCollector.execute(ThrowableCollector.java:73)
at org.junit.platform.engine.support.hierarchical.NodeTestTask.executeRecursively(NodeTestTask.java:138)
at org.junit.platform.engine.support.hierarchical.NodeTestTask.execute(NodeTestTask.java:95)
at java.base/java.util.ArrayList.forEach(ArrayList.java:1596)
at org.junit.platform.engine.support.hierarchical.SameThreadHierarchicalTestExecutorService.invokeAll(SameThreadHierarchicalTestExecutorService.java:41)
at org.junit.platform.engine.support.hierarchical.NodeTestTask.lambda$executeRecursively$6(NodeTestTask.java:155)
at org.junit.platform.engine.support.hierarchical.ThrowableCollector.execute(ThrowableCollector.java:73)
at org.junit.platform.engine.support.hierarchical.NodeTestTask.lambda$executeRecursively$8(NodeTestTask.java:141)
at org.junit.platform.engine.support.hierarchical.Node.around(Node.java:137)
at org.junit.platform.engine.support.hierarchical.NodeTestTask.lambda$executeRecursively$9(NodeTestTask.java:139)
at org.junit.platform.engine.support.hierarchical.ThrowableCollector.execute(ThrowableCollector.java:73)
at org.junit.platform.engine.support.hierarchical.NodeTestTask.executeRecursively(NodeTestTask.java:138)
at org.junit.platform.engine.support.hierarchical.NodeTestTask.execute(NodeTestTask.java:95)
at org.junit.platform.engine.support.hierarchical.SameThreadHierarchicalTestExecutorService.submit(SameThreadHierarchicalTestExecutorService.java:35)
at org.junit.platform.engine.support.hierarchical.HierarchicalTestExecutor.execute(HierarchicalTestExecutor.java:57)
at org.junit.platform.engine.support.hierarchical.HierarchicalTestEngine.execute(HierarchicalTestEngine.java:54)
at org.junit.platform.launcher.core.EngineExecutionOrchestrator.execute(EngineExecutionOrchestrator.java:147)
at org.junit.platform.launcher.core.EngineExecutionOrchestrator.execute(EngineExecutionOrchestrator.java:127)
at org.junit.platform.launcher.core.EngineExecutionOrchestrator.execute(EngineExecutionOrchestrator.java:90)
at org.junit.platform.launcher.core.EngineExecutionOrchestrator.lambda$execute$0(EngineExecutionOrchestrator.java:55)
at org.junit.platform.launcher.core.EngineExecutionOrchestrator.withInterceptedStreams(EngineExecutionOrchestrator.java:102)
at org.junit.platform.launcher.core.EngineExecutionOrchestrator.execute(EngineExecutionOrchestrator.java:54)
at org.junit.platform.launcher.core.DefaultLauncher.execute(DefaultLauncher.java:114)
at org.junit.platform.launcher.core.DefaultLauncher.execute(DefaultLauncher.java:95)
at org.junit.platform.launcher.core.DefaultLauncherSession$DelegatingLauncher.execute(DefaultLauncherSession.java:91)
at org.junit.platform.launcher.core.SessionPerRequestLauncher.execute(SessionPerRequestLauncher.java:60)
at org.eclipse.jdt.internal.junit5.runner.JUnit5TestReference.run(JUnit5TestReference.java:98)
at org.eclipse.jdt.internal.junit.runner.TestExecution.run(TestExecution.java:40)
at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.runTests(RemoteTestRunner.java:529)
at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.runTests(RemoteTestRunner.java:757)
at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.run(RemoteTestRunner.java:452)
at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.main(RemoteTestRunner.java:210)
Caused by: org.h2.jdbc.JdbcSQLNonTransientException: Внутренняя ошибка: "org.h2.mvstore.MVStoreException: The file is locked: C:/Users/K/source/ip/demo/data.mv.db [2.2.224/7]"
General error: "org.h2.mvstore.MVStoreException: The file is locked: C:/Users/K/source/ip/demo/data.mv.db [2.2.224/7]" [50000-224]
at org.h2.message.DbException.getJdbcSQLException(DbException.java:566)
at org.h2.message.DbException.getJdbcSQLException(DbException.java:489)
... 138 more
Caused by: org.h2.mvstore.MVStoreException: The file is locked: C:/Users/K/source/ip/demo/data.mv.db [2.2.224/7]
at org.h2.mvstore.DataUtils.newMVStoreException(DataUtils.java:996)
at org.h2.mvstore.SingleFileStore.lockFileChannel(SingleFileStore.java:143)
at org.h2.mvstore.SingleFileStore.open(SingleFileStore.java:117)
at org.h2.mvstore.SingleFileStore.open(SingleFileStore.java:81)
at org.h2.mvstore.MVStore.<init>(MVStore.java:286)
... 132 more

Binary file not shown.

View File

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

20
gradlew.bat vendored
View File

@ -43,11 +43,11 @@ 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.
echo. 1>&2
echo ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. 1>&2
echo. 1>&2
echo Please set the JAVA_HOME variable in your environment to match the 1>&2
echo location of your Java installation. 1>&2
goto fail
@ -57,11 +57,11 @@ 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.
echo. 1>&2
echo ERROR: JAVA_HOME is set to an invalid directory: %JAVA_HOME% 1>&2
echo. 1>&2
echo Please set the JAVA_HOME variable in your environment to match the 1>&2
echo location of your Java installation. 1>&2
goto fail

View File

@ -1,66 +0,0 @@
package com.example.demo;
import java.util.Date;
import java.util.List;
import java.util.ArrayList;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
@RestController
@RequestMapping("/usertest")
public class ApiController {
private final Logger log = LoggerFactory.getLogger(ApiController.class);
List<UserTest> data = new ArrayList<>(List.of(
new UserTest("handle1", "email1", "name1", "password1"),
new UserTest("handle2", "email2", "name2", "password2")));
@PostMapping
public UserTest create(@RequestBody UserTest user) {
data.add(user);
return user;
}
@GetMapping
public List<UserTest> readAll() {
return data;
}
@GetMapping("/{id}")
public UserTest read(@PathVariable(name = "id") int id) {
return data.get(id);
}
@PutMapping("/{id}")
public UserTest update(@PathVariable(name = "id") int id, @RequestBody UserTest user) {
UserTest us = data.get(id);
if (us != null) {
data.remove(id);
}
data.add(id, user);
return data.get(id);
}
@DeleteMapping("/{id}")
public UserTest delete(@PathVariable(name = "id") int id) {
UserTest us = data.get(id);
if (us != null) {
data.remove(id);
}
return null;
}
}

View File

@ -1,12 +1,119 @@
package com.example.demo;
import java.util.Arrays;
import java.time.LocalDate;
import java.time.format.DateTimeFormatter;
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 com.example.demo.ivents.model.IventEntity;
import com.example.demo.ivents.service.IventService;
import com.example.demo.types.model.TypeEntity;
import com.example.demo.types.service.TypeService;
import com.example.demo.places.model.PlaceEntity;
import com.example.demo.places.service.PlaceService;
import com.example.demo.users.model.UserEntity;
import com.example.demo.users.service.UserService;
@SpringBootApplication
public class DemoApplication {
public class DemoApplication implements CommandLineRunner {
private final Logger log = LoggerFactory.getLogger(DemoApplication.class);
private final TypeService typeService;
private final PlaceService placeService;
private final IventService iventService;
private final UserService userService;
public DemoApplication(PlaceService placeService, TypeService typeService, IventService iventService, UserService userService) {
this.placeService = placeService;
this.typeService = typeService;
this.iventService = iventService;
this.userService = userService;
}
public static void main(String[] args) {
SpringApplication.run(DemoApplication.class, args);
}
@Override
public void run(String... args) throws Exception {
if (args.length > 0 && Arrays.asList(args).contains("--populate")) {
log.info("Create default types&dates values");
DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd");
LocalDate _date = LocalDate.parse("2023-10-15", formatter);
final var type1 = typeService.create(new TypeEntity("Концерт"));
final var type2 = typeService.create(new TypeEntity("Кино"));
final var type3 = typeService.create(new TypeEntity("Театр"));
final var place1 = placeService.create(new PlaceEntity("US, California"));
final var place2 = placeService.create(new PlaceEntity("Germany, Berlin"));
final var place3 = placeService.create(new PlaceEntity("UK, London"));
log.info("Create default ivents values");
iventService.create(new IventEntity(
"Slipknot",
type1,
_date,
"Slipknot - американская ню-метал группа, основанная в 1995 году. Они известны своим агрессивным звучанием, смешением хардкор-панк и тяжелого метала с индастриалом и элементами альтернативного рока.",
"Участники группы Slipknot - это:<....>",
2500.33,
30,
place1,
""));
iventService.create(new IventEntity(
"Placebo",
type1,
_date,
"Placebo - британская альтернативная рок-группа, основанная в 1994 году. Они известны своим уникальным звучанием, погружающим слушателей в меланхоличную атмосферу и наполняющим музыку эмоциональным содержанием.",
"Группа Placebo состояла из следующих участников:<....>",
2500.33,
30,
place2,
""));
iventService.create(new IventEntity(
"Radiohead",
type1,
_date,
"Radiohead - британская рок-группа, образованная в 1985 году.",
"Участниками Radiohead являются:<....>",
2500.33,
30,
place3,
""));
iventService.create(new IventEntity(
"Сияние",
type2,
_date,
"\"Сияние\" - это психологический триллер режиссера Стэнли Кубрика, вышедший в 1980 году.",
"Актеры:<....>",
2500.33,
45,
place3,
""));
iventService.create(new IventEntity(
"Мастер и Маргарита",
type3,
_date,
"тут должно быть описание",
"Автор: М. А. Булгаков",
2500.33,
30,
place2,
""));
log.info("Create default users values");
userService.create(new UserEntity("Admin", "Admin@gmail.com", "admin", "admin"));
userService.create(new UserEntity("Milana", "milana@gmail.com", "milana", "user"));
userService.create(new UserEntity("TestUser", "user@gmail.com", "test", "user"));
}
}
}

View File

@ -1,42 +0,0 @@
package com.example.demo;
import com.fasterxml.jackson.annotation.JsonCreator;
import com.fasterxml.jackson.annotation.JsonProperty;
public class UserTest {
private String handle;
private String email;
private String name;
private String password;
public UserTest() {
}
@JsonCreator
public UserTest(
@JsonProperty(value = "handle") String handle,
@JsonProperty(value = "email") String email,
@JsonProperty(value = "name") String name,
@JsonProperty(value = "password") String password) {
this.handle = handle;
this.email = email;
this.name = name;
this.password = password;
}
public String getHandle() {
return handle;
}
public String getEmail() {
return email;
}
public String getName() {
return name;
}
public String getPassword() {
return password;
}
}

View File

@ -0,0 +1,97 @@
package com.example.demo.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 com.example.demo.core.api;
import java.util.function.Function;
import org.springframework.data.domain.Page;
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 com.example.demo.core.configuration;
public class Constants {
public static final String SEQUENCE_NAME = "hibernate_sequence";
public static final String API_URL = "/api/1.0";
public static final String DEFAULT_PAGE_SIZE = "5";
private Constants() {
}
}

View File

@ -0,0 +1,14 @@
package com.example.demo.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

@ -1,4 +1,4 @@
package com.example.demo;
package com.example.demo.core.configuration;
import org.springframework.context.annotation.Configuration;
import org.springframework.lang.NonNull;
@ -6,7 +6,7 @@ import org.springframework.web.servlet.config.annotation.CorsRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
@Configuration
public class WebConfig implements WebMvcConfigurer {
public class WebConfiguration implements WebMvcConfigurer {
@Override
public void addCorsMappings(@NonNull CorsRegistry registry) {
registry.addMapping("/**")

View File

@ -0,0 +1,7 @@
package com.example.demo.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,32 @@
package com.example.demo.core.model;
import com.example.demo.core.configuration.Constants;
import jakarta.persistence.GeneratedValue;
import jakarta.persistence.GenerationType;
import jakarta.persistence.Id;
import jakarta.persistence.MappedSuperclass;
import jakarta.persistence.SequenceGenerator;
@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() {
}
protected BaseEntity(Long id) {
this.id = id;
}
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
}

View File

@ -0,0 +1,17 @@
package com.example.demo.core.repository;
import java.util.List;
public interface CommonRepository<E, T> {
List<E> getAll();
E get(T id);
E create(E entity);
E update(E entity);
E delete(E entity);
void deleteAll();
}

View File

@ -0,0 +1,58 @@
package com.example.demo.core.repository;
import java.util.List;
import java.util.Map;
import java.util.TreeMap;
import com.example.demo.core.model.BaseEntity;
public abstract class MapRepository<E extends BaseEntity> implements CommonRepository<E, Long> {
private final Map<Long, E> entities = new TreeMap<>();
private Long lastId = 0L;
protected MapRepository() {
}
@Override
public List<E> getAll() {
return entities.values().stream().toList();
}
@Override
public E get(Long id) {
return entities.get(id);
}
@Override
public E create(E entity) {
lastId++;
entity.setId(lastId);
entities.put(lastId, entity);
return entity;
}
@Override
public E update(E entity) {
if (get(entity.getId()) == null) {
return null;
}
entities.put(entity.getId(), entity);
return entity;
}
@Override
public E delete(E entity) {
if (get(entity.getId()) == null) {
return null;
}
entities.remove(entity.getId());
return entity;
}
@Override
public void deleteAll() {
lastId = 0L;
entities.clear();
}
}

View File

@ -0,0 +1,20 @@
package com.example.demo.core.utils;
import java.util.Date;
import java.text.ParseException;
import java.text.SimpleDateFormat;
public final class Formatter {
private Formatter() {
}
private static SimpleDateFormat dateFormatter = new SimpleDateFormat("yyyy-MM-dd");
public static String format(Date date) {
return dateFormatter.format(date);
}
public static Date parse(String date) throws ParseException {
return dateFormatter.parse(date);
}
}

View File

@ -0,0 +1,87 @@
package com.example.demo.ivents.api;
import java.time.LocalDate;
import java.time.format.DateTimeFormatter;
import java.util.List;
import java.util.Optional;
import org.modelmapper.ModelMapper;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import com.example.demo.ivents.model.IventEntity;
import com.example.demo.ivents.service.IventService;
import com.example.demo.core.configuration.Constants;
import com.example.demo.types.service.TypeService;
import com.example.demo.places.service.PlaceService;
import jakarta.validation.Valid;
@RestController
@RequestMapping(Constants.API_URL + "/ivents")
public class IventController {
private final IventService iventService;
private final TypeService typeService;
private final PlaceService placeService;
private final ModelMapper modelMapper;
public IventController(IventService iventService, TypeService typeService,
PlaceService placeService, ModelMapper modelMapper) {
this.iventService = iventService;
this.typeService = typeService;
this.placeService = placeService;
this.modelMapper = modelMapper;
}
private IventDto toDto(IventEntity entity) {
return modelMapper.map(entity, IventDto.class);
}
private IventEntity toEntity(IventDto dto) {
final IventEntity entity = modelMapper.map(dto, IventEntity.class);
entity.setType(typeService.get(dto.getTypeId()));
entity.setPlace(placeService.get(dto.getPlaceId()));
return entity;
}
@GetMapping
public List<IventDto> getAll(
@RequestParam(name = "typeId", defaultValue = "0") Long typeId,
@RequestParam(name = "placeId", defaultValue = "0") Long placeId,
@RequestParam(name = "startDate", defaultValue = "0001-01-01") String startDate,
@RequestParam(name = "endDate", defaultValue = "9999-12-31") String endDate) {
DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd");
LocalDate _startDate = LocalDate.parse(startDate, formatter);
LocalDate _endDate = LocalDate.parse(endDate, formatter);
return iventService.getAll(typeId, placeId, _startDate, _endDate).stream().map(this::toDto).toList();
}
@GetMapping("/{id}")
public IventDto get(@PathVariable(name = "id") Long id) {
return toDto(iventService.get(id));
}
@PostMapping
public IventDto create(@RequestBody @Valid IventDto dto) {
return toDto(iventService.create(toEntity(dto)));
}
@PutMapping("/{id}")
public IventDto update(@PathVariable(name = "id") Long id, @RequestBody IventDto dto) {
return toDto(iventService.update(id, toEntity(dto)));
}
@DeleteMapping("/{id}")
public IventDto delete(@PathVariable(name = "id") Long id) {
return toDto(iventService.delete(id));
}
}

View File

@ -0,0 +1,111 @@
package com.example.demo.ivents.api;
import com.fasterxml.jackson.annotation.JsonProperty;
import java.time.LocalDate;
import jakarta.validation.constraints.Min;
import jakarta.validation.constraints.NotBlank;
import jakarta.validation.constraints.NotNull;
public class IventDto {
@JsonProperty(access = JsonProperty.Access.READ_ONLY)
private Long id;
@NotBlank
private String itName;
@NotNull
@Min(1)
private Long typeId;
@NotNull
private LocalDate date;
@NotBlank
private String description;
@NotBlank
private String other;
@NotNull
@Min(1)
private Double price;
@NotNull
@Min(1)
private Integer count;
@NotNull
@Min(1)
private Long placeId;
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 String getName() {
return itName;
}
public void setName(String itName) {
this.itName = itName;
}
public LocalDate getDate() {
return date;
}
public void setDate(LocalDate date) {
this.date = date;
}
public String getDesc() {
return description;
}
public void setDesc(String description) {
this.description = description;
}
public String getOther() {
return other;
}
public void setOther(String other) {
this.other = other;
}
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;
}
public Long getPlaceId() {
return placeId;
}
public void setPLaceId(Long placeId) {
this.placeId = placeId;
}
@JsonProperty(access = JsonProperty.Access.READ_ONLY)
public Double getSum() {
return price * count;
}
}

View File

@ -0,0 +1,150 @@
package com.example.demo.ivents.model;
import java.util.Objects;
import java.time.LocalDate;
import com.example.demo.core.model.BaseEntity;
import com.example.demo.types.model.TypeEntity;
import com.example.demo.places.model.PlaceEntity;
import jakarta.persistence.Column;
import jakarta.persistence.Entity;
import jakarta.persistence.JoinColumn;
import jakarta.persistence.ManyToOne;
import jakarta.persistence.Table;
@Entity
@Table(name = "ivents")
public class IventEntity extends BaseEntity {
@Column(nullable = false)
private String name;
@ManyToOne
@JoinColumn(name = "typeId", nullable = false)
private TypeEntity type;
@Column(nullable = false)
private LocalDate date;
@Column(nullable = false)
private String description;
@Column(nullable = false)
private String other;
@Column(nullable = false)
private Double price;
@Column(nullable = false)
private Integer count;
@ManyToOne
@JoinColumn(name = "placeId", nullable = false)
private PlaceEntity place;
private String image;
public IventEntity() {
}
public IventEntity(String name, TypeEntity type, LocalDate date,
String description, String other, Double price, Integer count, PlaceEntity place, String image) {
this.name = name;
this.type = type;
this.date = date;
this.description = description;
this.other = other;
this.price = price;
this.count = count;
this.place = place;
this.image = image;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public TypeEntity getType() {
return type;
}
public void setType(TypeEntity type) {
this.type = type;
}
public LocalDate getDate() {
return date;
}
public void setDate(LocalDate date) {
this.date = date;
}
public String getDesc() {
return description;
}
public void setDesc(String description) {
this.description = description;
}
public String getOther() {
return other;
}
public void setOther(String other) {
this.other = other;
}
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;
}
public PlaceEntity getPlace() {
return place;
}
public void setPlace(PlaceEntity place) {
this.place = place;
}
public String getImage() {
return image;
}
public void setImage(String image) {
this.image = image;
}
@Override
public int hashCode() {
return Objects.hash(id, name, type, date, description, other, price, count, place, image);
}
@Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null || getClass() != obj.getClass())
return false;
final IventEntity otheren = (IventEntity) obj;
return Objects.equals(otheren.getId(), id)
&& Objects.equals(otheren.getName(), name)
&& Objects.equals(otheren.getType(), type)
&& Objects.equals(otheren.getDate(), date)
&& Objects.equals(otheren.getDesc(), description)
&& Objects.equals(otheren.getOther(), other)
&& Objects.equals(otheren.getPrice(), price)
&& Objects.equals(otheren.getCount(), count)
&& Objects.equals(otheren.getPlace(), place)
&& Objects.equals(otheren.getImage(), image);
}
}

View File

@ -0,0 +1,26 @@
package com.example.demo.ivents.repository;
import java.time.LocalDate;
import java.util.List;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.data.repository.CrudRepository;
import org.springframework.data.repository.PagingAndSortingRepository;
import com.example.demo.ivents.model.IventEntity;
import com.example.demo.places.model.PlaceEntity;
import com.example.demo.types.model.TypeEntity;
public interface IventRepository extends CrudRepository<IventEntity, Long> , PagingAndSortingRepository<IventEntity, Long> {
List<IventEntity> findByTypeId(Long typeId);
List<IventEntity> findByPlaceId(Long placeId);
List<IventEntity> findByTypeIdAndPlaceId(Long typeId, Long placeId);
List<IventEntity> findAllByDateBetween(LocalDate startDate, LocalDate endDate);
Page<IventEntity> findByTypeId(Long typeId, Pageable pageable);
Page<IventEntity> findByPlaceId(Long placeId, Pageable pageable);
Page<IventEntity> findByTypeIdAndPlaceId(Long typeId, Long placeId, Pageable pageable);
Page<IventEntity> findAllByDateBetween(LocalDate startDate, LocalDate endDate, Pageable pageable);
}

View File

@ -0,0 +1,145 @@
package com.example.demo.ivents.service;
import java.time.LocalDate;
import java.util.ArrayList;
import java.util.List;
import java.util.Objects;
import java.util.Optional;
import java.util.stream.StreamSupport;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import com.example.demo.core.error.NotFoundException;
import com.example.demo.ivents.model.IventEntity;
import com.example.demo.ivents.repository.IventRepository;
import com.example.demo.types.repository.TypeRepository;
import com.example.demo.places.repository.PlaceRepository;
import com.example.demo.places.model.PlaceEntity;
import com.example.demo.types.model.TypeEntity;
@Service
public class IventService {
private final TypeRepository typeRepository;
private final PlaceRepository placeRepository;
private final IventRepository repository;
public IventService(TypeRepository typeRepository, PlaceRepository placeRepository, IventRepository repository) {
this.repository = repository;
this.typeRepository = typeRepository;
this.placeRepository = placeRepository;
}
@Transactional
public List<IventEntity> getAll(Long typeId, Long placeId, LocalDate startDate, LocalDate endDate) {
List<IventEntity> result;
if (startDate != null || endDate != null) {
if (startDate != null && endDate != null) {
result = StreamSupport.stream(repository.findAllByDateBetween(startDate, endDate).spliterator(), false).toList();
} else if (startDate != null) {
result = StreamSupport.stream(repository.findAllByDateBetween(startDate, LocalDate.now()).spliterator(), false).toList();
} else {
result = StreamSupport.stream(repository.findAllByDateBetween(LocalDate.MIN, endDate).spliterator(), false).toList();
}
} else {
result = StreamSupport.stream(repository.findAll().spliterator(), false).toList();
}
if (typeId != null && typeId != 0L) {
if (placeId != null && placeId != 0L) {
result.retainAll(repository.findByTypeIdAndPlaceId(typeId, placeId));
} else {
result.retainAll(repository.findByTypeId(typeId));
}
}
if (placeId != null && placeId != 0L) {
if (typeId == null || typeId == 0L) {
result.retainAll(repository.findByPlaceId(placeId));
}
}
return result;
}
@Transactional
public Page<IventEntity> getAll(Long typeId, Long placeId, LocalDate startDate, LocalDate endDate, Pageable pageable) {
Page<IventEntity> resultPage;
if (startDate != null || endDate != null) {
if (startDate != null && endDate != null) {
resultPage = repository.findAllByDateBetween(startDate, endDate, pageable);
} else if (startDate != null) {
resultPage = repository.findAllByDateBetween(startDate, LocalDate.now(), pageable);
} else {
resultPage = repository.findAllByDateBetween(LocalDate.MIN, endDate, pageable);
}
} else {
resultPage = repository.findAll(pageable);
}
if (typeId != null && typeId != 0L) {
if (placeId != null && placeId != 0L) {
resultPage = repository.findByTypeIdAndPlaceId(typeId, placeId, pageable);
} else {
resultPage = repository.findByTypeId(typeId, pageable);
}
}
if (placeId != null && placeId != 0L) {
if (typeId == null || typeId == 0L) {
resultPage = repository.findByPlaceId(placeId, pageable);
}
}
return resultPage;
}
@Transactional(readOnly = true)
public IventEntity get(Long id) {
return repository.findById(id)
.orElseThrow(() -> new NotFoundException(IventEntity.class, id));
}
@Transactional
public IventEntity create(IventEntity entity) {
if (entity == null) {
throw new IllegalArgumentException("Entity is null");
}
return repository.save(entity);
}
@Transactional
public IventEntity update(Long id, IventEntity entity) {
final IventEntity existsEntity = get(id);
existsEntity.setName(entity.getName());
existsEntity.setType(entity.getType());
existsEntity.setDate(entity.getDate());
existsEntity.setDesc(entity.getDesc());
existsEntity.setOther(entity.getOther());
existsEntity.setPrice(entity.getPrice());
existsEntity.setCount(entity.getCount());
existsEntity.setPlace(entity.getPlace());
existsEntity.setImage(entity.getImage());
return repository.save(existsEntity);
}
@Transactional
public IventEntity delete(Long id) {
final IventEntity existsEntity = get(id);
repository.delete(existsEntity);
return existsEntity;
}
/*public List<IventEntity> getAllDate(LocalDate startDate, LocalDate endDate) {
if (startDate == null) {
throw new IllegalArgumentException("Дата 'от' должна быть указана");
}
LocalDate end = Objects.requireNonNullElse(endDate, LocalDate.now());
return repository.getAll().stream()
.filter(item -> item.getDate().isAfter(startDate.minusDays(1)) && item.getDate().isBefore(end.plusDays(1))) // использование методов isAfter и isBefore для LocalDate
.collect(Collectors.toList());
}*/
}

View File

@ -0,0 +1,65 @@
package com.example.demo.places.api;
import java.util.List;
import org.modelmapper.ModelMapper;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import com.example.demo.core.configuration.Constants;
import com.example.demo.places.model.PlaceEntity;
import com.example.demo.places.service.PlaceService;
import jakarta.validation.Valid;
@RestController
@RequestMapping(Constants.API_URL + "/place")
public class PlaceController {
private final PlaceService placeService;
private final ModelMapper modelMapper;
public PlaceController(PlaceService placeService, ModelMapper modelMapper) {
this.placeService = placeService;
this.modelMapper = modelMapper;
}
private PlaceDto toDto(PlaceEntity entity) {
return modelMapper.map(entity, PlaceDto.class);
}
private PlaceEntity toEntity(PlaceDto dto) {
return modelMapper.map(dto, PlaceEntity.class);
}
@GetMapping
public List<PlaceDto> getAll() {
return placeService.getAll().stream().map(this::toDto).toList();
}
@GetMapping("/{id}")
public PlaceDto get(@PathVariable(name = "id") Long id) {
return toDto(placeService.get(id));
}
@PostMapping
public PlaceDto create(@RequestBody @Valid PlaceDto dto) {
return toDto(placeService.create(toEntity(dto)));
}
@PutMapping("/{id}")
public PlaceDto update(@PathVariable(name = "id") Long id, @RequestBody PlaceDto dto) {
return toDto(placeService.update(id, toEntity(dto)));
}
@DeleteMapping("/{id}")
public PlaceDto delete(@PathVariable(name = "id") Long id) {
return toDto(placeService.delete(id));
}
}

View File

@ -0,0 +1,29 @@
package com.example.demo.places.api;
import com.fasterxml.jackson.annotation.JsonProperty;
import jakarta.validation.constraints.NotBlank;
public class PlaceDto {
@JsonProperty(access = JsonProperty.Access.READ_ONLY)
private Long id;
@NotBlank
private String name;
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;
}
}

View File

@ -0,0 +1,49 @@
package com.example.demo.places.model;
import java.util.Objects;
import com.example.demo.core.model.BaseEntity;
import jakarta.persistence.Column;
import jakarta.persistence.Entity;
import jakarta.persistence.Table;
@Entity
@Table(name = "places")
public class PlaceEntity extends BaseEntity {
@Column(nullable = false, unique = true)
private String name;
public PlaceEntity() {
}
public PlaceEntity(String name) {
this.name = name;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
@Override
public int hashCode() {
return Objects.hash(id, name);
}
@Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null || getClass() != obj.getClass())
return false;
final PlaceEntity other = (PlaceEntity) obj;
return Objects.equals(other.getId(), id)
&& Objects.equals(other.getName(), name);
}
}

View File

@ -0,0 +1,11 @@
package com.example.demo.places.repository;
import java.util.Optional;
import org.springframework.data.repository.CrudRepository;
import com.example.demo.places.model.PlaceEntity;
public interface PlaceRepository extends CrudRepository<PlaceEntity, Long> {
Optional<PlaceEntity> findByNameIgnoreCase(String name);
}

View File

@ -0,0 +1,62 @@
package com.example.demo.places.service;
import java.util.List;
import java.util.stream.StreamSupport;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import com.example.demo.core.error.NotFoundException;
import com.example.demo.places.model.PlaceEntity;
import com.example.demo.places.repository.PlaceRepository;
@Service
public class PlaceService {
private final PlaceRepository repository;
public PlaceService(PlaceRepository repository) {
this.repository = repository;
}
private void checkName(String name) {
if (repository.findByNameIgnoreCase(name).isPresent()) {
throw new IllegalArgumentException(
String.format("Place with name %s is already exists", name));
}
}
@Transactional(readOnly = true)
public List<PlaceEntity> getAll() {
return StreamSupport.stream(repository.findAll().spliterator(), false).toList();
}
@Transactional(readOnly = true)
public PlaceEntity get(Long id) {
return repository.findById(id)
.orElseThrow(() -> new NotFoundException(PlaceEntity.class, id));
}
@Transactional
public PlaceEntity create(PlaceEntity entity) {
if (entity == null) {
throw new IllegalArgumentException("Entity is null");
}
checkName(entity.getName());
return repository.save(entity);
}
@Transactional
public PlaceEntity update(Long id, PlaceEntity entity) {
final PlaceEntity existsEntity = get(id);
existsEntity.setName(entity.getName());
return repository.save(existsEntity);
}
@Transactional
public PlaceEntity delete(Long id) {
final PlaceEntity existsEntity = get(id);
repository.delete(existsEntity);
return existsEntity;
}
}

View File

@ -0,0 +1,65 @@
package com.example.demo.types.api;
import java.util.List;
import org.modelmapper.ModelMapper;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import com.example.demo.core.configuration.Constants;
import com.example.demo.types.model.TypeEntity;
import com.example.demo.types.service.TypeService;
import jakarta.validation.Valid;
@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 @Valid 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,29 @@
package com.example.demo.types.api;
import com.fasterxml.jackson.annotation.JsonProperty;
import jakarta.validation.constraints.NotBlank;
public class TypeDto {
@JsonProperty(access = JsonProperty.Access.READ_ONLY)
private Long id;
@NotBlank
private String name;
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;
}
}

View File

@ -0,0 +1,49 @@
package com.example.demo.types.model;
import java.util.Objects;
import com.example.demo.core.model.BaseEntity;
import jakarta.persistence.Column;
import jakarta.persistence.Entity;
import jakarta.persistence.Table;
@Entity
@Table(name = "types")
public class TypeEntity extends BaseEntity {
@Column(nullable = false, unique = true)
private String name;
public TypeEntity() {
}
public TypeEntity(String name) {
this.name = name;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
@Override
public int hashCode() {
return Objects.hash(id, name);
}
@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);
}
}

View File

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

View File

@ -0,0 +1,62 @@
package com.example.demo.types.service;
import java.util.List;
import java.util.stream.StreamSupport;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import com.example.demo.core.error.NotFoundException;
import com.example.demo.types.model.TypeEntity;
import com.example.demo.types.repository.TypeRepository;
@Service
public class TypeService {
private final TypeRepository repository;
public TypeService(TypeRepository repository) {
this.repository = repository;
}
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());
return repository.save(existsEntity);
}
@Transactional
public TypeEntity delete(Long id) {
final TypeEntity existsEntity = get(id);
repository.delete(existsEntity);
return existsEntity;
}
}

View File

@ -0,0 +1,67 @@
package com.example.demo.users.api;
import org.modelmapper.ModelMapper;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import com.example.demo.core.api.PageDto;
import com.example.demo.core.api.PageDtoMapper;
import com.example.demo.core.configuration.Constants;
import com.example.demo.users.model.UserEntity;
import com.example.demo.users.service.UserService;
import jakarta.validation.Valid;
@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 PageDto<UserDto> getAll(
@RequestParam(name = "page", defaultValue = "0") int page,
@RequestParam(name = "size", defaultValue = Constants.DEFAULT_PAGE_SIZE) int size) {
return PageDtoMapper.toDto(userService.getAll(page, size), this::toDto);
}
@GetMapping("/{id}")
public UserDto get(@PathVariable(name = "id") Long id) {
return toDto(userService.get(id));
}
@PostMapping
public UserDto create(@RequestBody @Valid UserDto dto) {
return toDto(userService.create(toEntity(dto)));
}
@PutMapping("/{id}")
public UserDto update(@PathVariable(name = "id") Long id, @RequestBody @Valid UserDto dto) {
return toDto(userService.update(id, toEntity(dto)));
}
@DeleteMapping("/{id}")
public UserDto delete(@PathVariable(name = "id") Long id) {
return toDto(userService.delete(id));
}
}

View File

@ -0,0 +1,61 @@
package com.example.demo.users.api;
import com.fasterxml.jackson.annotation.JsonProperty;
import jakarta.validation.constraints.NotBlank;
import jakarta.validation.constraints.Size;
public class UserDto {
@JsonProperty(access = JsonProperty.Access.READ_ONLY)
private Long id;
@NotBlank
private String handle;
@NotBlank
private String email;
@NotBlank
private String password;
@NotBlank
@Size(min = 1, max = 20)
private String accessLevel;
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public String getHandle() {
return handle;
}
public void setHandle(String handle) {
this.handle = handle;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
public String getAccessLevel() {
return accessLevel;
}
public void setAccessLevel(String accessLevel) {
this.accessLevel = accessLevel;
}
}

View File

@ -0,0 +1,88 @@
package com.example.demo.users.model;
import java.util.Objects;
import com.example.demo.core.model.BaseEntity;
import jakarta.persistence.CascadeType;
import jakarta.persistence.Column;
import jakarta.persistence.Entity;
import jakarta.persistence.OneToMany;
import jakarta.persistence.OrderBy;
import jakarta.persistence.Table;
@Entity
@Table(name = "users")
public class UserEntity extends BaseEntity {
@Column(nullable = false, unique = true)
private String handle;
@Column(nullable = false, unique = true)
private String email;
@Column(nullable = false)
private String password;
@Column(nullable = false)
private String accessLevel;
public UserEntity() {
}
public UserEntity(String handle, String email, String password, String accessLevel) {
this.handle = handle;
this.email = email;
this.password = password;
this.accessLevel = accessLevel;
}
public String getHandle() {
return handle;
}
public void setHandle(String handle) {
this.handle = handle;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
public String getAccessLevel() {
return accessLevel;
}
public void setAccessLevel(String accessLevel) {
this.accessLevel = accessLevel;
}
@Override
public int hashCode() {
return Objects.hash(id, handle, email, password, accessLevel);
}
@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.getHandle(), handle)
&& Objects.equals(other.getEmail(), email)
&& Objects.equals(other.getPassword(), password)
&& Objects.equals(other.getAccessLevel(), accessLevel);
}
}

View File

@ -0,0 +1,14 @@
package com.example.demo.users.repository;
import java.util.Optional;
import org.springframework.data.repository.CrudRepository;
import org.springframework.data.repository.PagingAndSortingRepository;
import com.example.demo.users.model.UserEntity;
public interface UserRepository
extends CrudRepository<UserEntity, Long>, PagingAndSortingRepository<UserEntity, Long> {
Optional<UserEntity> findByHandleIgnoreCase(String handle);
}

View File

@ -0,0 +1,73 @@
package com.example.demo.users.service;
import java.util.List;
import java.util.stream.StreamSupport;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import com.example.demo.core.error.NotFoundException;
import com.example.demo.users.model.UserEntity;
import com.example.demo.users.repository.UserRepository;
@Service
public class UserService {
private final UserRepository repository;
public UserService(UserRepository repository) {
this.repository = repository;
}
private void checkHandle(String handle) {
if (repository.findByHandleIgnoreCase(handle).isPresent()) {
throw new IllegalArgumentException(
String.format("User with login %s is already exists", handle));
}
}
@Transactional(readOnly = true)
public List<UserEntity> getAll() {
return StreamSupport.stream(repository.findAll().spliterator(), false).toList();
}
@Transactional(readOnly = true)
public Page<UserEntity> getAll(int page, int size) {
return repository.findAll(PageRequest.of(page, size));
}
@Transactional(readOnly = true)
public UserEntity get(long id) {
return repository.findById(id)
.orElseThrow(() -> new NotFoundException(UserEntity.class, id));
}
@Transactional
public UserEntity create(UserEntity entity) {
if (entity == null) {
throw new IllegalArgumentException("Entity is null");
}
checkHandle(entity.getHandle());
return repository.save(entity);
}
@Transactional
public UserEntity update(long id, UserEntity entity) {
final UserEntity existsEntity = get(id);
existsEntity.setHandle(entity.getHandle());
existsEntity.setEmail(entity.getEmail());
existsEntity.setPassword(entity.getPassword());
existsEntity.setAccessLevel(entity.getAccessLevel());
repository.save(existsEntity);
return existsEntity;
}
@Transactional
public UserEntity delete(long id) {
final UserEntity existsEntity = get(id);
repository.delete(existsEntity);
return existsEntity;
}
}

View File

@ -1 +1,20 @@
# Server
spring.main.banner-mode=off
server.port=8081
# 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

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

View File

@ -0,0 +1,178 @@
package com.example.demo;
import java.time.LocalDate;
import java.util.List;
import java.util.Optional;
import org.junit.jupiter.api.AfterEach;
import org.junit.jupiter.api.Assertions;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.MethodOrderer.OrderAnnotation;
import org.junit.jupiter.api.Order;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.TestMethodOrder;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.dao.DataIntegrityViolationException;
import org.springframework.transaction.annotation.Transactional;
import com.example.demo.ivents.model.IventEntity;
import com.example.demo.ivents.service.IventService;
import com.example.demo.types.model.TypeEntity;
import com.example.demo.types.service.TypeService;
import com.example.demo.places.model.PlaceEntity;
import com.example.demo.places.service.PlaceService;
import com.example.demo.core.error.NotFoundException;
import jakarta.persistence.EntityManager;
@SpringBootTest
@TestMethodOrder(OrderAnnotation.class)
class IventServiceTests {
@Autowired
private TypeService typeService;
@Autowired
private PlaceService placeService;
@Autowired
private IventService iventService;
private IventEntity ivent;
@BeforeEach
void createData() {
removeData();
final var type = typeService.create(new TypeEntity("Концерт"));
final var place = placeService.create(new PlaceEntity("USA, California"));
ivent = iventService.create(new IventEntity(
"Slipknot",
type,
LocalDate.of(2023, 10, 15),
"Описание Slipknot",
"Участники группы Slipknot",
2500.33,
30,
place,
""));
iventService.create(new IventEntity(
"Placebo",
type,
LocalDate.of(2024, 2, 13),
"Описание Placebo",
"Группа Placebo",
2500.33,
30,
place,
""));
iventService.create(new IventEntity(
"Radiohead",
type,
LocalDate.of(2024, 2, 15),
"Описание Radiohead",
"Участники Radiohead",
2500.33,
30,
place,
""));
}
@AfterEach
void removeData() {
iventService.getAll(0L, 0L, null, null).forEach(item -> iventService.delete(item.getId()));
typeService.getAll().forEach(item -> typeService.delete(item.getId()));
placeService.getAll().forEach(item -> placeService.delete(item.getId()));
}
@Transactional
@Test
@Order(1)
void createTest() {
Assertions.assertEquals(3, iventService.getAll(0L, 0L, null, null).size());
Assertions.assertEquals(ivent, iventService.get(ivent.getId()));
}
@Test
@Order(2)
void getTest() {
Assertions.assertThrows(NotFoundException.class, () -> iventService.get(0L));
}
@Test
@Order(3)
void sortDates() {
LocalDate start = LocalDate.of(2024, 1, 15);
LocalDate end = LocalDate.of(2024, 5, 15);
List<IventEntity> list = iventService.getAll(0L, 0L, start, end);
Assertions.assertEquals(2, list.size());
}
@Test
@Order(4)
void createNullableTest() {
final IventEntity nullIvent = new IventEntity(
null,
null,
null,
null,
null ,
null,
null,
null,
"");
Assertions.assertThrows(DataIntegrityViolationException.class, () -> iventService.create(nullIvent));
}
@Transactional
@Test
@Order(5)
void updateTest() {
final String test = "TEST";
final TypeEntity type = typeService.create(new TypeEntity("Кино"));
final PlaceEntity place = placeService.create(new PlaceEntity("Germany, Berlin"));
final String oldName = ivent.getName();
final TypeEntity oldType = ivent.getType();
final PlaceEntity oldPlace = ivent.getPlace();
final IventEntity newEntity = iventService.update(ivent.getId(), new IventEntity(
test,
type,
LocalDate.of(2023, 10, 15),
"Radiohead - британская рок-группа, образованная в 1985 году.",
"Участниками Radiohead являются:<....>",
2500.33,
30,
place,
""));
Assertions.assertEquals(3, iventService.getAll(0L, 0L, null, null).size());
Assertions.assertEquals(newEntity, iventService.get(ivent.getId()));
Assertions.assertEquals(test, newEntity.getName());
Assertions.assertEquals(type, newEntity.getType());
Assertions.assertEquals(place, newEntity.getPlace());
Assertions.assertNotEquals(oldName, newEntity.getName());
Assertions.assertNotEquals(oldType, newEntity.getType());
Assertions.assertNotEquals(oldPlace, newEntity.getPlace());
}
@Test
@Order(6)
void deleteTest() {
iventService.delete(ivent.getId());
Assertions.assertEquals(2, iventService.getAll(0L, 0L, null, null).size());
final IventEntity newEntity = iventService.create(new IventEntity(ivent.getName(), ivent.getType(),
ivent.getDate(), ivent.getDesc(), ivent.getOther(), ivent.getPrice(), ivent.getCount(),
ivent.getPlace(), ivent.getImage()));
Assertions.assertEquals(1, typeService.getAll().size());
Assertions.assertEquals(1, placeService.getAll().size());
Assertions.assertNotEquals(ivent.getId(), newEntity.getId());
}
}

View File

@ -0,0 +1,81 @@
package com.example.demo;
import org.junit.jupiter.api.AfterEach;
import org.junit.jupiter.api.Assertions;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.dao.DataIntegrityViolationException;
import com.example.demo.places.model.PlaceEntity;
import com.example.demo.places.service.PlaceService;
import com.example.demo.types.model.TypeEntity;
import com.example.demo.core.error.NotFoundException;
@SpringBootTest
class PlaceServiceTests {
@Autowired
private PlaceService placeService;
private PlaceEntity place;
@BeforeEach
void createData() {
removeData();
place = placeService.create(new PlaceEntity("USA, California"));
placeService.create(new PlaceEntity("Germany, Berlin"));
placeService.create(new PlaceEntity("UK, London"));
}
@AfterEach
void removeData() {
placeService.getAll().forEach(item -> placeService.delete(item.getId()));
}
@Test
void getTest() {
Assertions.assertThrows(NotFoundException.class, () -> placeService.get(0L));
}
@Test
void createTest() {
Assertions.assertEquals(3, placeService.getAll().size());
Assertions.assertEquals(place, placeService.get(place.getId()));
}
@Test
void createNotUniqueTest() {
final PlaceEntity nonUniquePlace = new PlaceEntity("USA, California");
Assertions.assertThrows(IllegalArgumentException.class, () -> placeService.create(nonUniquePlace));
}
@Test
void createNullableTest() {
final PlaceEntity nullablePlace= new PlaceEntity(null);
Assertions.assertThrows(DataIntegrityViolationException.class, () -> placeService.create(nullablePlace));
}
@Test
void updateTest() {
final String test = "TEST";
final String oldName = place.getName();
final PlaceEntity newEntity = placeService.update(place.getId(), new PlaceEntity(test));
Assertions.assertEquals(3, placeService.getAll().size());
Assertions.assertEquals(newEntity, placeService.get(place.getId()));
Assertions.assertEquals(test, newEntity.getName());
Assertions.assertNotEquals(oldName, newEntity.getName());
}
@Test
void deleteTest() {
placeService.delete(place.getId());
Assertions.assertEquals(2, placeService.getAll().size());
final PlaceEntity newEntity = placeService.create(new PlaceEntity(place.getName()));
Assertions.assertEquals(3, placeService.getAll().size());
Assertions.assertNotEquals(place.getId(), newEntity.getId());
}
}

View File

@ -0,0 +1,79 @@
package com.example.demo;
import org.junit.jupiter.api.AfterEach;
import org.junit.jupiter.api.Assertions;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.dao.DataIntegrityViolationException;
import com.example.demo.types.model.TypeEntity;
import com.example.demo.types.service.TypeService;
import com.example.demo.core.error.NotFoundException;
@SpringBootTest
class TypeServiceTests {
@Autowired
private TypeService typeService;
private TypeEntity type;
@BeforeEach
void createData() {
removeData();
type = typeService.create(new TypeEntity("USA, California"));
typeService.create(new TypeEntity("Germany, Berlin"));
typeService.create(new TypeEntity("UK, London"));
}
@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("USA, California");
Assertions.assertThrows(IllegalArgumentException.class, () -> typeService.create(nonUniqueType));
}
@Test
void createNullableTest() {
final TypeEntity nullableType= new TypeEntity(null);
Assertions.assertThrows(DataIntegrityViolationException.class, () -> typeService.create(nullableType));
}
@Test
void updateTest() {
final String test = "TEST";
final String oldName = type.getName();
final TypeEntity newEntity = typeService.update(type.getId(), new TypeEntity(test));
Assertions.assertEquals(3, typeService.getAll().size());
Assertions.assertEquals(newEntity, typeService.get(type.getId()));
Assertions.assertEquals(test, newEntity.getName());
Assertions.assertNotEquals(oldName, newEntity.getName());
}
@Test
void deleteTest() {
typeService.delete(type.getId());
Assertions.assertEquals(2, typeService.getAll().size());
final TypeEntity newEntity = typeService.create(new TypeEntity(type.getName()));
Assertions.assertEquals(3, typeService.getAll().size());
Assertions.assertNotEquals(type.getId(), newEntity.getId());
}
}

View File

@ -0,0 +1,86 @@
package com.example.demo;
import org.junit.jupiter.api.AfterEach;
import org.junit.jupiter.api.Assertions;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.dao.DataIntegrityViolationException;
import org.springframework.transaction.annotation.Transactional;
import com.example.demo.users.model.UserEntity;
import com.example.demo.users.service.UserService;
import com.example.demo.core.error.NotFoundException;
@SpringBootTest
class UserServiceTests {
@Autowired
private UserService userService;
private UserEntity user;
@BeforeEach
void createData() {
removeData();
user = userService.create(new UserEntity("Admin", "admin@gmail.com", "admin", "admin"));
userService.create(new UserEntity("Milana", "milana@gmail.com", "milana", "user"));
userService.create(new UserEntity("TestUser", "user@gmail.com", "test", "user"));
}
@AfterEach
void removeData() {
userService.getAll().forEach(item -> userService.delete(item.getId()));
}
@Test
void getTest() {
Assertions.assertThrows(NotFoundException.class, () -> userService.get(0L));
}
@Transactional
@Test
void createTest() {
Assertions.assertEquals(3, userService.getAll().size());
Assertions.assertEquals(user, userService.get(user.getId()));
}
@Test
void createNotUniqueTest() {
final UserEntity nonUniqueUser = new UserEntity("Milana", "milana@gmail.com", "milana", "user");
Assertions.assertThrows(IllegalArgumentException.class, () -> userService.create(nonUniqueUser));
}
@Test
void createNullableTest() {
final UserEntity nullableUser = new UserEntity(null, "email@gamil.com", "pass", "admin");
Assertions.assertThrows(DataIntegrityViolationException.class, () -> userService.create(nullableUser));
}
@Transactional
@Test
void updateTest() {
final String test = "TEST";
final String oldLogin = user.getHandle();
final UserEntity newEntity = userService.update(user.getId(),
new UserEntity(test, "admin@gmail.com", "admin", "admin"));
Assertions.assertEquals(3, userService.getAll().size());
Assertions.assertEquals(newEntity, userService.get(user.getId()));
Assertions.assertEquals(test, newEntity.getHandle());
Assertions.assertNotEquals(oldLogin, newEntity.getHandle());
}
@Test
void deleteTest() {
userService.delete(user.getId());
Assertions.assertEquals(2, userService.getAll().size());
final UserEntity newEntity = userService
.create(new UserEntity("Admin", "admin@gmail.com", "admin", "admin"));
Assertions.assertEquals(3, userService.getAll().size());
Assertions.assertNotEquals(user.getId(), newEntity.getId());
}
}