Compare commits

..

43 Commits
main ... lab3

Author SHA1 Message Date
5453c9291b Добавил проверку на различие пользователей в сущности подписки 2024-05-12 21:04:07 +04:00
39988e9b9d Поправил тест 2024-05-12 20:57:41 +04:00
3980bc5181 Добавил пагинацию на подписки 2024-05-12 20:53:55 +04:00
a4c9701daf Удалил лишние файлы 2024-05-12 20:32:26 +04:00
d6d02480e7 Пофиксил обраную совместимость для тестов 2024-05-12 20:25:45 +04:00
1f77211e1a Добавил пагинацию на метод получения постов по польззователю 2024-05-12 20:16:51 +04:00
7dc8b5025e Убрал лишние импорты 2024-05-12 19:59:19 +04:00
ab6be427a7 Реализовал пагинацию для пользователей 2024-05-12 18:28:55 +04:00
a52cad114b Поправил .gitignore 2024-05-11 13:05:14 +04:00
6a73a65af0 Поправил модель поста, добавав userId, поправил получение постов по userId 2024-05-11 13:00:29 +04:00
edc6422797 Переделал запрос на получение списка постов по пользователю 2024-05-11 12:33:50 +04:00
a43e17addb Убрал лишний импорт в тесте постов 2024-05-11 11:33:12 +04:00
0824055b3e Работает, надо допилить получение списка постов пользователя запросом 2024-04-29 18:22:19 +04:00
dbea2f09ef Пофиксил репозитории моделей 2024-04-29 16:09:20 +04:00
5db8565157 Поправил тест для подписок, поправил подписки для бд 2024-04-29 15:52:27 +04:00
39f8b460d1 Починил тесты для постов 2024-04-29 12:06:45 +04:00
2c033cd280 Починил тест для пользователей 2024-04-29 11:53:52 +04:00
59349a09d4 Починил тест для подписок 2024-04-29 11:49:43 +04:00
70f69fbce3 Начал переделку PostAPI на персистентность 2024-04-15 17:52:47 +04:00
03e593f624 Фиксы для работоспособности юзеров 2024-04-15 17:39:44 +04:00
f40bda0dc0 Переделка UserAPI под персистентность 2024-04-15 17:15:44 +04:00
67feac64d8 Добавил декораторы с проверками для полей 2024-04-15 15:58:20 +04:00
c507b6e65d Подключение JPA к проекту 2024-04-15 15:49:17 +04:00
661a030dc2 Изменен тест на delete 2024-04-01 18:14:01 +04:00
a05eb93a91 Добавлены новые методы в контроллеры 2024-04-01 18:04:52 +04:00
59262cd474 Добавлены тесты для подписок 2024-04-01 17:57:28 +04:00
a80766ce83 Фикс с датой 2024-04-01 17:37:28 +04:00
6b33d6770b Добавлена проверка при создании поста, добавлены тесты для постов 2024-04-01 17:36:52 +04:00
5bdac82b52 Реализован тест для сущности User 2024-04-01 16:07:48 +04:00
31823bfece Фикс бина репозитория 2024-04-01 15:37:30 +04:00
f9344933b3 Фикс бинов 2024-04-01 15:36:50 +04:00
69ff864dc4 Фикс декортаора для контроллера Subscribe 2024-04-01 15:33:57 +04:00
2941c30add Фикс поля в сущности Post 2024-04-01 15:31:43 +04:00
82802c260f Изменено поле user в сущности Post 2024-04-01 15:30:54 +04:00
edbeef071d Реализован API Subscribes 2024-04-01 15:27:36 +04:00
4d9ec8408b Начал реализацию API Subscribes 2024-03-29 14:36:28 +04:00
a038c57d1f Реализовано API для Post 2024-03-29 14:08:53 +04:00
f5cfb3d95f Начал делать API для постов 2024-03-18 19:25:27 +04:00
7d5d88a16c Решена проблема с null`ом в POST запросе 2024-03-18 19:00:32 +04:00
e6923c88ba Добавил API для User, не работает 2024-03-18 18:47:36 +04:00
a7c30530f6 Реализовал api для UserDTO 2024-03-17 00:16:58 +04:00
aab5074411 Добавлен класс WebConfig 2024-03-16 23:21:30 +04:00
2e45bfca54 Реализован класс UserDTO 2024-03-16 23:20:32 +04:00
35 changed files with 1824 additions and 16 deletions

14
.vscode/launch.json vendored Normal file
View File

@ -0,0 +1,14 @@
{
"configurations": [
{
"type": "java",
"name": "Spring Boot-NekontakteApplication<nekontakte>",
"request": "launch",
"cwd": "${workspaceFolder}",
"mainClass": "com.example.nekontakte.NekontakteApplication",
"projectName": "nekontakte",
"args": "",
"envFile": "${workspaceFolder}/.env"
}
]
}

4
.vscode/settings.json vendored Normal file
View File

@ -0,0 +1,4 @@
{
"java.configuration.updateBuildConfiguration": "interactive",
"java.debug.settings.onBuildFailureProceed": true
}

View File

@ -35,3 +35,5 @@ out/
### VS Code ### ### VS Code ###
.vscode/ .vscode/
*.db

View File

@ -1,6 +1,6 @@
plugins { plugins {
id 'java' id 'java'
id 'org.springframework.boot' version '3.2.3' id 'org.springframework.boot' version '3.2.5'
id 'io.spring.dependency-management' version '1.1.4' id 'io.spring.dependency-management' version '1.1.4'
} }
@ -18,9 +18,11 @@ repositories {
dependencies { dependencies {
implementation 'org.springframework.boot:spring-boot-starter-web' implementation 'org.springframework.boot:spring-boot-starter-web'
implementation 'org.springdoc:springdoc-openapi-starter-webmvc-ui:2.3.0' implementation 'org.springdoc:springdoc-openapi-starter-webmvc-ui:2.3.0'
// implementation 'org.modelmapper:modelmapper:3.2.0' implementation 'org.modelmapper:modelmapper:3.2.0'
// implementation 'com.fasterxml.jackson.core:jackson-databind:2.12.5' // implementation 'com.fasterxml.jackson.core:jackson-databind:2.12.5'
testImplementation 'org.springframework.boot:spring-boot-starter-test' testImplementation 'org.springframework.boot:spring-boot-starter-test'
implementation 'org.springframework.boot:spring-boot-starter-data-jpa'
implementation 'com.h2database:h2:2.2.224'
} }
tasks.named('test') { tasks.named('test') {

View File

@ -1,13 +1,34 @@
package com.example.nekontakte; package com.example.nekontakte;
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.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication; import org.springframework.boot.autoconfigure.SpringBootApplication;
@SpringBootApplication @SpringBootApplication
public class NekontakteApplication { public class NekontakteApplication implements CommandLineRunner {
private final Logger _logger = LoggerFactory.getLogger(NekontakteApplication.class);
public NekontakteApplication() {
}
public static void main(String[] args) { public static void main(String[] args) {
SpringApplication.run(NekontakteApplication.class, args); SpringApplication.run(NekontakteApplication.class, args);
} }
@Override
public void run(String... args) throws Exception {
if (args.length > 0 && Objects.equals("--populate", args[0])) {
// todo: fill database with test data...
_logger.info("fill database with test data");
}
}
} }

View File

@ -0,0 +1,97 @@
package com.example.nekontakte.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.nekontakte.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.nekontakte.core.configurations;
public class Constants {
public static final String SEQUENCE_NAME = "hibernate_sequence";
public static final String API_URL = "/api";
private Constants() {
}
}

View File

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

View File

@ -0,0 +1,16 @@
package com.example.nekontakte.core.configurations;
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;
@Configuration
public class WebConfig implements WebMvcConfigurer {
@Override
public void addCorsMappings(@NonNull CorsRegistry registry) {
registry.addMapping("/**")
.allowedMethods("GET", "POST", "PUT", "DELETE");
}
}

View File

@ -0,0 +1,11 @@
package com.example.nekontakte.core.errors;
public class NotFoundException extends RuntimeException {
public NotFoundException(Integer id) {
super(String.format("Entity with id <[%s]> not found", id));
}
public <T> NotFoundException(Class<T> clazz, Integer id) {
super(String.format("%s with id [%s] not found or not exists", clazz.getSimpleName(), id));
}
}

View File

@ -0,0 +1,32 @@
package com.example.nekontakte.core.model;
import com.example.nekontakte.core.configurations.Constants;
import jakarta.persistence.GeneratedValue;
import jakarta.persistence.GenerationType;
import jakarta.persistence.SequenceGenerator;
import jakarta.persistence.Id;
import jakarta.persistence.MappedSuperclass;
@MappedSuperclass
public class BaseEntity {
@Id
@GeneratedValue(strategy = GenerationType.SEQUENCE, generator = Constants.SEQUENCE_NAME)
@SequenceGenerator(name = Constants.SEQUENCE_NAME, sequenceName = Constants.SEQUENCE_NAME, allocationSize = 1)
public Integer id;
protected BaseEntity() {
}
protected BaseEntity(Integer id) {
this.id = id;
}
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
}

View File

@ -0,0 +1,17 @@
package com.example.nekontakte.core.repository;
import java.util.List;
public interface BaseRepository<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,64 @@
package com.example.nekontakte.core.repository;
import java.util.List;
import java.util.Map;
import java.util.TreeMap;
import com.example.nekontakte.core.model.BaseEntity;
public abstract class MapRepository<E extends BaseEntity> implements BaseRepository<E, Integer> {
private final Map<Integer, E> entities = new TreeMap<>();
private Integer lastId = 0;
private boolean checkNull(E entity) {
if (get(entity.getId()) == null)
return false;
return true;
}
protected MapRepository() {
}
@Override
public List<E> getAll() {
return entities.values().stream().toList();
}
@Override
public E get(Integer 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 (checkNull(entity)) {
entities.put(entity.getId(), entity);
return entity;
}
return null;
}
@Override
public E delete(E entity) {
if (checkNull(entity)) {
entities.remove(entity.getId());
return entity;
}
return null;
}
@Override
public void deleteAll() {
entities.clear();
lastId = 0;
}
}

View File

@ -0,0 +1,81 @@
package com.example.nekontakte.posts.api;
import com.example.nekontakte.core.api.PageDto;
import com.example.nekontakte.core.api.PageDtoMapper;
import com.example.nekontakte.core.configurations.Constants;
import org.apache.coyote.BadRequestException;
import org.modelmapper.ModelMapper;
import org.springframework.data.domain.PageRequest;
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.nekontakte.posts.model.PostEntity;
import com.example.nekontakte.posts.service.PostService;
import com.example.nekontakte.users.service.UserService;
import jakarta.validation.Valid;
@RestController
@RequestMapping(Constants.API_URL + "/post")
public class PostController {
private final PostService postService;
private final ModelMapper modelMapper;
public PostController(PostService postService, ModelMapper modelMapper, UserService userService) {
this.modelMapper = modelMapper;
this.postService = postService;
}
private PostEntity toEntity(PostDTO dto) {
return modelMapper.map(dto, PostEntity.class);
}
private PostDTO toDTO(PostEntity entity) {
return modelMapper.map(entity, PostDTO.class);
}
@GetMapping
public PageDto<PostDTO> getAll(@RequestParam(name = "pageNumber", defaultValue = "0") Integer pageNumber,
@RequestParam(name = "pageSize", defaultValue = "5") Integer pageSize) {
PageRequest pageRequest = PageRequest.of(pageNumber, pageSize);
return PageDtoMapper.toDto(postService.getAll(pageRequest), this::toDTO);
}
@GetMapping("/user/{userId}")
public PageDto<PostDTO> getAllByUserId(@PathVariable(name = "userId") Integer userId,
@RequestParam(name = "pageNumber", defaultValue = "0") Integer pageNumber,
@RequestParam(name = "pageSize", defaultValue = "5") Integer pageSize) {
PageRequest pageRequest = PageRequest.of(pageNumber, pageSize);
return PageDtoMapper.toDto(postService.getAllByUserId(userId, pageRequest), this::toDTO);
}
@GetMapping("/{id}")
public PostDTO get(@PathVariable(name = "id") Integer id) {
return toDTO(postService.get(id));
}
@PostMapping
public PostDTO create(@RequestBody @Valid PostDTO PostDTO) throws BadRequestException {
return toDTO(postService.create(toEntity(PostDTO)));
}
@PutMapping("/{id}")
public PostDTO update(@PathVariable(name = "id") Integer id, @RequestBody PostDTO PostDTO) {
return toDTO(postService.update(id, toEntity(PostDTO)));
}
@DeleteMapping("/{id}")
public PostDTO delete(@PathVariable(name = "id") Integer id) {
return toDTO(postService.delete(id));
}
}

View File

@ -0,0 +1,64 @@
package com.example.nekontakte.posts.api;
import java.util.Date;
import com.fasterxml.jackson.annotation.JsonProperty;
import jakarta.validation.constraints.NotNull;
public class PostDTO {
@JsonProperty(access = JsonProperty.Access.READ_ONLY)
private Integer id;
@NotNull
private Integer userId;
@NotNull
private Date pubDate;
private String image;
private String html;
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public Date getPubDate() {
return pubDate;
}
public void setPubDate(Date pubDate) {
this.pubDate = pubDate;
}
public String getImage() {
return image;
}
public void setImage(String image) {
this.image = image;
}
public String getHtml() {
return html;
}
public void setHtml(String html) {
this.html = html;
}
public Integer getUserId() {
return userId;
}
public void setUserId(Integer userId) {
this.userId = userId;
}
}

View File

@ -0,0 +1,92 @@
package com.example.nekontakte.posts.model;
import java.util.Date;
import java.util.Objects;
import com.example.nekontakte.core.model.BaseEntity;
import com.example.nekontakte.users.model.UserEntity;
import jakarta.persistence.Column;
import jakarta.persistence.Entity;
import jakarta.persistence.JoinColumn;
import jakarta.persistence.ManyToOne;
import jakarta.persistence.Table;
import jakarta.persistence.Temporal;
import jakarta.persistence.TemporalType;
@Entity
@Table(name = "posts")
public class PostEntity extends BaseEntity {
@ManyToOne
@JoinColumn(name = "userId", nullable = false)
private UserEntity user;
@Temporal(value = TemporalType.DATE)
@Column(nullable = false)
private Date pubDate;
@Column
private String image;
@Column
private String html;
public PostEntity() {
}
public UserEntity getUser() {
return user;
}
public void setUser(UserEntity user) {
this.user = user;
}
public Date getPubDate() {
return pubDate;
}
public void setPubDate(Date pubDate) {
this.pubDate = pubDate;
}
public String getImage() {
return image;
}
public void setImage(String image) {
this.image = image;
}
public String getHtml() {
return html;
}
public void setHtml(String html) {
this.html = html;
}
@Override
public int hashCode() {
return Objects.hash(
id,
user,
pubDate,
image,
html);
}
@Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null || getClass() != obj.getClass())
return false;
final PostEntity other = (PostEntity) obj;
return Objects.equals(other.getId(), id) &&
Objects.equals(other.getUser(), user) &&
Objects.equals(other.getPubDate(), pubDate) &&
Objects.equals(other.getImage(), image) &&
Objects.equals(other.getHtml(), html);
}
}

View File

@ -0,0 +1,17 @@
package com.example.nekontakte.posts.repository;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.repository.CrudRepository;
import org.springframework.data.repository.PagingAndSortingRepository;
import com.example.nekontakte.posts.model.PostEntity;
import java.util.List;
public interface PostRepository
extends CrudRepository<PostEntity, Integer>, PagingAndSortingRepository<PostEntity, Integer> {
Page<PostEntity> findByUserId(Integer userId, PageRequest pageable);
List<PostEntity> findByUserId(Integer userId);
}

View File

@ -0,0 +1,71 @@
package com.example.nekontakte.posts.service;
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.nekontakte.core.errors.NotFoundException;
import com.example.nekontakte.posts.model.PostEntity;
import com.example.nekontakte.posts.repository.PostRepository;
import java.util.List;
import java.util.stream.StreamSupport;
@Service
public class PostService {
private final PostRepository repository;
public PostService(PostRepository repository) {
this.repository = repository;
}
@Transactional(readOnly = true)
public Page<PostEntity> getAllByUserId(Integer userId, PageRequest pageRequest) {
return repository.findByUserId(userId, pageRequest);
}
@Transactional(readOnly = true)
public List<PostEntity> getAllByUserId(Integer userId) {
return repository.findByUserId(userId);
}
@Transactional(readOnly = true)
public Page<PostEntity> getAll(PageRequest pageRequest) {
return repository.findAll(pageRequest);
}
@Transactional(readOnly = true)
public List<PostEntity> getAll() {
return StreamSupport.stream(repository.findAll().spliterator(), false).toList();
}
@Transactional(readOnly = true)
public PostEntity get(Integer id) {
return repository.findById(id).orElseThrow(() -> new NotFoundException(PostEntity.class, id));
}
public PostEntity create(PostEntity entity) throws org.apache.coyote.BadRequestException {
if (entity.getImage() == null && entity.getHtml() == null) {
throw new org.apache.coyote.BadRequestException("Image or Html must be not null");
}
return repository.save(entity);
}
public PostEntity update(Integer id, PostEntity entity) {
final PostEntity existEntity = get(id);
existEntity.setUser(entity.getUser());
existEntity.setPubDate(entity.getPubDate());
existEntity.setImage(entity.getImage());
existEntity.setHtml(entity.getHtml());
repository.save(existEntity);
return existEntity;
}
public PostEntity delete(Integer id) {
final PostEntity existsentity = get(id);
repository.delete(existsentity);
return existsentity;
}
}

View File

@ -0,0 +1,84 @@
package com.example.nekontakte.subscribes.api;
import java.util.List;
import com.example.nekontakte.core.configurations.Constants;
import org.apache.coyote.BadRequestException;
import org.modelmapper.ModelMapper;
import org.springframework.data.domain.PageRequest;
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.nekontakte.subscribes.model.SubscribeEntity;
import com.example.nekontakte.subscribes.service.SubscribeService;
import jakarta.validation.Valid;
@RestController
@RequestMapping(Constants.API_URL + "/subscribe")
public class SubscribeController {
private final SubscribeService subscribeService;
private final ModelMapper modelMapper;
public SubscribeController(SubscribeService subscribeService, ModelMapper modelMapper) {
this.modelMapper = modelMapper;
this.subscribeService = subscribeService;
}
private SubscribeEntity toEntity(SubscribeDTO dto) {
return modelMapper.map(dto, SubscribeEntity.class);
}
private SubscribeDTO toDTO(SubscribeEntity entity) {
return modelMapper.map(entity, SubscribeDTO.class);
}
@GetMapping
public List<SubscribeDTO> getAll() {
return subscribeService.getAll().stream().map(this::toDTO).toList();
}
@GetMapping("/user/{userId}")
public List<SubscribeDTO> getAllByUserId(@PathVariable(name = "userId") Integer userId,
@RequestParam(name = "pageNumber", defaultValue = "0") Integer pageNumber,
@RequestParam(name = "pageSize", defaultValue = "5") Integer pageSize) {
PageRequest pageRequest = PageRequest.of(pageNumber, pageSize);
return subscribeService.getAllByUserId(userId, pageRequest).stream().map(this::toDTO).toList();
}
@GetMapping("/subscriber/{subscriberId}")
public List<SubscribeDTO> getAllBySubscriberId(@PathVariable(name = "subscriberId") Integer subscriberId,
@RequestParam(name = "pageNumber", defaultValue = "0") Integer pageNumber,
@RequestParam(name = "pageSize", defaultValue = "5") Integer pageSize) {
PageRequest pageRequest = PageRequest.of(pageNumber, pageSize);
return subscribeService.getAllBySubscriberId(subscriberId, pageRequest).stream().map(this::toDTO).toList();
}
@GetMapping("/{id}")
public SubscribeDTO get(@PathVariable(name = "id") Integer id) {
return toDTO(subscribeService.get(id));
}
@PostMapping
public SubscribeDTO create(@RequestBody @Valid SubscribeDTO SubscribeDTO) throws BadRequestException {
return toDTO(subscribeService.create(toEntity(SubscribeDTO)));
}
@PutMapping("/{id}")
public SubscribeDTO update(@PathVariable(name = "id") Integer id, @RequestBody SubscribeDTO SubscribeDTO) {
return toDTO(subscribeService.update(id, toEntity(SubscribeDTO)));
}
@DeleteMapping("/{id}")
public SubscribeDTO delete(@PathVariable(name = "id") Integer id) {
return toDTO(subscribeService.delete(id));
}
}

View File

@ -0,0 +1,36 @@
package com.example.nekontakte.subscribes.api;
import jakarta.validation.constraints.NotNull;
public class SubscribeDTO {
private Integer id;
@NotNull
private Integer userId;
@NotNull
private Integer subscriberId;
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public Integer getUserId() {
return userId;
}
public void setUserId(Integer userId) {
this.userId = userId;
}
public Integer getSubscriberId() {
return subscriberId;
}
public void setSubscriberId(Integer subscriberId) {
this.subscriberId = subscriberId;
}
}

View File

@ -0,0 +1,62 @@
package com.example.nekontakte.subscribes.model;
import java.util.Objects;
import com.example.nekontakte.core.model.BaseEntity;
import com.example.nekontakte.users.model.UserEntity;
import jakarta.persistence.Entity;
import jakarta.persistence.JoinColumn;
import jakarta.persistence.ManyToOne;
import jakarta.persistence.Table;
@Entity
@Table(name = "subscribes")
public class SubscribeEntity extends BaseEntity {
@ManyToOne
@JoinColumn(name = "userId", nullable = false)
private UserEntity user;
@ManyToOne
@JoinColumn(name = "subscriberId", nullable = false)
private UserEntity subscriber;
public SubscribeEntity() {
}
public UserEntity getUser() {
return user;
}
public void setUser(UserEntity user) {
this.user = user;
}
public UserEntity getSubscriber() {
return subscriber;
}
public void setSubscriber(UserEntity subscriber) {
this.subscriber = subscriber;
}
@Override
public int hashCode() {
return Objects.hash(
id,
user,
subscriber);
}
@Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null || getClass() != obj.getClass())
return false;
final SubscribeEntity other = (SubscribeEntity) obj;
return Objects.equals(other.getId(), id) &&
Objects.equals(other.getUser(), user) &&
Objects.equals(other.getSubscriber(), subscriber);
}
}

View File

@ -0,0 +1,21 @@
package com.example.nekontakte.subscribes.repository;
import java.util.List;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.repository.CrudRepository;
import org.springframework.data.repository.PagingAndSortingRepository;
import com.example.nekontakte.subscribes.model.SubscribeEntity;
public interface SubscribeRepository
extends CrudRepository<SubscribeEntity, Integer>, PagingAndSortingRepository<SubscribeEntity, Integer> {
List<SubscribeEntity> findByUserId(Integer userId);
Page<SubscribeEntity> findByUserId(Integer userId, PageRequest pageRequest);
List<SubscribeEntity> findBySubscriberId(Integer subscriberId);
Page<SubscribeEntity> findBySubscriberId(Integer subscriberId, PageRequest pageRequest);
}

View File

@ -0,0 +1,80 @@
package com.example.nekontakte.subscribes.service;
import java.util.List;
import java.util.stream.StreamSupport;
import org.apache.coyote.BadRequestException;
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.nekontakte.core.errors.NotFoundException;
import com.example.nekontakte.subscribes.model.SubscribeEntity;
import com.example.nekontakte.subscribes.repository.SubscribeRepository;
@Service
public class SubscribeService {
private final SubscribeRepository repository;
public SubscribeService(SubscribeRepository repository) {
this.repository = repository;
}
@Transactional(readOnly = true)
public List<SubscribeEntity> getAll() {
return StreamSupport.stream(repository.findAll().spliterator(), false).toList();
}
@Transactional(readOnly = true)
public Page<SubscribeEntity> getAll(PageRequest pageRequest) {
return repository.findAll(pageRequest);
}
@Transactional(readOnly = true)
public List<SubscribeEntity> getAllByUserId(Integer userId) {
return repository.findByUserId(userId);
}
@Transactional(readOnly = true)
public Page<SubscribeEntity> getAllByUserId(Integer userId, PageRequest pageRequest) {
return repository.findByUserId(userId, pageRequest);
}
@Transactional(readOnly = true)
public List<SubscribeEntity> getAllBySubscriberId(Integer subscriberId) {
return repository.findBySubscriberId(subscriberId);
}
@Transactional(readOnly = true)
public Page<SubscribeEntity> getAllBySubscriberId(Integer subscriberId, PageRequest pageRequest) {
return repository.findBySubscriberId(subscriberId, pageRequest);
}
@Transactional(readOnly = true)
public SubscribeEntity get(Integer id) {
return repository.findById(id).orElseThrow(() -> new NotFoundException(SubscribeEntity.class, id));
}
public SubscribeEntity create(SubscribeEntity entity) throws BadRequestException {
if (entity.getSubscriber().getId() == entity.getUser().getId()) {
throw new org.apache.coyote.BadRequestException("User do not subscribe themself");
}
return repository.save(entity);
}
public SubscribeEntity update(Integer id, SubscribeEntity entity) {
final SubscribeEntity existEntity = get(id);
existEntity.setId(entity.getId());
existEntity.setSubscriber(entity.getSubscriber());
existEntity.setUser(entity.getUser());
return repository.save(existEntity);
}
public SubscribeEntity delete(Integer id) {
final SubscribeEntity existsentity = get(id);
repository.delete(existsentity);
return existsentity;
}
}

View File

@ -0,0 +1,71 @@
package com.example.nekontakte.users.api;
import com.example.nekontakte.core.api.PageDtoMapper;
import com.example.nekontakte.core.api.PageDto;
import com.example.nekontakte.core.configurations.Constants;
import com.example.nekontakte.users.model.UserEntity;
import com.example.nekontakte.users.service.UserService;
import jakarta.validation.Valid;
import org.modelmapper.ModelMapper;
import org.springframework.data.domain.PageRequest;
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(Constants.API_URL + "/user")
public class UserController {
private final UserService userService;
private final ModelMapper modelMapper;
public UserController(UserService userService, ModelMapper modelMapper) {
this.modelMapper = modelMapper;
this.userService = userService;
}
private UserEntity toEntity(UserDTO dto) {
return modelMapper.map(dto, UserEntity.class);
}
private UserDTO toDTO(UserEntity entity) {
return modelMapper.map(entity, UserDTO.class);
}
@GetMapping
public PageDto<UserDTO> getAll(@RequestParam(name = "pageNumber", defaultValue = "0") Integer pageNumber,
@RequestParam(name = "pageSize", defaultValue = "5") Integer pageSize) {
PageRequest pageRequest = PageRequest.of(pageNumber, pageSize);
return PageDtoMapper.toDto(userService.getAll(pageRequest), this::toDTO);
}
@GetMapping("/{id}")
public UserDTO get(@PathVariable(name = "id") Integer id) {
return toDTO(userService.get(id));
}
@PostMapping
public UserDTO create(@RequestBody @Valid UserDTO userDTO) {
return toDTO(userService.create(toEntity(userDTO)));
}
@PutMapping("/{id}")
public UserDTO update(@PathVariable(name = "id") Integer id, @RequestBody UserDTO userDTO) {
return toDTO(userService.update(id, toEntity(userDTO)));
}
@DeleteMapping("/{id}")
public UserDTO delete(@PathVariable(name = "id") Integer id) {
return toDTO(userService.delete(id));
}
}

View File

@ -0,0 +1,121 @@
package com.example.nekontakte.users.api;
import java.sql.Date;
import com.fasterxml.jackson.annotation.JsonProperty;
import jakarta.validation.constraints.NotBlank;
import jakarta.validation.constraints.NotNull;
import jakarta.validation.constraints.Size;
public class UserDTO {
@JsonProperty(access = JsonProperty.Access.READ_ONLY)
private Integer id;
@NotBlank
private String name;
@NotBlank
private String surname;
@NotNull
private Date birthday;
private String city;
private String avatarImg;
@NotBlank
@Size(min = 3)
private String username;
@NotBlank
private String password;
@NotNull
private boolean isAdmin;
private String status;
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getSurname() {
return surname;
}
public void setSurname(String surname) {
this.surname = surname;
}
public Date getBirthday() {
return birthday;
}
public void setBirthday(Date birthday) {
this.birthday = birthday;
}
public String getCity() {
return city;
}
public void setCity(String city) {
this.city = city;
}
public String getAvatarImg() {
return avatarImg;
}
public void setAvatarImg(String avatarImg) {
this.avatarImg = avatarImg;
}
public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
public boolean getIsAdmin() {
return isAdmin;
}
public void setIsAdmin(boolean isAdmin) {
this.isAdmin = isAdmin;
}
public String getStatus() {
return status;
}
public void setStatus(String status) {
this.status = status;
}
}

View File

@ -0,0 +1,173 @@
package com.example.nekontakte.users.model;
import java.util.Date;
import java.util.Objects;
import java.util.HashSet;
import java.util.Set;
import com.example.nekontakte.core.model.BaseEntity;
import com.example.nekontakte.posts.model.PostEntity;
import jakarta.persistence.CascadeType;
import jakarta.persistence.Column;
import jakarta.persistence.OneToMany;
import jakarta.persistence.OrderBy;
import jakarta.persistence.Entity;
import jakarta.persistence.Table;
import jakarta.persistence.Temporal;
import jakarta.persistence.TemporalType;
@Entity
@Table(name = "users")
public class UserEntity extends BaseEntity {
@Column(nullable = false)
private String name;
@Column(nullable = false)
private String surname;
@Temporal(value = TemporalType.DATE)
@Column(nullable = false)
private Date birthday;
@Column
private String city;
@Column
private String avatarImg;
@Column(nullable = false, unique = true)
private String username;
@Column(nullable = false)
private String password;
@Column(nullable = false)
private boolean isAdmin;
@Column
private String status;
@OneToMany(mappedBy = "user", cascade = CascadeType.ALL)
@OrderBy("id ASC")
private Set<PostEntity> posts = new HashSet<>();
public UserEntity() {
}
public UserEntity(
String name,
String surname,
Date birthday,
String username,
String password,
boolean isAdmin) {
setName(name);
setSurname(surname);
setBirthday(birthday);
setUsername(username);
setPassword(password);
setIsAdmin(isAdmin);
}
public Set<PostEntity> getPosts() {
return posts;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getSurname() {
return surname;
}
public void setSurname(String surname) {
this.surname = surname;
}
public Date getBirthday() {
return birthday;
}
public void setBirthday(Date birthday) {
this.birthday = birthday;
}
public String getCity() {
return city;
}
public void setCity(String city) {
this.city = city;
}
public String getAvatarImg() {
return avatarImg;
}
public void setAvatarImg(String avatarImg) {
this.avatarImg = avatarImg;
}
public String getStatus() {
return status;
}
public void setStatus(String status) {
this.status = status;
}
public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
public boolean getIsAdmin() {
return isAdmin;
}
public void setIsAdmin(boolean isAdmin) {
this.isAdmin = isAdmin;
}
@Override
public int hashCode() {
return Objects.hash(
id,
username,
password,
isAdmin,
name,
surname,
status,
city,
birthday,
avatarImg);
}
@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.getUsername(), username) &&
Objects.equals(other.getIsAdmin(), isAdmin) &&
Objects.equals(other.getPassword(), password) &&
Objects.equals(other.getName(), name) &&
Objects.equals(other.getSurname(), surname) &&
Objects.equals(other.getStatus(), status) &&
Objects.equals(other.getCity(), city) &&
Objects.equals(other.getBirthday(), birthday) &&
Objects.equals(other.getAvatarImg(), avatarImg);
}
}

View File

@ -0,0 +1,13 @@
package com.example.nekontakte.users.repository;
import java.util.Optional;
import org.springframework.data.repository.CrudRepository;
import org.springframework.data.repository.PagingAndSortingRepository;
import com.example.nekontakte.users.model.UserEntity;
public interface UserRepository
extends CrudRepository<UserEntity, Integer>, PagingAndSortingRepository<UserEntity, Integer> {
Optional<UserEntity> findByUsernameIgnoreCase(String username);
}

View File

@ -0,0 +1,82 @@
package com.example.nekontakte.users.service;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.stereotype.Service;
import com.example.nekontakte.core.errors.NotFoundException;
import com.example.nekontakte.users.model.UserEntity;
import com.example.nekontakte.users.repository.UserRepository;
import org.springframework.transaction.annotation.Transactional;
import java.util.List;
import java.util.stream.StreamSupport;
@Service
public class UserService {
private final UserRepository repository;
private boolean checkUsernameIsExist(String username) {
return repository.findByUsernameIgnoreCase(username).isPresent();
}
public UserService(UserRepository repository) {
this.repository = repository;
}
@Transactional(readOnly = true)
public Page<UserEntity> getAll(PageRequest pageRequest) {
return repository.findAll(pageRequest);
}
@Transactional(readOnly = true)
public List<UserEntity> getAll() {
return StreamSupport.stream(repository.findAll().spliterator(), false).toList();
}
@Transactional(readOnly = true)
public UserEntity get(Integer 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");
}
if (checkUsernameIsExist(entity.getUsername())) {
throw new IllegalArgumentException(
String.format("User with username %s is already exists", entity.getUsername()));
}
return repository.save(entity);
}
@Transactional
public UserEntity update(Integer id, UserEntity entity) {
final UserEntity existsentity = get(id);
var usersWithSameUsername = repository.findByUsernameIgnoreCase(entity.getUsername());
if (usersWithSameUsername.get().getId() != existsentity.getId()) {
throw new IllegalArgumentException(
String.format("User with username %s is already exists", entity.getUsername()));
}
existsentity.setUsername(entity.getUsername());
existsentity.setPassword(entity.getPassword());
existsentity.setIsAdmin(entity.getIsAdmin());
existsentity.setName(entity.getName());
existsentity.setSurname(entity.getSurname());
existsentity.setStatus(entity.getStatus());
existsentity.setBirthday(entity.getBirthday());
existsentity.setCity(entity.getCity());
existsentity.setStatus(entity.getStatus());
repository.save(existsentity);
return existsentity;
}
@Transactional
public UserEntity delete(Integer id) {
final UserEntity existsEntity = get(id);
repository.delete(existsEntity);
return existsEntity;
}
}

View File

@ -1 +1,21 @@
spring.application.name=nekontakte spring.application.name=nekontakte
# Server
spring.main.banner-mode=off
server.port=8080
# Logger settings
# Available levels are: TRACE, DEBUG, INFO, WARN, ERROR, FATAL, OFF
logging.level.com.example.demo=DEBUG
# JPA Settings
spring.datasource.url=jdbc:h2:file:./test
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.nekontakte;
import org.junit.jupiter.api.Test;
import org.springframework.boot.test.context.SpringBootTest;
@SpringBootTest
class NekontakteApplicationTests {
@Test
void contextLoads() {
}
}

View File

@ -0,0 +1,150 @@
package com.example.nekontakte;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Locale;
import org.apache.coyote.BadRequestException;
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.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import com.example.nekontakte.core.errors.NotFoundException;
import com.example.nekontakte.posts.model.PostEntity;
import com.example.nekontakte.posts.service.PostService;
import com.example.nekontakte.users.model.UserEntity;
import com.example.nekontakte.users.service.UserService;
import org.junit.jupiter.api.TestMethodOrder;
@SpringBootTest
@TestMethodOrder(OrderAnnotation.class)
public class PostServiceTests {
@Autowired
private UserService userService;
@Autowired
private PostService postService;
private UserEntity firstUser;
private UserEntity secondUser;
private PostEntity firstPost;
private PostEntity secondPost;
private PostEntity thirdPost;
@BeforeEach
void createData() throws ParseException, BadRequestException {
removeData();
SimpleDateFormat dateFormatter = new SimpleDateFormat("dd.MM.yyyy", Locale.ENGLISH);
SimpleDateFormat dateTimeFormatter = new SimpleDateFormat("dd.MM.yyyy, HH:mm:ss", Locale.ENGLISH);
firstUser = new UserEntity();
firstUser.setUsername("nspotapov");
firstUser.setPassword("pass123456");
firstUser.setIsAdmin(true);
firstUser.setName("Никита");
firstUser.setSurname("Потапов");
firstUser.setCity("Ульяновск");
firstUser.setStatus("Я здесь админ");
firstUser.setBirthday(dateFormatter.parse("17.02.2003"));
secondUser = new UserEntity();
secondUser.setUsername("ekallin");
secondUser.setPassword("pass87654321");
secondUser.setIsAdmin(false);
secondUser.setName("Елена");
secondUser.setSurname("Каллин");
secondUser.setCity("Новоульяновск");
secondUser.setBirthday(dateFormatter.parse("14.06.2005"));
firstUser = userService.create(firstUser);
secondUser = userService.create(secondUser);
firstPost = new PostEntity();
firstPost.setUser(firstUser);
firstPost.setPubDate(dateFormatter.parse("01.04.2024"));
firstPost.setHtml("Первый тестовый пост");
firstPost = postService.create(firstPost);
secondPost = new PostEntity();
secondPost.setUser(firstUser);
secondPost.setPubDate(dateTimeFormatter.parse("22.03.2024, 09:34:01"));
secondPost.setImage("myimage.jpg");
secondPost.setHtml("Второй тестовый пост");
secondPost = postService.create(secondPost);
thirdPost = new PostEntity();
thirdPost.setUser(secondUser);
thirdPost.setPubDate(dateTimeFormatter.parse("13.02.2024, 18:01:01"));
thirdPost.setImage("ohmypost.jpg");
thirdPost.setHtml("Третий постовый пост");
thirdPost = postService.create(thirdPost);
}
@AfterEach
void removeData() {
postService.getAll().forEach(item -> postService.delete(item.getId()));
userService.getAll().forEach(item -> userService.delete(item.getId()));
}
@Test
void getTest() {
Assertions.assertThrows(NotFoundException.class, () -> postService.get(0));
}
@Test
@Order(1)
void createTest() throws ParseException, BadRequestException {
SimpleDateFormat dateTimeFormatter = new SimpleDateFormat("dd.MM.yyyy, HH:mm:ss", Locale.ENGLISH);
PostEntity fourthPost = new PostEntity();
fourthPost.setUser(secondUser);
fourthPost.setPubDate(dateTimeFormatter.parse("13.02.2024, 18:01:01"));
Assertions.assertThrows(BadRequestException.class,
() -> postService.create(fourthPost));
PostEntity test = postService.get(firstPost.getId());
Assertions.assertEquals(firstPost, test);
Assertions.assertEquals(firstUser, postService.get(firstPost.getId()).getUser());
Assertions.assertEquals(secondUser, postService.get(thirdPost.getId()).getUser());
Assertions.assertEquals(3, postService.getAll().size());
Assertions.assertEquals(2, postService.getAllByUserId(firstUser.getId()).size());
}
@Test
@Order(2)
void update() throws BadRequestException, ParseException {
Integer postId = firstPost.getId();
PostEntity oldPost = postService.get(postId);
String oldImage = oldPost.getImage();
PostEntity newPost = new PostEntity();
newPost.setId(oldPost.getId());
newPost.setUser(oldPost.getUser());
newPost.setPubDate(oldPost.getPubDate());
newPost.setImage("new image");
newPost.setHtml(oldPost.getHtml());
postService.update(postId, newPost);
Assertions.assertNotEquals(postService.get(postId).getImage(), oldImage);
}
@Test
@Order(3)
void delete() {
final int oldCount = postService.getAll().size();
postService.delete(firstPost.getId());
Assertions.assertEquals(oldCount - 1, postService.getAll().size());
}
}

View File

@ -0,0 +1,139 @@
package com.example.nekontakte;
import org.junit.jupiter.api.TestMethodOrder;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Locale;
import org.apache.coyote.BadRequestException;
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.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import com.example.nekontakte.core.errors.NotFoundException;
import com.example.nekontakte.subscribes.model.SubscribeEntity;
import com.example.nekontakte.subscribes.service.SubscribeService;
import com.example.nekontakte.users.service.UserService;
import com.example.nekontakte.users.model.UserEntity;
@SpringBootTest
@TestMethodOrder(OrderAnnotation.class)
public class SubscribeServiceTests {
@Autowired
private UserService userService;
@Autowired
private SubscribeService subscribeService;
private UserEntity firstUser;
private UserEntity secondUser;
private UserEntity thirdUser;
private SubscribeEntity secondSubscribe;
@BeforeEach
void createData() throws ParseException, BadRequestException {
removeData();
SimpleDateFormat dateFormatter = new SimpleDateFormat("dd.MM.yyyy", Locale.ENGLISH);
UserEntity firstUserEntity = new UserEntity();
firstUserEntity.setUsername("nspotapov");
firstUserEntity.setPassword("pass123456");
firstUserEntity.setIsAdmin(true);
firstUserEntity.setName("Никита");
firstUserEntity.setSurname("Потапов");
firstUserEntity.setCity("Ульяновск");
firstUserEntity.setStatus("Я здесь админ");
firstUserEntity.setBirthday(dateFormatter.parse("17.02.2003"));
UserEntity secondUserEntity = new UserEntity();
secondUserEntity.setUsername("ekallin");
secondUserEntity.setPassword("pass87654321");
secondUserEntity.setIsAdmin(false);
secondUserEntity.setName("Елена");
secondUserEntity.setSurname("Каллин");
secondUserEntity.setCity("Новоульяновск");
secondUserEntity.setBirthday(dateFormatter.parse("14.06.2005"));
UserEntity thirdUserEntity = new UserEntity();
thirdUserEntity.setUsername("olegulya");
thirdUserEntity.setPassword("passOleg");
thirdUserEntity.setIsAdmin(false);
thirdUserEntity.setName("Олег");
thirdUserEntity.setSurname("Тинькофф");
thirdUserEntity.setCity("Полысаево");
thirdUserEntity.setStatus(
"Вчера я потерял $250 млн за день, были дни и похуже, миллиарды в день терял. Поэтому это позитивный очень день");
thirdUserEntity.setBirthday(dateFormatter.parse("25.12.1967"));
firstUser = userService.create(firstUserEntity);
secondUser = userService.create(secondUserEntity);
thirdUser = userService.create(thirdUserEntity);
SubscribeEntity subscribeEntity = new SubscribeEntity();
subscribeEntity.setUser(firstUser);
subscribeEntity.setSubscriber(secondUser);
subscribeService.create(subscribeEntity);
subscribeEntity = new SubscribeEntity();
subscribeEntity.setUser(firstUser);
subscribeEntity.setSubscriber(thirdUser);
secondSubscribe = subscribeService.create(subscribeEntity);
subscribeEntity = new SubscribeEntity();
subscribeEntity.setUser(secondUser);
subscribeEntity.setSubscriber(thirdUser);
subscribeService.create(subscribeEntity);
}
@AfterEach
void removeData() {
subscribeService.getAll().forEach(item -> subscribeService.delete(item.getId()));
userService.getAll().forEach(item -> userService.delete(item.getId()));
}
@Test
void getTest() {
Assertions.assertThrows(NotFoundException.class, () -> subscribeService.get(0));
}
@Test
@Order(1)
void createTest() throws ParseException, BadRequestException {
Assertions.assertEquals(secondSubscribe, subscribeService.get(secondSubscribe.getId()));
Assertions.assertEquals(3, subscribeService.getAll().size());
Assertions.assertEquals(2, subscribeService.getAllByUserId(firstUser.getId()).size());
}
@Test
@Order(2)
void update() throws BadRequestException, ParseException {
Integer subscribeId = secondSubscribe.getId();
SubscribeEntity oldSubscribeEntity = subscribeService.get(subscribeId);
UserEntity oldSubscriber = oldSubscribeEntity.getSubscriber();
SubscribeEntity newSubscribeEntity = new SubscribeEntity();
newSubscribeEntity.setId(oldSubscribeEntity.getId());
newSubscribeEntity.setUser(oldSubscribeEntity.getUser());
newSubscribeEntity.setSubscriber(secondUser);
subscribeService.update(subscribeId, newSubscribeEntity);
Assertions.assertNotEquals(subscribeService.get(subscribeId).getSubscriber(), oldSubscriber);
}
@Test
@Order(3)
void delete() {
Integer oldCount = subscribeService.getAll().size();
subscribeService.delete(secondSubscribe.getId());
Assertions.assertEquals(oldCount - 1, subscribeService.getAll().size());
}
}

View File

@ -0,0 +1,116 @@
package com.example.nekontakte;
import org.junit.jupiter.api.TestMethodOrder;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Locale;
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.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import com.example.nekontakte.core.errors.NotFoundException;
import com.example.nekontakte.users.service.UserService;
import com.example.nekontakte.users.model.UserEntity;
@SpringBootTest
@TestMethodOrder(OrderAnnotation.class)
public class UserServiceTests {
@Autowired
private UserService userService;
private UserEntity firstUser;
@BeforeEach
void createData() throws ParseException {
removeData();
SimpleDateFormat dateFormatter = new SimpleDateFormat("dd.MM.yyyy", Locale.ENGLISH);
UserEntity firstUserEntity = new UserEntity();
firstUserEntity.setUsername("nspotapov");
firstUserEntity.setPassword("pass123456");
firstUserEntity.setIsAdmin(true);
firstUserEntity.setName("Никита");
firstUserEntity.setSurname("Потапов");
firstUserEntity.setCity("Ульяновск");
firstUserEntity.setStatus("Я здесь админ");
firstUserEntity.setBirthday(dateFormatter.parse("17.02.2003"));
UserEntity secondUserEntity = new UserEntity();
secondUserEntity.setUsername("ekallin");
secondUserEntity.setPassword("pass87654321");
secondUserEntity.setIsAdmin(false);
secondUserEntity.setName("Елена");
secondUserEntity.setSurname("Каллин");
secondUserEntity.setCity("Новоульяновск");
secondUserEntity.setBirthday(dateFormatter.parse("14.06.2005"));
UserEntity thirdUserEntity = new UserEntity();
thirdUserEntity.setUsername("olegulya");
thirdUserEntity.setPassword("passOleg");
thirdUserEntity.setIsAdmin(false);
thirdUserEntity.setName("Олег");
thirdUserEntity.setSurname("Тинькофф");
thirdUserEntity.setCity("Полысаево");
thirdUserEntity.setStatus(
"Вчера я потерял $250 млн за день, были дни и похуже, миллиарды в день терял. Поэтому это позитивный очень день");
thirdUserEntity.setBirthday(dateFormatter.parse("25.12.1967"));
firstUser = userService.create(firstUserEntity);
userService.create(secondUserEntity);
userService.create(thirdUserEntity);
}
@AfterEach
void removeData() {
userService.getAll().forEach(item -> userService.delete(item.getId()));
}
@Test
void getTest() {
Assertions.assertThrows(NotFoundException.class, () -> userService.get(0));
}
@Test
@Order(1)
void createTest() throws ParseException {
Assertions.assertEquals(3, userService.getAll().size());
}
@Test
@Order(2)
void update() {
final String newPassword = "newpassword";
final UserEntity existEntity = userService.get(firstUser.getId());
final String oldPassword = existEntity.getPassword();
final UserEntity entity = new UserEntity();
entity.setUsername(existEntity.getUsername());
entity.setPassword(newPassword);
entity.setIsAdmin(existEntity.getIsAdmin());
entity.setName(existEntity.getName());
entity.setSurname(existEntity.getSurname());
entity.setBirthday(existEntity.getBirthday());
entity.setCity(existEntity.getCity());
entity.setAvatarImg(existEntity.getAvatarImg());
entity.setStatus(existEntity.getStatus());
final UserEntity newEntity = userService.update(firstUser.getId(), entity);
Assertions.assertEquals(newPassword, newEntity.getPassword());
Assertions.assertNotEquals(oldPassword, newEntity.getPassword());
}
@Test
@Order(3)
void delete() {
userService.delete(firstUser.getId());
Assertions.assertEquals(2, userService.getAll().size());
}
}

BIN
test.mv.db Normal file

Binary file not shown.