LabWork02
This commit is contained in:
parent
d329b07ab0
commit
6f0a431bd9
@ -17,6 +17,10 @@ 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'
|
||||
|
||||
testImplementation 'org.springframework.boot:spring-boot-starter-test'
|
||||
}
|
||||
|
||||
|
@ -1,13 +1,56 @@
|
||||
package com.example.demo;
|
||||
|
||||
import java.util.Objects;
|
||||
|
||||
import org.slf4j.Logger;
|
||||
import org.slf4j.LoggerFactory;
|
||||
import org.springframework.boot.CommandLineRunner;
|
||||
import org.springframework.boot.SpringApplication;
|
||||
import org.springframework.boot.autoconfigure.SpringBootApplication;
|
||||
|
||||
@SpringBootApplication
|
||||
public class DemoApplication {
|
||||
import com.example.demo.items.model.ItemEntity;
|
||||
import com.example.demo.items.service.ItemService;
|
||||
import com.example.demo.types.model.TypeEntity;
|
||||
import com.example.demo.types.service.TypeService;
|
||||
|
||||
@SpringBootApplication
|
||||
public class DemoApplication implements CommandLineRunner {
|
||||
// Логгер
|
||||
private final Logger log = LoggerFactory.getLogger(DemoApplication.class);
|
||||
|
||||
// Бизнес-логика для сущности "Тип" (Тип книг)
|
||||
private final TypeService typeService;
|
||||
|
||||
// Бизнес-логика для сущности "Заказ" (Заказ, содержащий книги)
|
||||
private final ItemService itemService;
|
||||
|
||||
// Конструктор
|
||||
public DemoApplication(TypeService typeService, ItemService itemService) {
|
||||
this.typeService = typeService;
|
||||
this.itemService = itemService;
|
||||
}
|
||||
|
||||
// Входная точка программы
|
||||
public static void main(String[] args) {
|
||||
SpringApplication.run(DemoApplication.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(null, "Protection"));
|
||||
final var type2 = typeService.create(new TypeEntity(null, "Sharpness"));
|
||||
final var type3 = typeService.create(new TypeEntity(null, "Infinity"));
|
||||
|
||||
log.info("Create default items values");
|
||||
itemService.create(new ItemEntity(null, type1, 50.00, 20));
|
||||
itemService.create(new ItemEntity(null, type1, 12.00, 3));
|
||||
itemService.create(new ItemEntity(null, type2, 15.00, 30));
|
||||
itemService.create(new ItemEntity(null, type2, 64.00, 10));
|
||||
itemService.create(new ItemEntity(null, type2, 15.00, 6));
|
||||
itemService.create(new ItemEntity(null, type3, 80.00, 6));
|
||||
itemService.create(new ItemEntity(null, type3, 64.00, 3));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
@ -0,0 +1,10 @@
|
||||
package com.example.demo.core.configuration;
|
||||
|
||||
// Класс для задания констант
|
||||
public class Constants {
|
||||
// Базовый префикс REST-API
|
||||
public static final String API_URL = "/api/1.0";
|
||||
|
||||
private Constants() {
|
||||
}
|
||||
}
|
@ -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;
|
||||
|
||||
// Конфигурация для библиотеки ModelMapper
|
||||
@Configuration
|
||||
public class MapperConfiguration {
|
||||
@Bean
|
||||
ModelMapper modelMapper() {
|
||||
return new ModelMapper();
|
||||
}
|
||||
}
|
@ -0,0 +1,16 @@
|
||||
package com.example.demo.core.configuration;
|
||||
|
||||
import org.springframework.context.annotation.Configuration;
|
||||
import org.springframework.lang.NonNull;
|
||||
import org.springframework.web.servlet.config.annotation.CorsRegistry;
|
||||
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
|
||||
|
||||
// Конфигурация для отключения Cors-проверки
|
||||
@Configuration
|
||||
public class WebConfiguration implements WebMvcConfigurer {
|
||||
@Override
|
||||
public void addCorsMappings(@NonNull CorsRegistry registry) {
|
||||
registry.addMapping("/**")
|
||||
.allowedMethods("GET", "POST", "PUT", "DELETE");
|
||||
}
|
||||
}
|
@ -0,0 +1,8 @@
|
||||
package com.example.demo.core.error;
|
||||
|
||||
// Собственное непроверяемое исключение
|
||||
public class NotFoundException extends RuntimeException {
|
||||
public NotFoundException(Long id) {
|
||||
super(String.format("Entity with id [%s] is not found or not exists", id));
|
||||
}
|
||||
}
|
@ -0,0 +1,26 @@
|
||||
package com.example.demo.core.model;
|
||||
|
||||
// Абстрактный класс для базовой сущности
|
||||
public abstract class BaseEntity {
|
||||
// Идентфикатор
|
||||
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;
|
||||
}
|
||||
}
|
@ -0,0 +1,24 @@
|
||||
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();
|
||||
}
|
@ -0,0 +1,68 @@
|
||||
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();
|
||||
}
|
||||
}
|
@ -0,0 +1,84 @@
|
||||
package com.example.demo.items.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.RequestParam;
|
||||
import org.springframework.web.bind.annotation.RestController;
|
||||
|
||||
import com.example.demo.core.configuration.Constants;
|
||||
import com.example.demo.items.model.ItemEntity;
|
||||
import com.example.demo.items.service.ItemService;
|
||||
import com.example.demo.types.service.TypeService;
|
||||
|
||||
import jakarta.validation.Valid;
|
||||
|
||||
// Контроллер для сущности "Заказ" (Заказ, содержащий книги)
|
||||
@RestController
|
||||
@RequestMapping(Constants.API_URL + "/item")
|
||||
public class ItemController {
|
||||
// Бизнес-логика для сущности "Заказ" (Заказ, содержащий книги)
|
||||
private final ItemService itemService;
|
||||
|
||||
// Бизнес-логика для сущности "Тип" (Тип книги)
|
||||
private final TypeService typeService;
|
||||
|
||||
// Библиотека для преобразования сущности
|
||||
private final ModelMapper modelMapper;
|
||||
|
||||
// Конструктор
|
||||
public ItemController(ItemService itemService, TypeService typeService, ModelMapper modelMapper) {
|
||||
this.itemService = itemService;
|
||||
this.typeService = typeService;
|
||||
this.modelMapper = modelMapper;
|
||||
}
|
||||
|
||||
// Преобразовать из сущности в DTO
|
||||
private ItemDto toDto(ItemEntity entity) {
|
||||
return modelMapper.map(entity, ItemDto.class);
|
||||
}
|
||||
|
||||
// Преобразовать из DTO в сущность
|
||||
private ItemEntity toEntity(@Valid ItemDto dto) {
|
||||
final ItemEntity entity = modelMapper.map(dto, ItemEntity.class);
|
||||
entity.setType(typeService.get(dto.getTypeId()));
|
||||
return entity;
|
||||
}
|
||||
|
||||
// Получить все элементы или по заданному фильтру
|
||||
@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 @Valid ItemDto dto) {
|
||||
return toDto(itemService.create(toEntity(dto)));
|
||||
}
|
||||
|
||||
// Изменить элемент
|
||||
@PutMapping("/{id}")
|
||||
public ItemDto update(@PathVariable(name = "id") Long id, @RequestBody @Valid ItemDto dto) {
|
||||
return toDto(itemService.update(id, toEntity(dto)));
|
||||
}
|
||||
|
||||
// Удалить элемент
|
||||
@DeleteMapping("/{id}")
|
||||
public ItemDto delete(@PathVariable(name = "id") Long id) {
|
||||
return toDto(itemService.delete(id));
|
||||
}
|
||||
}
|
74
demo/src/main/java/com/example/demo/items/api/ItemDto.java
Normal file
74
demo/src/main/java/com/example/demo/items/api/ItemDto.java
Normal file
@ -0,0 +1,74 @@
|
||||
package com.example.demo.items.api;
|
||||
|
||||
import com.fasterxml.jackson.annotation.JsonProperty;
|
||||
|
||||
import jakarta.validation.constraints.Min;
|
||||
import jakarta.validation.constraints.NotNull;
|
||||
|
||||
// DTO для сущности "Заказ" (Заказ, содержащий книги)
|
||||
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;
|
||||
|
||||
// Получить идентификатор
|
||||
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;
|
||||
}
|
||||
}
|
@ -0,0 +1,81 @@
|
||||
package com.example.demo.items.model;
|
||||
|
||||
import java.util.Objects;
|
||||
|
||||
import com.example.demo.core.model.BaseEntity;
|
||||
import com.example.demo.types.model.TypeEntity;
|
||||
|
||||
// Сущность "Заказ" (Заказ, содержащий книги)
|
||||
public class ItemEntity extends BaseEntity {
|
||||
// Тип книги
|
||||
private TypeEntity type;
|
||||
|
||||
// Цена книги
|
||||
private Double price;
|
||||
|
||||
// Количество книг
|
||||
private Integer count;
|
||||
|
||||
// Конструктор по умолчанию
|
||||
public ItemEntity() {
|
||||
super();
|
||||
}
|
||||
|
||||
// Конструктор с параметрами для создания объекта
|
||||
public ItemEntity(Long id, TypeEntity type, Double price, Integer count) {
|
||||
super(id);
|
||||
this.type = type;
|
||||
this.price = price;
|
||||
this.count = count;
|
||||
}
|
||||
|
||||
// Получить тип книги
|
||||
public TypeEntity getType() {
|
||||
return type;
|
||||
}
|
||||
|
||||
// Установить тип книги
|
||||
public void setType(TypeEntity type) {
|
||||
this.type = type;
|
||||
}
|
||||
|
||||
// Получить стоимость книги
|
||||
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;
|
||||
}
|
||||
|
||||
// Получить хэш-код объекта
|
||||
@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);
|
||||
}
|
||||
}
|
@ -0,0 +1,11 @@
|
||||
package com.example.demo.items.repository;
|
||||
|
||||
import org.springframework.stereotype.Repository;
|
||||
|
||||
import com.example.demo.core.repository.MapRepository;
|
||||
import com.example.demo.items.model.ItemEntity;
|
||||
|
||||
// Хранилище для сущности "Заказ" (Заказ, содержащий книги)
|
||||
@Repository
|
||||
public class ItemRepository extends MapRepository<ItemEntity> {
|
||||
}
|
@ -0,0 +1,59 @@
|
||||
package com.example.demo.items.service;
|
||||
|
||||
import java.util.List;
|
||||
import java.util.Objects;
|
||||
import java.util.Optional;
|
||||
|
||||
import org.springframework.stereotype.Service;
|
||||
|
||||
import com.example.demo.core.error.NotFoundException;
|
||||
import com.example.demo.items.model.ItemEntity;
|
||||
import com.example.demo.items.repository.ItemRepository;
|
||||
|
||||
// Бизнес-логика для сущности "Заказ" (Заказ, содержащий книги)
|
||||
@Service
|
||||
public class ItemService {
|
||||
// Хранилище элементов
|
||||
private final ItemRepository repository;
|
||||
|
||||
// Конструктор
|
||||
public ItemService(ItemRepository repository) {
|
||||
this.repository = repository;
|
||||
}
|
||||
|
||||
// Получить все элементы или по заданному фильтру
|
||||
public List<ItemEntity> getAll(Long typeId) {
|
||||
if (Objects.equals(typeId, 0L)) {
|
||||
return repository.getAll();
|
||||
}
|
||||
return repository.getAll().stream()
|
||||
.filter(item -> item.getType().getId().equals(typeId))
|
||||
.toList();
|
||||
}
|
||||
|
||||
// Получить элемент по идентификатору
|
||||
public ItemEntity get(Long id) {
|
||||
return Optional.ofNullable(repository.get(id))
|
||||
.orElseThrow(() -> new NotFoundException(id));
|
||||
}
|
||||
|
||||
// Создать элемент
|
||||
public ItemEntity create(ItemEntity entity) {
|
||||
return repository.create(entity);
|
||||
}
|
||||
|
||||
// Изменить элемент
|
||||
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.update(existsEntity);
|
||||
}
|
||||
|
||||
// Удалить элемент
|
||||
public ItemEntity delete(Long id) {
|
||||
final ItemEntity existsEntity = get(id);
|
||||
return repository.delete(existsEntity);
|
||||
}
|
||||
}
|
@ -0,0 +1,76 @@
|
||||
package com.example.demo.messages.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.messages.model.MessageEntity;
|
||||
import com.example.demo.messages.service.MessageService;
|
||||
|
||||
import jakarta.validation.Valid;
|
||||
|
||||
// Контроллер для сущности "Сообщение"
|
||||
@RestController
|
||||
@RequestMapping(Constants.API_URL + "/message")
|
||||
public class MessageController {
|
||||
// Бизнес-логика для сущности "Сообщение"
|
||||
private final MessageService messageService;
|
||||
|
||||
// Библиотека для преобразования сущности
|
||||
private final ModelMapper modelMapper;
|
||||
|
||||
// Конструктор
|
||||
public MessageController(MessageService messageService, ModelMapper modelMapper) {
|
||||
this.messageService = messageService;
|
||||
this.modelMapper = modelMapper;
|
||||
}
|
||||
|
||||
// Преобразовать из сущности в DTO
|
||||
private MessageDto toDto(MessageEntity entity) {
|
||||
return modelMapper.map(entity, MessageDto.class);
|
||||
}
|
||||
|
||||
// Преобразовать из DTO в сущность
|
||||
private MessageEntity toEntity(@Valid MessageDto dto) {
|
||||
return modelMapper.map(dto, MessageEntity.class);
|
||||
}
|
||||
|
||||
// Получить все элементы
|
||||
@GetMapping
|
||||
public List<MessageDto> getAll() {
|
||||
return messageService.getAll().stream().map(this::toDto).toList();
|
||||
}
|
||||
|
||||
// Получить элемент по идентификатору
|
||||
@GetMapping("/{id}")
|
||||
public MessageDto get(@PathVariable(name = "id") Long id) {
|
||||
return toDto(messageService.get(id));
|
||||
}
|
||||
|
||||
// Создать элемент
|
||||
@PostMapping
|
||||
public MessageDto create(@RequestBody @Valid MessageDto dto) {
|
||||
return toDto(messageService.create(toEntity(dto)));
|
||||
}
|
||||
|
||||
// Изменить элемент
|
||||
@PutMapping("/{id}")
|
||||
public MessageDto update(@PathVariable(name = "id") Long id, @RequestBody @Valid MessageDto dto) {
|
||||
return toDto(messageService.update(id, toEntity(dto)));
|
||||
}
|
||||
|
||||
// Удалить элемент
|
||||
@DeleteMapping("/{id}")
|
||||
public MessageDto delete(@PathVariable(name = "id") Long id) {
|
||||
return toDto(messageService.delete(id));
|
||||
}
|
||||
}
|
@ -0,0 +1,85 @@
|
||||
package com.example.demo.messages.api;
|
||||
|
||||
import java.util.Date;
|
||||
|
||||
import com.fasterxml.jackson.annotation.JsonProperty;
|
||||
|
||||
import jakarta.validation.constraints.Min;
|
||||
import jakarta.validation.constraints.NotNull;
|
||||
|
||||
// DTO для сущности "Сообщение"
|
||||
public class MessageDto {
|
||||
// Идентфикатор
|
||||
@JsonProperty(access = JsonProperty.Access.READ_ONLY)
|
||||
private Long id;
|
||||
|
||||
// Имя отправителя
|
||||
@NotNull
|
||||
@Min(1)
|
||||
private String name;
|
||||
|
||||
// Электронный адрес почты отправителя
|
||||
@NotNull
|
||||
@Min(1)
|
||||
private String email;
|
||||
|
||||
// Текст сообщения
|
||||
@NotNull
|
||||
@Min(1)
|
||||
private String text;
|
||||
|
||||
// Дата отправки
|
||||
@NotNull
|
||||
@Min(1)
|
||||
private Date date;
|
||||
|
||||
// Получить идентификатор
|
||||
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 String getEmail() {
|
||||
return email;
|
||||
}
|
||||
|
||||
// Установить электронный адрес почты отправителя
|
||||
public void setEmail(String email) {
|
||||
this.email = email;
|
||||
}
|
||||
|
||||
// Получить текст сообщения
|
||||
public String getText() {
|
||||
return text;
|
||||
}
|
||||
|
||||
// Установить текст сообщения
|
||||
public void setText(String text) {
|
||||
this.text = text;
|
||||
}
|
||||
|
||||
// Получить дату отправления
|
||||
public Date getDate() {
|
||||
return date;
|
||||
}
|
||||
|
||||
// Установить дату отправления
|
||||
public void setDate(Date date) {
|
||||
this.date = date;
|
||||
}
|
||||
}
|
@ -0,0 +1,96 @@
|
||||
package com.example.demo.messages.model;
|
||||
|
||||
import java.util.Date;
|
||||
import java.util.Objects;
|
||||
|
||||
import com.example.demo.core.model.BaseEntity;
|
||||
|
||||
// Сущность "Сообщение"
|
||||
public class MessageEntity extends BaseEntity {
|
||||
// Имя отправителя
|
||||
private String name;
|
||||
|
||||
// Электронный адрес почты отправителя
|
||||
private String email;
|
||||
|
||||
// Текст сообщения
|
||||
private String text;
|
||||
|
||||
// Дата отправки
|
||||
private Date date;
|
||||
|
||||
// Конструктор по умолчанию
|
||||
public MessageEntity() {
|
||||
super();
|
||||
}
|
||||
|
||||
// Конструктор с параметрами для создания объекта
|
||||
public MessageEntity(Long id, String name, String email, String text) {
|
||||
super(id);
|
||||
this.name = name;
|
||||
this.email = email;
|
||||
this.text = text;
|
||||
this.date = new Date();
|
||||
}
|
||||
|
||||
// Получить имя отправителя
|
||||
public String getName() {
|
||||
return name;
|
||||
}
|
||||
|
||||
// Установить имя отправителя
|
||||
public void setName(String name) {
|
||||
this.name = name;
|
||||
}
|
||||
|
||||
// Получить электронный адрес почты отправителя
|
||||
public String getEmail() {
|
||||
return email;
|
||||
}
|
||||
|
||||
// Установить электронный адрес почты отправителя
|
||||
public void setEmail(String email) {
|
||||
this.email = email;
|
||||
}
|
||||
|
||||
// Получить текст сообщения
|
||||
public String getText() {
|
||||
return text;
|
||||
}
|
||||
|
||||
// Установить текст сообщения
|
||||
public void setText(String text) {
|
||||
this.text = text;
|
||||
}
|
||||
|
||||
// Получить дату отправления
|
||||
public Date getDate() {
|
||||
return date;
|
||||
}
|
||||
|
||||
// Установить дату отправления
|
||||
public void setDate(Date date) {
|
||||
this.date = date;
|
||||
}
|
||||
|
||||
// Получить хэш-код объекта
|
||||
@Override
|
||||
public int hashCode() {
|
||||
return Objects.hash(id, name, email, text, date);
|
||||
}
|
||||
|
||||
// Сравнить объекты
|
||||
@Override
|
||||
public boolean equals(Object obj) {
|
||||
if (this == obj)
|
||||
return true;
|
||||
if (obj == null || getClass() != obj.getClass())
|
||||
return false;
|
||||
final MessageEntity other = (MessageEntity) obj;
|
||||
return Objects.equals(other.getId(), id)
|
||||
&& Objects.equals(other.getName(), name)
|
||||
&& Objects.equals(other.getEmail(), email)
|
||||
&& Objects.equals(other.getText(), text)
|
||||
&& Objects.equals(other.getDate(), date);
|
||||
}
|
||||
}
|
@ -0,0 +1,11 @@
|
||||
package com.example.demo.messages.repository;
|
||||
|
||||
import org.springframework.stereotype.Repository;
|
||||
|
||||
import com.example.demo.core.repository.MapRepository;
|
||||
import com.example.demo.messages.model.MessageEntity;
|
||||
|
||||
// Хранилище для сущности "Сообщение"
|
||||
@Repository
|
||||
public class MessageRepository extends MapRepository<MessageEntity> {
|
||||
}
|
@ -0,0 +1,53 @@
|
||||
package com.example.demo.messages.service;
|
||||
|
||||
import java.util.List;
|
||||
import java.util.Optional;
|
||||
|
||||
import org.springframework.stereotype.Service;
|
||||
|
||||
import com.example.demo.core.error.NotFoundException;
|
||||
import com.example.demo.messages.model.MessageEntity;
|
||||
import com.example.demo.messages.repository.MessageRepository;
|
||||
|
||||
// Бизнес-логика для сущности "Сообщение"
|
||||
@Service
|
||||
public class MessageService {
|
||||
// Хранилище элементов
|
||||
private final MessageRepository repository;
|
||||
|
||||
// Конструктор
|
||||
public MessageService(MessageRepository repository) {
|
||||
this.repository = repository;
|
||||
}
|
||||
|
||||
// Получить все элементы
|
||||
public List<MessageEntity> getAll() {
|
||||
return repository.getAll();
|
||||
}
|
||||
|
||||
// Получить элемент по идентификатору
|
||||
public MessageEntity get(Long id) {
|
||||
return Optional.ofNullable(repository.get(id))
|
||||
.orElseThrow(() -> new NotFoundException(id));
|
||||
}
|
||||
|
||||
// Создать элемент
|
||||
public MessageEntity create(MessageEntity entity) {
|
||||
return repository.create(entity);
|
||||
}
|
||||
|
||||
// Изменить элемент
|
||||
public MessageEntity update(Long id, MessageEntity entity) {
|
||||
final MessageEntity existsEntity = get(id);
|
||||
existsEntity.setName(entity.getName());
|
||||
existsEntity.setEmail(entity.getEmail());
|
||||
existsEntity.setText(entity.getText());
|
||||
return repository.update(existsEntity);
|
||||
}
|
||||
|
||||
// Удалить элемент
|
||||
public MessageEntity delete(Long id) {
|
||||
final MessageEntity existsEntity = get(id);
|
||||
return repository.delete(existsEntity);
|
||||
}
|
||||
}
|
@ -0,0 +1,23 @@
|
||||
package com.example.demo.speaker.api;
|
||||
|
||||
import org.springframework.web.bind.annotation.GetMapping;
|
||||
import org.springframework.web.bind.annotation.RequestParam;
|
||||
import org.springframework.web.bind.annotation.RestController;
|
||||
|
||||
import com.example.demo.speaker.service.SpeakerService;
|
||||
|
||||
@RestController
|
||||
public class SpeakerController {
|
||||
private final SpeakerService speakerService;
|
||||
|
||||
public SpeakerController(SpeakerService speakerService) {
|
||||
this.speakerService = speakerService;
|
||||
}
|
||||
|
||||
@GetMapping
|
||||
public String hello(
|
||||
@RequestParam(value = "name", defaultValue = "Мир") String name,
|
||||
@RequestParam(value = "lang", defaultValue = "ru") String lang) {
|
||||
return speakerService.say(name, lang);
|
||||
}
|
||||
}
|
@ -0,0 +1,27 @@
|
||||
package com.example.demo.speaker.configuration;
|
||||
|
||||
import org.slf4j.Logger;
|
||||
import org.slf4j.LoggerFactory;
|
||||
import org.springframework.context.annotation.Bean;
|
||||
import org.springframework.context.annotation.Configuration;
|
||||
|
||||
import com.example.demo.speaker.domain.Speaker;
|
||||
import com.example.demo.speaker.domain.SpeakerEng;
|
||||
import com.example.demo.speaker.domain.SpeakerRus;
|
||||
|
||||
@Configuration
|
||||
public class SpeakerConfiguration {
|
||||
private final Logger log = LoggerFactory.getLogger(SpeakerConfiguration.class);
|
||||
|
||||
@Bean(value = "ru", initMethod = "init", destroyMethod = "destroy")
|
||||
public SpeakerRus createRusSpeaker() {
|
||||
log.info("Call createRusSpeaker()");
|
||||
return new SpeakerRus();
|
||||
}
|
||||
|
||||
@Bean(value = "en")
|
||||
public Speaker createEngSpeaker() {
|
||||
log.info("Call createEngSpeaker()");
|
||||
return new SpeakerEng();
|
||||
}
|
||||
}
|
@ -0,0 +1,5 @@
|
||||
package com.example.demo.speaker.domain;
|
||||
|
||||
public interface Speaker {
|
||||
String say();
|
||||
}
|
@ -0,0 +1,28 @@
|
||||
package com.example.demo.speaker.domain;
|
||||
|
||||
import org.slf4j.Logger;
|
||||
import org.slf4j.LoggerFactory;
|
||||
import org.springframework.stereotype.Component;
|
||||
|
||||
import jakarta.annotation.PostConstruct;
|
||||
import jakarta.annotation.PreDestroy;
|
||||
|
||||
@Component(value = "de")
|
||||
public class SpeakerDeu implements Speaker {
|
||||
private final Logger log = LoggerFactory.getLogger(SpeakerDeu.class);
|
||||
|
||||
@Override
|
||||
public String say() {
|
||||
return "Hallo";
|
||||
}
|
||||
|
||||
@PostConstruct
|
||||
public void init() {
|
||||
log.info("SpeakerDeu.init()");
|
||||
}
|
||||
|
||||
@PreDestroy
|
||||
public void destroy() {
|
||||
log.info("SpeakerDeu.destroy()");
|
||||
}
|
||||
}
|
@ -0,0 +1,26 @@
|
||||
package com.example.demo.speaker.domain;
|
||||
|
||||
import org.slf4j.Logger;
|
||||
import org.slf4j.LoggerFactory;
|
||||
import org.springframework.beans.factory.DisposableBean;
|
||||
import org.springframework.beans.factory.InitializingBean;
|
||||
|
||||
public class SpeakerEng implements Speaker, InitializingBean, DisposableBean {
|
||||
private final Logger log = LoggerFactory.getLogger(SpeakerEng.class);
|
||||
|
||||
@Override
|
||||
public String say() {
|
||||
return "Hello";
|
||||
}
|
||||
|
||||
@Override
|
||||
public void afterPropertiesSet() {
|
||||
log.info("SpeakerEng.afterPropertiesSet()");
|
||||
}
|
||||
|
||||
@Override
|
||||
public void destroy() {
|
||||
log.info("SpeakerEng.destroy()");
|
||||
|
||||
}
|
||||
}
|
@ -0,0 +1,21 @@
|
||||
package com.example.demo.speaker.domain;
|
||||
|
||||
import org.slf4j.Logger;
|
||||
import org.slf4j.LoggerFactory;
|
||||
|
||||
public class SpeakerRus implements Speaker {
|
||||
private final Logger log = LoggerFactory.getLogger(SpeakerRus.class);
|
||||
|
||||
@Override
|
||||
public String say() {
|
||||
return "Привет";
|
||||
}
|
||||
|
||||
public void init() {
|
||||
log.info("SpeakerRus.init()");
|
||||
}
|
||||
|
||||
public void destroy() {
|
||||
log.info("SpeakerRus.destroy()");
|
||||
}
|
||||
}
|
@ -0,0 +1,21 @@
|
||||
package com.example.demo.speaker.service;
|
||||
|
||||
import org.springframework.context.ApplicationContext;
|
||||
import org.springframework.stereotype.Service;
|
||||
|
||||
import com.example.demo.speaker.domain.Speaker;
|
||||
|
||||
@Service
|
||||
public class SpeakerService {
|
||||
private final ApplicationContext applicationContext;
|
||||
|
||||
public SpeakerService(ApplicationContext applicationContext) {
|
||||
this.applicationContext = applicationContext;
|
||||
}
|
||||
|
||||
public String say(String name, String lang) {
|
||||
@SuppressWarnings("null")
|
||||
final Speaker speaker = (Speaker) applicationContext.getBean(lang);
|
||||
return String.format("%s, %s!", speaker.say(), name);
|
||||
}
|
||||
}
|
@ -0,0 +1,76 @@
|
||||
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;
|
||||
}
|
||||
|
||||
// Преобразовать из сущности в DTO
|
||||
private TypeDto toDto(TypeEntity entity) {
|
||||
return modelMapper.map(entity, TypeDto.class);
|
||||
}
|
||||
|
||||
// Преобразовать из DTO в сущность
|
||||
private TypeEntity toEntity(@Valid 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 @Valid TypeDto dto) {
|
||||
return toDto(typeService.update(id, toEntity(dto)));
|
||||
}
|
||||
|
||||
// Удалить элемент
|
||||
@DeleteMapping("/{id}")
|
||||
public TypeDto delete(@PathVariable(name = "id") Long id) {
|
||||
return toDto(typeService.delete(id));
|
||||
}
|
||||
}
|
36
demo/src/main/java/com/example/demo/types/api/TypeDto.java
Normal file
36
demo/src/main/java/com/example/demo/types/api/TypeDto.java
Normal file
@ -0,0 +1,36 @@
|
||||
package com.example.demo.types.api;
|
||||
|
||||
import com.fasterxml.jackson.annotation.JsonProperty;
|
||||
|
||||
import jakarta.validation.constraints.NotBlank;
|
||||
|
||||
// DTO для сущности "Тип" (Тип книги)
|
||||
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;
|
||||
}
|
||||
}
|
@ -0,0 +1,50 @@
|
||||
package com.example.demo.types.model;
|
||||
|
||||
import java.util.Objects;
|
||||
|
||||
import com.example.demo.core.model.BaseEntity;
|
||||
|
||||
// Сущность "Тип" (Тип книги)
|
||||
public class TypeEntity extends BaseEntity {
|
||||
// Название типа
|
||||
private String name;
|
||||
|
||||
// Конструктор по умолчанию
|
||||
public TypeEntity() {
|
||||
super();
|
||||
}
|
||||
|
||||
// Конструктор с параметрами для создания объекта
|
||||
public TypeEntity(Long id, String name) {
|
||||
super(id);
|
||||
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);
|
||||
}
|
||||
}
|
@ -0,0 +1,11 @@
|
||||
package com.example.demo.types.repository;
|
||||
|
||||
import org.springframework.stereotype.Repository;
|
||||
|
||||
import com.example.demo.core.repository.MapRepository;
|
||||
import com.example.demo.types.model.TypeEntity;
|
||||
|
||||
// Хранилище для сущности "Тип" (Тип книги)
|
||||
@Repository
|
||||
public class TypeRepository extends MapRepository<TypeEntity> {
|
||||
}
|
@ -0,0 +1,51 @@
|
||||
package com.example.demo.types.service;
|
||||
|
||||
import java.util.List;
|
||||
import java.util.Optional;
|
||||
|
||||
import org.springframework.stereotype.Service;
|
||||
|
||||
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;
|
||||
}
|
||||
|
||||
// Получить все элементы
|
||||
public List<TypeEntity> getAll() {
|
||||
return repository.getAll();
|
||||
}
|
||||
|
||||
// Получить элемент по идентификатору
|
||||
public TypeEntity get(Long id) {
|
||||
return Optional.ofNullable(repository.get(id))
|
||||
.orElseThrow(() -> new NotFoundException(id));
|
||||
}
|
||||
|
||||
// Создать элемент
|
||||
public TypeEntity create(TypeEntity entity) {
|
||||
return repository.create(entity);
|
||||
}
|
||||
|
||||
// Изменить элемент
|
||||
public TypeEntity update(Long id, TypeEntity entity) {
|
||||
final TypeEntity existsEntity = get(id);
|
||||
existsEntity.setName(entity.getName());
|
||||
return repository.update(existsEntity);
|
||||
}
|
||||
|
||||
// Удалить элемент
|
||||
public TypeEntity delete(Long id) {
|
||||
final TypeEntity existsEntity = get(id);
|
||||
return repository.delete(existsEntity);
|
||||
}
|
||||
}
|
@ -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() {
|
||||
}
|
||||
|
||||
}
|
69
demo/src/test/java/com/example/demo/ItemServiceTests.java
Normal file
69
demo/src/test/java/com/example/demo/ItemServiceTests.java
Normal file
@ -0,0 +1,69 @@
|
||||
package com.example.demo;
|
||||
|
||||
import org.junit.jupiter.api.Assertions;
|
||||
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 com.example.demo.core.error.NotFoundException;
|
||||
import com.example.demo.items.model.ItemEntity;
|
||||
import com.example.demo.items.service.ItemService;
|
||||
import com.example.demo.types.model.TypeEntity;
|
||||
import com.example.demo.types.service.TypeService;
|
||||
|
||||
@SpringBootTest
|
||||
@TestMethodOrder(OrderAnnotation.class)
|
||||
public class ItemServiceTests {
|
||||
@Autowired
|
||||
private ItemService itemService;
|
||||
|
||||
@Autowired
|
||||
private TypeService typeService;
|
||||
|
||||
@Test
|
||||
void getTest() {
|
||||
Assertions.assertThrows(NotFoundException.class, () -> itemService.get(0L));
|
||||
}
|
||||
|
||||
@Test
|
||||
@Order(1)
|
||||
void createTest() {
|
||||
final TypeEntity type = typeService.create(new TypeEntity(null, "Protection"));
|
||||
itemService.create(new ItemEntity(null, type, 50.00, 20));
|
||||
itemService.create(new ItemEntity(null, type, 12.00, 3));
|
||||
final ItemEntity last = itemService.create(new ItemEntity(null, type, 15.00, 6));
|
||||
|
||||
Assertions.assertEquals(3, itemService.getAll(0L).size());
|
||||
Assertions.assertEquals(last, itemService.get(3L));
|
||||
}
|
||||
|
||||
@Test
|
||||
@Order(2)
|
||||
void updateTest() {
|
||||
final TypeEntity type = typeService.create(new TypeEntity(null, "Sharpness"));
|
||||
final ItemEntity entity = itemService.get(3L);
|
||||
final Double oldPrice = entity.getPrice();
|
||||
final ItemEntity newEntity = itemService.update(3L, new ItemEntity(null, type, 30.00, 6));
|
||||
|
||||
Assertions.assertEquals(3, itemService.getAll(0L).size());
|
||||
Assertions.assertEquals(newEntity, itemService.get(3L));
|
||||
Assertions.assertEquals(30.00, newEntity.getPrice());
|
||||
Assertions.assertNotEquals(oldPrice, newEntity.getPrice());
|
||||
}
|
||||
|
||||
@Test
|
||||
@Order(3)
|
||||
void deleteTest() {
|
||||
itemService.delete(3L);
|
||||
Assertions.assertEquals(2, itemService.getAll(0L).size());
|
||||
Assertions.assertThrows(NotFoundException.class, () -> itemService.get(3L));
|
||||
|
||||
final TypeEntity type = typeService.create(new TypeEntity(null, "Protection"));
|
||||
final ItemEntity newEntity = itemService.create(new ItemEntity(null, type, 50.00, 10));
|
||||
Assertions.assertEquals(3, itemService.getAll(0L).size());
|
||||
Assertions.assertEquals(4L, newEntity.getId());
|
||||
}
|
||||
}
|
65
demo/src/test/java/com/example/demo/MessageServiceTests.java
Normal file
65
demo/src/test/java/com/example/demo/MessageServiceTests.java
Normal file
@ -0,0 +1,65 @@
|
||||
package com.example.demo;
|
||||
|
||||
import org.junit.jupiter.api.Assertions;
|
||||
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 com.example.demo.core.error.NotFoundException;
|
||||
import com.example.demo.messages.model.MessageEntity;
|
||||
import com.example.demo.messages.service.MessageService;
|
||||
|
||||
@SpringBootTest
|
||||
@TestMethodOrder(OrderAnnotation.class)
|
||||
public class MessageServiceTests {
|
||||
@Autowired
|
||||
private MessageService messageService;
|
||||
|
||||
@Test
|
||||
void getTest() {
|
||||
Assertions.assertThrows(NotFoundException.class, () -> messageService.get(0L));
|
||||
}
|
||||
|
||||
@Test
|
||||
@Order(1)
|
||||
void createTest() {
|
||||
messageService.create(new MessageEntity(null, "Владимир", "vladimir@mail.ru", "Текст"));
|
||||
messageService.create(new MessageEntity(null, "Путин", "putin@mail.ru", "Молодец"));
|
||||
final MessageEntity last = messageService.create(new MessageEntity(null, "Политик", "lider@mail.ru", "Борец"));
|
||||
|
||||
Assertions.assertEquals(3, messageService.getAll().size());
|
||||
Assertions.assertEquals(last, messageService.get(3L));
|
||||
}
|
||||
|
||||
@Test
|
||||
@Order(2)
|
||||
void updateTest() {
|
||||
final String test = "TEST";
|
||||
final String email = "masenkin73@gmail.com";
|
||||
final String text = "aboba";
|
||||
final MessageEntity entity = messageService.get(3L);
|
||||
final String oldName = entity.getName();
|
||||
final MessageEntity newEntity = messageService.update(3L, new MessageEntity(1L, test, email, text));
|
||||
|
||||
Assertions.assertEquals(3, messageService.getAll().size());
|
||||
Assertions.assertEquals(newEntity, messageService.get(3L));
|
||||
Assertions.assertEquals(test, newEntity.getName());
|
||||
Assertions.assertNotEquals(oldName, newEntity.getName());
|
||||
}
|
||||
|
||||
@Test
|
||||
@Order(3)
|
||||
void deleteTest() {
|
||||
messageService.delete(3L);
|
||||
Assertions.assertEquals(2, messageService.getAll().size());
|
||||
final MessageEntity last = messageService.get(2L);
|
||||
Assertions.assertEquals(2L, last.getId());
|
||||
|
||||
final MessageEntity newEntity = messageService.create(new MessageEntity(null, "name", "address@email.com", "text"));
|
||||
Assertions.assertEquals(3, messageService.getAll().size());
|
||||
Assertions.assertEquals(4L, newEntity.getId());
|
||||
}
|
||||
}
|
38
demo/src/test/java/com/example/demo/SpeakerServiceTests.java
Normal file
38
demo/src/test/java/com/example/demo/SpeakerServiceTests.java
Normal file
@ -0,0 +1,38 @@
|
||||
package com.example.demo;
|
||||
|
||||
import org.junit.jupiter.api.Assertions;
|
||||
import org.junit.jupiter.api.Test;
|
||||
import org.springframework.beans.factory.NoSuchBeanDefinitionException;
|
||||
import org.springframework.beans.factory.annotation.Autowired;
|
||||
import org.springframework.boot.test.context.SpringBootTest;
|
||||
|
||||
import com.example.demo.speaker.service.SpeakerService;
|
||||
|
||||
@SpringBootTest
|
||||
class SpeakerServiceTests {
|
||||
@Autowired
|
||||
SpeakerService speakerService;
|
||||
|
||||
@Test
|
||||
void testSpeakerRus() {
|
||||
final String res = speakerService.say("Мир", "ru");
|
||||
Assertions.assertEquals("Привет, Мир!", res);
|
||||
}
|
||||
|
||||
@Test
|
||||
void testSpeakerEng() {
|
||||
final String res = speakerService.say("World", "en");
|
||||
Assertions.assertEquals("Hello, World!", res);
|
||||
}
|
||||
|
||||
@Test
|
||||
void testSpeakerDeu() {
|
||||
final String res = speakerService.say("Welt", "de");
|
||||
Assertions.assertEquals("Hallo, Welt!", res);
|
||||
}
|
||||
|
||||
@Test
|
||||
void testSpeakerErrorWired() {
|
||||
Assertions.assertThrows(NoSuchBeanDefinitionException.class, () -> speakerService.say("Мир", "rus"));
|
||||
}
|
||||
}
|
63
demo/src/test/java/com/example/demo/TypeServiceTests.java
Normal file
63
demo/src/test/java/com/example/demo/TypeServiceTests.java
Normal file
@ -0,0 +1,63 @@
|
||||
package com.example.demo;
|
||||
|
||||
import org.junit.jupiter.api.Assertions;
|
||||
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 com.example.demo.core.error.NotFoundException;
|
||||
import com.example.demo.types.model.TypeEntity;
|
||||
import com.example.demo.types.service.TypeService;
|
||||
|
||||
@SpringBootTest
|
||||
@TestMethodOrder(OrderAnnotation.class)
|
||||
class TypeServiceTests {
|
||||
@Autowired
|
||||
private TypeService typeService;
|
||||
|
||||
@Test
|
||||
void getTest() {
|
||||
Assertions.assertThrows(NotFoundException.class, () -> typeService.get(0L));
|
||||
}
|
||||
|
||||
@Test
|
||||
@Order(1)
|
||||
void createTest() {
|
||||
typeService.create(new TypeEntity(null, "Protection"));
|
||||
typeService.create(new TypeEntity(null, "Sharpness"));
|
||||
final TypeEntity last = typeService.create(new TypeEntity(null, "Infinity"));
|
||||
|
||||
Assertions.assertEquals(3, typeService.getAll().size());
|
||||
Assertions.assertEquals(last, typeService.get(3L));
|
||||
}
|
||||
|
||||
@Test
|
||||
@Order(2)
|
||||
void updateTest() {
|
||||
final String test = "TEST";
|
||||
final TypeEntity entity = typeService.get(3L);
|
||||
final String oldName = entity.getName();
|
||||
final TypeEntity newEntity = typeService.update(3L, new TypeEntity(1L, test));
|
||||
|
||||
Assertions.assertEquals(3, typeService.getAll().size());
|
||||
Assertions.assertEquals(newEntity, typeService.get(3L));
|
||||
Assertions.assertEquals(test, newEntity.getName());
|
||||
Assertions.assertNotEquals(oldName, newEntity.getName());
|
||||
}
|
||||
|
||||
@Test
|
||||
@Order(3)
|
||||
void deleteTest() {
|
||||
typeService.delete(3L);
|
||||
Assertions.assertEquals(2, typeService.getAll().size());
|
||||
final TypeEntity last = typeService.get(2L);
|
||||
Assertions.assertEquals(2L, last.getId());
|
||||
|
||||
final TypeEntity newEntity = typeService.create(new TypeEntity(null, "Infinity"));
|
||||
Assertions.assertEquals(3, typeService.getAll().size());
|
||||
Assertions.assertEquals(4L, newEntity.getId());
|
||||
}
|
||||
}
|
Loading…
x
Reference in New Issue
Block a user