diff --git a/.jpb/jpb-settings.xml b/.jpb/jpb-settings.xml new file mode 100644 index 0000000..935cf0d --- /dev/null +++ b/.jpb/jpb-settings.xml @@ -0,0 +1,6 @@ + + + + + \ No newline at end of file diff --git a/pom.xml b/pom.xml index 7cb490f..94ab4e8 100644 --- a/pom.xml +++ b/pom.xml @@ -10,17 +10,28 @@ com.petproject Boardgamefun + jar 0.0.1-SNAPSHOT Boardgamefun Boardgamefun 17 + 1.6.20-M1 + 1.4.2.Final - + - + + + + + + + + + org.springframework.boot @@ -42,10 +53,24 @@ org.springframework.boot spring-boot-starter-web + + org.springframework.boot + spring-boot-starter-security + + + io.jsonwebtoken + jjwt + 0.9.1 + org.springframework.boot spring-boot-starter-webflux + + com.fasterxml.jackson.datatype + jackson-datatype-jsr310 + + org.springframework.boot @@ -78,22 +103,168 @@ reactor-test test + + com.fasterxml.jackson.jaxrs + jackson-jaxrs-json-provider + 2.13.0 + + + org.jetbrains.kotlin + kotlin-stdlib-jdk8 + ${kotlin.version} + + + org.liquibase + liquibase-core + + + org.jetbrains.kotlin + kotlin-test + ${kotlin.version} + test + + + org.springframework.security + spring-security-test + 5.5.3 + test + + + junit + junit + test + + + org.mapstruct + mapstruct + ${org.mapstruct.version} + + + org.liquibase + liquibase-maven-plugin + 3.6.2 + + + org.liquibase + liquibase-maven-plugin + 3.6.2 + + src/main/resources/liquibase.properties + src/main/resources/liquibase/changelog-master.xml + + org.springframework.boot spring-boot-maven-plugin - - - org.projectlombok - lombok - - + true + + + + kotlin-maven-plugin + org.jetbrains.kotlin + ${kotlin.version} + + + compile + + compile + + + + ${project.basedir}/src/main/kotlin + ${project.basedir}/src/main/java + + + + + kapt + + kapt + + + + + org.mapstruct + mapstruct-processor + ${org.mapstruct.version} + + + + + + test-compile + + test-compile + + + + ${project.basedir}/src/test/kotlin + ${project.basedir}/src/test/java + + + + + + + org.apache.maven.plugins + maven-compiler-plugin + + + + default-compile + none + + + + + + default-testCompile + none + + + java-compile + compile + + compile + + + + java-test-compile + test-compile + + testCompile + + + + + + cz.habarta.typescript-generator + typescript-generator-maven-plugin + 2.34.976 + + + generate + + generate + + process-classes + + + + jackson2 + + com.petproject.boardgamefun.dto.* + + target/rest.d.ts + module + diff --git a/src/main/java/com/petproject/boardgamefun/controller/DesignerController.java b/src/main/java/com/petproject/boardgamefun/controller/DesignerController.java new file mode 100644 index 0000000..ddc5e95 --- /dev/null +++ b/src/main/java/com/petproject/boardgamefun/controller/DesignerController.java @@ -0,0 +1,101 @@ +package com.petproject.boardgamefun.controller; + +import com.petproject.boardgamefun.dto.DesignerDTO; +import com.petproject.boardgamefun.dto.GameDataDTO; +import com.petproject.boardgamefun.dto.request.DesignerRequest; +import com.petproject.boardgamefun.model.Designer; +import com.petproject.boardgamefun.repository.DesignerRepository; +import com.petproject.boardgamefun.service.DesignerService; +import org.springframework.http.HttpStatus; +import org.springframework.http.ResponseEntity; +import org.springframework.security.access.prepost.PreAuthorize; +import org.springframework.web.bind.annotation.*; + +import javax.transaction.Transactional; +import java.util.List; + +@RestController +@RequestMapping("/designer") +public class DesignerController { + + private final DesignerRepository designerRepository; + private final DesignerService designerService; + + public DesignerController(DesignerRepository designerRepository, DesignerService designerService) { + this.designerRepository = designerRepository; + this.designerService = designerService; + } + + @Transactional + @GetMapping("") + public ResponseEntity> getDesigners(){ + var designers = designerService.entitiesToDesignerDTO(designerRepository.findAll()); + + return new ResponseEntity<>(designers, HttpStatus.OK); + } + + @Transactional + @GetMapping("/{name}") + public ResponseEntity getDesignerByName(@PathVariable String name){ + var designer = designerService.entityToDesignerDTO(designerRepository.findDesignerByName(name)); + + return new ResponseEntity<>(designer, HttpStatus.OK); + } + + @Transactional + @PostMapping("/add") + @PreAuthorize("hasRole('USER') or hasRole('MODERATOR') or hasRole('ADMIN')") + public ResponseEntity> addDesigner(@RequestBody DesignerRequest designerRequest){ + var designer = new Designer(); + designer.setName(designerRequest.getName()); + designerRepository.save(designer); + + var designers = designerService.entitiesToDesignerDTO(designerRepository.findAll()); + + return new ResponseEntity<>(designers, HttpStatus.OK); + } + + @Transactional + @PatchMapping("/update/{id}") + @PreAuthorize("hasRole('USER') or hasRole('MODERATOR') or hasRole('ADMIN')") + public ResponseEntity> updateDesigner(@PathVariable Integer id, @RequestBody DesignerRequest designerRequest){ + var designer = designerRepository.findDesignerById(id); + + designer.setName(designerRequest.getName()); + designerRepository.save(designer); + + var designers = designerService.entitiesToDesignerDTO(designerRepository.findAll()); + + return new ResponseEntity<>(designers, HttpStatus.OK); + } + + @Transactional + @DeleteMapping("/delete/{id}") + @PreAuthorize("hasRole('USER') or hasRole('MODERATOR') or hasRole('ADMIN')") + public ResponseEntity> deleteDesigner(@PathVariable Integer id){ + + var designer = designerRepository.findDesignerById(id); + designerRepository.delete(designer); + var designers = designerService.entitiesToDesignerDTO(designerRepository.findAll()); + return new ResponseEntity<>(designers, HttpStatus.OK); + } + + + @PostMapping("/{gameId}/set-designer/{designerId}") + @PreAuthorize("hasRole('USER') or hasRole('MODERATOR') or hasRole('ADMIN')") + public ResponseEntity addDesignerToGame(@PathVariable Integer gameId, @PathVariable Integer designerId) { + + var gameDTO = designerService.addDesignerToGame(gameId, designerId); + return new ResponseEntity<>(gameDTO, HttpStatus.OK); + } + + @DeleteMapping("{gameId}/remove-designer/{gameByDesignerId}") + @PreAuthorize("hasRole('USER') or hasRole('MODERATOR') or hasRole('ADMIN')") + public ResponseEntity deleteDesignerFromGame(@PathVariable Integer gameId, @PathVariable Integer gameByDesignerId) { + + var gameDTO = designerService.deleteDesignerFromGame(gameId, gameByDesignerId); + return new ResponseEntity<>(gameDTO, HttpStatus.OK); + } + + +} diff --git a/src/main/java/com/petproject/boardgamefun/controller/DiaryController.java b/src/main/java/com/petproject/boardgamefun/controller/DiaryController.java new file mode 100644 index 0000000..92ba21f --- /dev/null +++ b/src/main/java/com/petproject/boardgamefun/controller/DiaryController.java @@ -0,0 +1,244 @@ +package com.petproject.boardgamefun.controller; + +import com.petproject.boardgamefun.dto.DiaryCommentDTO; +import com.petproject.boardgamefun.dto.DiaryDataDTO; +import com.petproject.boardgamefun.dto.DiaryRatingDTO; +import com.petproject.boardgamefun.dto.request.DiaryCommentRequest; +import com.petproject.boardgamefun.dto.request.DiaryRatingRequest; +import com.petproject.boardgamefun.model.Diary; +import com.petproject.boardgamefun.model.DiaryComment; +import com.petproject.boardgamefun.model.DiaryRating; +import com.petproject.boardgamefun.repository.DiaryCommentRepository; +import com.petproject.boardgamefun.repository.DiaryRatingRepository; +import com.petproject.boardgamefun.repository.DiaryRepository; +import com.petproject.boardgamefun.repository.UserRepository; +import com.petproject.boardgamefun.service.DiaryCommentService; +import com.petproject.boardgamefun.service.DiaryRatingService; +import com.petproject.boardgamefun.service.DiaryService; +import org.springframework.http.HttpStatus; +import org.springframework.http.ResponseEntity; +import org.springframework.security.access.prepost.PreAuthorize; +import org.springframework.web.bind.annotation.*; + +import javax.transaction.Transactional; +import java.time.OffsetDateTime; +import java.util.List; +import java.util.Objects; + + +@RestController +@RequestMapping("/diaries") +public class DiaryController { + final DiaryCommentRepository diaryCommentRepository; + final UserRepository userRepository; + final DiaryRepository diaryRepository; + final DiaryRatingRepository diaryRatingRepository; + final DiaryService diaryService; + final DiaryCommentService diaryCommentService; + final DiaryRatingService diaryRatingService; + + public DiaryController(DiaryCommentRepository diaryCommentRepository, UserRepository userRepository, DiaryRepository diaryRepository, DiaryRatingRepository diaryRatingRepository, DiaryService diaryService, DiaryCommentService diaryCommentService, DiaryRatingService diaryRatingService) { + this.diaryCommentRepository = diaryCommentRepository; + this.userRepository = userRepository; + this.diaryRepository = diaryRepository; + this.diaryRatingRepository = diaryRatingRepository; + this.diaryService = diaryService; + this.diaryCommentService = diaryCommentService; + this.diaryRatingService = diaryRatingService; + } + + @Transactional + @GetMapping("") + public ResponseEntity> getDiaries(@RequestParam(required = false) Integer userId, @RequestParam(required = false) Integer gameId) { + + List diaries; + + if (userId != null) + diaries = diaryService.projectionsToDiaryDTO(diaryRepository.findUserDiaries(userId)); + else if(gameId != null) + diaries = diaryService.projectionsToDiaryDTO(diaryRepository.findGameDiaries(gameId)); + else + diaries = diaryService.projectionsToDiaryDTO(diaryRepository.getAllDiaries()); + + return new ResponseEntity<>(diaries, HttpStatus.OK); + } + + @Transactional + @GetMapping("/{diaryId}") + public ResponseEntity getDiary(@PathVariable Integer diaryId) { + var diaryProjection = diaryService.projectionToDiaryDTO(diaryRepository.findDiaryUsingId(diaryId)); + + return new ResponseEntity<>(diaryProjection, HttpStatus.OK); + } + + @Transactional + @GetMapping("/{diaryId}/comments") + public ResponseEntity> getDiaryComments(@PathVariable Integer diaryId) { + var diaryComments = diaryCommentService.entitiesToCommentDTO(diaryCommentRepository.findDiaryComment_ByDiaryId(diaryId)); + + return new ResponseEntity<>(diaryComments, HttpStatus.OK); + } + + @Transactional + @PostMapping(value = "{diaryId}/add-comment/{userId}") + @PreAuthorize("hasRole('USER') or hasRole('MODERATOR') or hasRole('ADMIN')") + public ResponseEntity> addComment(@PathVariable Integer diaryId, @PathVariable Integer userId, @RequestBody DiaryCommentRequest diaryCommentRequest) { + + var user = userRepository.findUserById(userId); + var diary = diaryRepository.findDiaryById(diaryId); + + var diaryComment = new DiaryComment(); + diaryComment.setDiary(diary); + diaryComment.setUser(user); + diaryComment.setCommentTime(OffsetDateTime.now()); + diaryComment.setComment(diaryCommentRequest.getComment()); + diaryCommentRepository.save(diaryComment); + + var diaryComments = diaryCommentService.entitiesToCommentDTO(diaryCommentRepository.findDiaryComment_ByDiaryId(diaryId)); + + return new ResponseEntity<>(diaryComments, HttpStatus.OK); + } + + @Transactional + @PatchMapping(value = "{diaryId}/update-comment/{diaryCommentId}") + @PreAuthorize("hasRole('USER') or hasRole('MODERATOR') or hasRole('ADMIN')") + public ResponseEntity> updateComment(@PathVariable Integer diaryId, @PathVariable Integer diaryCommentId, @RequestBody DiaryCommentRequest diaryCommentRequest) { + var diaryComment = diaryCommentRepository.findDiaryCommentById(diaryCommentId); + if (diaryCommentRequest != null && !diaryCommentRequest.getComment().equals(diaryComment.getComment())) { + diaryComment.setComment(diaryCommentRequest.getComment()); + diaryCommentRepository.save(diaryComment); + } + + var diaryComments = diaryCommentService.entitiesToCommentDTO(diaryCommentRepository.findDiaryComment_ByDiaryId(diaryId)); + + return new ResponseEntity<>(diaryComments, HttpStatus.OK); + } + + @Transactional + @DeleteMapping("{diaryId}/delete-comment/{diaryCommentId}") + @PreAuthorize("hasRole('USER') or hasRole('MODERATOR') or hasRole('ADMIN')") + public ResponseEntity> deleteComment(@PathVariable Integer diaryId, @PathVariable Integer diaryCommentId) { + + var diaryComment = diaryCommentRepository.findDiaryCommentById(diaryCommentId); + diaryCommentRepository.delete(diaryComment); + var diaryComments = diaryCommentService.entitiesToCommentDTO(diaryCommentRepository.findDiaryComment_ByDiaryId(diaryId)); + + return new ResponseEntity<>(diaryComments, HttpStatus.OK); + } + + @Transactional + @PostMapping("/{diaryId}/set-rating/{userId}") + @PreAuthorize("hasRole('USER') or hasRole('MODERATOR') or hasRole('ADMIN')") + public ResponseEntity setDiaryRating(@PathVariable Integer diaryId, @PathVariable Integer userId, @RequestBody DiaryRatingRequest ratingRequest) { + var diary = diaryRepository.findDiaryById(diaryId); + var user = userRepository.findUserById(userId); + + var diaryRating = new DiaryRating(); + diaryRating.setDiary(diary); + diaryRating.setUser(user); + diaryRating.setRating(ratingRequest.getRating()); + diaryRatingRepository.save(diaryRating); + + var diaryRatingDTO = diaryRatingService.entityToDiaryRatingDTO(diaryRating); + + return new ResponseEntity<>(diaryRatingDTO, HttpStatus.OK); + } + + @Transactional + @PatchMapping("/update-rating/{ratingId}") + @PreAuthorize("hasRole('USER') or hasRole('MODERATOR') or hasRole('ADMIN')") + public ResponseEntity updateDiaryRating(@PathVariable Integer ratingId, @RequestBody DiaryRatingRequest ratingRequest) { + var diaryRating = diaryRatingRepository.findDiaryRatingById(ratingId); + + if (ratingRequest != null && !Objects.equals(diaryRating.getRating(), ratingRequest.getRating())) { + diaryRating.setRating(ratingRequest.getRating()); + } + + diaryRatingRepository.save(diaryRating); + var diaryRatingDTO = diaryRatingService.entityToDiaryRatingDTO(diaryRating); + + return new ResponseEntity<>(diaryRatingDTO, HttpStatus.OK); + } + + @Transactional + @DeleteMapping("/delete-rating/{ratingId}") + @PreAuthorize("hasRole('USER') or hasRole('MODERATOR') or hasRole('ADMIN')") + public ResponseEntity deleteDiaryRating(@PathVariable Integer ratingId) { + var diaryRating = diaryRatingRepository.findDiaryRatingById(ratingId); + diaryRatingRepository.delete(diaryRating); + return new ResponseEntity<>("Рейтинг убран с игры", HttpStatus.OK); + } + + /* @Transactional + @PostMapping("{userId}/add-diary/{gameId}") + @PreAuthorize("hasRole('USER') or hasRole('MODERATOR') or hasRole('ADMIN')") + public ResponseEntity addDiary(@PathVariable Integer userId, @PathVariable Integer gameId, @RequestBody Diary diary) { + + if (diary == null || diary.getGame() == null) { + return new ResponseEntity<>(null, HttpStatus.BAD_REQUEST); + } + + var user = userRepository.findUserById(userId); + var game = gameRepository.findGameById(gameId); + + if (game == null || user == null) { + return new ResponseEntity<>(null, HttpStatus.NOT_FOUND); + } + + diary.setUser(user); + diary.setGame(game); + diary.setPublicationTime(OffsetDateTime.now()); + diaryRepository.save(diary); + + var diaryDTO = diaryService.entityToDiaryDTO(diary); + + return new ResponseEntity<>(diaryDTO, HttpStatus.OK); + } + + @Transactional + @DeleteMapping("{userId}/remove-diary/{diaryId}") + @PreAuthorize("hasRole('USER') or hasRole('MODERATOR') or hasRole('ADMIN')") + public ResponseEntity deleteDiary(@PathVariable Integer userId, @PathVariable Integer diaryId) { + + var diary = diaryRepository.findDiary_ByUserIdAndId(userId, diaryId); + if (diary == null) { + return new ResponseEntity<>(null, HttpStatus.NOT_FOUND); + } + + diaryRepository.delete(diary); + + return new ResponseEntity<>("Дневник " + diary.getTitle() + " удален из ваших дневников", HttpStatus.OK); + } + + @Transactional + @PutMapping({"{userId}/update-diary/{diaryId}"}) + @PreAuthorize("hasRole('USER') or hasRole('MODERATOR') or hasRole('ADMIN')") + public ResponseEntity updateDiary(@PathVariable Integer diaryId, @PathVariable Integer userId, @RequestBody Diary diaryRequest) { + + if (diaryRequest.getId() == null) { + return new ResponseEntity<>(null, HttpStatus.BAD_REQUEST); + } + + var diary = diaryRepository.findDiary_ByUserIdAndId(userId, diaryId); + if (diary == null) { + return new ResponseEntity<>(null, HttpStatus.NOT_FOUND); + } + + if (diaryRequest.getTitle() != null && !Objects.equals(diary.getTitle(), diaryRequest.getTitle())) { + diary.setTitle(diaryRequest.getTitle()); + } + if (diaryRequest.getText() != null && !Objects.equals(diary.getText(), diaryRequest.getText())) { + diary.setText(diaryRequest.getText()); + } + + diaryRepository.save(diary); + + var diaryDTO = diaryService.entityToDiaryDTO(diary); + + return new ResponseEntity<>(diaryDTO, HttpStatus.OK); + }*/ + + + //todo: add updated time to comment; + //todo: add additional processing to ALL responses, not only OK +} diff --git a/src/main/java/com/petproject/boardgamefun/controller/ExpansionController.java b/src/main/java/com/petproject/boardgamefun/controller/ExpansionController.java new file mode 100644 index 0000000..15994ec --- /dev/null +++ b/src/main/java/com/petproject/boardgamefun/controller/ExpansionController.java @@ -0,0 +1,44 @@ +package com.petproject.boardgamefun.controller; + +import com.petproject.boardgamefun.dto.GameDataDTO; +import com.petproject.boardgamefun.service.ExpansionService; +import org.springframework.http.HttpStatus; +import org.springframework.http.ResponseEntity; +import org.springframework.security.access.prepost.PreAuthorize; +import org.springframework.web.bind.annotation.*; + +import java.util.List; + +@RestController +@RequestMapping("/expansions") +public class ExpansionController { + + final ExpansionService expansionService; + + public ExpansionController(ExpansionService expansionService) { + this.expansionService = expansionService; + } + + @GetMapping("/{gameId}") + public ResponseEntity> getExpansions(@PathVariable Integer gameId) { + + var gamesExpansions = expansionService.getExpansions(gameId); + return new ResponseEntity<>(gamesExpansions, HttpStatus.OK); + } + + @PostMapping("/{parentGameId}/{daughterGameId}") + @PreAuthorize("hasRole('USER') or hasRole('MODERATOR') or hasRole('ADMIN')") + public ResponseEntity> addExpansion(@PathVariable Integer parentGameId, @PathVariable Integer daughterGameId) { + + var gamesExpansions = expansionService.addExpansion(parentGameId, daughterGameId); + return new ResponseEntity<>(gamesExpansions, HttpStatus.OK); + } + + @DeleteMapping("/{parentGameId}/{daughterGameId}") + @PreAuthorize("hasRole('USER') or hasRole('MODERATOR') or hasRole('ADMIN')") + public ResponseEntity> deleteExpansion(@PathVariable Integer parentGameId, @PathVariable Integer daughterGameId) { + + var gamesExpansions = expansionService.deleteExpansion(parentGameId, daughterGameId); + return new ResponseEntity<>(gamesExpansions, HttpStatus.OK); + } +} diff --git a/src/main/java/com/petproject/boardgamefun/controller/ForumController.java b/src/main/java/com/petproject/boardgamefun/controller/ForumController.java new file mode 100644 index 0000000..3e99b1c --- /dev/null +++ b/src/main/java/com/petproject/boardgamefun/controller/ForumController.java @@ -0,0 +1,221 @@ +package com.petproject.boardgamefun.controller; + +import com.petproject.boardgamefun.dto.ForumDataDTO; +import com.petproject.boardgamefun.dto.ForumMessageDTO; +import com.petproject.boardgamefun.dto.request.ForumMessageRequest; +import com.petproject.boardgamefun.dto.request.ForumRatingRequest; +import com.petproject.boardgamefun.dto.request.ForumRequest; +import com.petproject.boardgamefun.model.Forum; +import com.petproject.boardgamefun.model.ForumMessage; +import com.petproject.boardgamefun.model.ForumRating; +import com.petproject.boardgamefun.repository.*; +import com.petproject.boardgamefun.service.ForumMessageService; +import com.petproject.boardgamefun.service.ForumService; +import org.springframework.http.HttpStatus; +import org.springframework.http.ResponseEntity; +import org.springframework.security.access.prepost.PreAuthorize; +import org.springframework.web.bind.annotation.*; + +import javax.transaction.Transactional; +import java.time.OffsetDateTime; +import java.util.List; +import java.util.Objects; + +@RestController +@RequestMapping("/forum") +public class ForumController { + + private final ForumRepository forumRepository; + private final GameRepository gameRepository; + private final UserRepository userRepository; + private final ForumMessageRepository forumMessageRepository; + private final ForumRatingRepository forumRatingRepository; + private final ForumService forumService; + private final ForumMessageService forumMessageService; + + public ForumController(ForumRepository forumRepository, GameRepository gameRepository, UserRepository userRepository, ForumMessageRepository forumMessageRepository, ForumRatingRepository forumRatingRepository, ForumService forumService, ForumMessageService forumMessageService) { + this.forumRepository = forumRepository; + this.gameRepository = gameRepository; + this.userRepository = userRepository; + this.forumMessageRepository = forumMessageRepository; + this.forumRatingRepository = forumRatingRepository; + this.forumService = forumService; + this.forumMessageService = forumMessageService; + } + + @Transactional + @GetMapping("") + public ResponseEntity> getForums(@RequestParam(required = false) Integer gameId, @RequestParam(required = false) Integer userId) { + List forums; + if (gameId != null) { + forums = forumService.projectionsToForumDTO(forumRepository.findForumsGameWithRating(gameId)); + } else if (userId != null) { + forums = forumService.projectionsToForumDTO(forumRepository.findForumsUserWithRating(userId)); + } else { + forums = forumService.projectionsToForumDTO(forumRepository.findForumsWithRating()); + } + + return new ResponseEntity<>(forums, HttpStatus.OK); + } + + @Transactional + @GetMapping("/{forumId}") + public ResponseEntity getForum(@PathVariable Integer forumId) { + var forum = forumService.projectionToForumDTO(forumRepository.findForumWithRatingUsingId(forumId)); + + return new ResponseEntity<>(forum, HttpStatus.OK); + } + + @Transactional + @PostMapping("add-forum/{gameId}/{userId}") + @PreAuthorize("hasRole('USER') or hasRole('MODERATOR') or hasRole('ADMIN')") + public ResponseEntity addForum(@PathVariable Integer gameId, @PathVariable Integer userId, @RequestBody ForumRequest forumRequest) { + + var user = userRepository.findUserById(userId); + var game = gameRepository.findGameById(gameId); + + var forum = new Forum(); + forum.setGame(game); + forum.setUser(user); + forum.setText(forumRequest.getText()); + forum.setTitle(forumRequest.getTitle()); + forum.setPublicationTime(OffsetDateTime.now()); + + forumRepository.save(forum); + + var forumDTO = forumService.entityToForumDTO(forum); + + return new ResponseEntity<>(forumDTO, HttpStatus.OK); + } + + @Transactional + @PatchMapping("/update-forum/{forumId}") + @PreAuthorize("hasRole('USER') or hasRole('MODERATOR') or hasRole('ADMIN')") + public ResponseEntity updateForum(@PathVariable Integer forumId, @RequestBody ForumRequest forumRequest) { + var forum = forumRepository.findForumById(forumId); + + if (forumRequest.getTitle() != null && !Objects.equals(forumRequest.getTitle(), forum.getTitle())) + forum.setTitle(forumRequest.getTitle()); + + if (forumRequest.getText() != null && !Objects.equals(forumRequest.getText(), forum.getText())) + forum.setText(forumRequest.getText()); + + forumRepository.save(forum); + + var forumDTO = forumService.entityToForumDTO(forum); + + return new ResponseEntity<>(forumDTO, HttpStatus.OK); + } + + @Transactional + @DeleteMapping("/delete-forum/{forumId}") + @PreAuthorize("hasRole('USER') or hasRole('MODERATOR') or hasRole('ADMIN')") + public ResponseEntity deleteForum(@PathVariable Integer forumId) { + + var forum = forumRepository.findForumById(forumId); + forumRepository.delete(forum); + + return new ResponseEntity<>("Топик " + forum.getTitle() + " удален из игры", HttpStatus.OK); + } + + @Transactional + @GetMapping("/messages") + public ResponseEntity> getMessages(@RequestParam(required = false) Integer forumId, @RequestParam(required = false) Integer userId) { + List messages; + if (forumId != null) + messages = forumMessageRepository.findByForumId(forumId); + else if (userId != null) + messages = forumMessageRepository.findByUserId(userId); + else + messages = forumMessageRepository.findAll(); + + var forumMessagesDTO = forumMessageService.entitiesToForumMessagesDTO(messages); + return new ResponseEntity<>(forumMessagesDTO, HttpStatus.OK); + } + + @Transactional + @PostMapping("/{forumId}/add-message/{userId}") + @PreAuthorize("hasRole('USER') or hasRole('MODERATOR') or hasRole('ADMIN')") + public ResponseEntity> addMessage(@PathVariable Integer forumId, @PathVariable Integer userId, @RequestBody ForumMessageRequest forumMessageRequest) { + var forum = forumRepository.findForumById(forumId); + var user = userRepository.findUserById(userId); + + var forumMessage = new ForumMessage(); + forumMessage.setForum(forum); + forumMessage.setUser(user); + forumMessage.setTime(OffsetDateTime.now()); + forumMessage.setComment(forumMessageRequest.getComment()); + + forumMessageRepository.save(forumMessage); + + var messages = forumMessageRepository.findByForumId(forumId); + + var forumMessagesDTO = forumMessageService.entitiesToForumMessagesDTO(messages); + + return new ResponseEntity<>(forumMessagesDTO, HttpStatus.OK); + } + + @Transactional + @PatchMapping("/{forumId}/update-message/{messageId}") + @PreAuthorize("hasRole('USER') or hasRole('MODERATOR') or hasRole('ADMIN')") + public ResponseEntity> updateMessage(@PathVariable Integer messageId, @PathVariable Integer forumId, @RequestBody ForumMessageRequest forumMessageRequest) { + var message = forumMessageRepository.findForumMessageById(messageId); + + if (!Objects.equals(forumMessageRequest.getComment(), message.getComment())) + message.setComment(forumMessageRequest.getComment()); + + forumMessageRepository.save(message); + + var messages = forumMessageService.entitiesToForumMessagesDTO(forumMessageRepository.findByForumId(forumId)); + + return new ResponseEntity<>(messages, HttpStatus.OK); + } + + @Transactional + @DeleteMapping("/{forumId}/delete-message/{messageId}") + @PreAuthorize("hasRole('USER') or hasRole('MODERATOR') or hasRole('ADMIN')") + public ResponseEntity> deleteMessage(@PathVariable Integer forumId, @PathVariable Integer messageId) { + var message = forumMessageRepository.findForumMessageById(messageId); + + forumMessageRepository.delete(message); + + var messages = forumMessageService.entitiesToForumMessagesDTO(forumMessageRepository.findByForumId(forumId)); + return new ResponseEntity<>(messages, HttpStatus.OK); + } + + @Transactional + @PostMapping("/{forumId}/set-rating/{userId}") + @PreAuthorize("hasRole('USER') or hasRole('MODERATOR') or hasRole('ADMIN')") + public ResponseEntity setForumRating(@PathVariable Integer forumId, @PathVariable Integer userId, @RequestBody ForumRatingRequest forumRatingRequest) { + + var forumRating = forumRatingRepository.findForumRating_ByForumIdAndUserId(forumId, userId); + if (forumRating == null) { + var forum = forumRepository.findForumById(forumId); + var user = userRepository.findUserById(userId); + + forumRating = new ForumRating(); + forumRating.setForum(forum); + forumRating.setUser(user); + } + forumRating.setRating(forumRatingRequest.getRating()); + + forumRatingRepository.save(forumRating); + var forum = forumService.projectionToForumDTO(forumRepository.findForumWithRatingUsingId(userId)); + return new ResponseEntity<>(forum, HttpStatus.OK); + } + + @Transactional + @DeleteMapping("/{forumId}/remove-rating/{ratingId}") + @PreAuthorize("hasRole('USER') or hasRole('MODERATOR') or hasRole('ADMIN')") + public ResponseEntity removeRatingFromForum(@PathVariable Integer forumId, @PathVariable Integer ratingId) { + var forumRating = forumRatingRepository.findForumRatingById(ratingId); + forumRatingRepository.delete(forumRating); + + var forum = forumService.projectionToForumDTO(forumRepository.findForumWithRatingUsingId(forumId)); + + return new ResponseEntity<>(forum, HttpStatus.OK); + } + + //todo: union patch method??? + //todo: forumDTO with rating and count messages +} diff --git a/src/main/java/com/petproject/boardgamefun/controller/GameController.java b/src/main/java/com/petproject/boardgamefun/controller/GameController.java new file mode 100644 index 0000000..f5a87c5 --- /dev/null +++ b/src/main/java/com/petproject/boardgamefun/controller/GameController.java @@ -0,0 +1,86 @@ +package com.petproject.boardgamefun.controller; + +import com.petproject.boardgamefun.dto.FilterGamesDTO; +import com.petproject.boardgamefun.dto.GameDataDTO; +import com.petproject.boardgamefun.model.Game; +import com.petproject.boardgamefun.service.GameService; +import org.jetbrains.annotations.NotNull; +import org.springframework.http.HttpStatus; +import org.springframework.http.ResponseEntity; +import org.springframework.security.access.prepost.PreAuthorize; +import org.springframework.web.bind.annotation.*; +import org.springframework.web.multipart.MultipartFile; + +import java.io.IOException; +import java.util.List; + +@RestController +@RequestMapping("/games") +public class GameController { + + final GameService gameService; + + public GameController(GameService gameService) { + this.gameService = gameService; + } + + @GetMapping() + ResponseEntity> getGames() { + var games = gameService.getGames(); + return new ResponseEntity<>(games, HttpStatus.OK); + } + + @GetMapping("/{id}") + public ResponseEntity getGameById(@PathVariable Integer id) { + var gameDataDTO = gameService.getGameById(id); + return new ResponseEntity<>(gameDataDTO, HttpStatus.OK); + } + + @GetMapping("/get-games-by-filter/{title}") + public ResponseEntity> getGamesByTitle(@PathVariable String title) { + var games = gameService.getGameByTitle(title); + return new ResponseEntity<>(games, HttpStatus.OK); + } + + @PostMapping("/") + @PreAuthorize("hasRole('MODERATOR') or hasRole('ADMIN')") + public ResponseEntity addGame(@RequestBody Game newGame) { + gameService.checkExistence(newGame); + return getGameDataDTOResponseEntity(newGame); + } + + @PostMapping("/upload-image/{gameId}") + @PreAuthorize("hasRole('USER') or hasRole('MODERATOR') or hasRole('ADMIN')") + public ResponseEntity uploadImage(@PathVariable Integer gameId, @RequestParam("picture") MultipartFile file) throws IOException { + var gameDTO = gameService.uploadImage(gameId, file); + return new ResponseEntity<>(gameDTO, HttpStatus.OK); + } + + @PutMapping("/") + @PreAuthorize("hasRole('MODERATOR') or hasRole('ADMIN')") + public ResponseEntity updateGame(@RequestBody Game updatedGame) { + return getGameDataDTOResponseEntity(updatedGame); + } + + @NotNull + private ResponseEntity getGameDataDTOResponseEntity(Game updatedGame) { + var game = gameService.save(updatedGame); + return new ResponseEntity<>(game, HttpStatus.OK); + } + + @DeleteMapping("/") + @PreAuthorize("hasRole('MODERATOR') or hasRole('ADMIN')") + public ResponseEntity removeGameFromSite(@RequestBody Game deleteGame) { + gameService.delete(deleteGame); + return new ResponseEntity<>(deleteGame.getTitle() + " удалена из базы данных", HttpStatus.OK); + } + @GetMapping("/{userId}/games") + public ResponseEntity> getUserCollection(@PathVariable Integer userId) { + + var games = gameService.getUserCollection(userId); + return new ResponseEntity<>(games, HttpStatus.OK); + } + + // todo: use standard hibernate deleteById and findById!!! + //todo: ratings list +} diff --git a/src/main/java/com/petproject/boardgamefun/controller/GameSellController.java b/src/main/java/com/petproject/boardgamefun/controller/GameSellController.java new file mode 100644 index 0000000..08c4047 --- /dev/null +++ b/src/main/java/com/petproject/boardgamefun/controller/GameSellController.java @@ -0,0 +1,49 @@ +package com.petproject.boardgamefun.controller; + +import com.petproject.boardgamefun.dto.GameSellDTO; +import com.petproject.boardgamefun.model.GameSell; +import com.petproject.boardgamefun.service.GameSellService; +import org.springframework.http.HttpStatus; +import org.springframework.http.ResponseEntity; +import org.springframework.security.access.prepost.PreAuthorize; +import org.springframework.web.bind.annotation.*; + +import java.util.List; + +@RestController +@RequestMapping("/game-sell") +public class GameSellController { + final GameSellService gameSellService; + + public GameSellController(GameSellService gameSellService) { + this.gameSellService = gameSellService; + } + + @PostMapping("{userId}/{gameId}") + @PreAuthorize("hasRole('USER') or hasRole('MODERATOR') or hasRole('ADMIN')") + public ResponseEntity> addGameToSellList(@PathVariable Integer userId, @PathVariable Integer gameId, @RequestBody GameSell gameSell) { + List gameSellList = gameSellService.addGameToSellList(userId, gameId, gameSell); + return new ResponseEntity<>(gameSellList, HttpStatus.OK); + } + + @DeleteMapping("{userId}/{gameId}") + @PreAuthorize("hasRole('USER') or hasRole('MODERATOR') or hasRole('ADMIN')") + public ResponseEntity removeGameFromSell(@PathVariable Integer userId, @PathVariable Integer gameId) { + gameSellService.removeGameFromSell(userId, gameId); + return new ResponseEntity<>(gameId, HttpStatus.OK); + } + + @PutMapping("") + @PreAuthorize("hasRole('USER') or hasRole('MODERATOR') or hasRole('ADMIN')") + public ResponseEntity updateSellGame(@RequestBody GameSell gameSell) { + gameSellService.updateGameSell(gameSell); + return new ResponseEntity<>(gameSell.getGame().getTitle() + " обновлена", HttpStatus.OK); + } + + @GetMapping("{userId}") + public ResponseEntity> getGameSellList(@PathVariable Integer userId) { + + var gameSellList = gameSellService.getGameSellList(userId); + return new ResponseEntity<>(gameSellList, HttpStatus.OK); + } +} diff --git a/src/main/java/com/petproject/boardgamefun/controller/ImageController.java b/src/main/java/com/petproject/boardgamefun/controller/ImageController.java new file mode 100644 index 0000000..15b919f --- /dev/null +++ b/src/main/java/com/petproject/boardgamefun/controller/ImageController.java @@ -0,0 +1,28 @@ +package com.petproject.boardgamefun.controller; + +import com.petproject.boardgamefun.model.Image; +import com.petproject.boardgamefun.repository.ImageRepository; +import org.springframework.http.HttpStatus; +import org.springframework.http.ResponseEntity; +import org.springframework.web.bind.annotation.GetMapping; +import org.springframework.web.bind.annotation.RequestMapping; +import org.springframework.web.bind.annotation.RestController; + +import java.util.List; + +@RestController +@RequestMapping("/images") +public class ImageController { + final ImageRepository imageRepository; + + public ImageController(ImageRepository imageRepository) { + this.imageRepository = imageRepository; + } + + @GetMapping() + ResponseEntity> getImages() { + var images = imageRepository.findAll(); + return new ResponseEntity<>(images, HttpStatus.OK); + + } +} diff --git a/src/main/java/com/petproject/boardgamefun/controller/RatingGameByUserController.java b/src/main/java/com/petproject/boardgamefun/controller/RatingGameByUserController.java new file mode 100644 index 0000000..e1a1d38 --- /dev/null +++ b/src/main/java/com/petproject/boardgamefun/controller/RatingGameByUserController.java @@ -0,0 +1,57 @@ +package com.petproject.boardgamefun.controller; + +import com.petproject.boardgamefun.dto.GameDataDTO; +import com.petproject.boardgamefun.dto.RatingGameByUserDTO; +import com.petproject.boardgamefun.service.RatingGameByUserService; +import org.springframework.http.HttpStatus; +import org.springframework.http.ResponseEntity; +import org.springframework.security.access.prepost.PreAuthorize; +import org.springframework.web.bind.annotation.*; + +import java.util.List; + +@RestController +@RequestMapping("/rating-game-by-user") +public class RatingGameByUserController { + final RatingGameByUserService ratingGameByUserService; + + public RatingGameByUserController(RatingGameByUserService ratingGameByUserService) { + this.ratingGameByUserService = ratingGameByUserService; + } + + @DeleteMapping("/{userId}/delete-game-rating/{gameId}") + @PreAuthorize("hasRole('USER') or hasRole('MODERATOR') or hasRole('ADMIN')") + public ResponseEntity deleteGameRating(@PathVariable Integer userId, @PathVariable Integer gameId) { + ratingGameByUserService.deleteGameRating(userId, gameId); + return new ResponseEntity<>("Оценка с текущей игры удалена", HttpStatus.OK); + } + + @PostMapping("/{userId}/{gameId}/{rating}") + @PreAuthorize("hasRole('USER') or hasRole('MODERATOR') or hasRole('ADMIN')") + public ResponseEntity setGameRating(@PathVariable Integer userId, @PathVariable Integer gameId, @PathVariable Integer rating) { + Double res = ratingGameByUserService.setGameRating(userId, gameId, rating); + return new ResponseEntity<>(res, HttpStatus.OK); + } + + @PatchMapping("/{userId}/{gameId}/{rating}") + @PreAuthorize("hasRole('USER') or hasRole('MODERATOR') or hasRole('ADMIN')") + public ResponseEntity updateGameRating(@PathVariable Integer userId, @PathVariable Integer gameId, @PathVariable Integer rating) { + Double res = ratingGameByUserService.updateGameRating(userId, gameId, rating); + return new ResponseEntity<>(res, HttpStatus.OK); + } + + @GetMapping("/{gameId}/users-rating") + public ResponseEntity> getUsersRating(@PathVariable Integer gameId) { + + var ratings = ratingGameByUserService.getUsersRating(gameId); + return new ResponseEntity<>(ratings, HttpStatus.OK); + } + + @GetMapping("/{userId}/games-rating") + public ResponseEntity> getUserRatingList(@PathVariable Integer userId) { + + var ratingGamesByUser = ratingGameByUserService.getUserRatingList(userId); + return new ResponseEntity<>(ratingGamesByUser, HttpStatus.OK); + } + +} diff --git a/src/main/java/com/petproject/boardgamefun/controller/SimilarGameController.java b/src/main/java/com/petproject/boardgamefun/controller/SimilarGameController.java new file mode 100644 index 0000000..f0ac3f5 --- /dev/null +++ b/src/main/java/com/petproject/boardgamefun/controller/SimilarGameController.java @@ -0,0 +1,45 @@ +package com.petproject.boardgamefun.controller; + + +import com.petproject.boardgamefun.dto.GameDataDTO; +import com.petproject.boardgamefun.service.SimilarGameService; +import org.springframework.http.HttpStatus; +import org.springframework.http.ResponseEntity; +import org.springframework.security.access.prepost.PreAuthorize; +import org.springframework.web.bind.annotation.*; + +import java.util.List; + +@RestController +@RequestMapping("/similar-games") +public class SimilarGameController { + + final SimilarGameService similarGameService; + + public SimilarGameController(SimilarGameService service) { + this.similarGameService = service; + } + + @GetMapping("/{gameId}") + public ResponseEntity> getSimilarGames(@PathVariable Integer gameId) { + + var similarGames = similarGameService.getSimilarGames(gameId); + return new ResponseEntity<>(similarGames, HttpStatus.OK); + } + + @PostMapping("/{referenceGameId}/{sourceGameId}") + @PreAuthorize("hasRole('USER') or hasRole('MODERATOR') or hasRole('ADMIN')") + public ResponseEntity> addSimilarGame(@PathVariable Integer referenceGameId, @PathVariable Integer sourceGameId) { + + var sameGames = similarGameService.addSimilarGame(referenceGameId, sourceGameId); + return new ResponseEntity<>(sameGames, HttpStatus.OK); + } + + @DeleteMapping("/{referenceGameId}/{sourceGameId}") + @PreAuthorize("hasRole('USER') or hasRole('MODERATOR') or hasRole('ADMIN')") + public ResponseEntity> deleteSameGame(@PathVariable Integer referenceGameId, @PathVariable Integer sourceGameId) { + + var sameGames = similarGameService.deleteSameGame(referenceGameId, sourceGameId); + return new ResponseEntity<>(sameGames, HttpStatus.OK); + } +} diff --git a/src/main/java/com/petproject/boardgamefun/controller/UserController.java b/src/main/java/com/petproject/boardgamefun/controller/UserController.java new file mode 100644 index 0000000..dbf3542 --- /dev/null +++ b/src/main/java/com/petproject/boardgamefun/controller/UserController.java @@ -0,0 +1,111 @@ +package com.petproject.boardgamefun.controller; + +import com.petproject.boardgamefun.dto.UserDTO; +import com.petproject.boardgamefun.dto.request.PasswordChangeRequest; +import com.petproject.boardgamefun.dto.request.UserEditRequest; +import com.petproject.boardgamefun.model.*; +import com.petproject.boardgamefun.security.jwt.JwtUtils; +import com.petproject.boardgamefun.security.model.JwtResponse; +import com.petproject.boardgamefun.security.model.LoginRequest; +import com.petproject.boardgamefun.security.model.RefreshTokenRequest; +import com.petproject.boardgamefun.security.model.RefreshTokenResponse; +import com.petproject.boardgamefun.security.services.RefreshTokenService; +import com.petproject.boardgamefun.security.services.UserDetailsImpl; +import com.petproject.boardgamefun.service.UserService; +import org.springframework.http.HttpStatus; +import org.springframework.http.ResponseEntity; +import org.springframework.security.access.prepost.PreAuthorize; +import org.springframework.security.authentication.AuthenticationManager; +import org.springframework.security.authentication.UsernamePasswordAuthenticationToken; +import org.springframework.security.core.Authentication; +import org.springframework.security.core.context.SecurityContextHolder; +import org.springframework.web.bind.annotation.*; +import org.springframework.web.multipart.MultipartFile; + +import java.io.IOException; +import java.util.List; + + +@RestController +@RequestMapping("/users") +public class UserController { + final UserService userService; + final JwtUtils jwtUtils; + final AuthenticationManager authenticationManager; + final RefreshTokenService refreshTokenService; + + public UserController(UserService userService,JwtUtils jwtUtils,AuthenticationManager authenticationManager, RefreshTokenService refreshTokenService) { + this.userService = userService; + this.jwtUtils = jwtUtils; + this.authenticationManager = authenticationManager; + this.refreshTokenService = refreshTokenService; + } + + @GetMapping() + public ResponseEntity> getUsers() { + var users = userService.getUsers(); + return new ResponseEntity<>(users, HttpStatus.OK); + } + + @PostMapping("sign-in") + public ResponseEntity authenticateUser(@RequestBody LoginRequest loginRequest) { + if (!userService.existsByName(loginRequest.getName())) { + return new ResponseEntity<>("Пользователя с таким никнеймом не существует", HttpStatus.NOT_FOUND); + } + Authentication authentication = authenticationManager.authenticate(new UsernamePasswordAuthenticationToken(loginRequest.getName(), loginRequest.getPassword())); + + SecurityContextHolder.getContext().setAuthentication(authentication); + String jwt = jwtUtils.generateJwtToken(authentication); + UserDetailsImpl userDetails = (UserDetailsImpl) authentication.getPrincipal(); + + var refreshToken = refreshTokenService.createRefreshToken(loginRequest.getName()); + return new ResponseEntity<>(new JwtResponse(jwt, userDetails.getId(), userDetails.getUsername(), userDetails.getEmail(), refreshToken), HttpStatus.OK); + } + + @PostMapping("/sign-up") + public ResponseEntity registerUser(@RequestBody User user) { + userService.registerUser(user); + return new ResponseEntity<>(user, HttpStatus.OK); + } + + @PostMapping("/refresh-token") + public ResponseEntity refreshToken(@RequestBody RefreshTokenRequest refreshTokenRequest) { + String refreshToken = refreshTokenRequest.getRefreshToken(); + if (refreshTokenService.verifyExpiration(refreshToken)) { + var token = jwtUtils.generateJwtToken(refreshTokenRequest.getUserName()); + return new ResponseEntity<>(new RefreshTokenResponse(token, refreshToken), HttpStatus.OK); + } + return new ResponseEntity<>(HttpStatus.UNAUTHORIZED); + } + + @PostMapping("/upload-avatar/{userName}") + public ResponseEntity uploadAvatar(@PathVariable String userName, @RequestParam("avatar") MultipartFile file) throws IOException { + this.userService.uploadAvatar(userName, file); + return new ResponseEntity<>(HttpStatus.OK); + } + + @PatchMapping("/{userId}") + @PreAuthorize("hasRole('USER') or hasRole('MODERATOR') or hasRole('ADMIN')") + public ResponseEntity editUser(@PathVariable Integer userId, @RequestBody UserEditRequest userEditRequest) { + UserDTO user = userService.editUser(userId, userEditRequest); + return new ResponseEntity<>(user, HttpStatus.OK); + } + + @PatchMapping("/change-password/{userId}") + @PreAuthorize("hasRole('USER') or hasRole('MODERATOR') or hasRole('ADMIN')") + public ResponseEntity changePassword(@PathVariable Integer userId, @RequestBody PasswordChangeRequest passwordRequest) { + UserDTO user = userService.changePassword(userId, passwordRequest); + return new ResponseEntity<>(user, HttpStatus.OK); + } + + @GetMapping("{id}") + public ResponseEntity getUser(@PathVariable Integer id) { + var userDTO = userService.getUser(id); + return new ResponseEntity<>(userDTO, HttpStatus.OK); + } + + //todo: optimize response - not whole model, only needed fields + //todo: add news + //todo: unique repository??? + +} diff --git a/src/main/java/com/petproject/boardgamefun/controller/UserOwnGameController.java b/src/main/java/com/petproject/boardgamefun/controller/UserOwnGameController.java new file mode 100644 index 0000000..424e775 --- /dev/null +++ b/src/main/java/com/petproject/boardgamefun/controller/UserOwnGameController.java @@ -0,0 +1,32 @@ +package com.petproject.boardgamefun.controller; + +import com.petproject.boardgamefun.service.UserOwnGameService; +import org.springframework.http.HttpStatus; +import org.springframework.http.ResponseEntity; +import org.springframework.security.access.prepost.PreAuthorize; +import org.springframework.web.bind.annotation.*; + +@RestController +@RequestMapping("/user-own-game") +public class UserOwnGameController { + + final UserOwnGameService userOwnGameService; + + public UserOwnGameController(UserOwnGameService userOwnGameService) { + this.userOwnGameService = userOwnGameService; + } + + @PostMapping("{userId}/{gameId}") + @PreAuthorize("hasRole('USER') or hasRole('MODERATOR') or hasRole('ADMIN')") + public ResponseEntity addGameToUser(@PathVariable Integer userId, @PathVariable Integer gameId) { + String gameTitle = userOwnGameService.addGameToUser(userId, gameId); + return new ResponseEntity<>(gameTitle + " добавлена в вашу коллекцию", HttpStatus.OK); + } + + @DeleteMapping("{userId}/{gameId}") + @PreAuthorize("hasRole('USER') or hasRole('MODERATOR') or hasRole('ADMIN')") + public ResponseEntity deleteGameFromUserCollection(@PathVariable Integer userId, @PathVariable Integer gameId) { + userOwnGameService.deleteGameFromUserCollection(userId, gameId); + return new ResponseEntity<>(gameId, HttpStatus.OK); + } +} diff --git a/src/main/java/com/petproject/boardgamefun/controller/UserWishController.java b/src/main/java/com/petproject/boardgamefun/controller/UserWishController.java new file mode 100644 index 0000000..8d20197 --- /dev/null +++ b/src/main/java/com/petproject/boardgamefun/controller/UserWishController.java @@ -0,0 +1,41 @@ +package com.petproject.boardgamefun.controller; + +import com.petproject.boardgamefun.dto.GameDataDTO; +import com.petproject.boardgamefun.service.UserWishService; +import org.springframework.http.HttpStatus; +import org.springframework.http.ResponseEntity; +import org.springframework.security.access.prepost.PreAuthorize; +import org.springframework.web.bind.annotation.*; + +import java.util.List; + +@RestController +@RequestMapping("/user-wishlist") +public class UserWishController { + + final UserWishService userWishService; + + public UserWishController(UserWishService userWishService) { + this.userWishService = userWishService; + } + + @PostMapping("{userId}/{gameId}") + @PreAuthorize("hasRole('USER') or hasRole('MODERATOR') or hasRole('ADMIN')") + public ResponseEntity addGameToUserWishlist(@PathVariable Integer userId, @PathVariable Integer gameId) { + String gameTitle = userWishService.addGameToUserWishlist(userId, gameId); + return new ResponseEntity<>(gameTitle + " добавлена в ваши желания", HttpStatus.OK); + } + + @DeleteMapping("{userWishId}") + @PreAuthorize("hasRole('USER') or hasRole('MODERATOR') or hasRole('ADMIN')") + public ResponseEntity deleteGameFromUserWishlist(@PathVariable Integer userWishId) { + userWishService.deleteGameFromUserWishlist(userWishId); + return new ResponseEntity<>(true, HttpStatus.OK); + } + + @GetMapping("/{id}") + public ResponseEntity> getUserWishlist(@PathVariable Integer id) { + var games = userWishService.getUserWishList(id); + return new ResponseEntity<>(games, HttpStatus.OK); + } +} diff --git a/src/main/java/com/petproject/boardgamefun/dto/DesignerDTO.java b/src/main/java/com/petproject/boardgamefun/dto/DesignerDTO.java new file mode 100644 index 0000000..00f9f63 --- /dev/null +++ b/src/main/java/com/petproject/boardgamefun/dto/DesignerDTO.java @@ -0,0 +1,11 @@ +package com.petproject.boardgamefun.dto; + +import lombok.AllArgsConstructor; +import lombok.Data; + +@Data +@AllArgsConstructor +public class DesignerDTO { + private Integer id; + private String designer; +} diff --git a/src/main/java/com/petproject/boardgamefun/dto/DiaryCommentDTO.java b/src/main/java/com/petproject/boardgamefun/dto/DiaryCommentDTO.java new file mode 100644 index 0000000..fce3963 --- /dev/null +++ b/src/main/java/com/petproject/boardgamefun/dto/DiaryCommentDTO.java @@ -0,0 +1,15 @@ +package com.petproject.boardgamefun.dto; + +import lombok.AllArgsConstructor; +import lombok.Data; + +import java.time.OffsetDateTime; + +@Data +@AllArgsConstructor +public class DiaryCommentDTO { + private Integer id; + private String comment; + private OffsetDateTime time; + private UserDTO user; +} diff --git a/src/main/java/com/petproject/boardgamefun/dto/DiaryDTO.java b/src/main/java/com/petproject/boardgamefun/dto/DiaryDTO.java new file mode 100644 index 0000000..2046153 --- /dev/null +++ b/src/main/java/com/petproject/boardgamefun/dto/DiaryDTO.java @@ -0,0 +1,8 @@ +package com.petproject.boardgamefun.dto; + +import java.io.Serializable; +import java.time.OffsetDateTime; + +public record DiaryDTO(Integer id, String title, String text, OffsetDateTime publicationTime, GameDTO game, + UserDTO user) implements Serializable { +} diff --git a/src/main/java/com/petproject/boardgamefun/dto/DiaryDataDTO.kt b/src/main/java/com/petproject/boardgamefun/dto/DiaryDataDTO.kt new file mode 100644 index 0000000..fee820a --- /dev/null +++ b/src/main/java/com/petproject/boardgamefun/dto/DiaryDataDTO.kt @@ -0,0 +1,3 @@ +package com.petproject.boardgamefun.dto + +data class DiaryDataDTO(val diary: DiaryDTO, val rating: Double?) \ No newline at end of file diff --git a/src/main/java/com/petproject/boardgamefun/dto/DiaryRatingDTO.java b/src/main/java/com/petproject/boardgamefun/dto/DiaryRatingDTO.java new file mode 100644 index 0000000..00d0509 --- /dev/null +++ b/src/main/java/com/petproject/boardgamefun/dto/DiaryRatingDTO.java @@ -0,0 +1,6 @@ +package com.petproject.boardgamefun.dto; + +import java.io.Serializable; + +public record DiaryRatingDTO(Integer id, Double rating) implements Serializable { +} diff --git a/src/main/java/com/petproject/boardgamefun/dto/FilterGamesDTO.java b/src/main/java/com/petproject/boardgamefun/dto/FilterGamesDTO.java new file mode 100644 index 0000000..95ecef5 --- /dev/null +++ b/src/main/java/com/petproject/boardgamefun/dto/FilterGamesDTO.java @@ -0,0 +1,11 @@ +package com.petproject.boardgamefun.dto; + +import lombok.AllArgsConstructor; +import lombok.Data; + +@Data +@AllArgsConstructor +public class FilterGamesDTO { + private Integer id; + private String title; +} diff --git a/src/main/java/com/petproject/boardgamefun/dto/ForumDTO.java b/src/main/java/com/petproject/boardgamefun/dto/ForumDTO.java new file mode 100644 index 0000000..7a4257c --- /dev/null +++ b/src/main/java/com/petproject/boardgamefun/dto/ForumDTO.java @@ -0,0 +1,8 @@ +package com.petproject.boardgamefun.dto; + +import java.io.Serializable; +import java.time.OffsetDateTime; + +public record ForumDTO(Integer id, String title, String text, OffsetDateTime publicationTime, GameDTO game, + UserDTO user) implements Serializable { +} diff --git a/src/main/java/com/petproject/boardgamefun/dto/ForumDataDTO.java b/src/main/java/com/petproject/boardgamefun/dto/ForumDataDTO.java new file mode 100644 index 0000000..f5b2c3e --- /dev/null +++ b/src/main/java/com/petproject/boardgamefun/dto/ForumDataDTO.java @@ -0,0 +1,13 @@ +package com.petproject.boardgamefun.dto; + +import lombok.AllArgsConstructor; +import lombok.Data; +import lombok.NoArgsConstructor; + +@Data +@AllArgsConstructor +@NoArgsConstructor +public class ForumDataDTO { + private ForumDTO forum; + private Double rating; +} diff --git a/src/main/java/com/petproject/boardgamefun/dto/ForumMessageDTO.java b/src/main/java/com/petproject/boardgamefun/dto/ForumMessageDTO.java new file mode 100644 index 0000000..bdc40dc --- /dev/null +++ b/src/main/java/com/petproject/boardgamefun/dto/ForumMessageDTO.java @@ -0,0 +1,15 @@ +package com.petproject.boardgamefun.dto; + +import lombok.AllArgsConstructor; +import lombok.Data; + +import java.time.OffsetDateTime; + +@Data +@AllArgsConstructor +public class ForumMessageDTO { + private Integer id; + private String message; + private OffsetDateTime messageTime; + private UserDTO user; +} diff --git a/src/main/java/com/petproject/boardgamefun/dto/GameDTO.java b/src/main/java/com/petproject/boardgamefun/dto/GameDTO.java new file mode 100644 index 0000000..94871bb --- /dev/null +++ b/src/main/java/com/petproject/boardgamefun/dto/GameDTO.java @@ -0,0 +1,9 @@ +package com.petproject.boardgamefun.dto; + +import java.io.Serializable; +import java.time.OffsetDateTime; + +public record GameDTO(Integer id, String title, OffsetDateTime yearOfRelease, String annotation, String description, + byte[] picture, String playerAge, Integer playersMin, Integer playersMax, Integer timeToPlayMin, + Integer timeToPlayMax) implements Serializable { +} diff --git a/src/main/java/com/petproject/boardgamefun/dto/GameDataDTO.java b/src/main/java/com/petproject/boardgamefun/dto/GameDataDTO.java new file mode 100644 index 0000000..0cf7fbb --- /dev/null +++ b/src/main/java/com/petproject/boardgamefun/dto/GameDataDTO.java @@ -0,0 +1,14 @@ +package com.petproject.boardgamefun.dto; + +import lombok.AllArgsConstructor; +import lombok.Data; + +import java.util.List; + +@Data +@AllArgsConstructor +public class GameDataDTO { + private GameDTO game; + private Double rating; + private List designers; +} diff --git a/src/main/java/com/petproject/boardgamefun/dto/GameSellDTO.java b/src/main/java/com/petproject/boardgamefun/dto/GameSellDTO.java new file mode 100644 index 0000000..39b92b6 --- /dev/null +++ b/src/main/java/com/petproject/boardgamefun/dto/GameSellDTO.java @@ -0,0 +1,15 @@ +package com.petproject.boardgamefun.dto; + +import lombok.AllArgsConstructor; +import lombok.Data; +import lombok.NoArgsConstructor; + +@Data +@AllArgsConstructor +@NoArgsConstructor +public class GameSellDTO { + private GameDTO game; + private String condition; + private String comment; + private Integer price; +} diff --git a/src/main/java/com/petproject/boardgamefun/dto/RatingGameByUserDTO.java b/src/main/java/com/petproject/boardgamefun/dto/RatingGameByUserDTO.java new file mode 100644 index 0000000..f03dfe8 --- /dev/null +++ b/src/main/java/com/petproject/boardgamefun/dto/RatingGameByUserDTO.java @@ -0,0 +1,6 @@ +package com.petproject.boardgamefun.dto; + +import java.io.Serializable; + +public record RatingGameByUserDTO(Integer id, Double rating) implements Serializable { +} diff --git a/src/main/java/com/petproject/boardgamefun/dto/UserDTO.java b/src/main/java/com/petproject/boardgamefun/dto/UserDTO.java new file mode 100644 index 0000000..62f849a --- /dev/null +++ b/src/main/java/com/petproject/boardgamefun/dto/UserDTO.java @@ -0,0 +1,9 @@ +package com.petproject.boardgamefun.dto; + +import java.io.Serializable; +import java.time.OffsetDateTime; + + +public record UserDTO(Integer id, String name, String password, String role, String mail, String town, Double rating, + byte[] avatar, OffsetDateTime registrationDate) implements Serializable { +} diff --git a/src/main/java/com/petproject/boardgamefun/dto/projection/DesignersProjection.java b/src/main/java/com/petproject/boardgamefun/dto/projection/DesignersProjection.java new file mode 100644 index 0000000..1cee152 --- /dev/null +++ b/src/main/java/com/petproject/boardgamefun/dto/projection/DesignersProjection.java @@ -0,0 +1,6 @@ +package com.petproject.boardgamefun.dto.projection; + + +public interface DesignersProjection { + String getDesigner(); +} diff --git a/src/main/java/com/petproject/boardgamefun/dto/projection/DiaryWithRatingsProjection.kt b/src/main/java/com/petproject/boardgamefun/dto/projection/DiaryWithRatingsProjection.kt new file mode 100644 index 0000000..db1fb25 --- /dev/null +++ b/src/main/java/com/petproject/boardgamefun/dto/projection/DiaryWithRatingsProjection.kt @@ -0,0 +1,8 @@ +package com.petproject.boardgamefun.dto.projection + +import com.petproject.boardgamefun.model.Diary + +interface DiaryWithRatingsProjection { + val diary: Diary + val rating: Double? +} \ No newline at end of file diff --git a/src/main/java/com/petproject/boardgamefun/dto/projection/ForumProjection.java b/src/main/java/com/petproject/boardgamefun/dto/projection/ForumProjection.java new file mode 100644 index 0000000..fa34e00 --- /dev/null +++ b/src/main/java/com/petproject/boardgamefun/dto/projection/ForumProjection.java @@ -0,0 +1,8 @@ +package com.petproject.boardgamefun.dto.projection; + +import com.petproject.boardgamefun.model.Forum; + +public interface ForumProjection { + Forum getForum(); + Double getRating(); +} diff --git a/src/main/java/com/petproject/boardgamefun/dto/projection/GameProjection.java b/src/main/java/com/petproject/boardgamefun/dto/projection/GameProjection.java new file mode 100644 index 0000000..428dc4e --- /dev/null +++ b/src/main/java/com/petproject/boardgamefun/dto/projection/GameProjection.java @@ -0,0 +1,9 @@ +package com.petproject.boardgamefun.dto.projection; + +import com.petproject.boardgamefun.model.Game; + + +public interface GameProjection { + Game getGame(); + Double getRating(); +} diff --git a/src/main/java/com/petproject/boardgamefun/dto/projection/GameSellProjection.java b/src/main/java/com/petproject/boardgamefun/dto/projection/GameSellProjection.java new file mode 100644 index 0000000..4009b36 --- /dev/null +++ b/src/main/java/com/petproject/boardgamefun/dto/projection/GameSellProjection.java @@ -0,0 +1,10 @@ +package com.petproject.boardgamefun.dto.projection; + +import com.petproject.boardgamefun.model.Game; + +public interface GameSellProjection { + Game getGame(); + String getCondition(); + String getComment(); + Integer getPrice(); +} diff --git a/src/main/java/com/petproject/boardgamefun/dto/projection/GamesFilterByTitleProjection.java b/src/main/java/com/petproject/boardgamefun/dto/projection/GamesFilterByTitleProjection.java new file mode 100644 index 0000000..e9a5d5b --- /dev/null +++ b/src/main/java/com/petproject/boardgamefun/dto/projection/GamesFilterByTitleProjection.java @@ -0,0 +1,6 @@ +package com.petproject.boardgamefun.dto.projection; + +public interface GamesFilterByTitleProjection { + String getTitle(); + Integer getId(); +} diff --git a/src/main/java/com/petproject/boardgamefun/dto/projection/UserGameRatingProjection.java b/src/main/java/com/petproject/boardgamefun/dto/projection/UserGameRatingProjection.java new file mode 100644 index 0000000..6d3fe63 --- /dev/null +++ b/src/main/java/com/petproject/boardgamefun/dto/projection/UserGameRatingProjection.java @@ -0,0 +1,8 @@ +package com.petproject.boardgamefun.dto.projection; + +import com.petproject.boardgamefun.model.Game; + +public interface UserGameRatingProjection { + Game getGame(); + Integer getRating(); +} \ No newline at end of file diff --git a/src/main/java/com/petproject/boardgamefun/dto/projection/UsersGameRatingProjection.java b/src/main/java/com/petproject/boardgamefun/dto/projection/UsersGameRatingProjection.java new file mode 100644 index 0000000..68d6d7e --- /dev/null +++ b/src/main/java/com/petproject/boardgamefun/dto/projection/UsersGameRatingProjection.java @@ -0,0 +1,8 @@ +package com.petproject.boardgamefun.dto.projection; + +import com.petproject.boardgamefun.model.User; + +public interface UsersGameRatingProjection { + User getUser(); + Double getRating(); +} diff --git a/src/main/java/com/petproject/boardgamefun/dto/request/DesignerRequest.java b/src/main/java/com/petproject/boardgamefun/dto/request/DesignerRequest.java new file mode 100644 index 0000000..e840f8d --- /dev/null +++ b/src/main/java/com/petproject/boardgamefun/dto/request/DesignerRequest.java @@ -0,0 +1,8 @@ +package com.petproject.boardgamefun.dto.request; + +import lombok.Data; + +@Data +public class DesignerRequest { + String name; +} diff --git a/src/main/java/com/petproject/boardgamefun/dto/request/DiaryCommentRequest.java b/src/main/java/com/petproject/boardgamefun/dto/request/DiaryCommentRequest.java new file mode 100644 index 0000000..7f3b989 --- /dev/null +++ b/src/main/java/com/petproject/boardgamefun/dto/request/DiaryCommentRequest.java @@ -0,0 +1,8 @@ +package com.petproject.boardgamefun.dto.request; + +import lombok.Data; + +@Data +public class DiaryCommentRequest { + private String comment; +} diff --git a/src/main/java/com/petproject/boardgamefun/dto/request/DiaryRatingRequest.java b/src/main/java/com/petproject/boardgamefun/dto/request/DiaryRatingRequest.java new file mode 100644 index 0000000..db4a681 --- /dev/null +++ b/src/main/java/com/petproject/boardgamefun/dto/request/DiaryRatingRequest.java @@ -0,0 +1,8 @@ +package com.petproject.boardgamefun.dto.request; + +import lombok.Data; + +@Data +public class DiaryRatingRequest { + private Double rating; +} diff --git a/src/main/java/com/petproject/boardgamefun/dto/request/ForumMessageRequest.java b/src/main/java/com/petproject/boardgamefun/dto/request/ForumMessageRequest.java new file mode 100644 index 0000000..63593f7 --- /dev/null +++ b/src/main/java/com/petproject/boardgamefun/dto/request/ForumMessageRequest.java @@ -0,0 +1,8 @@ +package com.petproject.boardgamefun.dto.request; + +import lombok.Data; + +@Data +public class ForumMessageRequest { + String comment; +} diff --git a/src/main/java/com/petproject/boardgamefun/dto/request/ForumRatingRequest.java b/src/main/java/com/petproject/boardgamefun/dto/request/ForumRatingRequest.java new file mode 100644 index 0000000..dfd46d3 --- /dev/null +++ b/src/main/java/com/petproject/boardgamefun/dto/request/ForumRatingRequest.java @@ -0,0 +1,8 @@ +package com.petproject.boardgamefun.dto.request; + +import lombok.Data; + +@Data +public class ForumRatingRequest { + Double rating; +} diff --git a/src/main/java/com/petproject/boardgamefun/dto/request/ForumRequest.java b/src/main/java/com/petproject/boardgamefun/dto/request/ForumRequest.java new file mode 100644 index 0000000..2e73a06 --- /dev/null +++ b/src/main/java/com/petproject/boardgamefun/dto/request/ForumRequest.java @@ -0,0 +1,9 @@ +package com.petproject.boardgamefun.dto.request; + +import lombok.Data; + +@Data +public class ForumRequest { + String title; + String text; +} diff --git a/src/main/java/com/petproject/boardgamefun/dto/request/PasswordChangeRequest.java b/src/main/java/com/petproject/boardgamefun/dto/request/PasswordChangeRequest.java new file mode 100644 index 0000000..311609c --- /dev/null +++ b/src/main/java/com/petproject/boardgamefun/dto/request/PasswordChangeRequest.java @@ -0,0 +1,8 @@ +package com.petproject.boardgamefun.dto.request; + +import lombok.Data; + +@Data +public class PasswordChangeRequest { + private String password; +} diff --git a/src/main/java/com/petproject/boardgamefun/dto/request/UserEditRequest.java b/src/main/java/com/petproject/boardgamefun/dto/request/UserEditRequest.java new file mode 100644 index 0000000..508dfe4 --- /dev/null +++ b/src/main/java/com/petproject/boardgamefun/dto/request/UserEditRequest.java @@ -0,0 +1,10 @@ +package com.petproject.boardgamefun.dto.request; + +import lombok.Data; + +@Data +public class UserEditRequest { + public String name; + public String role; + public byte[] avatar; +} diff --git a/src/main/java/com/petproject/boardgamefun/exception/BadRequestException.java b/src/main/java/com/petproject/boardgamefun/exception/BadRequestException.java new file mode 100644 index 0000000..9cafda7 --- /dev/null +++ b/src/main/java/com/petproject/boardgamefun/exception/BadRequestException.java @@ -0,0 +1,9 @@ +package com.petproject.boardgamefun.exception; + +public class BadRequestException extends RuntimeException{ + public BadRequestException(String message) { + super(message); + } + + public BadRequestException() {super();} +} diff --git a/src/main/java/com/petproject/boardgamefun/exception/DBChangeEntityOperationException.java b/src/main/java/com/petproject/boardgamefun/exception/DBChangeEntityOperationException.java new file mode 100644 index 0000000..2563ab8 --- /dev/null +++ b/src/main/java/com/petproject/boardgamefun/exception/DBChangeEntityOperationException.java @@ -0,0 +1,7 @@ +package com.petproject.boardgamefun.exception; + +public class DBChangeEntityOperationException extends RuntimeException { + public DBChangeEntityOperationException(String message) { + super(message); + } +} diff --git a/src/main/java/com/petproject/boardgamefun/exception/ErrorResponse.java b/src/main/java/com/petproject/boardgamefun/exception/ErrorResponse.java new file mode 100644 index 0000000..965d79f --- /dev/null +++ b/src/main/java/com/petproject/boardgamefun/exception/ErrorResponse.java @@ -0,0 +1,13 @@ +package com.petproject.boardgamefun.exception; + +public class ErrorResponse { + private String message; + + public String getMessage() { + return message; + } + + public void setMessage(String message) { + this.message = message; + } +} diff --git a/src/main/java/com/petproject/boardgamefun/exception/GlobalExceptionHandler.java b/src/main/java/com/petproject/boardgamefun/exception/GlobalExceptionHandler.java new file mode 100644 index 0000000..e6c36f1 --- /dev/null +++ b/src/main/java/com/petproject/boardgamefun/exception/GlobalExceptionHandler.java @@ -0,0 +1,71 @@ +package com.petproject.boardgamefun.exception; + +import org.springframework.http.HttpStatus; +import org.springframework.http.converter.HttpMessageNotReadableException; +import org.springframework.security.core.AuthenticationException; +import org.springframework.web.bind.annotation.ExceptionHandler; +import org.springframework.web.bind.annotation.ResponseBody; +import org.springframework.web.bind.annotation.ResponseStatus; +import org.springframework.web.bind.annotation.RestControllerAdvice; + +@RestControllerAdvice +public class GlobalExceptionHandler { + + @ExceptionHandler(NoRecordFoundException.class) + @ResponseStatus(HttpStatus.NOT_FOUND) + @ResponseBody + public ErrorResponse handleNoRecordFoundException(NoRecordFoundException ex) { + + ErrorResponse errorResponse = new ErrorResponse(); + errorResponse.setMessage("No Record Found"); + return errorResponse; + } + + @ExceptionHandler(DBChangeEntityOperationException.class) + @ResponseStatus(HttpStatus.INTERNAL_SERVER_ERROR) + @ResponseBody + public ErrorResponse handleDBChangeEntityOperationException(DBChangeEntityOperationException ex) { + + ErrorResponse errorResponse = new ErrorResponse(); + errorResponse.setMessage(ex.getMessage()); + return errorResponse; + } + + /*@ExceptionHandler(Exception.class) + @ResponseStatus(HttpStatus.INTERNAL_SERVER_ERROR) + @ResponseBody + public ErrorResponse handleDefaultException(Exception ex) { + ErrorResponse response = new ErrorResponse(); + response.setMessage(ex.getMessage()); + return response; + }*/ + + @ExceptionHandler(HttpMessageNotReadableException.class) + @ResponseStatus(HttpStatus.BAD_REQUEST) + @ResponseBody + public ErrorResponse handleRequiredRequestBodyException(Exception ex) { + ErrorResponse response = new ErrorResponse(); + response.setMessage(ex.getMessage()); + return response; + } + + @ExceptionHandler(AuthenticationException.class) + @ResponseStatus(HttpStatus.UNAUTHORIZED) + @ResponseBody + public ErrorResponse handleAuthException(AuthenticationException ex) { + ErrorResponse response = new ErrorResponse(); + response.setMessage(ex.getMessage()); + return response; + } + + @ExceptionHandler(BadRequestException.class) + @ResponseStatus(HttpStatus.BAD_REQUEST) + @ResponseBody + public ErrorResponse handleBadRequestException(BadRequestException ex) { + ErrorResponse errorResponse = new ErrorResponse(); + errorResponse.setMessage(ex.getMessage()); + return errorResponse; + } +} + + diff --git a/src/main/java/com/petproject/boardgamefun/exception/NoRecordFoundException.java b/src/main/java/com/petproject/boardgamefun/exception/NoRecordFoundException.java new file mode 100644 index 0000000..854e99e --- /dev/null +++ b/src/main/java/com/petproject/boardgamefun/exception/NoRecordFoundException.java @@ -0,0 +1,9 @@ +package com.petproject.boardgamefun.exception; + +public class NoRecordFoundException extends RuntimeException { + public NoRecordFoundException(String message) { + super(message); + } + + public NoRecordFoundException() {super();} +} diff --git a/src/main/java/com/petproject/boardgamefun/model/Category.java b/src/main/java/com/petproject/boardgamefun/model/Category.java new file mode 100644 index 0000000..db04f55 --- /dev/null +++ b/src/main/java/com/petproject/boardgamefun/model/Category.java @@ -0,0 +1,37 @@ +package com.petproject.boardgamefun.model; + +import org.hibernate.annotations.Type; + +import javax.persistence.*; + +@Table(name = "category", indexes = { + @Index(name = "category_name", columnList = "category", unique = true) +}) +@Entity +public class Category { + @Id + @GeneratedValue(strategy = GenerationType.IDENTITY) + @Column(name = "id", nullable = false) + private Integer id; + + @Lob + @Type(type = "org.hibernate.type.TextType") + @Column(name = "category") + private String category; + + public String getCategory() { + return category; + } + + public void setCategory(String category) { + this.category = category; + } + + public Integer getId() { + return id; + } + + public void setId(Integer id) { + this.id = id; + } +} \ No newline at end of file diff --git a/src/main/java/com/petproject/boardgamefun/model/Designer.java b/src/main/java/com/petproject/boardgamefun/model/Designer.java new file mode 100644 index 0000000..e8d4880 --- /dev/null +++ b/src/main/java/com/petproject/boardgamefun/model/Designer.java @@ -0,0 +1,33 @@ +package com.petproject.boardgamefun.model; + +import javax.persistence.*; + +@Table(name = "designers", indexes = { + @Index(name = "designers_un", columnList = "name", unique = true) +}) +@Entity +public class Designer { + @Id + @GeneratedValue(strategy = GenerationType.IDENTITY) + @Column(name = "id", nullable = false) + private Integer id; + + @Column(name = "name") + private String name; + + public String getName() { + return name; + } + + public void setName(String name) { + this.name = name; + } + + public Integer getId() { + return id; + } + + public void setId(Integer id) { + this.id = id; + } +} \ No newline at end of file diff --git a/src/main/java/com/petproject/boardgamefun/model/Diary.java b/src/main/java/com/petproject/boardgamefun/model/Diary.java new file mode 100644 index 0000000..19107b5 --- /dev/null +++ b/src/main/java/com/petproject/boardgamefun/model/Diary.java @@ -0,0 +1,84 @@ +package com.petproject.boardgamefun.model; + +import org.hibernate.annotations.Type; + +import javax.persistence.*; +import java.time.OffsetDateTime; + +@Table(name = "diary") +@Entity +public class Diary { + @Id + @GeneratedValue(strategy = GenerationType.IDENTITY) + @Column(name = "id", nullable = false) + private Integer id; + + @Lob + @Type(type = "org.hibernate.type.TextType") + @Column(name = "title", nullable = false) + private String title; + + @Lob + @Type(type = "org.hibernate.type.TextType") + @Column(name = "text", nullable = false) + private String text; + + @Column(name = "publication_time", nullable = false) + private OffsetDateTime publicationTime; + + @ManyToOne + @JoinColumn(name = "game") + private Game game; + + @ManyToOne(optional = false) + @JoinColumn(name = "\"user\"", nullable = false) + private User user; + + public User getUser() { + return user; + } + + public void setUser(User user) { + this.user = user; + } + + public Game getGame() { + return game; + } + + public void setGame(Game game) { + this.game = game; + } + + public OffsetDateTime getPublicationTime() { + return publicationTime; + } + + public void setPublicationTime(OffsetDateTime publicationTime) { + this.publicationTime = publicationTime; + } + + public String getText() { + return text; + } + + public void setText(String text) { + this.text = text; + } + + public String getTitle() { + return title; + } + + public void setTitle(String title) { + this.title = title; + } + + public Integer getId() { + return id; + } + + public void setId(Integer id) { + this.id = id; + } +} \ No newline at end of file diff --git a/src/main/java/com/petproject/boardgamefun/model/DiaryComment.java b/src/main/java/com/petproject/boardgamefun/model/DiaryComment.java new file mode 100644 index 0000000..c2f92bd --- /dev/null +++ b/src/main/java/com/petproject/boardgamefun/model/DiaryComment.java @@ -0,0 +1,72 @@ +package com.petproject.boardgamefun.model; + +import org.hibernate.annotations.Type; + +import javax.persistence.*; +import java.time.OffsetDateTime; + + +@Table(name = "diary_comment") +@Entity +public class DiaryComment { + @Id + @GeneratedValue(strategy = GenerationType.IDENTITY) + @Column(name = "id", nullable = false) + private Integer id; + + @Lob + @Type(type = "org.hibernate.type.TextType") + @Column(name = "comment", nullable = false) + private String comment; + + @Column(name = "comment_time", nullable = false) + private OffsetDateTime commentTime; + + @ManyToOne(optional = false) + @JoinColumn(name = "diary", nullable = false) + private Diary diary; + + @ManyToOne(optional = false) + @JoinColumn(name = "\"user\"", nullable = false) + private User user; + + public User getUser() { + return user; + } + + public void setUser(User user) { + this.user = user; + } + + public Diary getDiary() { + return diary; + } + + public void setDiary(Diary diary) { + this.diary = diary; + } + + public OffsetDateTime getCommentTime() { + return commentTime; + } + + public void setCommentTime(OffsetDateTime commentTime) { + this.commentTime = commentTime; + } + + public String getComment() { + return comment; + } + + public void setComment(String comment) { + this.comment = comment; + } + + public Integer getId() { + return id; + } + + public void setId(Integer id) { + this.id = id; + } +} \ No newline at end of file diff --git a/src/main/java/com/petproject/boardgamefun/model/DiaryRating.java b/src/main/java/com/petproject/boardgamefun/model/DiaryRating.java new file mode 100644 index 0000000..b179999 --- /dev/null +++ b/src/main/java/com/petproject/boardgamefun/model/DiaryRating.java @@ -0,0 +1,55 @@ +package com.petproject.boardgamefun.model; + +import javax.persistence.*; + +@Table(name = "diary_rating") +@Entity +public class DiaryRating { + @Id + @GeneratedValue(strategy = GenerationType.IDENTITY) + @Column(name = "id", nullable = false) + private Integer id; + + @Column(name = "rating", nullable = false) + private Double rating; + + @ManyToOne(optional = false) + @JoinColumn(name = "diary", nullable = false) + private Diary diary; + + @ManyToOne(optional = false) + @JoinColumn(name = "\"user\"", nullable = false) + private User user; + + public User getUser() { + return user; + } + + public void setUser(User user) { + this.user = user; + } + + public Diary getDiary() { + return diary; + } + + public void setDiary(Diary diary) { + this.diary = diary; + } + + public Double getRating() { + return rating; + } + + public void setRating(Double rating) { + this.rating = rating; + } + + public Integer getId() { + return id; + } + + public void setId(Integer id) { + this.id = id; + } +} \ No newline at end of file diff --git a/src/main/java/com/petproject/boardgamefun/model/Expansion.java b/src/main/java/com/petproject/boardgamefun/model/Expansion.java new file mode 100644 index 0000000..aef1196 --- /dev/null +++ b/src/main/java/com/petproject/boardgamefun/model/Expansion.java @@ -0,0 +1,44 @@ +package com.petproject.boardgamefun.model; + +import javax.persistence.*; + +@Table(name = "expansions") +@Entity +public class Expansion { + @Id + @GeneratedValue(strategy = GenerationType.IDENTITY) + @Column(name = "id", nullable = false) + private Integer id; + + @ManyToOne(optional = false) + @JoinColumn(name = "parent_game", nullable = false) + private Game parentGame; + + @ManyToOne(optional = false) + @JoinColumn(name = "daughter_game", nullable = false) + private Game daughterGame; + + public Game getDaughterGame() { + return daughterGame; + } + + public void setDaughterGame(Game daughterGame) { + this.daughterGame = daughterGame; + } + + public Game getParentGame() { + return parentGame; + } + + public void setParentGame(Game parentGame) { + this.parentGame = parentGame; + } + + public Integer getId() { + return id; + } + + public void setId(Integer id) { + this.id = id; + } +} \ No newline at end of file diff --git a/src/main/java/com/petproject/boardgamefun/model/File.java b/src/main/java/com/petproject/boardgamefun/model/File.java new file mode 100644 index 0000000..88a7b48 --- /dev/null +++ b/src/main/java/com/petproject/boardgamefun/model/File.java @@ -0,0 +1,55 @@ +package com.petproject.boardgamefun.model; + +import javax.persistence.*; + +@Table(name = "files") +@Entity +public class File { + @Id + @GeneratedValue(strategy = GenerationType.IDENTITY) + @Column(name = "id", nullable = false) + private Integer id; + + @ManyToOne(optional = false) + @JoinColumn(name = "game", nullable = false) + private Game game; + + @ManyToOne(optional = false) + @JoinColumn(name = "\"user\"", nullable = false) + private User user; + + @Column(name = "file", nullable = false) + private byte[] file; + + public byte[] getFile() { + return file; + } + + public void setFile(byte[] file) { + this.file = file; + } + + public User getUser() { + return user; + } + + public void setUser(User user) { + this.user = user; + } + + public Game getGame() { + return game; + } + + public void setGame(Game game) { + this.game = game; + } + + public Integer getId() { + return id; + } + + public void setId(Integer id) { + this.id = id; + } +} \ No newline at end of file diff --git a/src/main/java/com/petproject/boardgamefun/model/Forum.java b/src/main/java/com/petproject/boardgamefun/model/Forum.java new file mode 100644 index 0000000..35e9577 --- /dev/null +++ b/src/main/java/com/petproject/boardgamefun/model/Forum.java @@ -0,0 +1,84 @@ +package com.petproject.boardgamefun.model; + +import org.hibernate.annotations.Type; + +import javax.persistence.*; +import java.time.OffsetDateTime; + +@Table(name = "forum") +@Entity +public class Forum { + @Id + @GeneratedValue(strategy = GenerationType.IDENTITY) + @Column(name = "id", nullable = false) + private Integer id; + + @Lob + @Type(type = "org.hibernate.type.TextType") + @Column(name = "title", nullable = false) + private String title; + + @Lob + @Type(type = "org.hibernate.type.TextType") + @Column(name = "text", nullable = false) + private String text; + + @Column(name = "publication_time", nullable = false) + private OffsetDateTime publicationTime; + + @ManyToOne(optional = false) + @JoinColumn(name = "game", nullable = false) + private Game game; + + @ManyToOne(optional = false) + @JoinColumn(name = "\"user\"", nullable = false) + private User user; + + public User getUser() { + return user; + } + + public void setUser(User user) { + this.user = user; + } + + public Game getGame() { + return game; + } + + public void setGame(Game game) { + this.game = game; + } + + public OffsetDateTime getPublicationTime() { + return publicationTime; + } + + public void setPublicationTime(OffsetDateTime publicationTime) { + this.publicationTime = publicationTime; + } + + public String getText() { + return text; + } + + public void setText(String text) { + this.text = text; + } + + public String getTitle() { + return title; + } + + public void setTitle(String title) { + this.title = title; + } + + public Integer getId() { + return id; + } + + public void setId(Integer id) { + this.id = id; + } +} \ No newline at end of file diff --git a/src/main/java/com/petproject/boardgamefun/model/ForumMessage.java b/src/main/java/com/petproject/boardgamefun/model/ForumMessage.java new file mode 100644 index 0000000..825e0dc --- /dev/null +++ b/src/main/java/com/petproject/boardgamefun/model/ForumMessage.java @@ -0,0 +1,72 @@ +package com.petproject.boardgamefun.model; + +import org.hibernate.annotations.Type; + +import javax.persistence.*; +import java.time.OffsetDateTime; +import java.time.OffsetTime; + +@Table(name = "forum_message") +@Entity +public class ForumMessage { + @Id + @GeneratedValue(strategy = GenerationType.IDENTITY) + @Column(name = "id", nullable = false) + private Integer id; + + @ManyToOne(optional = false) + @JoinColumn(name = "forum", nullable = false) + private Forum forum; + + @Lob + @Type(type = "org.hibernate.type.TextType") + @Column(name = "comment", nullable = false) + private String comment; + + @ManyToOne(optional = false) + @JoinColumn(name = "\"user\"", nullable = false) + private User user; + + @Column(name = "\"time_message\"", nullable = false) + private OffsetDateTime time; + + public OffsetDateTime getTime() { + return time; + } + + public void setTime(OffsetDateTime time) { + this.time = time; + } + + public User getUser() { + return user; + } + + public void setUser(User user) { + this.user = user; + } + + public String getComment() { + return comment; + } + + public void setComment(String comment) { + this.comment = comment; + } + + public Forum getForum() { + return forum; + } + + public void setForum(Forum forum) { + this.forum = forum; + } + + public Integer getId() { + return id; + } + + public void setId(Integer id) { + this.id = id; + } +} \ No newline at end of file diff --git a/src/main/java/com/petproject/boardgamefun/model/ForumRating.java b/src/main/java/com/petproject/boardgamefun/model/ForumRating.java new file mode 100644 index 0000000..09e463f --- /dev/null +++ b/src/main/java/com/petproject/boardgamefun/model/ForumRating.java @@ -0,0 +1,55 @@ +package com.petproject.boardgamefun.model; + +import javax.persistence.*; + +@Table(name = "forum_rating") +@Entity +public class ForumRating { + @Id + @GeneratedValue(strategy = GenerationType.IDENTITY) + @Column(name = "id", nullable = false) + private Integer id; + + @ManyToOne(optional = false) + @JoinColumn(name = "forum", nullable = false) + private Forum forum; + + @ManyToOne(optional = false) + @JoinColumn(name = "\"user\"", nullable = false) + private User user; + + @Column(name = "rating", nullable = false) + private Double rating; + + public Double getRating() { + return rating; + } + + public void setRating(Double rating) { + this.rating = rating; + } + + public User getUser() { + return user; + } + + public void setUser(User user) { + this.user = user; + } + + public Forum getForum() { + return forum; + } + + public void setForum(Forum forum) { + this.forum = forum; + } + + public Integer getId() { + return id; + } + + public void setId(Integer id) { + this.id = id; + } +} \ No newline at end of file diff --git a/src/main/java/com/petproject/boardgamefun/model/Game.java b/src/main/java/com/petproject/boardgamefun/model/Game.java new file mode 100644 index 0000000..8712a29 --- /dev/null +++ b/src/main/java/com/petproject/boardgamefun/model/Game.java @@ -0,0 +1,139 @@ +package com.petproject.boardgamefun.model; + +import org.hibernate.annotations.Type; + +import javax.persistence.*; +import java.time.OffsetDateTime; + +@Table(name = "game", indexes = { + @Index(name = "game_un", columnList = "title", unique = true) +}) +@Entity +public class Game { + @Id + @GeneratedValue(strategy = GenerationType.IDENTITY) + @Column(name = "id", nullable = false) + private Integer id; + + @Column(name = "title", nullable = false) + private String title; + + @Column(name = "year_of_release", nullable = false) + private OffsetDateTime yearOfRelease; + + @Lob + @Type(type = "org.hibernate.type.TextType") + @Column(name = "annotation", nullable = false) + private String annotation; + + @Lob + @Type(type = "org.hibernate.type.TextType") + @Column(name = "description", nullable = false) + private String description; + + @Column(name = "picture") + private byte[] picture; + + @Column(name = "player_age") + private String playerAge; + + @Column(name = "players_min", nullable = false) + private Integer playersMin; + + @Column(name = "players_max", nullable = false) + private Integer playersMax; + + @Column(name = "time_to_play_min", nullable = false) + private Integer timeToPlayMin; + + @Column(name = "time_to_play_max", nullable = false) + private Integer timeToPlayMax; + + public Integer getTimeToPlayMax() { + return timeToPlayMax; + } + + public void setTimeToPlayMax(Integer timeToPlayMax) { + this.timeToPlayMax = timeToPlayMax; + } + + public Integer getTimeToPlayMin() { + return timeToPlayMin; + } + + public void setTimeToPlayMin(Integer timeToPlayMin) { + this.timeToPlayMin = timeToPlayMin; + } + + public Integer getPlayersMax() { + return playersMax; + } + + public void setPlayersMax(Integer playersMax) { + this.playersMax = playersMax; + } + + public Integer getPlayersMin() { + return playersMin; + } + + public void setPlayersMin(Integer playersMin) { + this.playersMin = playersMin; + } + + public String getPlayerAge() { + return playerAge; + } + + public void setPlayerAge(String playerAge) { + this.playerAge = playerAge; + } + + public byte[] getPicture() { + return picture; + } + + public void setPicture(byte[] picture) { + this.picture = picture; + } + + public String getDescription() { + return description; + } + + public void setDescription(String description) { + this.description = description; + } + + public String getAnnotation() { + return annotation; + } + + public void setAnnotation(String annotation) { + this.annotation = annotation; + } + + public OffsetDateTime getYearOfRelease() { + return yearOfRelease; + } + + public void setYearOfRelease(OffsetDateTime yearOfRelease) { + this.yearOfRelease = yearOfRelease; + } + + public String getTitle() { + return title; + } + + public void setTitle(String title) { + this.title = title; + } + + public Integer getId() { + return id; + } + + public void setId(Integer id) { + this.id = id; + } +} \ No newline at end of file diff --git a/src/main/java/com/petproject/boardgamefun/model/GameByDesigner.java b/src/main/java/com/petproject/boardgamefun/model/GameByDesigner.java new file mode 100644 index 0000000..719a3fb --- /dev/null +++ b/src/main/java/com/petproject/boardgamefun/model/GameByDesigner.java @@ -0,0 +1,44 @@ +package com.petproject.boardgamefun.model; + +import javax.persistence.*; + +@Table(name = "game_by_designers") +@Entity +public class GameByDesigner { + @Id + @GeneratedValue(strategy = GenerationType.IDENTITY) + @Column(name = "id", nullable = false) + private Integer id; + + @ManyToOne(optional = false) + @JoinColumn(name = "designer", nullable = false) + private Designer designer; + + @ManyToOne(optional = false) + @JoinColumn(name = "game", nullable = false) + private Game game; + + public Game getGame() { + return game; + } + + public void setGame(Game game) { + this.game = game; + } + + public Designer getDesigner() { + return designer; + } + + public void setDesigner(Designer designer) { + this.designer = designer; + } + + public Integer getId() { + return id; + } + + public void setId(Integer id) { + this.id = id; + } +} \ No newline at end of file diff --git a/src/main/java/com/petproject/boardgamefun/model/GameCategory.java b/src/main/java/com/petproject/boardgamefun/model/GameCategory.java new file mode 100644 index 0000000..ba31d60 --- /dev/null +++ b/src/main/java/com/petproject/boardgamefun/model/GameCategory.java @@ -0,0 +1,44 @@ +package com.petproject.boardgamefun.model; + +import javax.persistence.*; + +@Table(name = "game_category") +@Entity +public class GameCategory { + @Id + @GeneratedValue(strategy = GenerationType.IDENTITY) + @Column(name = "id", nullable = false) + private Integer id; + + @ManyToOne(optional = false) + @JoinColumn(name = "category", nullable = false) + private Category category; + + @ManyToOne(optional = false) + @JoinColumn(name = "game", nullable = false) + private Game game; + + public Game getGame() { + return game; + } + + public void setGame(Game game) { + this.game = game; + } + + public Category getCategory() { + return category; + } + + public void setCategory(Category category) { + this.category = category; + } + + public Integer getId() { + return id; + } + + public void setId(Integer id) { + this.id = id; + } +} \ No newline at end of file diff --git a/src/main/java/com/petproject/boardgamefun/model/GameSell.java b/src/main/java/com/petproject/boardgamefun/model/GameSell.java new file mode 100644 index 0000000..5598867 --- /dev/null +++ b/src/main/java/com/petproject/boardgamefun/model/GameSell.java @@ -0,0 +1,83 @@ +package com.petproject.boardgamefun.model; + +import org.hibernate.annotations.Type; + +import javax.persistence.*; + +@Table(name = "game_sell") +@Entity +public class GameSell { + @Id + @GeneratedValue(strategy = GenerationType.IDENTITY) + @Column(name = "id", nullable = false) + private Integer id; + + @Lob + @Type(type = "org.hibernate.type.TextType") + @Column(name = "condition", nullable = false) + private String condition; + + @Column(name = "price", nullable = false) + private Integer price; + + @Lob + @Type(type = "org.hibernate.type.TextType") + @Column(name = "comment", nullable = false) + private String comment; + + @ManyToOne(optional = false) + @JoinColumn(name = "\"user\"", nullable = false) + private User user; + + @ManyToOne(optional = false) + @JoinColumn(name = "game", nullable = false) + private Game game; + + public Game getGame() { + return game; + } + + public void setGame(Game game) { + this.game = game; + } + + public User getUser() { + return user; + } + + public void setUser(User user) { + this.user = user; + } + + public String getComment() { + return comment; + } + + public void setComment(String comment) { + this.comment = comment; + } + + public Integer getPrice() { + return price; + } + + public void setPrice(Integer price) { + this.price = price; + } + + public String getCondition() { + return condition; + } + + public void setCondition(String condition) { + this.condition = condition; + } + + public Integer getId() { + return id; + } + + public void setId(Integer id) { + this.id = id; + } +} \ No newline at end of file diff --git a/src/main/java/com/petproject/boardgamefun/model/Image.java b/src/main/java/com/petproject/boardgamefun/model/Image.java new file mode 100644 index 0000000..c4e0787 --- /dev/null +++ b/src/main/java/com/petproject/boardgamefun/model/Image.java @@ -0,0 +1,31 @@ +package com.petproject.boardgamefun.model; + +import javax.persistence.*; + +@Table(name = "image") +@Entity +public class Image { + @Id + @GeneratedValue(strategy = GenerationType.IDENTITY) + @Column(name = "id", nullable = false) + private Integer id; + + @Column(name = "image", nullable = false) + private byte[] image; + + public byte[] getImage() { + return image; + } + + public void setImage(byte[] image) { + this.image = image; + } + + public Integer getId() { + return id; + } + + public void setId(Integer id) { + this.id = id; + } +} \ No newline at end of file diff --git a/src/main/java/com/petproject/boardgamefun/model/ImageBinder.java b/src/main/java/com/petproject/boardgamefun/model/ImageBinder.java new file mode 100644 index 0000000..c6487de --- /dev/null +++ b/src/main/java/com/petproject/boardgamefun/model/ImageBinder.java @@ -0,0 +1,92 @@ +package com.petproject.boardgamefun.model; + +import javax.persistence.*; + +@Table(name = "image_binder") +@Entity +public class ImageBinder { + @Id + @GeneratedValue(strategy = GenerationType.IDENTITY) + @Column(name = "id", nullable = false) + private Integer id; + + @ManyToOne + @JoinColumn(name = "news") + private News news; + + @ManyToOne + @JoinColumn(name = "diary") + private Diary diary; + + @ManyToOne(optional = false) + @JoinColumn(name = "\"user\"", nullable = false) + private User user; + + @ManyToOne + @JoinColumn(name = "forum") + private ForumMessage forum; + + @ManyToOne(optional = false) + @JoinColumn(name = "image", nullable = false) + private Image image; + + @ManyToOne + @JoinColumn(name = "game") + private Game game; + + public Game getGame() { + return game; + } + + public void setGame(Game game) { + this.game = game; + } + + public Image getImage() { + return image; + } + + public void setImage(Image image) { + this.image = image; + } + + public ForumMessage getForum() { + return forum; + } + + public void setForum(ForumMessage forum) { + this.forum = forum; + } + + public User getUser() { + return user; + } + + public void setUser(User user) { + this.user = user; + } + + public Diary getDiary() { + return diary; + } + + public void setDiary(Diary diary) { + this.diary = diary; + } + + public News getNews() { + return news; + } + + public void setNews(News news) { + this.news = news; + } + + public Integer getId() { + return id; + } + + public void setId(Integer id) { + this.id = id; + } +} \ No newline at end of file diff --git a/src/main/java/com/petproject/boardgamefun/model/Messenger.java b/src/main/java/com/petproject/boardgamefun/model/Messenger.java new file mode 100644 index 0000000..5a9c811 --- /dev/null +++ b/src/main/java/com/petproject/boardgamefun/model/Messenger.java @@ -0,0 +1,82 @@ +package com.petproject.boardgamefun.model; + +import org.hibernate.annotations.Type; + +import javax.persistence.*; +import java.time.OffsetTime; + +@Table(name = "messenger") +@Entity +public class Messenger { + @Id + @GeneratedValue(strategy = GenerationType.IDENTITY) + @Column(name = "id", nullable = false) + private Integer id; + + @Lob + @Type(type = "org.hibernate.type.TextType") + @Column(name = "text", nullable = false) + private String text; + + @Column(name = "is_red", nullable = false) + private Boolean isRed = false; + + @Column(name = "message_time", nullable = false) + private OffsetTime messageTime; + + @ManyToOne(optional = false) + @JoinColumn(name = "user_to", nullable = false) + private User userTo; + + @ManyToOne(optional = false) + @JoinColumn(name = "user_from", nullable = false) + private User userFrom; + + public User getUserFrom() { + return userFrom; + } + + public void setUserFrom(User userFrom) { + this.userFrom = userFrom; + } + + public User getUserTo() { + return userTo; + } + + public void setUserTo(User userTo) { + this.userTo = userTo; + } + + public OffsetTime getMessageTime() { + return messageTime; + } + + public void setMessageTime(OffsetTime messageTime) { + this.messageTime = messageTime; + } + + public Boolean getIsRed() { + return isRed; + } + + public void setIsRed(Boolean isRed) { + this.isRed = isRed; + } + + public String getText() { + return text; + } + + public void setText(String text) { + this.text = text; + } + + public Integer getId() { + return id; + } + + public void setId(Integer id) { + this.id = id; + } +} \ No newline at end of file diff --git a/src/main/java/com/petproject/boardgamefun/model/News.java b/src/main/java/com/petproject/boardgamefun/model/News.java new file mode 100644 index 0000000..06d55e5 --- /dev/null +++ b/src/main/java/com/petproject/boardgamefun/model/News.java @@ -0,0 +1,84 @@ +package com.petproject.boardgamefun.model; + +import org.hibernate.annotations.Type; + +import javax.persistence.*; +import java.time.OffsetDateTime; + +@Table(name = "news") +@Entity +public class News { + @Id + @GeneratedValue(strategy = GenerationType.IDENTITY) + @Column(name = "id", nullable = false) + private Integer id; + + @Lob + @Type(type = "org.hibernate.type.TextType") + @Column(name = "title", nullable = false) + private String title; + + @Lob + @Type(type = "org.hibernate.type.TextType") + @Column(name = "text", nullable = false) + private String text; + + @ManyToOne(optional = false) + @JoinColumn(name = "\"user\"", nullable = false) + private User user; + + @ManyToOne + @JoinColumn(name = "game") + private Game game; + + @Column(name = "publication_time", nullable = false) + private OffsetDateTime publicationTime; + + public OffsetDateTime getPublicationTime() { + return publicationTime; + } + + public void setPublicationTime(OffsetDateTime publicationTime) { + this.publicationTime = publicationTime; + } + + public Game getGame() { + return game; + } + + public void setGame(Game game) { + this.game = game; + } + + public User getUser() { + return user; + } + + public void setUser(User user) { + this.user = user; + } + + public String getText() { + return text; + } + + public void setText(String text) { + this.text = text; + } + + public String getTitle() { + return title; + } + + public void setTitle(String title) { + this.title = title; + } + + public Integer getId() { + return id; + } + + public void setId(Integer id) { + this.id = id; + } +} \ No newline at end of file diff --git a/src/main/java/com/petproject/boardgamefun/model/NewsComment.java b/src/main/java/com/petproject/boardgamefun/model/NewsComment.java new file mode 100644 index 0000000..cd98d36 --- /dev/null +++ b/src/main/java/com/petproject/boardgamefun/model/NewsComment.java @@ -0,0 +1,71 @@ +package com.petproject.boardgamefun.model; + +import org.hibernate.annotations.Type; + +import javax.persistence.*; +import java.time.OffsetTime; + +@Table(name = "news_comments") +@Entity +public class NewsComment { + @Id + @GeneratedValue(strategy = GenerationType.IDENTITY) + @Column(name = "id", nullable = false) + private Integer id; + + @Lob + @Type(type = "org.hibernate.type.TextType") + @Column(name = "comment", nullable = false) + private String comment; + + @Column(name = "comment_time", nullable = false) + private OffsetTime commentTime; + + @ManyToOne(optional = false) + @JoinColumn(name = "\"user\"", nullable = false) + private User user; + + @ManyToOne(optional = false) + @JoinColumn(name = "news", nullable = false) + private News news; + + public News getNews() { + return news; + } + + public void setNews(News news) { + this.news = news; + } + + public User getUser() { + return user; + } + + public void setUser(User user) { + this.user = user; + } + + public OffsetTime getCommentTime() { + return commentTime; + } + + public void setCommentTime(OffsetTime commentTime) { + this.commentTime = commentTime; + } + + public String getComment() { + return comment; + } + + public void setComment(String comment) { + this.comment = comment; + } + + public Integer getId() { + return id; + } + + public void setId(Integer id) { + this.id = id; + } +} \ No newline at end of file diff --git a/src/main/java/com/petproject/boardgamefun/model/NewsRating.java b/src/main/java/com/petproject/boardgamefun/model/NewsRating.java new file mode 100644 index 0000000..9194384 --- /dev/null +++ b/src/main/java/com/petproject/boardgamefun/model/NewsRating.java @@ -0,0 +1,55 @@ +package com.petproject.boardgamefun.model; + +import javax.persistence.*; + +@Table(name = "news_rating") +@Entity +public class NewsRating { + @Id + @GeneratedValue(strategy = GenerationType.IDENTITY) + @Column(name = "id", nullable = false) + private Integer id; + + @Column(name = "rating", nullable = false) + private Double rating; + + @ManyToOne(optional = false) + @JoinColumn(name = "news", nullable = false) + private News news; + + @ManyToOne(optional = false) + @JoinColumn(name = "\"user\"", nullable = false) + private User user; + + public User getUser() { + return user; + } + + public void setUser(User user) { + this.user = user; + } + + public News getNews() { + return news; + } + + public void setNews(News news) { + this.news = news; + } + + public Double getRating() { + return rating; + } + + public void setRating(Double rating) { + this.rating = rating; + } + + public Integer getId() { + return id; + } + + public void setId(Integer id) { + this.id = id; + } +} \ No newline at end of file diff --git a/src/main/java/com/petproject/boardgamefun/model/RatingGameByUser.java b/src/main/java/com/petproject/boardgamefun/model/RatingGameByUser.java new file mode 100644 index 0000000..dfe4679 --- /dev/null +++ b/src/main/java/com/petproject/boardgamefun/model/RatingGameByUser.java @@ -0,0 +1,55 @@ +package com.petproject.boardgamefun.model; + +import javax.persistence.*; + +@Table(name = "rating_game_by_user") +@Entity +public class RatingGameByUser { + @Id + @GeneratedValue(strategy = GenerationType.IDENTITY) + @Column(name = "id", nullable = false) + private Integer id; + + @Column(name = "rating", nullable = false) + private Double rating; + + @ManyToOne(optional = false) + @JoinColumn(name = "\"user\"", nullable = false) + private User user; + + @ManyToOne(optional = false) + @JoinColumn(name = "game", nullable = false) + private Game game; + + public Game getGame() { + return game; + } + + public void setGame(Game game) { + this.game = game; + } + + public User getUser() { + return user; + } + + public void setUser(User user) { + this.user = user; + } + + public Double getRating() { + return rating; + } + + public void setRating(Double rating) { + this.rating = rating; + } + + public Integer getId() { + return id; + } + + public void setId(Integer id) { + this.id = id; + } +} \ No newline at end of file diff --git a/src/main/java/com/petproject/boardgamefun/model/SameGame.java b/src/main/java/com/petproject/boardgamefun/model/SameGame.java new file mode 100644 index 0000000..2e969dd --- /dev/null +++ b/src/main/java/com/petproject/boardgamefun/model/SameGame.java @@ -0,0 +1,44 @@ +package com.petproject.boardgamefun.model; + +import javax.persistence.*; + +@Table(name = "same_game") +@Entity +public class SameGame { + @Id + @GeneratedValue(strategy = GenerationType.IDENTITY) + @Column(name = "id", nullable = false) + private Integer id; + + @ManyToOne(optional = false) + @JoinColumn(name = "reference_game", nullable = false) + private Game referenceGame; + + @ManyToOne(optional = false) + @JoinColumn(name = "source_game", nullable = false) + private Game sourceGame; + + public Game getSourceGame() { + return sourceGame; + } + + public void setSourceGame(Game sourceGame) { + this.sourceGame = sourceGame; + } + + public Game getReferenceGame() { + return referenceGame; + } + + public void setReferenceGame(Game referenceGame) { + this.referenceGame = referenceGame; + } + + public Integer getId() { + return id; + } + + public void setId(Integer id) { + this.id = id; + } +} \ No newline at end of file diff --git a/src/main/java/com/petproject/boardgamefun/model/User.java b/src/main/java/com/petproject/boardgamefun/model/User.java new file mode 100644 index 0000000..7a8a957 --- /dev/null +++ b/src/main/java/com/petproject/boardgamefun/model/User.java @@ -0,0 +1,115 @@ +package com.petproject.boardgamefun.model; + +import org.hibernate.annotations.Type; + +import javax.persistence.*; +import java.time.OffsetDateTime; + +@Table(name = "site_user", indexes = { + @Index(name = "mail_un", columnList = "mail", unique = true), + @Index(name = "user_un", columnList = "name", unique = true) +}) +@Entity +public class User { + @Id + @GeneratedValue(strategy = GenerationType.IDENTITY) + @Column(name = "id", nullable = false) + private Integer id; + + @Column(name = "name", nullable = false) + private String name; + + @Lob + @Column(name = "password", nullable = false) + private String password; + + @Column(name = "role", nullable = false) + private String role; + + @Column(name = "mail", nullable = false) + private String mail; + + @Column(name = "town") + private String town; + + @Column(name = "rating") + private Double rating; + + @Column(name = "avatar") + private byte[] avatar; + + @Column(name = "registration_date", nullable = false) + private OffsetDateTime registrationDate; + + public OffsetDateTime getRegistrationDate() { + return registrationDate; + } + + public void setRegistrationDate(OffsetDateTime registrationDate) { + this.registrationDate = registrationDate; + } + + public byte[] getAvatar() { + return avatar; + } + + public void setAvatar(byte[] avatar) { + this.avatar = avatar; + } + + public Double getRating() { + return rating; + } + + public void setRating(Double rating) { + this.rating = rating; + } + + public String getTown() { + return town; + } + + public void setTown(String town) { + this.town = town; + } + + public String getMail() { + return mail; + } + + public void setMail(String mail) { + this.mail = mail; + } + + public String getRole() { + return role; + } + + public void setRole(String role) { + this.role = role; + } + + public String getPassword() { + return password; + } + + public void setPassword(String password) { + this.password = password; + } + + public String getName() { + return name; + } + + public void setName(String name) { + this.name = name; + } + + public Integer getId() { + return id; + } + + public void setId(Integer id) { + this.id = id; + } +} \ No newline at end of file diff --git a/src/main/java/com/petproject/boardgamefun/model/UserOwnGame.java b/src/main/java/com/petproject/boardgamefun/model/UserOwnGame.java new file mode 100644 index 0000000..28fc194 --- /dev/null +++ b/src/main/java/com/petproject/boardgamefun/model/UserOwnGame.java @@ -0,0 +1,44 @@ +package com.petproject.boardgamefun.model; + +import javax.persistence.*; + +@Table(name = "user_own_game") +@Entity +public class UserOwnGame { + @Id + @GeneratedValue(strategy = GenerationType.IDENTITY) + @Column(name = "id", nullable = false) + private Integer id; + + @ManyToOne(optional = false) + @JoinColumn(name = "game", nullable = false) + private Game game; + + @ManyToOne(optional = false) + @JoinColumn(name = "\"user\"", nullable = false) + private User user; + + public User getUser() { + return user; + } + + public void setUser(User user) { + this.user = user; + } + + public Game getGame() { + return game; + } + + public void setGame(Game game) { + this.game = game; + } + + public Integer getId() { + return id; + } + + public void setId(Integer id) { + this.id = id; + } +} \ No newline at end of file diff --git a/src/main/java/com/petproject/boardgamefun/model/UserRating.java b/src/main/java/com/petproject/boardgamefun/model/UserRating.java new file mode 100644 index 0000000..9f9e0b5 --- /dev/null +++ b/src/main/java/com/petproject/boardgamefun/model/UserRating.java @@ -0,0 +1,70 @@ +package com.petproject.boardgamefun.model; + +import org.hibernate.annotations.Type; + +import javax.persistence.*; + +@Table(name = "user_ratings") +@Entity +public class UserRating { + @Id + @GeneratedValue(strategy = GenerationType.IDENTITY) + @Column(name = "id", nullable = false) + private Integer id; + + @Lob + @Type(type = "org.hibernate.type.TextType") + @Column(name = "comment") + private String comment; + + @ManyToOne(optional = false) + @JoinColumn(name = "evaluating_user", nullable = false) + private User evaluatingUser; + + @ManyToOne(optional = false) + @JoinColumn(name = "evaluated_user", nullable = false) + private User evaluatedUser; + + @Column(name = "rating", nullable = false) + private Double rating; + + public Double getRating() { + return rating; + } + + public void setRating(Double rating) { + this.rating = rating; + } + + public User getEvaluatedUser() { + return evaluatedUser; + } + + public void setEvaluatedUser(User evaluatedUser) { + this.evaluatedUser = evaluatedUser; + } + + public User getEvaluatingUser() { + return evaluatingUser; + } + + public void setEvaluatingUser(User evaluatingUser) { + this.evaluatingUser = evaluatingUser; + } + + public String getComment() { + return comment; + } + + public void setComment(String comment) { + this.comment = comment; + } + + public Integer getId() { + return id; + } + + public void setId(Integer id) { + this.id = id; + } +} \ No newline at end of file diff --git a/src/main/java/com/petproject/boardgamefun/model/UserWish.java b/src/main/java/com/petproject/boardgamefun/model/UserWish.java new file mode 100644 index 0000000..cf21e2a --- /dev/null +++ b/src/main/java/com/petproject/boardgamefun/model/UserWish.java @@ -0,0 +1,44 @@ +package com.petproject.boardgamefun.model; + +import javax.persistence.*; + +@Table(name = "user_wish") +@Entity +public class UserWish { + @Id + @GeneratedValue(strategy = GenerationType.IDENTITY) + @Column(name = "id", nullable = false) + private Integer id; + + @ManyToOne(optional = false) + @JoinColumn(name = "\"user\"", nullable = false) + private User user; + + @ManyToOne(optional = false) + @JoinColumn(name = "game", nullable = false) + private Game game; + + public Game getGame() { + return game; + } + + public void setGame(Game game) { + this.game = game; + } + + public User getUser() { + return user; + } + + public void setUser(User user) { + this.user = user; + } + + public Integer getId() { + return id; + } + + public void setId(Integer id) { + this.id = id; + } +} \ No newline at end of file diff --git a/src/main/java/com/petproject/boardgamefun/repository/CategoryRepository.java b/src/main/java/com/petproject/boardgamefun/repository/CategoryRepository.java new file mode 100644 index 0000000..709ad46 --- /dev/null +++ b/src/main/java/com/petproject/boardgamefun/repository/CategoryRepository.java @@ -0,0 +1,7 @@ +package com.petproject.boardgamefun.repository; + +import com.petproject.boardgamefun.model.Category; +import org.springframework.data.jpa.repository.JpaRepository; + +public interface CategoryRepository extends JpaRepository { +} \ No newline at end of file diff --git a/src/main/java/com/petproject/boardgamefun/repository/DesignerRepository.java b/src/main/java/com/petproject/boardgamefun/repository/DesignerRepository.java new file mode 100644 index 0000000..a3b984c --- /dev/null +++ b/src/main/java/com/petproject/boardgamefun/repository/DesignerRepository.java @@ -0,0 +1,17 @@ +package com.petproject.boardgamefun.repository; + +import com.petproject.boardgamefun.dto.projection.DesignersProjection; +import com.petproject.boardgamefun.model.Designer; +import org.springframework.data.jpa.repository.JpaRepository; +import org.springframework.data.jpa.repository.Query; + +import java.util.List; + +public interface DesignerRepository extends JpaRepository { + Designer findDesignerById(Integer id); + Designer findDesignerByName(String name); + @Query("select d.name as designer from Designer d " + + "join GameByDesigner gbd on gbd.designer.id = d.id " + + "where gbd.game.id = :gameId") + List findDesignersUsingGame(Integer gameId); +} \ No newline at end of file diff --git a/src/main/java/com/petproject/boardgamefun/repository/DiaryCommentRepository.java b/src/main/java/com/petproject/boardgamefun/repository/DiaryCommentRepository.java new file mode 100644 index 0000000..7ba526f --- /dev/null +++ b/src/main/java/com/petproject/boardgamefun/repository/DiaryCommentRepository.java @@ -0,0 +1,11 @@ +package com.petproject.boardgamefun.repository; + +import com.petproject.boardgamefun.model.DiaryComment; +import org.springframework.data.jpa.repository.JpaRepository; + +import java.util.List; + +public interface DiaryCommentRepository extends JpaRepository { + DiaryComment findDiaryCommentById(Integer id); + List findDiaryComment_ByDiaryId(Integer diaryId); +} \ No newline at end of file diff --git a/src/main/java/com/petproject/boardgamefun/repository/DiaryRatingRepository.java b/src/main/java/com/petproject/boardgamefun/repository/DiaryRatingRepository.java new file mode 100644 index 0000000..4238e74 --- /dev/null +++ b/src/main/java/com/petproject/boardgamefun/repository/DiaryRatingRepository.java @@ -0,0 +1,8 @@ +package com.petproject.boardgamefun.repository; + +import com.petproject.boardgamefun.model.DiaryRating; +import org.springframework.data.jpa.repository.JpaRepository; + +public interface DiaryRatingRepository extends JpaRepository { + DiaryRating findDiaryRatingById(Integer id); +} \ No newline at end of file diff --git a/src/main/java/com/petproject/boardgamefun/repository/DiaryRepository.java b/src/main/java/com/petproject/boardgamefun/repository/DiaryRepository.java new file mode 100644 index 0000000..4fad768 --- /dev/null +++ b/src/main/java/com/petproject/boardgamefun/repository/DiaryRepository.java @@ -0,0 +1,40 @@ +package com.petproject.boardgamefun.repository; + +import com.petproject.boardgamefun.dto.projection.DiaryWithRatingsProjection; +import com.petproject.boardgamefun.model.Diary; +import org.springframework.data.jpa.repository.JpaRepository; +import org.springframework.data.jpa.repository.Query; + +import java.util.List; + +public interface DiaryRepository extends JpaRepository { + // todo: only diary id? + Diary findDiary_ByUserIdAndId(Integer userId, Integer id); + + @Query("select d as diary, avg(dr.rating) as rating from Diary d " + + "left join DiaryRating dr on d.id = dr.diary.id " + + "join User u on u.id = d.user.id " + + "where u.id = :userId " + + "group by d") + ListfindUserDiaries(Integer userId); + + @Query("select d as diary, avg(dr.rating) as rating from Diary d " + + "left join DiaryRating dr on d.id = dr.diary.id " + + "join Game g on g.id = d.game.id " + + "where g.id = :gameId " + + "group by d") + List findGameDiaries(Integer gameId); + + @Query("select d as diary, avg(dr.rating) as rating from Diary d " + + "left join DiaryRating dr on d.id = dr.diary.id " + + "where d.id = :id " + + "group by d") + DiaryWithRatingsProjection findDiaryUsingId(Integer id); + + Diary findDiaryById(Integer id); + + @Query("select d as diary, avg(dr.rating) as rating from Diary d " + + "left join DiaryRating dr on d.id = dr.diary.id" + + " group by d") + List getAllDiaries(); +} \ No newline at end of file diff --git a/src/main/java/com/petproject/boardgamefun/repository/ExpansionRepository.java b/src/main/java/com/petproject/boardgamefun/repository/ExpansionRepository.java new file mode 100644 index 0000000..dcf09de --- /dev/null +++ b/src/main/java/com/petproject/boardgamefun/repository/ExpansionRepository.java @@ -0,0 +1,8 @@ +package com.petproject.boardgamefun.repository; + +import com.petproject.boardgamefun.model.Expansion; +import org.springframework.data.jpa.repository.JpaRepository; + +public interface ExpansionRepository extends JpaRepository { + Expansion findExpansion_ByParentGameIdAndDaughterGameId(Integer parentGameId, Integer daughterId); +} \ No newline at end of file diff --git a/src/main/java/com/petproject/boardgamefun/repository/FileRepository.java b/src/main/java/com/petproject/boardgamefun/repository/FileRepository.java new file mode 100644 index 0000000..061a71f --- /dev/null +++ b/src/main/java/com/petproject/boardgamefun/repository/FileRepository.java @@ -0,0 +1,7 @@ +package com.petproject.boardgamefun.repository; + +import com.petproject.boardgamefun.model.File; +import org.springframework.data.jpa.repository.JpaRepository; + +public interface FileRepository extends JpaRepository { +} \ No newline at end of file diff --git a/src/main/java/com/petproject/boardgamefun/repository/ForumMessageRepository.java b/src/main/java/com/petproject/boardgamefun/repository/ForumMessageRepository.java new file mode 100644 index 0000000..e7551bb --- /dev/null +++ b/src/main/java/com/petproject/boardgamefun/repository/ForumMessageRepository.java @@ -0,0 +1,12 @@ +package com.petproject.boardgamefun.repository; + +import com.petproject.boardgamefun.model.ForumMessage; +import org.springframework.data.jpa.repository.JpaRepository; + +import java.util.List; + +public interface ForumMessageRepository extends JpaRepository { + List findByUserId(Integer id); + List findByForumId(Integer id); + ForumMessage findForumMessageById(Integer id); +} \ No newline at end of file diff --git a/src/main/java/com/petproject/boardgamefun/repository/ForumRatingRepository.java b/src/main/java/com/petproject/boardgamefun/repository/ForumRatingRepository.java new file mode 100644 index 0000000..dcf7b7f --- /dev/null +++ b/src/main/java/com/petproject/boardgamefun/repository/ForumRatingRepository.java @@ -0,0 +1,9 @@ +package com.petproject.boardgamefun.repository; + +import com.petproject.boardgamefun.model.ForumRating; +import org.springframework.data.jpa.repository.JpaRepository; + +public interface ForumRatingRepository extends JpaRepository { + ForumRating findForumRating_ByForumIdAndUserId(Integer forumId, Integer userId); + ForumRating findForumRatingById(Integer id); +} \ No newline at end of file diff --git a/src/main/java/com/petproject/boardgamefun/repository/ForumRepository.java b/src/main/java/com/petproject/boardgamefun/repository/ForumRepository.java new file mode 100644 index 0000000..e6a4ad8 --- /dev/null +++ b/src/main/java/com/petproject/boardgamefun/repository/ForumRepository.java @@ -0,0 +1,37 @@ +package com.petproject.boardgamefun.repository; + +import com.petproject.boardgamefun.dto.projection.ForumProjection; +import com.petproject.boardgamefun.model.Forum; +import org.springframework.data.jpa.repository.JpaRepository; +import org.springframework.data.jpa.repository.Query; + +import java.util.List; + +public interface ForumRepository extends JpaRepository { + @Query("select f as forum, avg(fr.rating) as rating from Forum f " + + "join Game g on g.id = f.game.id " + + "left join ForumRating fr on fr.forum.id = f.id " + + "where g.id = :gameId " + + "group by f") + List findForumsGameWithRating(Integer gameId); + + @Query("select f as forum, avg(fr.rating) as rating from Forum f " + + "join User u on u.id = f.user.id " + + "left join ForumRating fr on fr.forum.id = f.id " + + "where u.id = :userId " + + "group by f") + List findForumsUserWithRating(Integer userId); + + @Query("select f as forum, avg(fr.rating) as rating from Forum f " + + "left join ForumRating fr on fr.forum.id = f.id " + + "group by f") + List findForumsWithRating(); + + @Query("select f as forum, avg(fr.rating) as rating from Forum f " + + "left join ForumRating fr on fr.forum.id = f.id " + + "where f.id = :id " + + "group by f") + ForumProjection findForumWithRatingUsingId(Integer id); + + Forum findForumById(Integer id); +} \ No newline at end of file diff --git a/src/main/java/com/petproject/boardgamefun/repository/GameByDesignerRepository.java b/src/main/java/com/petproject/boardgamefun/repository/GameByDesignerRepository.java new file mode 100644 index 0000000..ae8516d --- /dev/null +++ b/src/main/java/com/petproject/boardgamefun/repository/GameByDesignerRepository.java @@ -0,0 +1,7 @@ +package com.petproject.boardgamefun.repository; + +import com.petproject.boardgamefun.model.GameByDesigner; +import org.springframework.data.jpa.repository.JpaRepository; + +public interface GameByDesignerRepository extends JpaRepository { +} \ No newline at end of file diff --git a/src/main/java/com/petproject/boardgamefun/repository/GameCategoryRepository.java b/src/main/java/com/petproject/boardgamefun/repository/GameCategoryRepository.java new file mode 100644 index 0000000..e6b6c1c --- /dev/null +++ b/src/main/java/com/petproject/boardgamefun/repository/GameCategoryRepository.java @@ -0,0 +1,7 @@ +package com.petproject.boardgamefun.repository; + +import com.petproject.boardgamefun.model.GameCategory; +import org.springframework.data.jpa.repository.JpaRepository; + +public interface GameCategoryRepository extends JpaRepository { +} \ No newline at end of file diff --git a/src/main/java/com/petproject/boardgamefun/repository/GameRepository.java b/src/main/java/com/petproject/boardgamefun/repository/GameRepository.java new file mode 100644 index 0000000..68133f9 --- /dev/null +++ b/src/main/java/com/petproject/boardgamefun/repository/GameRepository.java @@ -0,0 +1,66 @@ +package com.petproject.boardgamefun.repository; + +import com.petproject.boardgamefun.dto.projection.GameProjection; +import com.petproject.boardgamefun.dto.projection.GamesFilterByTitleProjection; +import com.petproject.boardgamefun.dto.projection.UserGameRatingProjection; +import com.petproject.boardgamefun.dto.projection.GameSellProjection; +import com.petproject.boardgamefun.model.Game; +import org.springframework.data.jpa.repository.JpaRepository; +import org.springframework.data.jpa.repository.Query; + +import java.util.List; + +public interface GameRepository extends JpaRepository { + Game findGameById(Integer id); + + @Query("select g as game, avg(rgbu.rating) as rating from Game g " + + "left join RatingGameByUser rgbu on rgbu.game.id = g.id " + + "where g.id = :id " + + "group by g") + GameProjection findGameWithRating(Integer id); + + @Query("select g.title as title, g.id as id from Game g " + + "where lower(g.title) like :title%") + List findGamesUsingTitle(String title); + + @Query("select g as game, avg(rgbu.rating) as rating from Game g " + + "left join RatingGameByUser rgbu on rgbu.game.id = g.id " + + "group by g") + List findGames(); + + @Query("Select g from Game g " + + "join UserOwnGame uog on g.id = uog.game.id " + + "join User u on u.id = uog.user.id " + + "where u.id = :id") + List findUserGames(Integer id); + + @Query("Select g as game, rgbu.rating as rating from Game g " + + "join RatingGameByUser rgbu on rgbu.game.id = g.id " + + "join User u on u.id = rgbu.user.id " + + "where u.id = :id " + + "order by rgbu.rating desc") + List findUserGameRatingList(Integer id); + + @Query("Select g from Game g " + + "join UserWish uw on g.id = uw.game.id " + + "join User u on u.id = uw.user.id " + + "where u.id = :id") + List findUserWishlist(Integer id); + + @Query("Select g as game, gs.comment as comment, gs.condition as condition, gs.price as price " + + "from Game g " + + "join GameSell gs on g.id = gs.game.id " + + "join User u on u.id = gs.user.id " + + "where u.id = :id") + List getGameSellList(Integer id); + + @Query("select g from Game g " + + "join Expansion ex on ex.daughterGame.id = g.id " + + "where ex.parentGame.id = :parentGameId") + List getExpansions(Integer parentGameId); + + @Query("select g from Game g " + + "join SameGame sg on sg.sourceGame.id = g.id " + + "where sg.referenceGame.id = :referenceGameId") + List getSimilarGames(Integer referenceGameId); +} \ No newline at end of file diff --git a/src/main/java/com/petproject/boardgamefun/repository/GameSellRepository.java b/src/main/java/com/petproject/boardgamefun/repository/GameSellRepository.java new file mode 100644 index 0000000..4fd3e0e --- /dev/null +++ b/src/main/java/com/petproject/boardgamefun/repository/GameSellRepository.java @@ -0,0 +1,8 @@ +package com.petproject.boardgamefun.repository; + +import com.petproject.boardgamefun.model.GameSell; +import org.springframework.data.jpa.repository.JpaRepository; + +public interface GameSellRepository extends JpaRepository { + GameSell findGameSell_ByUserIdAndGameId( Integer userId, Integer gameId); +} \ No newline at end of file diff --git a/src/main/java/com/petproject/boardgamefun/repository/ImageRepository.java b/src/main/java/com/petproject/boardgamefun/repository/ImageRepository.java new file mode 100644 index 0000000..34fcc45 --- /dev/null +++ b/src/main/java/com/petproject/boardgamefun/repository/ImageRepository.java @@ -0,0 +1,7 @@ +package com.petproject.boardgamefun.repository; + +import com.petproject.boardgamefun.model.Image; +import org.springframework.data.jpa.repository.JpaRepository; + +public interface ImageRepository extends JpaRepository { +} \ No newline at end of file diff --git a/src/main/java/com/petproject/boardgamefun/repository/MessengerRepository.java b/src/main/java/com/petproject/boardgamefun/repository/MessengerRepository.java new file mode 100644 index 0000000..3c2bc8f --- /dev/null +++ b/src/main/java/com/petproject/boardgamefun/repository/MessengerRepository.java @@ -0,0 +1,7 @@ +package com.petproject.boardgamefun.repository; + +import com.petproject.boardgamefun.model.Messenger; +import org.springframework.data.jpa.repository.JpaRepository; + +public interface MessengerRepository extends JpaRepository { +} \ No newline at end of file diff --git a/src/main/java/com/petproject/boardgamefun/repository/NewsCommentRepository.java b/src/main/java/com/petproject/boardgamefun/repository/NewsCommentRepository.java new file mode 100644 index 0000000..92fa4d8 --- /dev/null +++ b/src/main/java/com/petproject/boardgamefun/repository/NewsCommentRepository.java @@ -0,0 +1,7 @@ +package com.petproject.boardgamefun.repository; + +import com.petproject.boardgamefun.model.NewsComment; +import org.springframework.data.jpa.repository.JpaRepository; + +public interface NewsCommentRepository extends JpaRepository { +} \ No newline at end of file diff --git a/src/main/java/com/petproject/boardgamefun/repository/NewsRatingRepository.java b/src/main/java/com/petproject/boardgamefun/repository/NewsRatingRepository.java new file mode 100644 index 0000000..3db792e --- /dev/null +++ b/src/main/java/com/petproject/boardgamefun/repository/NewsRatingRepository.java @@ -0,0 +1,7 @@ +package com.petproject.boardgamefun.repository; + +import com.petproject.boardgamefun.model.NewsRating; +import org.springframework.data.jpa.repository.JpaRepository; + +public interface NewsRatingRepository extends JpaRepository { +} \ No newline at end of file diff --git a/src/main/java/com/petproject/boardgamefun/repository/NewsRepository.java b/src/main/java/com/petproject/boardgamefun/repository/NewsRepository.java new file mode 100644 index 0000000..f017ab9 --- /dev/null +++ b/src/main/java/com/petproject/boardgamefun/repository/NewsRepository.java @@ -0,0 +1,7 @@ +package com.petproject.boardgamefun.repository; + +import com.petproject.boardgamefun.model.News; +import org.springframework.data.jpa.repository.JpaRepository; + +public interface NewsRepository extends JpaRepository { +} \ No newline at end of file diff --git a/src/main/java/com/petproject/boardgamefun/repository/RatingGameByUserRepository.java b/src/main/java/com/petproject/boardgamefun/repository/RatingGameByUserRepository.java new file mode 100644 index 0000000..af46bca --- /dev/null +++ b/src/main/java/com/petproject/boardgamefun/repository/RatingGameByUserRepository.java @@ -0,0 +1,8 @@ +package com.petproject.boardgamefun.repository; + +import com.petproject.boardgamefun.model.RatingGameByUser; +import org.springframework.data.jpa.repository.JpaRepository; + +public interface RatingGameByUserRepository extends JpaRepository { + RatingGameByUser findRatingGame_ByUserIdAndGameId(Integer userId, Integer gameId ); +} \ No newline at end of file diff --git a/src/main/java/com/petproject/boardgamefun/repository/SameGameRepository.java b/src/main/java/com/petproject/boardgamefun/repository/SameGameRepository.java new file mode 100644 index 0000000..69b9a11 --- /dev/null +++ b/src/main/java/com/petproject/boardgamefun/repository/SameGameRepository.java @@ -0,0 +1,8 @@ +package com.petproject.boardgamefun.repository; + +import com.petproject.boardgamefun.model.SameGame; +import org.springframework.data.jpa.repository.JpaRepository; + +public interface SameGameRepository extends JpaRepository { + SameGame findSameGame_ByReferenceGameIdAndSourceGameId(Integer referenceGameId, Integer sourceGameId); +} \ No newline at end of file diff --git a/src/main/java/com/petproject/boardgamefun/repository/UserOwnGameRepository.java b/src/main/java/com/petproject/boardgamefun/repository/UserOwnGameRepository.java new file mode 100644 index 0000000..3124ce0 --- /dev/null +++ b/src/main/java/com/petproject/boardgamefun/repository/UserOwnGameRepository.java @@ -0,0 +1,8 @@ +package com.petproject.boardgamefun.repository; + +import com.petproject.boardgamefun.model.UserOwnGame; +import org.springframework.data.jpa.repository.JpaRepository; + +public interface UserOwnGameRepository extends JpaRepository { + UserOwnGame findUserOwnGame_ByUserIdAndGameId(Integer userId, Integer gameId); +} diff --git a/src/main/java/com/petproject/boardgamefun/repository/UserRatingRepository.java b/src/main/java/com/petproject/boardgamefun/repository/UserRatingRepository.java new file mode 100644 index 0000000..56808a6 --- /dev/null +++ b/src/main/java/com/petproject/boardgamefun/repository/UserRatingRepository.java @@ -0,0 +1,7 @@ +package com.petproject.boardgamefun.repository; + +import com.petproject.boardgamefun.model.UserRating; +import org.springframework.data.jpa.repository.JpaRepository; + +public interface UserRatingRepository extends JpaRepository { +} \ No newline at end of file diff --git a/src/main/java/com/petproject/boardgamefun/repository/UserRepository.java b/src/main/java/com/petproject/boardgamefun/repository/UserRepository.java new file mode 100644 index 0000000..e721b9f --- /dev/null +++ b/src/main/java/com/petproject/boardgamefun/repository/UserRepository.java @@ -0,0 +1,21 @@ +package com.petproject.boardgamefun.repository; + +import com.petproject.boardgamefun.dto.projection.UsersGameRatingProjection; +import com.petproject.boardgamefun.model.User; +import org.springframework.data.jpa.repository.JpaRepository; +import org.springframework.data.jpa.repository.Query; + +import java.util.List; + +public interface UserRepository extends JpaRepository { + User findUserById(Integer id); + User findUserByName(String name); + Boolean existsByName(String username); + Boolean existsByMail(String email); + + @Query("select u as user, rgbu.rating as rating from User u " + + "join RatingGameByUser rgbu on rgbu.user.id = u.id " + + "join Game g on g.id = rgbu.game.id " + + "where g.id = :gameId") + List findGameRatings(Integer gameId); +} \ No newline at end of file diff --git a/src/main/java/com/petproject/boardgamefun/repository/UserWishRepository.java b/src/main/java/com/petproject/boardgamefun/repository/UserWishRepository.java new file mode 100644 index 0000000..6fa358f --- /dev/null +++ b/src/main/java/com/petproject/boardgamefun/repository/UserWishRepository.java @@ -0,0 +1,10 @@ +package com.petproject.boardgamefun.repository; + +import com.petproject.boardgamefun.model.Game; +import com.petproject.boardgamefun.model.User; +import com.petproject.boardgamefun.model.UserWish; +import org.springframework.data.jpa.repository.JpaRepository; + +public interface UserWishRepository extends JpaRepository { + UserWish findByUserAndGame(User user, Game game); +} \ No newline at end of file diff --git a/src/main/java/com/petproject/boardgamefun/security/WebSecurityConfig.java b/src/main/java/com/petproject/boardgamefun/security/WebSecurityConfig.java new file mode 100644 index 0000000..8b9f18b --- /dev/null +++ b/src/main/java/com/petproject/boardgamefun/security/WebSecurityConfig.java @@ -0,0 +1,86 @@ +package com.petproject.boardgamefun.security; + +import com.petproject.boardgamefun.security.jwt.AuthEntryPointJwt; +import com.petproject.boardgamefun.security.jwt.AuthTokenFilter; +import com.petproject.boardgamefun.security.services.UserDetailsServiceImpl; +import org.springframework.context.annotation.Bean; +import org.springframework.context.annotation.Configuration; +import org.springframework.security.authentication.AuthenticationManager; +import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder; +import org.springframework.security.config.annotation.method.configuration.EnableGlobalMethodSecurity; +import org.springframework.security.config.annotation.web.builders.HttpSecurity; +import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity; +import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter; +import org.springframework.security.config.http.SessionCreationPolicy; +import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder; +import org.springframework.security.crypto.password.PasswordEncoder; +import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter; +import org.springframework.web.cors.CorsConfiguration; +import org.springframework.web.cors.UrlBasedCorsConfigurationSource; +import org.springframework.web.filter.CorsFilter; + +@Configuration +@EnableWebSecurity +@EnableGlobalMethodSecurity(prePostEnabled = true) +public class WebSecurityConfig extends WebSecurityConfigurerAdapter { + + final UserDetailsServiceImpl userDetailsServiceImpl; + + final AuthEntryPointJwt unauthorizedHandler; + + public WebSecurityConfig(UserDetailsServiceImpl userDetailsServiceImpl, AuthEntryPointJwt unauthorizedHandler) { + this.userDetailsServiceImpl = userDetailsServiceImpl; + this.unauthorizedHandler = unauthorizedHandler; + } + + @Bean + public AuthTokenFilter authenticationJwtTokenFilter(){ + return new AuthTokenFilter(); + } + + @Override + public void configure(AuthenticationManagerBuilder builder) throws Exception { + builder.userDetailsService(userDetailsServiceImpl).passwordEncoder(passwordEncoder()); + } + + @Bean + @Override + public AuthenticationManager authenticationManagerBean() throws Exception { + return super.authenticationManagerBean(); + } + + @Bean + public PasswordEncoder passwordEncoder(){ + return new BCryptPasswordEncoder(); + } + + @Override + protected void configure(HttpSecurity httpSecurity) throws Exception{ + httpSecurity.cors().and().csrf().disable() + .exceptionHandling().authenticationEntryPoint(unauthorizedHandler).and() + .sessionManagement().sessionCreationPolicy(SessionCreationPolicy.STATELESS).and() + .authorizeRequests().antMatchers("/users/**").permitAll() + .anyRequest().permitAll(); + + httpSecurity.addFilterBefore(authenticationJwtTokenFilter(), UsernamePasswordAuthenticationFilter.class); + } + + @Bean + public CorsFilter corsFilter() { + UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource(); + CorsConfiguration config = new CorsConfiguration(); + config.setAllowCredentials(false); + config.addAllowedOrigin("*"); + config.addAllowedHeader("*"); + config.addAllowedMethod("OPTIONS"); + config.addAllowedMethod("PATCH"); + config.addAllowedMethod("GET"); + config.addAllowedMethod("POST"); + config.addAllowedMethod("PUT"); + config.addAllowedMethod("DELETE"); + config.addAllowedMethod("HEAD"); + source.registerCorsConfiguration("/**", config); + return new CorsFilter(source); + } + +} diff --git a/src/main/java/com/petproject/boardgamefun/security/controller/TokenControllerAdvice.java b/src/main/java/com/petproject/boardgamefun/security/controller/TokenControllerAdvice.java new file mode 100644 index 0000000..4f28737 --- /dev/null +++ b/src/main/java/com/petproject/boardgamefun/security/controller/TokenControllerAdvice.java @@ -0,0 +1,24 @@ +package com.petproject.boardgamefun.security.controller; + +import com.petproject.boardgamefun.security.exception.RefreshTokenException; +import com.petproject.boardgamefun.security.model.ErrorMessage; +import org.springframework.http.HttpStatus; +import org.springframework.web.bind.annotation.ExceptionHandler; +import org.springframework.web.bind.annotation.ResponseStatus; +import org.springframework.web.bind.annotation.RestControllerAdvice; +import org.springframework.web.context.request.WebRequest; + +import java.util.Date; + +@RestControllerAdvice +public class TokenControllerAdvice { + + @ExceptionHandler(value = RefreshTokenException.class) + @ResponseStatus(HttpStatus.UNAUTHORIZED) + public ErrorMessage handleRefreshTokenException(RefreshTokenException exception, WebRequest request) { + return new ErrorMessage(HttpStatus.UNAUTHORIZED.value(), + new Date(), + exception.getMessage(), + request.getDescription(false)); + } +} diff --git a/src/main/java/com/petproject/boardgamefun/security/enums/Role.java b/src/main/java/com/petproject/boardgamefun/security/enums/Role.java new file mode 100644 index 0000000..b6edee5 --- /dev/null +++ b/src/main/java/com/petproject/boardgamefun/security/enums/Role.java @@ -0,0 +1,7 @@ +package com.petproject.boardgamefun.security.enums; + +public enum Role { + ROLE_USER, + ROLE_MODERATOR, + ROLE_ADMIN +} diff --git a/src/main/java/com/petproject/boardgamefun/security/exception/RefreshTokenException.java b/src/main/java/com/petproject/boardgamefun/security/exception/RefreshTokenException.java new file mode 100644 index 0000000..f80d5ba --- /dev/null +++ b/src/main/java/com/petproject/boardgamefun/security/exception/RefreshTokenException.java @@ -0,0 +1,12 @@ +package com.petproject.boardgamefun.security.exception; + +import org.springframework.http.HttpStatus; +import org.springframework.web.bind.annotation.ResponseStatus; + +@ResponseStatus(HttpStatus.UNAUTHORIZED) +public class RefreshTokenException extends RuntimeException { + private static final long serialVersionUID = 1L; + public RefreshTokenException(String token, String message) { + super(String.format("Failed for [%s]: %s", token, message)); + } +} diff --git a/src/main/java/com/petproject/boardgamefun/security/jwt/AuthEntryPointJwt.java b/src/main/java/com/petproject/boardgamefun/security/jwt/AuthEntryPointJwt.java new file mode 100644 index 0000000..2b13ae4 --- /dev/null +++ b/src/main/java/com/petproject/boardgamefun/security/jwt/AuthEntryPointJwt.java @@ -0,0 +1,24 @@ +package com.petproject.boardgamefun.security.jwt; + +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.springframework.security.core.AuthenticationException; +import org.springframework.security.web.AuthenticationEntryPoint; +import org.springframework.stereotype.Component; + +import javax.servlet.ServletException; +import javax.servlet.http.HttpServletRequest; +import javax.servlet.http.HttpServletResponse; +import java.io.IOException; + +@Component +public class AuthEntryPointJwt implements AuthenticationEntryPoint { + private static final Logger logger = LoggerFactory.getLogger(AuthEntryPointJwt.class); + + + @Override + public void commence(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, AuthenticationException e) throws IOException, ServletException { + logger.error("Unauthorized error: {}", e.getMessage()); + httpServletResponse.sendError(httpServletResponse.SC_UNAUTHORIZED, "Error: Unauthorized"); + } +} diff --git a/src/main/java/com/petproject/boardgamefun/security/jwt/AuthTokenFilter.java b/src/main/java/com/petproject/boardgamefun/security/jwt/AuthTokenFilter.java new file mode 100644 index 0000000..89bd53b --- /dev/null +++ b/src/main/java/com/petproject/boardgamefun/security/jwt/AuthTokenFilter.java @@ -0,0 +1,61 @@ +package com.petproject.boardgamefun.security.jwt; + +import com.petproject.boardgamefun.security.services.UserDetailsServiceImpl; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.security.authentication.UsernamePasswordAuthenticationToken; +import org.springframework.security.core.context.SecurityContextHolder; +import org.springframework.security.core.userdetails.UserDetails; +import org.springframework.security.web.authentication.WebAuthenticationDetailsSource; +import org.springframework.web.filter.OncePerRequestFilter; + +import javax.servlet.FilterChain; +import javax.servlet.ServletException; +import javax.servlet.http.HttpServletRequest; +import javax.servlet.http.HttpServletResponse; +import java.io.IOException; + +import org.springframework.util.StringUtils; + +public class AuthTokenFilter extends OncePerRequestFilter { + + private static final Logger logger = LoggerFactory.getLogger(AuthTokenFilter.class); + + @Autowired + private JwtUtils jwtUtils; + + @Autowired + private UserDetailsServiceImpl userDetailsServiceImpl; + + @Override + protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain) throws ServletException, IOException { + try { + String jwt = ParseJwt(request); + if (jwt != null && jwtUtils.validateJwtToken(jwt)) { + String username = jwtUtils.getUserNameFromJwtToken(jwt); + UserDetails userDetails = userDetailsServiceImpl.loadUserByUsername(username); + UsernamePasswordAuthenticationToken authenticationToken = new UsernamePasswordAuthenticationToken( + userDetails, null, userDetails.getAuthorities()); + + authenticationToken.setDetails(new WebAuthenticationDetailsSource().buildDetails(request)); + + SecurityContextHolder.getContext().setAuthentication(authenticationToken); + } + + } catch (Exception e) { + logger.error("Error during internal filter: {}", e.getMessage()); + } + filterChain.doFilter(request, response); + } + + private String ParseJwt(HttpServletRequest request) { + String header = request.getHeader("Authorization"); + + if (StringUtils.hasText(header) && header.startsWith("Bearer ")) { + return header.substring(7); + } + + return null; + } +} diff --git a/src/main/java/com/petproject/boardgamefun/security/jwt/JwtUtils.java b/src/main/java/com/petproject/boardgamefun/security/jwt/JwtUtils.java new file mode 100644 index 0000000..250a371 --- /dev/null +++ b/src/main/java/com/petproject/boardgamefun/security/jwt/JwtUtils.java @@ -0,0 +1,65 @@ +package com.petproject.boardgamefun.security.jwt; + +import com.petproject.boardgamefun.security.services.UserDetailsImpl; +import io.jsonwebtoken.*; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.springframework.beans.factory.annotation.Value; +import org.springframework.security.core.Authentication; +import org.springframework.stereotype.Component; + +import java.util.Date; + + +@Component +public class JwtUtils { + private static final Logger logger = LoggerFactory.getLogger(JwtUtils.class); + + @Value("${boardgamefun.app.jwtSecret}") + private String jwtSecret; + + @Value("${boardgamefun.app.jwtExpirationMs}") + private int jwtExpirationMs; + + public String generateJwtToken(Authentication authentication) { + UserDetailsImpl userPrincipal = (UserDetailsImpl) authentication.getPrincipal(); + + return Jwts.builder() + .setSubject((userPrincipal.getUsername())) + .setIssuedAt(new Date()).setExpiration(new Date((new Date()).getTime() + jwtExpirationMs)) + .signWith(SignatureAlgorithm.HS512, jwtSecret) + .compact(); + } + + public String generateJwtToken(String userName) { + return Jwts.builder() + .setSubject((userName)) + .setIssuedAt(new Date()).setExpiration(new Date((new Date()).getTime() + jwtExpirationMs)) + .signWith(SignatureAlgorithm.HS512, jwtSecret) + .compact(); + } + + public String getUserNameFromJwtToken(String token) { + return Jwts.parser().setSigningKey(jwtSecret).parseClaimsJws(token).getBody() + .getSubject(); + } + + public boolean validateJwtToken(String authToken) { + try { + Jwts.parser().setSigningKey(jwtSecret).parseClaimsJws(authToken); + return true; + } catch (SignatureException e) { + logger.error("Invalid jwt signature: {}", e.getMessage()); + } catch (MalformedJwtException e) { + logger.error("Invalid JWT token: {}", e.getMessage()); + } catch (ExpiredJwtException e) { + logger.error("JWT token is expired: {}", e.getMessage()); + } catch (UnsupportedJwtException e) { + logger.error("JWT token is unsupported: {}", e.getMessage()); + } catch (IllegalArgumentException e) { + logger.error("JWT claims string is empty: {}", e.getMessage()); + } + + return false; + } +} diff --git a/src/main/java/com/petproject/boardgamefun/security/model/ErrorMessage.java b/src/main/java/com/petproject/boardgamefun/security/model/ErrorMessage.java new file mode 100644 index 0000000..2405d4c --- /dev/null +++ b/src/main/java/com/petproject/boardgamefun/security/model/ErrorMessage.java @@ -0,0 +1,15 @@ +package com.petproject.boardgamefun.security.model; + +import lombok.AllArgsConstructor; +import lombok.Getter; + +import java.util.Date; + +@Getter +@AllArgsConstructor +public class ErrorMessage { + private int statusCode; + private Date timestamp; + private String message; + private String description; +} diff --git a/src/main/java/com/petproject/boardgamefun/security/model/JwtResponse.java b/src/main/java/com/petproject/boardgamefun/security/model/JwtResponse.java new file mode 100644 index 0000000..e80ddc7 --- /dev/null +++ b/src/main/java/com/petproject/boardgamefun/security/model/JwtResponse.java @@ -0,0 +1,21 @@ +package com.petproject.boardgamefun.security.model; + +import lombok.Data; + +@Data +public class JwtResponse { + private String token; + private final String type = "Bearer"; + private Integer id; + private String userName; + private String email; + private String refreshToken; + + public JwtResponse(String jwt, Integer id, String username, String email, String refreshToken) { + this.token = jwt; + this.id = id; + this.userName = username; + this.email = email; + this.refreshToken = refreshToken; + } +} diff --git a/src/main/java/com/petproject/boardgamefun/security/model/LoginRequest.java b/src/main/java/com/petproject/boardgamefun/security/model/LoginRequest.java new file mode 100644 index 0000000..dd146b8 --- /dev/null +++ b/src/main/java/com/petproject/boardgamefun/security/model/LoginRequest.java @@ -0,0 +1,12 @@ +package com.petproject.boardgamefun.security.model; + +import lombok.*; + +@Data +@AllArgsConstructor +@NoArgsConstructor +public class LoginRequest { + + private String name; + private String password; +} diff --git a/src/main/java/com/petproject/boardgamefun/security/model/RefreshTokenRequest.java b/src/main/java/com/petproject/boardgamefun/security/model/RefreshTokenRequest.java new file mode 100644 index 0000000..3095031 --- /dev/null +++ b/src/main/java/com/petproject/boardgamefun/security/model/RefreshTokenRequest.java @@ -0,0 +1,13 @@ +package com.petproject.boardgamefun.security.model; + +import lombok.AllArgsConstructor; +import lombok.Data; +import lombok.NoArgsConstructor; + +@Data +@AllArgsConstructor +@NoArgsConstructor +public class RefreshTokenRequest { + private String userName; + private String refreshToken; +} diff --git a/src/main/java/com/petproject/boardgamefun/security/model/RefreshTokenResponse.java b/src/main/java/com/petproject/boardgamefun/security/model/RefreshTokenResponse.java new file mode 100644 index 0000000..905d0d4 --- /dev/null +++ b/src/main/java/com/petproject/boardgamefun/security/model/RefreshTokenResponse.java @@ -0,0 +1,15 @@ +package com.petproject.boardgamefun.security.model; + +import lombok.Data; + +@Data +public class RefreshTokenResponse { + private String accessToken; + private String refreshToken; + private String tokenType = "Bearer"; + + public RefreshTokenResponse(String accessToken, String refreshToken) { + this.accessToken = accessToken; + this.refreshToken = refreshToken; + } +} diff --git a/src/main/java/com/petproject/boardgamefun/security/services/RefreshTokenService.java b/src/main/java/com/petproject/boardgamefun/security/services/RefreshTokenService.java new file mode 100644 index 0000000..d73b665 --- /dev/null +++ b/src/main/java/com/petproject/boardgamefun/security/services/RefreshTokenService.java @@ -0,0 +1,40 @@ +package com.petproject.boardgamefun.security.services; + +import com.petproject.boardgamefun.security.exception.RefreshTokenException; +import io.jsonwebtoken.*; +import org.springframework.beans.factory.annotation.Value; +import org.springframework.stereotype.Service; + +import java.util.Date; + +@Service +public class RefreshTokenService { + + @Value("${boardgamefun.app.refreshTokenExpirationMs}") + private Long refreshTokenDurationMs; + + @Value("${boardgamefun.app.jwtRefreshSecret}") + private String jwtRefreshSecret; + + public String createRefreshToken(String userName) { + return Jwts.builder() + .setSubject((userName)) + .setIssuedAt(new Date()).setExpiration(new Date((new Date()).getTime() + refreshTokenDurationMs)) + .signWith(SignatureAlgorithm.HS512, jwtRefreshSecret) + .compact(); + } + + public boolean verifyExpiration(String authToken) { + var token = authToken.substring(0, authToken.lastIndexOf('.') + 1); + if (token.equals("")) + throw new RefreshTokenException(authToken, "Incorrect access token"); + try { + var expiration = ((Claims) Jwts.parser().parse(token).getBody()).getExpiration(); + } catch (ExpiredJwtException e) { + throw new RefreshTokenException(authToken, "refresh token was expired"); + } + + return true; + } + +} diff --git a/src/main/java/com/petproject/boardgamefun/security/services/UserDetailsImpl.java b/src/main/java/com/petproject/boardgamefun/security/services/UserDetailsImpl.java new file mode 100644 index 0000000..1586bf9 --- /dev/null +++ b/src/main/java/com/petproject/boardgamefun/security/services/UserDetailsImpl.java @@ -0,0 +1,95 @@ +package com.petproject.boardgamefun.security.services; + +import com.fasterxml.jackson.annotation.JsonIgnore; +import com.petproject.boardgamefun.model.User; +import com.petproject.boardgamefun.security.enums.Role; +import org.springframework.security.core.GrantedAuthority; +import org.springframework.security.core.authority.SimpleGrantedAuthority; +import org.springframework.security.core.userdetails.UserDetails; + +import java.util.Arrays; +import java.util.Collection; +import java.util.List; +import java.util.Objects; +import java.util.stream.Collectors; + +public class UserDetailsImpl implements UserDetails { + + private Integer id; + + private String username; + + private String email; + + @JsonIgnore + private String password; + + private Collection authorities; + + public UserDetailsImpl(Integer id, String username, String email, String password, + Collection authorities) { + this.id = id; + this.username = username; + this.email = email; + this.password = password; + this.authorities = authorities; + } + + public static UserDetailsImpl build(User user) { + List authorities = Arrays.stream(Role.values()).map(role -> new SimpleGrantedAuthority(role.name())).collect(Collectors.toList()); + return new UserDetailsImpl(user.getId(), user.getName(), user.getMail(), user.getPassword(), authorities); + } + + @Override + public Collection getAuthorities() { + return authorities; + } + + @Override + public String getPassword() { + return password; + } + + @Override + public String getUsername() { + return username; + } + + public Integer getId() { + return id; + } + + public String getEmail() { + return email; + } + + @Override + public boolean isAccountNonExpired() { + return true; + } + + @Override + public boolean isAccountNonLocked() { + return true; + } + + @Override + public boolean isCredentialsNonExpired() { + return true; + } + + @Override + public boolean isEnabled() { + return true; + } + + @Override + public boolean equals(Object o) { + if (this == o) + return true; + if (o == null || getClass() != o.getClass()) + return false; + UserDetailsImpl user = (UserDetailsImpl) o; + return Objects.equals(id, user.id); + } +} diff --git a/src/main/java/com/petproject/boardgamefun/security/services/UserDetailsServiceImpl.java b/src/main/java/com/petproject/boardgamefun/security/services/UserDetailsServiceImpl.java new file mode 100644 index 0000000..247842e --- /dev/null +++ b/src/main/java/com/petproject/boardgamefun/security/services/UserDetailsServiceImpl.java @@ -0,0 +1,31 @@ +package com.petproject.boardgamefun.security.services; + +import com.petproject.boardgamefun.model.User; +import com.petproject.boardgamefun.repository.UserRepository; +import org.springframework.security.core.userdetails.UserDetails; +import org.springframework.security.core.userdetails.UserDetailsService; +import org.springframework.security.core.userdetails.UsernameNotFoundException; +import org.springframework.stereotype.Service; + +import javax.transaction.Transactional; + +@Service +public class UserDetailsServiceImpl implements UserDetailsService { + private final UserRepository userRepository; + + public UserDetailsServiceImpl(UserRepository userRepository){ + this.userRepository = userRepository; + } + + + + @Override + @Transactional + public UserDetails loadUserByUsername(String userName) throws UsernameNotFoundException { + User user = userRepository.findUserByName(userName); + if(user == null) + throw new UsernameNotFoundException("User Not Found with username: " + userName); + + return UserDetailsImpl.build(user); + } +} diff --git a/src/main/java/com/petproject/boardgamefun/service/DesignerService.java b/src/main/java/com/petproject/boardgamefun/service/DesignerService.java new file mode 100644 index 0000000..44b888c --- /dev/null +++ b/src/main/java/com/petproject/boardgamefun/service/DesignerService.java @@ -0,0 +1,69 @@ +package com.petproject.boardgamefun.service; + +import com.petproject.boardgamefun.dto.DesignerDTO; +import com.petproject.boardgamefun.dto.GameDataDTO; +import com.petproject.boardgamefun.exception.NoRecordFoundException; +import com.petproject.boardgamefun.model.Designer; +import com.petproject.boardgamefun.model.GameByDesigner; +import com.petproject.boardgamefun.repository.DesignerRepository; +import com.petproject.boardgamefun.repository.GameByDesignerRepository; +import com.petproject.boardgamefun.repository.GameRepository; +import org.springframework.stereotype.Service; + +import javax.transaction.Transactional; +import java.util.ArrayList; +import java.util.List; + +@Service +public class DesignerService { + + final GameRepository gameRepository; + final GameByDesignerRepository gameByDesignerRepository; + final GameService gameService; + final DesignerRepository designerRepository; + public DesignerService(GameRepository gameRepository, GameByDesignerRepository gameByDesignerRepository, GameService gameService, DesignerRepository designerRepository) { + this.gameRepository = gameRepository; + this.gameByDesignerRepository = gameByDesignerRepository; + this.gameService = gameService; + this.designerRepository = designerRepository; + } + + @Transactional + public GameDataDTO addDesignerToGame(Integer gameId, Integer designerId) { + var game = gameRepository.findGameById(gameId); + var designer = designerRepository.findDesignerById(designerId); + + if (game == null || designer == null){ + throw new NoRecordFoundException("Game or designer not found"); + } + + var gameByDesigner = new GameByDesigner(); + gameByDesigner.setDesigner(designer); + gameByDesigner.setGame(game); + + gameByDesignerRepository.save(gameByDesigner); + return gameService.projectionsToGameDTO(gameRepository.findGameWithRating(gameId), + designerRepository.findDesignersUsingGame(gameId)); + } + + @Transactional + public GameDataDTO deleteDesignerFromGame(Integer gameId, Integer gameByDesignerId) { + gameByDesignerRepository.deleteById(gameByDesignerId); + return gameService.projectionsToGameDTO(gameRepository.findGameWithRating(gameId), + designerRepository.findDesignersUsingGame(gameId)); + } + + public List entitiesToDesignerDTO(List designers) { + List designersDTO = new ArrayList<>(); + + for (var item : + designers) { + designersDTO.add(new DesignerDTO(item.getId(), item.getName())); + } + return designersDTO; + } + + public DesignerDTO entityToDesignerDTO(Designer designer){ + return new DesignerDTO(designer.getId(), designer.getName()); + } +} diff --git a/src/main/java/com/petproject/boardgamefun/service/DiaryCommentService.java b/src/main/java/com/petproject/boardgamefun/service/DiaryCommentService.java new file mode 100644 index 0000000..360adcb --- /dev/null +++ b/src/main/java/com/petproject/boardgamefun/service/DiaryCommentService.java @@ -0,0 +1,32 @@ +package com.petproject.boardgamefun.service; + +import com.petproject.boardgamefun.dto.DiaryCommentDTO; +import com.petproject.boardgamefun.model.DiaryComment; +import com.petproject.boardgamefun.service.mappers.UserMapper; +import org.springframework.stereotype.Service; + +import java.util.ArrayList; +import java.util.List; + +@Service +public class DiaryCommentService { + + final UserMapper userMapper; + + public DiaryCommentService(UserMapper userMapper) { + this.userMapper = userMapper; + } + + public DiaryCommentDTO entityToDiaryCommentDTO(DiaryComment diaryComment) { + return new DiaryCommentDTO(diaryComment.getId(), diaryComment.getComment(), diaryComment.getCommentTime(), userMapper.userToUserDTO(diaryComment.getUser())); + } + + public List entitiesToCommentDTO(List diaryComments){ + ArrayList diaryCommentsDTO = new ArrayList<>(); + for (var diaryComment : + diaryComments) { + diaryCommentsDTO.add(new DiaryCommentDTO(diaryComment.getId(), diaryComment.getComment(), diaryComment.getCommentTime(), userMapper.userToUserDTO(diaryComment.getUser()))); + } + return diaryCommentsDTO; + } +} diff --git a/src/main/java/com/petproject/boardgamefun/service/DiaryRatingService.java b/src/main/java/com/petproject/boardgamefun/service/DiaryRatingService.java new file mode 100644 index 0000000..504543b --- /dev/null +++ b/src/main/java/com/petproject/boardgamefun/service/DiaryRatingService.java @@ -0,0 +1,24 @@ +package com.petproject.boardgamefun.service; + +import com.petproject.boardgamefun.dto.DiaryRatingDTO; +import com.petproject.boardgamefun.model.DiaryRating; +import org.springframework.stereotype.Service; + +import java.util.ArrayList; +import java.util.List; + +@Service +public class DiaryRatingService { + public List entitiesToDiaryRatingDTO(List diaryRatings){ + ArrayList diaryRatingsDTO = new ArrayList<>(); + for (var diaryRating : + diaryRatings) { + diaryRatingsDTO.add(new DiaryRatingDTO(diaryRating.getId(), diaryRating.getRating())); + } + return diaryRatingsDTO; + } + + public DiaryRatingDTO entityToDiaryRatingDTO(DiaryRating diaryRating){ + return new DiaryRatingDTO(diaryRating.getId(), diaryRating.getRating()); + } +} diff --git a/src/main/java/com/petproject/boardgamefun/service/DiaryService.kt b/src/main/java/com/petproject/boardgamefun/service/DiaryService.kt new file mode 100644 index 0000000..ee1842f --- /dev/null +++ b/src/main/java/com/petproject/boardgamefun/service/DiaryService.kt @@ -0,0 +1,28 @@ +package com.petproject.boardgamefun.service + +import com.petproject.boardgamefun.dto.projection.DiaryWithRatingsProjection +import com.petproject.boardgamefun.dto.DiaryDataDTO +import com.petproject.boardgamefun.model.Diary +import com.petproject.boardgamefun.service.mappers.DiaryMapper +import org.springframework.stereotype.Service +import java.util.ArrayList + +@Service +class DiaryService (private val diaryMapper: DiaryMapper) { + + fun projectionsToDiaryDTO(projections: List): List { + val diaries: MutableList = ArrayList() + for (projection in projections) { + diaries.add(DiaryDataDTO(diaryMapper.diaryToDiaryDTO(projection.diary), projection.rating)) + } + return diaries + } + + fun entityToDiaryDTO(diary: Diary): DiaryDataDTO { + return DiaryDataDTO(diaryMapper.diaryToDiaryDTO(diary), 0.0) + } + + fun projectionToDiaryDTO(projection: DiaryWithRatingsProjection): DiaryDataDTO { + return DiaryDataDTO(diaryMapper.diaryToDiaryDTO(projection.diary), projection.rating) + } +} \ No newline at end of file diff --git a/src/main/java/com/petproject/boardgamefun/service/ExpansionService.java b/src/main/java/com/petproject/boardgamefun/service/ExpansionService.java new file mode 100644 index 0000000..f962466 --- /dev/null +++ b/src/main/java/com/petproject/boardgamefun/service/ExpansionService.java @@ -0,0 +1,60 @@ +package com.petproject.boardgamefun.service; + +import com.petproject.boardgamefun.dto.GameDataDTO; +import com.petproject.boardgamefun.exception.NoRecordFoundException; +import com.petproject.boardgamefun.model.Expansion; +import com.petproject.boardgamefun.repository.ExpansionRepository; +import com.petproject.boardgamefun.repository.GameRepository; +import org.springframework.stereotype.Service; +import javax.transaction.Transactional; +import java.util.List; + +@Service +public class ExpansionService { + + final ExpansionRepository expansionRepository; + final GameRepository gameRepository; + final GameService gameService; + + public ExpansionService(ExpansionRepository expansionRepository, GameRepository gameRepository, GameService gameService) { + this.expansionRepository = expansionRepository; + this.gameRepository = gameRepository; + this.gameService = gameService; + } + + @Transactional + public List getExpansions(Integer gameId) { + if (gameId == null) + throw new NoRecordFoundException("Game does not exist with id " + gameId); + + return gameService.entitiesToGameDTO(gameRepository.getExpansions(gameId)); + } + + @Transactional + public List addExpansion(Integer parentGameId, Integer daughterGameId){ + var parentGame = gameRepository.findGameById(parentGameId); + var daughterGame = gameRepository.findGameById(daughterGameId); + + if (parentGame == null || daughterGame == null) { + throw new NoRecordFoundException("DaughterGame or ParentGame not found"); + } + + var expansion = new Expansion(); + expansion.setParentGame(parentGame); + expansion.setDaughterGame(daughterGame); + expansionRepository.save(expansion); + + return gameService.entitiesToGameDTO(gameRepository.getExpansions(parentGameId)); + } + + @Transactional + public List deleteExpansion(Integer parentGameId, Integer daughterGameId) { + var expansion = expansionRepository.findExpansion_ByParentGameIdAndDaughterGameId(parentGameId, daughterGameId); + if (expansion == null) { + throw new NoRecordFoundException("Expansion not found for parent"); + } + expansionRepository.delete(expansion); + return gameService.entitiesToGameDTO(gameRepository.getExpansions(parentGameId)); + } + +} diff --git a/src/main/java/com/petproject/boardgamefun/service/ForumMessageService.java b/src/main/java/com/petproject/boardgamefun/service/ForumMessageService.java new file mode 100644 index 0000000..5faed75 --- /dev/null +++ b/src/main/java/com/petproject/boardgamefun/service/ForumMessageService.java @@ -0,0 +1,32 @@ +package com.petproject.boardgamefun.service; + +import com.petproject.boardgamefun.dto.ForumMessageDTO; +import com.petproject.boardgamefun.model.ForumMessage; +import com.petproject.boardgamefun.service.mappers.UserMapper; +import org.springframework.stereotype.Service; + +import java.util.ArrayList; +import java.util.List; + +@Service +public class ForumMessageService { + + final UserMapper userMapper; + + public ForumMessageService(UserMapper userMapper) { + this.userMapper = userMapper; + } + + public ForumMessageDTO entityToForumMessageDTO(ForumMessage forumMessage) { + return new ForumMessageDTO(forumMessage.getId(), forumMessage.getComment(), forumMessage.getTime(), userMapper.userToUserDTO(forumMessage.getUser())); + } + + public List entitiesToForumMessagesDTO(List forumMessages) { + ArrayList forumMessagesDTO = new ArrayList<>(); + for (var forumMessage : + forumMessages) { + forumMessagesDTO.add(new ForumMessageDTO(forumMessage.getId(), forumMessage.getComment(), forumMessage.getTime(), userMapper.userToUserDTO(forumMessage.getUser()))); + } + return forumMessagesDTO; + } +} diff --git a/src/main/java/com/petproject/boardgamefun/service/ForumService.java b/src/main/java/com/petproject/boardgamefun/service/ForumService.java new file mode 100644 index 0000000..d5d38f3 --- /dev/null +++ b/src/main/java/com/petproject/boardgamefun/service/ForumService.java @@ -0,0 +1,48 @@ +package com.petproject.boardgamefun.service; + +import com.petproject.boardgamefun.dto.ForumDataDTO; +import com.petproject.boardgamefun.dto.projection.ForumProjection; +import com.petproject.boardgamefun.model.Forum; +import com.petproject.boardgamefun.service.mappers.ForumMapper; +import org.springframework.stereotype.Service; + +import java.util.ArrayList; +import java.util.List; + +@Service +public class ForumService { + + final ForumMapper forumMapper; + + public ForumService(ForumMapper forumMapper) { + this.forumMapper = forumMapper; + } + + public List projectionsToForumDTO(List projections) { + ArrayList forums = new ArrayList<>(); + for (var projection : projections) { + forums.add(new ForumDataDTO(forumMapper.forumToForumDTO(projection.getForum()), projection.getRating())); + } + return forums; + } + + public ForumDataDTO projectionToForumDTO(ForumProjection projection) { + ForumDataDTO forum = new ForumDataDTO(); + forum.setForum(forumMapper.forumToForumDTO(projection.getForum())); + forum.setRating(projection.getRating()); + return forum; + } + + public List entitiesToForumDTO(List forums) { + ArrayList forumsDTO = new ArrayList<>(); + for (var forum : + forums) { + forumsDTO.add(new ForumDataDTO(forumMapper.forumToForumDTO(forum), null)); + } + return forumsDTO; + } + + public ForumDataDTO entityToForumDTO(Forum forum) { + return new ForumDataDTO(forumMapper.forumToForumDTO(forum), null); + } +} diff --git a/src/main/java/com/petproject/boardgamefun/service/GameSellService.java b/src/main/java/com/petproject/boardgamefun/service/GameSellService.java new file mode 100644 index 0000000..58a3305 --- /dev/null +++ b/src/main/java/com/petproject/boardgamefun/service/GameSellService.java @@ -0,0 +1,107 @@ +package com.petproject.boardgamefun.service; + +import com.petproject.boardgamefun.dto.GameSellDTO; +import com.petproject.boardgamefun.dto.projection.GameSellProjection; +import com.petproject.boardgamefun.exception.BadRequestException; +import com.petproject.boardgamefun.exception.NoRecordFoundException; +import com.petproject.boardgamefun.model.Game; +import com.petproject.boardgamefun.model.GameSell; +import com.petproject.boardgamefun.repository.GameRepository; +import com.petproject.boardgamefun.repository.GameSellRepository; +import com.petproject.boardgamefun.repository.UserRepository; +import com.petproject.boardgamefun.service.mappers.GameMapper; +import org.springframework.stereotype.Service; + +import javax.transaction.Transactional; +import java.util.ArrayList; +import java.util.List; + +@Service +public class GameSellService { + + final GameMapper gameMapper; + final GameSellRepository gameSellRepository; + final UserRepository userRepository; + final GameRepository gameRepository; + + public GameSellService(GameMapper gameMapper, GameSellRepository gameSellRepository, UserRepository userRepository, GameRepository gameRepository) { + this.gameMapper = gameMapper; + this.gameSellRepository = gameSellRepository; + this.userRepository = userRepository; + this.gameRepository = gameRepository; + } + + @Transactional + public List addGameToSellList(Integer userId, Integer gameId, GameSell gameSell) { + if (gameSell.getId() != null) { + throw new BadRequestException("Game for sell is already exist"); + } + + var user = userRepository.findUserById(userId); + var game = gameRepository.findGameById(gameId); + + if (game == null || user == null) { + throw new NoRecordFoundException("User or game not found"); + } + + gameSell.setGame(game); + gameSell.setUser(user); + + gameSellRepository.save(gameSell); + return projectionsToGameSellDTO(gameRepository.getGameSellList(userId)); + } + + @Transactional + public void removeGameFromSell(Integer userId, Integer gameId) { + var gameSell = gameSellRepository.findGameSell_ByUserIdAndGameId(userId, gameId); + if (gameSell == null) { + throw new NoRecordFoundException("No game for sell is found"); + } + gameSellRepository.delete(gameSell); + } + + @Transactional + public void updateGameSell(GameSell gameSell) { + if (gameSell.getId() == null || gameSell.getGame() == null || gameSell.getUser() == null) { + throw new BadRequestException("Nothing to update!"); + } + + if (gameSell.getComment() != null) { + gameSell.setComment(gameSell.getComment()); + } + if (gameSell.getPrice() != null) { + gameSell.setPrice(gameSell.getPrice()); + } + if (gameSell.getCondition() != null) { + gameSell.setCondition(gameSell.getCondition()); + } + + gameSellRepository.save(gameSell); + } + + @Transactional + public List getGameSellList(Integer userId) { + if (userId < 0){ + throw new NoRecordFoundException("User with id " + userId + " not found"); + } + return projectionsToGameSellDTO(gameRepository.getGameSellList(userId)); + } + + public GameSellDTO entityToGameSellDTO(Game game) { + return new GameSellDTO(gameMapper.gameToGameDTO(game), null, null, null); + } + + public List projectionsToGameSellDTO(List projections) { + ArrayList gamesForSell = new ArrayList<>(); + for (var projection : + projections) { + gamesForSell.add(new GameSellDTO(gameMapper.gameToGameDTO(projection.getGame()), + projection.getCondition(), + projection.getComment(), + projection.getPrice() + )); + } + + return gamesForSell; + } +} diff --git a/src/main/java/com/petproject/boardgamefun/service/GameService.java b/src/main/java/com/petproject/boardgamefun/service/GameService.java new file mode 100644 index 0000000..01a8e53 --- /dev/null +++ b/src/main/java/com/petproject/boardgamefun/service/GameService.java @@ -0,0 +1,152 @@ +package com.petproject.boardgamefun.service; + +import com.petproject.boardgamefun.dto.FilterGamesDTO; +import com.petproject.boardgamefun.dto.RatingGameByUserDTO; +import com.petproject.boardgamefun.dto.projection.*; +import com.petproject.boardgamefun.dto.GameDataDTO; +import com.petproject.boardgamefun.exception.BadRequestException; +import com.petproject.boardgamefun.exception.NoRecordFoundException; +import com.petproject.boardgamefun.model.Game; +import com.petproject.boardgamefun.repository.*; +import com.petproject.boardgamefun.service.mappers.GameMapper; +import org.springframework.stereotype.Service; +import org.springframework.transaction.annotation.Transactional; +import org.springframework.web.multipart.MultipartFile; + +import java.io.IOException; +import java.util.ArrayList; +import java.util.List; +import java.util.stream.Collectors; + +@Service +public class GameService { + + final GameMapper gameMapper; + final GameRepository gameRepository; + final DesignerRepository designerRepository; + + public GameService(GameMapper gameMapper, GameRepository gameRepository, DesignerRepository designerRepository) { + this.gameMapper = gameMapper; + this.gameRepository = gameRepository; + this.designerRepository = designerRepository; + } + + @Transactional + public List getGames() + { + return projectionsToGameDTO(gameRepository.findGames()); + } + + @Transactional + public GameDataDTO getGameById(Integer id){ + var gameDataDTO = projectionsToGameDTO(gameRepository.findGameWithRating(id), designerRepository.findDesignersUsingGame(id)); + if (gameDataDTO == null) { + throw new NoRecordFoundException("No game with id " + id + " found"); + } + return gameDataDTO; + } + + @Transactional + public List getGameByTitle (String title) { + return getTitlesFromProjections(gameRepository.findGamesUsingTitle(title)); + } + + @Transactional + public GameDataDTO uploadImage (Integer gameId, MultipartFile multipartFile) throws IOException { + var game = gameRepository.findGameById(gameId); + if (game == null) + throw new NoRecordFoundException("Game not found"); + game.setPicture(multipartFile.getBytes()); + gameRepository.save(game); + return projectionsToGameDTO(gameRepository.findGameWithRating(gameId), designerRepository.findDesignersUsingGame(gameId)); + } + + @Transactional + public void checkExistence(Game newGame) { + if (newGame.getId() != null) { + throw new BadRequestException("Game already exists"); + } + } + + @Transactional + public GameDataDTO save(Game updatedGame) { + if (updatedGame.getTitle() == null || updatedGame.getAnnotation() == null || updatedGame.getDescription() == null || updatedGame.getTimeToPlayMax() == null || updatedGame.getTimeToPlayMin() == null || updatedGame.getYearOfRelease() == null || updatedGame.getPlayersMin() == null || updatedGame.getPlayersMax() == null) { + throw new BadRequestException("Invalid game fields"); + } + gameRepository.save(updatedGame); + return entityToGameDTO(updatedGame); + } + + @Transactional + public List getUserCollection(Integer userId){ + return entitiesToGameDTO(gameRepository.findUserGames(userId)); + } + + @Transactional + public void delete(Game game) { + if (game.getId() == null) + throw new NoRecordFoundException("Game does not exist"); + gameRepository.delete(game); + } + + public GameDataDTO projectionsToGameDTO(GameProjection gameProjection, List designersProjection) { + if (gameProjection == null) + return null; + return new GameDataDTO(gameMapper.gameToGameDTO(gameProjection.getGame()), + gameProjection.getRating(), + designersProjection.stream().map(DesignersProjection::getDesigner).collect(Collectors.toList())); + } + + public GameDataDTO projectionToGameDTO(GameProjection gameProjection) { + return new GameDataDTO(gameMapper.gameToGameDTO(gameProjection.getGame()), null, null); + } + + public List projectionsToGameDTO(List gameProjections) { + List games = new ArrayList<>(); + for (var game : + gameProjections) { + games.add(new GameDataDTO(gameMapper.gameToGameDTO(game.getGame()), game.getRating(), null)); + } + return games; + } + + + public List entitiesToGameDTO(List games) { + ArrayList gamesDTO = new ArrayList<>(); + for (var game : + games) { + gamesDTO.add(new GameDataDTO(gameMapper.gameToGameDTO(game), null, null)); + } + return gamesDTO; + } + + public GameDataDTO entityToGameDTO(Game game) { + return new GameDataDTO(gameMapper.gameToGameDTO(game), null, null); + } + + public List getTitlesFromProjections(List projections) { + ArrayList games = new ArrayList<>(); + for (var projection : projections) { + games.add(new FilterGamesDTO(projection.getId(), projection.getTitle())); + } + return games; + } + + public List userGameRatingToGameDTO(List projections) { + ArrayList games = new ArrayList<>(); + for (var projection : + projections) { + games.add(new GameDataDTO(gameMapper.gameToGameDTO(projection.getGame()), (double) projection.getRating(), null)); + } + return games; + } + + public List usersGameRatingToDTO(List projections) { + ArrayList users = new ArrayList<>(); + for (var projection : + projections) { + users.add(new RatingGameByUserDTO(projection.getUser().getId(), projection.getRating())); + } + return users; + } +} diff --git a/src/main/java/com/petproject/boardgamefun/service/RatingGameByUserService.java b/src/main/java/com/petproject/boardgamefun/service/RatingGameByUserService.java new file mode 100644 index 0000000..4217f47 --- /dev/null +++ b/src/main/java/com/petproject/boardgamefun/service/RatingGameByUserService.java @@ -0,0 +1,90 @@ +package com.petproject.boardgamefun.service; + +import com.petproject.boardgamefun.dto.GameDataDTO; +import com.petproject.boardgamefun.dto.RatingGameByUserDTO; +import com.petproject.boardgamefun.exception.BadRequestException; +import com.petproject.boardgamefun.exception.NoRecordFoundException; +import com.petproject.boardgamefun.model.RatingGameByUser; +import com.petproject.boardgamefun.repository.GameRepository; +import com.petproject.boardgamefun.repository.RatingGameByUserRepository; +import com.petproject.boardgamefun.repository.UserRepository; +import org.springframework.stereotype.Service; + +import javax.transaction.Transactional; +import java.util.List; + +@Service +public class RatingGameByUserService { + + final RatingGameByUserRepository ratingGameByUserRepository; + final GameRepository gameRepository; + final UserRepository userRepository; + final GameService gameService; + + public RatingGameByUserService(RatingGameByUserRepository ratingGameByUserRepository, GameRepository gameRepository, UserRepository userRepository, GameService gameService) { + this.ratingGameByUserRepository = ratingGameByUserRepository; + this.gameRepository = gameRepository; + this.userRepository = userRepository; + this.gameService = gameService; + } + + @Transactional + public void deleteGameRating(Integer userId, Integer gameId) { + var ratingGameByUser = ratingGameByUserRepository.findRatingGame_ByUserIdAndGameId(userId, gameId); + + if (ratingGameByUser == null) + throw new NoRecordFoundException(); + + ratingGameByUserRepository.delete(ratingGameByUser); + } + + @Transactional + public Double setGameRating(Integer userId, Integer gameId, Integer rating) { + if (rating > 10 || rating < 1) { + throw new BadRequestException("Invalid rating"); + } + if (ratingGameByUserRepository.findRatingGame_ByUserIdAndGameId(userId, gameId) != null) { + throw new BadRequestException("Rating already exists"); + } + + var gameRating = new RatingGameByUser(); + var game = gameRepository.findGameById(gameId); + var user = userRepository.findUserById(userId); + + if (game == null || user == null) + throw new NoRecordFoundException("Game or user not found"); + + gameRating.setGame(game); + gameRating.setUser(user); + gameRating.setRating(rating.doubleValue()); + + ratingGameByUserRepository.save(gameRating); + + return rating.doubleValue(); + } + + @Transactional + public Double updateGameRating(Integer userId, Integer gameId, Integer rating) { + if (rating > 10 || rating < 1) { + throw new BadRequestException("Invalid rating"); + } + var ratingGameByUser = ratingGameByUserRepository.findRatingGame_ByUserIdAndGameId(userId, gameId); + if (ratingGameByUser == null) { + throw new NoRecordFoundException("No rating by user"); + } + + ratingGameByUser.setRating(rating.doubleValue()); + ratingGameByUserRepository.save(ratingGameByUser); + return rating.doubleValue(); + } + + @Transactional + public List getUsersRating(Integer gameId){ + return gameService.usersGameRatingToDTO(userRepository.findGameRatings(gameId)); + } + + public List getUserRatingList(Integer userId){ + return gameService.userGameRatingToGameDTO(gameRepository.findUserGameRatingList(userId)); + } + +} diff --git a/src/main/java/com/petproject/boardgamefun/service/SimilarGameService.java b/src/main/java/com/petproject/boardgamefun/service/SimilarGameService.java new file mode 100644 index 0000000..2cb9388 --- /dev/null +++ b/src/main/java/com/petproject/boardgamefun/service/SimilarGameService.java @@ -0,0 +1,59 @@ +package com.petproject.boardgamefun.service; + +import com.petproject.boardgamefun.dto.GameDataDTO; +import com.petproject.boardgamefun.exception.NoRecordFoundException; +import com.petproject.boardgamefun.model.SameGame; +import com.petproject.boardgamefun.repository.GameRepository; +import com.petproject.boardgamefun.repository.SameGameRepository; +import org.springframework.stereotype.Service; +import org.springframework.web.bind.annotation.PathVariable; + +import javax.transaction.Transactional; +import java.util.List; + +@Service +public class SimilarGameService { + + final GameService gameService; + final GameRepository gameRepository; + final SameGameRepository sameGameRepository; + + public SimilarGameService(GameService gameService, GameRepository gameRepository, SameGameRepository sameGameRepository) { + this.gameService = gameService; + this.gameRepository = gameRepository; + this.sameGameRepository = sameGameRepository; + } + + @Transactional + public List getSimilarGames(Integer gameId) { + if (gameId == null) + throw new NoRecordFoundException("Game with id " + gameId + " not found"); + return gameService.entitiesToGameDTO(gameRepository.getSimilarGames(gameId)); + } + + @Transactional + public List addSimilarGame(Integer referenceGameId, Integer sourceGameId) { + var referenceGame = gameRepository.findGameById(referenceGameId); + var sourceGame = gameRepository.findGameById(sourceGameId); + + if (referenceGame == null || sourceGame == null) + throw new NoRecordFoundException("referenceGame or sourceGame are null"); + + var sameGame = new SameGame(); + sameGame.setReferenceGame(referenceGame); + sameGame.setSourceGame(sourceGame); + sameGameRepository.save(sameGame); + return gameService.entitiesToGameDTO(gameRepository.getSimilarGames(referenceGameId)); + } + + @Transactional + public List deleteSameGame(@PathVariable Integer referenceGameId, @PathVariable Integer sourceGameId) { + var sameGame = sameGameRepository.findSameGame_ByReferenceGameIdAndSourceGameId(referenceGameId, sourceGameId); + if (sameGame == null) { + throw new NoRecordFoundException("No same game found for reference"); + } + sameGameRepository.delete(sameGame); + + return gameService.entitiesToGameDTO(gameRepository.getSimilarGames(referenceGameId)); + } +} diff --git a/src/main/java/com/petproject/boardgamefun/service/UserOwnGameService.java b/src/main/java/com/petproject/boardgamefun/service/UserOwnGameService.java new file mode 100644 index 0000000..d92bd11 --- /dev/null +++ b/src/main/java/com/petproject/boardgamefun/service/UserOwnGameService.java @@ -0,0 +1,56 @@ +package com.petproject.boardgamefun.service; + +import com.petproject.boardgamefun.exception.BadRequestException; +import com.petproject.boardgamefun.exception.NoRecordFoundException; +import com.petproject.boardgamefun.model.UserOwnGame; +import com.petproject.boardgamefun.repository.GameRepository; +import com.petproject.boardgamefun.repository.UserOwnGameRepository; +import com.petproject.boardgamefun.repository.UserRepository; +import org.springframework.stereotype.Service; + +import javax.transaction.Transactional; + +@Service +public class UserOwnGameService { + + final UserOwnGameRepository userOwnGameRepository; + final GameRepository gameRepository; + final UserRepository userRepository; + + public UserOwnGameService(UserOwnGameRepository userOwnGameRepository, GameRepository gameRepository, UserRepository userRepository) { + this.userOwnGameRepository = userOwnGameRepository; + this.gameRepository = gameRepository; + this.userRepository = userRepository; + } + + @Transactional + public String addGameToUser(Integer userId, Integer gameId) { + var user = userRepository.findUserById(userId); + var game = gameRepository.findGameById(gameId); + + if (user == null || game == null) + throw new NoRecordFoundException(); + + var games = gameRepository.findUserGames(userId); + if (games.size() != 0 && games.stream().anyMatch(g -> g.getId().equals(gameId))) { + throw new BadRequestException(); + } + + var userOwnGame = new UserOwnGame(); + userOwnGame.setGame(game); + userOwnGame.setUser(user); + + userOwnGameRepository.save(userOwnGame); + + return game.getTitle(); + } + @Transactional + public void deleteGameFromUserCollection(Integer userId, Integer gameId){ + var userOwnGame = userOwnGameRepository.findUserOwnGame_ByUserIdAndGameId(userId, gameId); + + if (userOwnGame == null) + throw new NoRecordFoundException(); + + userOwnGameRepository.delete(userOwnGame); + } +} diff --git a/src/main/java/com/petproject/boardgamefun/service/UserService.java b/src/main/java/com/petproject/boardgamefun/service/UserService.java new file mode 100644 index 0000000..47fa757 --- /dev/null +++ b/src/main/java/com/petproject/boardgamefun/service/UserService.java @@ -0,0 +1,123 @@ +package com.petproject.boardgamefun.service; + +import com.petproject.boardgamefun.dto.UserDTO; +import com.petproject.boardgamefun.dto.request.PasswordChangeRequest; +import com.petproject.boardgamefun.dto.request.UserEditRequest; +import com.petproject.boardgamefun.exception.BadRequestException; +import com.petproject.boardgamefun.exception.NoRecordFoundException; +import com.petproject.boardgamefun.model.User; +import com.petproject.boardgamefun.repository.GameRepository; +import com.petproject.boardgamefun.repository.UserOwnGameRepository; +import com.petproject.boardgamefun.repository.UserRepository; +import com.petproject.boardgamefun.security.enums.Role; +import com.petproject.boardgamefun.service.mappers.UserMapper; +import org.springframework.security.crypto.password.PasswordEncoder; +import org.springframework.stereotype.Service; +import org.springframework.web.multipart.MultipartFile; + +import javax.transaction.Transactional; +import java.io.IOException; +import java.time.OffsetDateTime; +import java.util.ArrayList; +import java.util.List; +import java.util.Objects; + +@Service +public class UserService { + final UserMapper userMapper; + final UserRepository userRepository; + final GameRepository gameRepository; + final PasswordEncoder passwordEncoder; + + public UserService(UserMapper userMapper, UserRepository userRepository, GameRepository gameRepository, UserOwnGameRepository userOwnGameRepository, PasswordEncoder passwordEncoder) { + this.userMapper = userMapper; + this.userRepository = userRepository; + this.gameRepository = gameRepository; + this.passwordEncoder = passwordEncoder; + } + + public List getUsers() { + return entitiesToUserDTO(userRepository.findAll()); + } + + public Boolean existsByName(String name) { + return userRepository.existsByName(name); + } + + public void registerUser(User user) { + if (userRepository.existsByName(user.getName())) { + throw new BadRequestException("Пользователь с таким никнеймом уже существует"); + } + + if (userRepository.existsByMail(user.getMail())) { + throw new BadRequestException("Пользователь с такой почтой уже существует"); + } + + user.setRole(Role.ROLE_USER.name()); + user.setPassword(passwordEncoder.encode(user.getPassword())); + user.setRegistrationDate(OffsetDateTime.now()); + userRepository.save(user); + } + + @Transactional + public void uploadAvatar(String userName, MultipartFile multipartFile) throws IOException { + var user = userRepository.findUserByName(userName); + if (user == null) { + throw new NoRecordFoundException("No user with name " + userName + " found"); + } + user.setAvatar(multipartFile.getBytes()); + userRepository.save(user); + } + + @Transactional + public UserDTO editUser(Integer userId, UserEditRequest userEditRequest) { + var user = userRepository.findUserById(userId); + if (userEditRequest.getName() != null && !userRepository.existsByName(userEditRequest.getName())) { + user.setName(userEditRequest.getName()); + } else { + throw new BadRequestException("Пользователь с таким никнеймом уже существует"); + } + if (userEditRequest.getRole() != null && !Objects.equals(userEditRequest.getRole(), user.getRole())) { + user.setRole(userEditRequest.getRole()); + } + userRepository.save(user); + + return entityToUserDTO(user); + } + + @Transactional + public UserDTO changePassword(Integer userId, PasswordChangeRequest passwordRequest) { + var user = userRepository.findUserById(userId); + if (passwordRequest.getPassword() != null && passwordEncoder.matches(passwordRequest.getPassword(), user.getPassword())) { + user.setPassword(passwordEncoder.encode(passwordRequest.getPassword())); + } else { + throw new BadRequestException("Вы ввели точно такой же пароль"); + } + userRepository.save(user); + return entityToUserDTO(user); + + } + + @Transactional + public UserDTO getUser(Integer userId) { + UserDTO userDTO = entityToUserDTO(userRepository.findUserById(userId)); + if (userDTO == null) { + throw new NoRecordFoundException(); + } + return userDTO; + } + + + public List entitiesToUserDTO(List users) { + List usersDTO = new ArrayList<>(); + for (var user : + users) { + usersDTO.add(userMapper.userToUserDTO(user)); + } + return usersDTO; + } + + public UserDTO entityToUserDTO(User user) { + return userMapper.userToUserDTO(user); + } +} diff --git a/src/main/java/com/petproject/boardgamefun/service/UserWishService.java b/src/main/java/com/petproject/boardgamefun/service/UserWishService.java new file mode 100644 index 0000000..7878376 --- /dev/null +++ b/src/main/java/com/petproject/boardgamefun/service/UserWishService.java @@ -0,0 +1,65 @@ +package com.petproject.boardgamefun.service; + +import com.petproject.boardgamefun.dto.GameDataDTO; +import com.petproject.boardgamefun.exception.BadRequestException; +import com.petproject.boardgamefun.exception.NoRecordFoundException; +import com.petproject.boardgamefun.model.UserWish; +import com.petproject.boardgamefun.repository.GameRepository; +import com.petproject.boardgamefun.repository.UserRepository; +import com.petproject.boardgamefun.repository.UserWishRepository; +import org.springframework.stereotype.Service; + +import javax.transaction.Transactional; +import java.util.List; + +@Service +public class UserWishService { + + final UserWishRepository userWishRepository; + final UserRepository userRepository; + final GameRepository gameRepository; + final GameService gameService; + + public UserWishService(UserWishRepository userWishRepository, UserRepository userRepository, GameRepository gameRepository, GameService gameUserService) { + this.userWishRepository = userWishRepository; + this.userRepository = userRepository; + this.gameRepository = gameRepository; + this.gameService = gameUserService; + } + + @Transactional + public String addGameToUserWishlist(Integer userId, Integer gameId) { + var user = userRepository.findUserById(userId); + var game = gameRepository.findGameById(gameId); + + if (userWishRepository.findByUserAndGame(user, game) != null) { + throw new BadRequestException("user wish already exists"); + } + + if (user == null || game == null) { + throw new NoRecordFoundException("user or game not found"); + } + + var userWish = new UserWish(); + userWish.setGame(game); + userWish.setUser(user); + + userWishRepository.save(userWish); + return game.getTitle(); + } + + @Transactional + public void deleteGameFromUserWishlist(Integer userWishId) { + var userWish = userWishRepository.findById(userWishId); + + if (userWish.isEmpty()) { + throw new NoRecordFoundException("Userwish is not found"); + } + userWishRepository.delete(userWish.get()); + } + + @Transactional + public List getUserWishList(Integer id){ + return gameService.entitiesToGameDTO(gameRepository.findUserWishlist(id)); + } +} diff --git a/src/main/java/com/petproject/boardgamefun/service/mappers/DiaryMapper.java b/src/main/java/com/petproject/boardgamefun/service/mappers/DiaryMapper.java new file mode 100644 index 0000000..dc6523f --- /dev/null +++ b/src/main/java/com/petproject/boardgamefun/service/mappers/DiaryMapper.java @@ -0,0 +1,15 @@ +package com.petproject.boardgamefun.service.mappers; + +import com.petproject.boardgamefun.dto.DiaryDTO; +import com.petproject.boardgamefun.model.Diary; +import org.mapstruct.*; + +@Mapper(unmappedTargetPolicy = ReportingPolicy.IGNORE, componentModel = "spring") +public interface DiaryMapper { + Diary diaryDTOToDiary(DiaryDTO diaryDTO); + + DiaryDTO diaryToDiaryDTO(Diary diary); + + @BeanMapping(nullValuePropertyMappingStrategy = NullValuePropertyMappingStrategy.IGNORE) + void updateDiaryFromDiaryDTO(DiaryDTO diaryDTO, @MappingTarget Diary diary); +} diff --git a/src/main/java/com/petproject/boardgamefun/service/mappers/DiaryRatingMapper.java b/src/main/java/com/petproject/boardgamefun/service/mappers/DiaryRatingMapper.java new file mode 100644 index 0000000..d6e742d --- /dev/null +++ b/src/main/java/com/petproject/boardgamefun/service/mappers/DiaryRatingMapper.java @@ -0,0 +1,15 @@ +package com.petproject.boardgamefun.service.mappers; + +import com.petproject.boardgamefun.dto.DiaryRatingDTO; +import com.petproject.boardgamefun.model.DiaryRating; +import org.mapstruct.*; + +@Mapper(unmappedTargetPolicy = ReportingPolicy.IGNORE, componentModel = "spring") +public interface DiaryRatingMapper { + DiaryRating diaryRatingDTOToDiaryRating(DiaryRatingDTO diaryRatingDTO); + + DiaryRatingDTO diaryRatingToDiaryRatingDTO(DiaryRating diaryRating); + + @BeanMapping(nullValuePropertyMappingStrategy = NullValuePropertyMappingStrategy.IGNORE) + void updateDiaryRatingFromDiaryRatingDTO(DiaryRatingDTO diaryRatingDTO, @MappingTarget DiaryRating diaryRating); +} diff --git a/src/main/java/com/petproject/boardgamefun/service/mappers/ForumMapper.java b/src/main/java/com/petproject/boardgamefun/service/mappers/ForumMapper.java new file mode 100644 index 0000000..d51a84a --- /dev/null +++ b/src/main/java/com/petproject/boardgamefun/service/mappers/ForumMapper.java @@ -0,0 +1,15 @@ +package com.petproject.boardgamefun.service.mappers; + +import com.petproject.boardgamefun.dto.ForumDTO; +import com.petproject.boardgamefun.model.Forum; +import org.mapstruct.*; + +@Mapper(unmappedTargetPolicy = ReportingPolicy.IGNORE, componentModel = "spring") +public interface ForumMapper { + Forum forumDTOToForum(ForumDTO forumDTO); + + ForumDTO forumToForumDTO(Forum forum); + + @BeanMapping(nullValuePropertyMappingStrategy = NullValuePropertyMappingStrategy.IGNORE) + void updateForumFromForumDTO(ForumDTO forumDTO, @MappingTarget Forum forum); +} diff --git a/src/main/java/com/petproject/boardgamefun/service/mappers/GameMapper.java b/src/main/java/com/petproject/boardgamefun/service/mappers/GameMapper.java new file mode 100644 index 0000000..43e8286 --- /dev/null +++ b/src/main/java/com/petproject/boardgamefun/service/mappers/GameMapper.java @@ -0,0 +1,15 @@ +package com.petproject.boardgamefun.service.mappers; + +import com.petproject.boardgamefun.dto.GameDTO; +import com.petproject.boardgamefun.model.Game; +import org.mapstruct.*; + +@Mapper(unmappedTargetPolicy = ReportingPolicy.IGNORE, componentModel = "spring", injectionStrategy = InjectionStrategy.CONSTRUCTOR) +public interface GameMapper { + Game gameDTOToGame(GameDTO gameDTO); + + GameDTO gameToGameDTO(Game game); + + @BeanMapping(nullValuePropertyMappingStrategy = NullValuePropertyMappingStrategy.IGNORE) + void updateGameFromGameDTO(GameDTO gameDTO, @MappingTarget Game game); +} diff --git a/src/main/java/com/petproject/boardgamefun/service/mappers/GameSellMapper.java b/src/main/java/com/petproject/boardgamefun/service/mappers/GameSellMapper.java new file mode 100644 index 0000000..a9fda96 --- /dev/null +++ b/src/main/java/com/petproject/boardgamefun/service/mappers/GameSellMapper.java @@ -0,0 +1,17 @@ +package com.petproject.boardgamefun.service.mappers; + +import com.petproject.boardgamefun.dto.GameSellDTO; +import com.petproject.boardgamefun.model.GameSell; +import org.mapstruct.InjectionStrategy; +import org.mapstruct.Mapper; +import org.mapstruct.ReportingPolicy; + +@Mapper(unmappedTargetPolicy = ReportingPolicy.IGNORE, componentModel = "spring", injectionStrategy = InjectionStrategy.CONSTRUCTOR) +public interface GameSellMapper { + + GameSell GameSellDTOToGameSell(GameSellDTO gameSellDTO); + + GameSellDTO GameSellToGameSellDTO(GameSell gameSell); + + +} diff --git a/src/main/java/com/petproject/boardgamefun/service/mappers/RatingGameByUserMapper.java b/src/main/java/com/petproject/boardgamefun/service/mappers/RatingGameByUserMapper.java new file mode 100644 index 0000000..2517b8c --- /dev/null +++ b/src/main/java/com/petproject/boardgamefun/service/mappers/RatingGameByUserMapper.java @@ -0,0 +1,22 @@ +package com.petproject.boardgamefun.service.mappers; + +import com.petproject.boardgamefun.dto.RatingGameByUserDTO; +import com.petproject.boardgamefun.model.RatingGameByUser; +import org.mapstruct.*; + +@Mapper(unmappedTargetPolicy = ReportingPolicy.IGNORE, componentModel = "spring") +public interface RatingGameByUserMapper { + RatingGameByUser ratingGameByUserDTOToRatingGameByUser(RatingGameByUserDTO ratingGameByUserDTO); + + RatingGameByUserDTO ratingGameByUserToRatingGameByUserDTO(RatingGameByUser ratingGameByUser); + + @BeanMapping(nullValuePropertyMappingStrategy = NullValuePropertyMappingStrategy.IGNORE) + void updateRatingGameByUserFromRatingGameByUserDTO(RatingGameByUserDTO ratingGameByUserDTO, @MappingTarget RatingGameByUser ratingGameByUser); + + RatingGameByUser ratingGameByUserDTOToRatingGameByUser1(com.petproject.boardgamefun.dto.RatingGameByUserDTO ratingGameByUserDTO); + + com.petproject.boardgamefun.dto.RatingGameByUserDTO ratingGameByUserToRatingGameByUserDTO1(RatingGameByUser ratingGameByUser); + + @BeanMapping(nullValuePropertyMappingStrategy = NullValuePropertyMappingStrategy.IGNORE) + void updateRatingGameByUserFromRatingGameByUserDTO1(com.petproject.boardgamefun.dto.RatingGameByUserDTO ratingGameByUserDTO, @MappingTarget RatingGameByUser ratingGameByUser); +} diff --git a/src/main/java/com/petproject/boardgamefun/service/mappers/UserMapper.java b/src/main/java/com/petproject/boardgamefun/service/mappers/UserMapper.java new file mode 100644 index 0000000..a67ffac --- /dev/null +++ b/src/main/java/com/petproject/boardgamefun/service/mappers/UserMapper.java @@ -0,0 +1,15 @@ +package com.petproject.boardgamefun.service.mappers; + +import com.petproject.boardgamefun.dto.UserDTO; +import com.petproject.boardgamefun.model.User; +import org.mapstruct.*; + +@Mapper(unmappedTargetPolicy = ReportingPolicy.WARN, componentModel = "spring", injectionStrategy = InjectionStrategy.CONSTRUCTOR) +public interface UserMapper { + User userDTOToUser(UserDTO userDTO); + + UserDTO userToUserDTO(User user); + + @BeanMapping(nullValuePropertyMappingStrategy = NullValuePropertyMappingStrategy.IGNORE) + void updateUserFromUserDTO(UserDTO userDTO, @MappingTarget User user); +} diff --git a/src/main/resources/application.properties b/src/main/resources/application.properties index 66180dd..9345de0 100644 --- a/src/main/resources/application.properties +++ b/src/main/resources/application.properties @@ -3,3 +3,12 @@ server.port=8090 spring.datasource.url=jdbc:postgresql://localhost:5432/BoardgameFun spring.datasource.username=postgres spring.datasource.password=1 + +# App Properties +boardgamefun.app.jwtSecret = PetProjectSecretKey +boardgamefun.app.jwtExpirationMs = 600000 +boardgamefun.app.jwtRefreshSecret = PetProjectRefreshKey +boardgamefun.app.refreshTokenExpirationMs = 86400000 + +spring.liquibase.change-log=classpath:liquibase/changelog-master.xml +spring.liquibase.enabled=false \ No newline at end of file diff --git a/src/main/resources/liquibase.properties b/src/main/resources/liquibase.properties new file mode 100644 index 0000000..69b5443 --- /dev/null +++ b/src/main/resources/liquibase.properties @@ -0,0 +1,3 @@ +url=jdbc:postgresql://localhost:5432/BoardgameFun +username=postgres +password=1 \ No newline at end of file diff --git a/src/main/resources/liquibase/2022-09/v1-08-09-2022-changelog.xml b/src/main/resources/liquibase/2022-09/v1-08-09-2022-changelog.xml new file mode 100644 index 0000000..f67be6a --- /dev/null +++ b/src/main/resources/liquibase/2022-09/v1-08-09-2022-changelog.xml @@ -0,0 +1,691 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/src/main/resources/liquibase/changelog-master.xml b/src/main/resources/liquibase/changelog-master.xml new file mode 100644 index 0000000..66949e2 --- /dev/null +++ b/src/main/resources/liquibase/changelog-master.xml @@ -0,0 +1,6 @@ + + + \ No newline at end of file diff --git a/src/test/java/com/petproject/boardgamefun/SpringSecurityWebTestConfig.java b/src/test/java/com/petproject/boardgamefun/SpringSecurityWebTestConfig.java new file mode 100644 index 0000000..f390ba0 --- /dev/null +++ b/src/test/java/com/petproject/boardgamefun/SpringSecurityWebTestConfig.java @@ -0,0 +1,30 @@ +package com.petproject.boardgamefun; + +import com.petproject.boardgamefun.security.services.UserDetailsImpl; +import org.springframework.boot.test.context.TestConfiguration; +import org.springframework.context.annotation.Bean; +import org.springframework.context.annotation.Primary; +import org.springframework.security.core.authority.SimpleGrantedAuthority; +import org.springframework.security.core.userdetails.UserDetailsService; +import org.springframework.security.provisioning.InMemoryUserDetailsManager; + +import java.util.Arrays; +import java.util.List; + +@TestConfiguration +public class SpringSecurityWebTestConfig { + @Bean + @Primary + public UserDetailsService userDetailsService() { + UserDetailsImpl basicUser = new UserDetailsImpl(1,"Basic User", "user@company.com", "password", List.of( + new SimpleGrantedAuthority("ROLE_USER"))); + + + UserDetailsImpl managerUser = new UserDetailsImpl(2,"Admin", "admin@company.com", "adminPassword", List.of( + new SimpleGrantedAuthority("ROLE_ADMIN"))); + + return new InMemoryUserDetailsManager(Arrays.asList( + basicUser, managerUser + )); + } +} diff --git a/src/test/java/com/petproject/boardgamefun/controller/ExpansionControllerTests.java b/src/test/java/com/petproject/boardgamefun/controller/ExpansionControllerTests.java new file mode 100644 index 0000000..88b79ad --- /dev/null +++ b/src/test/java/com/petproject/boardgamefun/controller/ExpansionControllerTests.java @@ -0,0 +1,187 @@ +package com.petproject.boardgamefun.controller; + +import com.fasterxml.jackson.databind.ObjectMapper; +import com.petproject.boardgamefun.SpringSecurityWebTestConfig; +import com.petproject.boardgamefun.dto.GameDataDTO; +import com.petproject.boardgamefun.exception.NoRecordFoundException; +import com.petproject.boardgamefun.model.Designer; +import com.petproject.boardgamefun.model.Expansion; +import com.petproject.boardgamefun.model.Game; +import com.petproject.boardgamefun.service.ExpansionService; +import com.petproject.boardgamefun.service.GameService; +import com.petproject.boardgamefun.service.mappers.GameMapper; +import org.junit.jupiter.api.*; +import org.junit.jupiter.api.extension.ExtendWith; +import org.mockito.junit.jupiter.MockitoExtension; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.boot.test.autoconfigure.web.servlet.AutoConfigureMockMvc; +import org.springframework.boot.test.context.SpringBootTest; +import org.springframework.boot.test.mock.mockito.MockBean; +import org.springframework.security.test.context.support.WithMockUser; +import org.springframework.test.web.servlet.MockMvc; +import org.springframework.test.web.servlet.request.MockMvcRequestBuilders; +import org.springframework.web.context.WebApplicationContext; + +import java.time.OffsetDateTime; +import java.util.ArrayList; +import java.util.List; + +import static org.mockito.Mockito.verify; +import static org.mockito.Mockito.when; +import static org.springframework.test.web.servlet.result.MockMvcResultHandlers.print; +import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status; + +@ExtendWith(MockitoExtension.class) +@SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.MOCK, classes = SpringSecurityWebTestConfig.class) +@AutoConfigureMockMvc +@TestMethodOrder(MethodOrderer.OrderAnnotation.class) +@TestInstance(TestInstance.Lifecycle.PER_CLASS) +public class ExpansionControllerTests { + @Autowired + private MockMvc mockMvc; + + @Autowired + private WebApplicationContext webApplicationContext; + + private final String Gateway = "/expansions"; + + ObjectMapper objectMapper; + + @Autowired + GameMapper gameMapper; + + @MockBean + private ExpansionService expansionService; + + private List gamesDataDTO; + private Game game; + private Game game2; + private GameDataDTO gameDataDTO; + + @BeforeAll + public void setup(){ + objectMapper = new ObjectMapper(); + objectMapper.findAndRegisterModules(); + + String instantExpected = "2014-12-22T10:15:30Z"; + + game = new Game(); + game.setId(1); + game.setTitle(" Игра номер 1"); + game.setDescription("Отличная игра войнушка номер 1"); + game.setAnnotation("Отличная игра номер 1"); + game.setPicture(null); + game.setPlayerAge("14"); + game.setPlayersMin(3); + game.setPlayersMax(5); + game.setTimeToPlayMin(120); + game.setTimeToPlayMax(360); + game.setYearOfRelease(OffsetDateTime.parse(instantExpected)); + + game2 = new Game(); + game2.setId(1); + game2.setTitle(" Игра номер 2"); + game2.setDescription("Отличная игра войнушка номер 2"); + game2.setAnnotation("Отличная игра номер 2"); + game2.setPicture(null); + game2.setPlayerAge("16"); + game2.setPlayersMin(2); + game2.setPlayersMax(4); + game2.setTimeToPlayMin(30); + game2.setTimeToPlayMax(120); + game2.setYearOfRelease(OffsetDateTime.parse(instantExpected)); + + Designer designer = new Designer(); + designer.setId(1); + designer.setName("Designer number one"); + + Designer designer2 = new Designer(); + designer2.setId(2); + designer2.setName("Designer number two"); + + List designers = new ArrayList<>(); + designers.add(designer.getName()); + designers.add(designer2.getName()); + + gameDataDTO = new GameDataDTO(gameMapper.gameToGameDTO(game), 8.4, designers); + GameDataDTO gameDataDTO1 = new GameDataDTO(gameMapper.gameToGameDTO(game2), 7.9, designers); + gamesDataDTO = new ArrayList<>(); + gamesDataDTO.add(gameDataDTO); + gamesDataDTO.add(gameDataDTO1); + } + + @Test + public void getExpansionsShouldReturnOk() throws Exception { + when(expansionService.getExpansions(1)).thenReturn(gamesDataDTO); + var mvcRes = this.mockMvc.perform(MockMvcRequestBuilders.get(Gateway+ "/1")).andDo(print()).andExpect(status().isOk()).andReturn(); + var res = objectMapper.readValue(mvcRes.getResponse().getContentAsByteArray(), GameDataDTO[].class); + verify(expansionService).getExpansions(1); + Assertions.assertEquals(res.length, 2); + } + + @Test + public void getExpansionsShouldReturnOk_BlankArray() throws Exception { + when(expansionService.getExpansions(1)).thenReturn(new ArrayList<>()); + var mvcRes = this.mockMvc.perform(MockMvcRequestBuilders.get(Gateway+ "/1")).andDo(print()).andExpect(status().isOk()).andReturn(); + var res = objectMapper.readValue(mvcRes.getResponse().getContentAsByteArray(), GameDataDTO[].class); + verify(expansionService).getExpansions(1); + Assertions.assertEquals(res.length, 0); + } + + @Test + public void getExpansionsShouldReturnNotFound() throws Exception { + when(expansionService.getExpansions(-1)).thenThrow(new NoRecordFoundException()); + this.mockMvc.perform(MockMvcRequestBuilders.get(Gateway+ "/-1")).andDo(print()).andExpect(status().isNotFound()); + verify(expansionService).getExpansions(-1); + Assertions.assertThrows(NoRecordFoundException.class, () ->expansionService.getExpansions(-1)); + } + @Test + @WithMockUser(roles = "USER") + public void addExpansionsShouldReturnOK() throws Exception { + when(expansionService.addExpansion(1, 2)).thenReturn(gamesDataDTO); + var mvcRes = this.mockMvc.perform(MockMvcRequestBuilders.post(Gateway+ "/1/2")).andDo(print()).andExpect(status().isOk()).andReturn(); + var res = objectMapper.readValue(mvcRes.getResponse().getContentAsByteArray(), GameDataDTO[].class); + verify(expansionService).addExpansion(1,2); + Assertions.assertEquals(res.length, 2); + } + + @Test + @WithMockUser(roles = "USER") + public void addExpansionsShouldReturnNotFound() throws Exception { + when(expansionService.addExpansion(-1, -2)).thenThrow(NoRecordFoundException.class); + this.mockMvc.perform(MockMvcRequestBuilders.post(Gateway+ "/-1/-2")).andDo(print()).andExpect(status().isNotFound()); + verify(expansionService).addExpansion(-1,-2); + Assertions.assertThrows(NoRecordFoundException.class, () -> expansionService.addExpansion(-1,-2)); + } + + @Test + public void addExpansionsShouldReturnNotAuthorized() throws Exception { + this.mockMvc.perform(MockMvcRequestBuilders.post(Gateway+ "/1/2")).andDo(print()).andExpect(status().isUnauthorized()); + } + + @Test + @WithMockUser(roles = "USER") + public void deleteExpansionsShouldReturnOK() throws Exception { + when(expansionService.deleteExpansion(1, 2)).thenReturn(gamesDataDTO); + var mvcRes = this.mockMvc.perform(MockMvcRequestBuilders.delete(Gateway+ "/1/2")).andDo(print()).andExpect(status().isOk()).andReturn(); + var res = objectMapper.readValue(mvcRes.getResponse().getContentAsByteArray(), GameDataDTO[].class); + verify(expansionService).deleteExpansion(1,2); + Assertions.assertEquals(res.length, 2); + } + + @Test + @WithMockUser(roles = "USER") + public void deleteExpansionsShouldReturnNotFound() throws Exception { + when(expansionService.deleteExpansion(-1, -2)).thenThrow(NoRecordFoundException.class); + this.mockMvc.perform(MockMvcRequestBuilders.delete(Gateway+ "/-1/-2")).andDo(print()).andExpect(status().isNotFound()); + verify(expansionService).deleteExpansion(-1,-2); + Assertions.assertThrows(NoRecordFoundException.class, () -> expansionService.deleteExpansion(-1,-2)); + } + + @Test + public void deleteExpansionsShouldReturnNotAuthorized() throws Exception { + this.mockMvc.perform(MockMvcRequestBuilders.delete(Gateway+ "/1/2")).andDo(print()).andExpect(status().isUnauthorized()); + } + + +} diff --git a/src/test/java/com/petproject/boardgamefun/controller/GameControllerTests.java b/src/test/java/com/petproject/boardgamefun/controller/GameControllerTests.java new file mode 100644 index 0000000..eccd5a9 --- /dev/null +++ b/src/test/java/com/petproject/boardgamefun/controller/GameControllerTests.java @@ -0,0 +1,1321 @@ + +package com.petproject.boardgamefun.controller; + +import static org.mockito.Mockito.when; +import static org.springframework.test.web.servlet.result.MockMvcResultHandlers.print; +import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status; + +import com.fasterxml.jackson.databind.ObjectMapper; +import com.petproject.boardgamefun.SpringSecurityWebTestConfig; +import com.petproject.boardgamefun.dto.FilterGamesDTO; +import com.petproject.boardgamefun.dto.GameDataDTO; +import com.petproject.boardgamefun.dto.projection.GameProjection; +import com.petproject.boardgamefun.dto.projection.GamesFilterByTitleProjection; +import com.petproject.boardgamefun.exception.BadRequestException; +import com.petproject.boardgamefun.exception.NoRecordFoundException; +import com.petproject.boardgamefun.model.*; +import com.petproject.boardgamefun.service.GameService; +import com.petproject.boardgamefun.service.mappers.GameMapper; +import org.junit.jupiter.api.*; +import org.junit.jupiter.api.extension.ExtendWith; +import org.mockito.Mockito; +import org.mockito.junit.jupiter.MockitoExtension; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.boot.test.autoconfigure.web.servlet.AutoConfigureMockMvc; +import org.springframework.boot.test.context.SpringBootTest; +import org.springframework.boot.test.mock.mockito.MockBean; +import org.springframework.http.MediaType; +import org.springframework.mock.web.MockMultipartFile; +import org.springframework.security.test.context.support.WithMockUser; +import org.springframework.test.web.servlet.MockMvc; +import org.springframework.test.web.servlet.request.MockMultipartHttpServletRequestBuilder; +import org.springframework.test.web.servlet.request.MockMvcRequestBuilders; +import org.springframework.web.context.WebApplicationContext; + + +import static org.mockito.Mockito.*; + +import java.time.OffsetDateTime; +import java.util.ArrayList; +import java.util.List; + +@ExtendWith(MockitoExtension.class) +@SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.MOCK, classes = SpringSecurityWebTestConfig.class) +@AutoConfigureMockMvc +@TestMethodOrder(MethodOrderer.OrderAnnotation.class) +@TestInstance(TestInstance.Lifecycle.PER_CLASS) +public class GameControllerTests { + @Autowired + private MockMvc mockMvc; + + @Autowired + private WebApplicationContext webApplicationContext; + + private final String Gateway = "/games"; + + ObjectMapper objectMapper; + + @Autowired + GameMapper gameMapper; + + @MockBean + private GameService gameService; + + private Game game; + private Game game2; + private List games; + private GameProjection gameProjection; + private List gameProjectionList; + private GameDataDTO gameDataDTO; + private List gamesDataDTO; + private List gamesFilterByTitleProjectionList; + private List filterGamesDTOList; + private MockMultipartFile multipartFile; + + @BeforeAll + public void setup() { + objectMapper = new ObjectMapper(); + objectMapper.findAndRegisterModules(); + + String instantExpected = "2014-12-22T10:15:30Z"; + + game = new Game(); + game.setId(1); + game.setTitle(" Игра номер 1"); + game.setDescription("Отличная игра войнушка номер 1"); + game.setAnnotation("Отличная игра номер 1"); + game.setPicture(null); + game.setPlayerAge("14"); + game.setPlayersMin(3); + game.setPlayersMax(5); + game.setTimeToPlayMin(120); + game.setTimeToPlayMax(360); + game.setYearOfRelease(OffsetDateTime.parse(instantExpected)); + + + game2 = new Game(); + game2.setId(1); + game2.setTitle(" Игра номер 2"); + game2.setDescription("Отличная игра войнушка номер 2"); + game2.setAnnotation("Отличная игра номер 2"); + game2.setPicture(null); + game2.setPlayerAge("16"); + game2.setPlayersMin(2); + game2.setPlayersMax(4); + game2.setTimeToPlayMin(30); + game2.setTimeToPlayMax(120); + game2.setYearOfRelease(OffsetDateTime.parse(instantExpected)); + + games = new ArrayList<>(); + games.add(game); + games.add(game2); + + gameProjection = new GamePOJO(game, 8.0); + gameProjectionList = new ArrayList<>(); + gameProjectionList.add(gameProjection); + + Designer designer = new Designer(); + designer.setId(1); + designer.setName("Designer number one"); + + Designer designer2 = new Designer(); + designer2.setId(2); + designer2.setName("Designer number two"); + + List designers = new ArrayList<>(); + designers.add(designer.getName()); + designers.add(designer2.getName()); + + gameDataDTO = new GameDataDTO(gameMapper.gameToGameDTO(game), 8.4, designers); + designers.remove(1); + GameDataDTO gameDataDTO1 = new GameDataDTO(gameMapper.gameToGameDTO(game), 7.9, designers); + + gamesDataDTO = new ArrayList<>(); + gamesDataDTO.add(gameDataDTO); + gamesDataDTO.add(gameDataDTO1); + + gamesFilterByTitleProjectionList = new ArrayList<>(); + gamesFilterByTitleProjectionList.add(new GameTitlePOJO("some title", 2)); + gamesFilterByTitleProjectionList.add(new GameTitlePOJO("some title 2", 3)); + + filterGamesDTOList = new ArrayList<>(); + filterGamesDTOList.add(new FilterGamesDTO(2, "some title")); + filterGamesDTOList.add(new FilterGamesDTO(3, "some title 2")); + + multipartFile = new MockMultipartFile( + "picture", + "hello.jpg", + MediaType.IMAGE_JPEG_VALUE, + "0x36".getBytes() + ); + } + + @Test + public void getGamesShouldReturnOk() throws Exception { + + when(gameService.getGames()).thenReturn(gamesDataDTO); + var mvcRes = this.mockMvc.perform(MockMvcRequestBuilders.get(Gateway)).andDo(print()).andExpect(status().isOk()).andReturn(); + var res = objectMapper.readValue(mvcRes.getResponse().getContentAsByteArray(), GameDataDTO[].class); + verify(gameService).getGames(); + Assertions.assertEquals(res.length, 2); + + } + + @Test + public void getGamesShouldReturnOk_BlankList() throws Exception { + + when(gameService.getGames()).thenReturn(new ArrayList<>()); + var mvcRes = this.mockMvc.perform(MockMvcRequestBuilders.get(Gateway)).andDo(print()).andExpect(status().isOk()).andReturn(); + var res = objectMapper.readValue(mvcRes.getResponse().getContentAsByteArray(), GameDataDTO[].class); + verify(gameService).getGames(); + Assertions.assertEquals(res.length, 0); + } + + @Test + public void getGameByIdShouldReturnOk() throws Exception { + + when(gameService.getGameById(1)).thenReturn(gameDataDTO); + var mvcRes = this.mockMvc.perform(MockMvcRequestBuilders.get(Gateway + "/1")).andDo(print()).andExpect(status().isOk()).andReturn(); + var res = objectMapper.readValue(mvcRes.getResponse().getContentAsByteArray(), GameDataDTO.class); + verify(gameService).getGameById(1); + Assertions.assertEquals(res.getGame().id(), gameDataDTO.getGame().id()); + } + + @Test + public void getGameByIdShouldReturnNotFound() throws Exception { + when(gameService.getGameById(-1)).thenThrow(new NoRecordFoundException()); + this.mockMvc.perform(MockMvcRequestBuilders.get(Gateway + "/-1")).andDo(print()).andExpect(status().isNotFound()); + Assertions.assertThrows(NoRecordFoundException.class, () -> gameService.getGameById(-1)); + } + + @Test + public void getGamesByTitleShouldReturnOk() throws Exception { + + when(gameService.getGameByTitle("so")).thenReturn(filterGamesDTOList); + var mvcRes = this.mockMvc.perform(MockMvcRequestBuilders.get(Gateway + "/get-games-by-filter/so")).andDo(print()).andExpect(status().isOk()).andReturn(); + var res = objectMapper.readValue(mvcRes.getResponse().getContentAsByteArray(), FilterGamesDTO[].class); + verify(gameService).getGameByTitle("so"); + Assertions.assertEquals(gamesFilterByTitleProjectionList.size(), res.length); + } + + @Test + public void getGamesByTitleShouldReturnOk_BlankArray() throws Exception { + when(gameService.getGameByTitle("title not exist")).thenReturn(new ArrayList<>()); + var mvcRes = this.mockMvc.perform(MockMvcRequestBuilders.get(Gateway + "/get-games-by-filter/title not exist")).andDo(print()).andExpect(status().isOk()).andReturn(); + var res = objectMapper.readValue(mvcRes.getResponse().getContentAsByteArray(), FilterGamesDTO[].class); + verify(gameService).getGameByTitle("title not exist"); + Assertions.assertEquals(0, res.length); + } + + @Test + @WithMockUser(roles = "MODERATOR") + public void addGameShouldReturnOk() throws Exception { + game.setId(null); + doNothing().when(gameService).checkExistence(game); + when(gameService.save(game)).thenReturn(gameDataDTO); + this.mockMvc.perform(MockMvcRequestBuilders.post(Gateway + "/").contentType(MediaType.APPLICATION_JSON) + .accept(MediaType.APPLICATION_JSON) + .content(objectMapper.writeValueAsString(game))).andExpect(status().isOk()); + verify(gameService).checkExistence(refEq(game)); + verify(gameService).save(refEq(game)); + game.setId(1); + } + + @Test + @WithMockUser(roles = "MODERATOR") + public void addGameShouldReturnBadRequest() throws Exception { + doThrow(new BadRequestException()).when(gameService).checkExistence(any(Game.class)); + this.mockMvc.perform(MockMvcRequestBuilders.post(Gateway + "/").contentType(MediaType.APPLICATION_JSON) + .accept(MediaType.APPLICATION_JSON) + .content(objectMapper.writeValueAsString(game))).andExpect(status().isBadRequest()); + Assertions.assertThrows(BadRequestException.class, () -> gameService.checkExistence(game)); + } + + @Test + @WithMockUser(roles = "MODERATOR") + public void addGameShouldReturnBadRequest_BadModel() throws Exception { + doNothing().when(gameService).checkExistence(any(Game.class)); + when(gameService.save(any(Game.class))).thenThrow(new BadRequestException("Bad model")); + this.mockMvc.perform(MockMvcRequestBuilders.post(Gateway + "/").contentType(MediaType.APPLICATION_JSON) + .accept(MediaType.APPLICATION_JSON) + .content(objectMapper.writeValueAsString(game))).andExpect(status().isBadRequest()); + verify(gameService).checkExistence(any(Game.class)); + Assertions.assertThrows(BadRequestException.class, () -> gameService.save(game)); + } + + @Test + @WithMockUser(roles = "USER") + public void addGameShouldReturnForbidden() throws Exception { + this.mockMvc.perform(MockMvcRequestBuilders.post(Gateway + "/").contentType(MediaType.APPLICATION_JSON) + .accept(MediaType.APPLICATION_JSON) + .content(objectMapper.writeValueAsString(game))).andExpect(status().isForbidden()); + } + + @Test + public void addGameShouldReturnUnauthorized() throws Exception { + this.mockMvc.perform(MockMvcRequestBuilders.post(Gateway + "/").contentType(MediaType.APPLICATION_JSON) + .accept(MediaType.APPLICATION_JSON) + .content(objectMapper.writeValueAsString(game))).andExpect(status().isUnauthorized()); + } + + @Test + @WithMockUser(roles = "USER") + public void uploadImageShouldReturnIsOk() throws Exception { + when(gameService.uploadImage(1, multipartFile)).thenReturn(gameDataDTO); + MockMultipartHttpServletRequestBuilder multipartRequest = + MockMvcRequestBuilders.multipart(Gateway + "/upload-image/1"); + mockMvc.perform(multipartRequest.file(multipartFile)) + .andExpect(status().isOk()); + verify(gameService).uploadImage(1, multipartFile); + } + + @Test + @WithMockUser(roles = "USER") + public void uploadImageShouldReturnNotFound() throws Exception { + when(gameService.uploadImage(-1, multipartFile)).thenThrow(new NoRecordFoundException("Game does not exist with id ")); + + MockMultipartHttpServletRequestBuilder multipartRequest = + MockMvcRequestBuilders.multipart(Gateway + "/upload-image/-1"); + mockMvc.perform(multipartRequest.file(multipartFile)) + .andExpect(status().isNotFound()); + Assertions.assertThrows(NoRecordFoundException.class, () -> gameService.uploadImage(-1, multipartFile)); + } + + @Test + @WithMockUser(roles = "USER") + public void uploadImageShouldReturnBadRequest() throws Exception { + MockMultipartFile multipartFile1 = new MockMultipartFile( + "picture", + "hello.txt", + MediaType.TEXT_PLAIN_VALUE, + "0x36".getBytes() + ); + when(gameService.uploadImage(1, multipartFile1)).thenThrow(new BadRequestException("File has uncorrected format")); + + MockMultipartHttpServletRequestBuilder multipartRequest = + MockMvcRequestBuilders.multipart(Gateway + "/upload-image/1"); + mockMvc.perform(multipartRequest.file(multipartFile1)) + .andExpect(status().isBadRequest()); + + Assertions.assertThrows(BadRequestException.class, () -> gameService.uploadImage(1, multipartFile1)); + } + + @Test + public void uploadImageShouldReturnUnauthorized() throws Exception { + MockMultipartHttpServletRequestBuilder multipartRequest = + MockMvcRequestBuilders.multipart(Gateway + "/upload-image/-1"); + mockMvc.perform(multipartRequest.file(multipartFile)) + .andExpect(status().isUnauthorized()); + } + + @Test + @WithMockUser(roles = "MODERATOR") + public void updateGameShouldReturnOk() throws Exception { + when(gameService.save(game)).thenReturn(gameDataDTO); + this.mockMvc.perform(MockMvcRequestBuilders.put(Gateway + "/").contentType(MediaType.APPLICATION_JSON) + .accept(MediaType.APPLICATION_JSON) + .content(objectMapper.writeValueAsString(game))).andExpect(status().isOk()); + verify(gameService).save(refEq(game)); + + } + + @Test + @WithMockUser(roles = "MODERATOR") + public void updateGameShouldReturnBadRequest() throws Exception { + game.setId(null); + when(gameService.save(any(Game.class))).thenThrow(new BadRequestException("Game with id " + game.getId() + " doesn't exist")); + this.mockMvc.perform(MockMvcRequestBuilders.put(Gateway + "/").contentType(MediaType.APPLICATION_JSON) + .accept(MediaType.APPLICATION_JSON) + .content(objectMapper.writeValueAsString(game))).andExpect(status().isBadRequest()); + Assertions.assertThrows(BadRequestException.class, () -> gameService.save(game)); + game.setId(1); + } + + @Test + @WithMockUser(roles = "MODERATOR") + public void updateGameShouldReturnBadRequest_BadModel() throws Exception { + when(gameService.save(any(Game.class))).thenThrow(new BadRequestException("Bad model")); + this.mockMvc.perform(MockMvcRequestBuilders.put(Gateway + "/").contentType(MediaType.APPLICATION_JSON) + .accept(MediaType.APPLICATION_JSON) + .content(objectMapper.writeValueAsString(game))).andExpect(status().isBadRequest()); + Assertions.assertThrows(BadRequestException.class, () -> gameService.save(game)); + } + + @Test + @WithMockUser(roles = "USER") + public void updateGameShouldReturnForbidden() throws Exception { + this.mockMvc.perform(MockMvcRequestBuilders.put(Gateway + "/").contentType(MediaType.APPLICATION_JSON) + .accept(MediaType.APPLICATION_JSON) + .content(objectMapper.writeValueAsString(game))).andExpect(status().isForbidden()); + } + + @Test + public void updateGameShouldReturnUnauthorized() throws Exception { + this.mockMvc.perform(MockMvcRequestBuilders.put(Gateway + "/").contentType(MediaType.APPLICATION_JSON) + .accept(MediaType.APPLICATION_JSON) + .content(objectMapper.writeValueAsString(game))).andExpect(status().isUnauthorized()); + } + + @Test + @WithMockUser(roles = "MODERATOR") + public void removeGameFromSiteShouldReturnIsOk() throws Exception { + doNothing().when(gameService).delete(any(Game.class)); + + this.mockMvc.perform(MockMvcRequestBuilders.delete(Gateway + "/").contentType(MediaType.APPLICATION_JSON) + .accept(MediaType.APPLICATION_JSON) + .content(objectMapper.writeValueAsString(game))).andExpect(status().isOk()); + + verify(gameService).delete(any(Game.class)); + } + + @Test + @WithMockUser(roles = "MODERATOR") + public void removeGameFromSiteShouldReturnNotFound() throws Exception { + doThrow(new NoRecordFoundException("Game with id does not exist")).when(gameService).delete(any(Game.class)); + this.mockMvc.perform(MockMvcRequestBuilders.delete(Gateway + "/").contentType(MediaType.APPLICATION_JSON) + .accept(MediaType.APPLICATION_JSON) + .content(objectMapper.writeValueAsString(game))).andExpect(status().isNotFound()); + Assertions.assertThrows(NoRecordFoundException.class, () -> gameService.delete(game)); + } + + @Test + @WithMockUser(roles = "USER") + public void removeGameFromSiteShouldReturnForbidden() throws Exception { + this.mockMvc.perform(MockMvcRequestBuilders.delete(Gateway + "/").contentType(MediaType.APPLICATION_JSON) + .accept(MediaType.APPLICATION_JSON) + .content(objectMapper.writeValueAsString(game))).andExpect(status().isForbidden()); + } + + @Test + public void removeGameFromSiteShouldReturnIsUnauthorized() throws Exception { + this.mockMvc.perform(MockMvcRequestBuilders.delete(Gateway + "/").contentType(MediaType.APPLICATION_JSON) + .accept(MediaType.APPLICATION_JSON) + .content(objectMapper.writeValueAsString(game))).andExpect(status().isUnauthorized()); + } + + @Test + public void getUserCollectionShouldReturnOk() throws Exception { + when(gameService.getUserCollection(1)).thenReturn(gamesDataDTO); + var mvcRes = this.mockMvc.perform(MockMvcRequestBuilders.get(Gateway + "/1/games")).andDo(print()).andExpect(status().isOk()).andReturn(); + var res = objectMapper.readValue(mvcRes.getResponse().getContentAsByteArray(), GameDataDTO[].class); + verify(gameService).getUserCollection(1); + Assertions.assertEquals(res.length, gamesDataDTO.size()); + + } + + @Test + public void getUserCollectionShouldReturnNotFound() throws Exception { + when(gameService.getUserCollection(-1)).thenThrow(new NoRecordFoundException("User with this id not found")); + this.mockMvc.perform(MockMvcRequestBuilders.get(Gateway + "/-1/games")).andDo(print()).andExpect(status().isNotFound()); + Assertions.assertThrows(NoRecordFoundException.class, () ->gameService.getUserCollection(-1)); + } + + @Test + public void getUserCollectionShouldReturnOk_BlankList() throws Exception { + when(gameService.getUserCollection(1)).thenReturn(new ArrayList<>()); + var mvcRes = this.mockMvc.perform(MockMvcRequestBuilders.get(Gateway + "/1/games")).andDo(print()).andExpect(status().isOk()).andReturn(); + var res = objectMapper.readValue(mvcRes.getResponse().getContentAsByteArray(), GameDataDTO[].class); + verify(gameService).getUserCollection(1); + Assertions.assertEquals(res.length, 0); + } + +} + + +/* +@ExtendWith(MockitoExtension.class) +@SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.MOCK, classes = SpringSecurityWebTestConfig.class) +@AutoConfigureMockMvc +@TestMethodOrder(MethodOrderer.OrderAnnotation.class) +@TestInstance(TestInstance.Lifecycle.PER_CLASS) +public class GameControllerTests { + + @Autowired + private MockMvc mockMvc; + + @Autowired + private WebApplicationContext webApplicationContext; + + private final String Gateway = "/games"; + + ObjectMapper objectMapper; + + @Autowired + GameMapper gameMapper; + + @MockBean + private GameService gameService; + + @MockBean + private GameRepository gameRepository; + + @MockBean + private DesignerRepository designerRepository; + + @MockBean + private ExpansionRepository expansionRepository; + + @MockBean + private SameGameRepository sameGameRepository; + + @MockBean + private UserRepository userRepository; + + @MockBean + private GameByDesignerRepository gameByDesignerRepository; + + private Game game; + private Game game2; + private List games; + private GameProjection gameProjection; + private List gameProjectionList; + private GameDataDTO gameDataDTO; + private List gamesDataDTO; + private Designer designer; + private List designersProjectionList; + private DesignersProjection designersProjection; + private DesignerDTO designerDTO; + private List gamesFilterByTitleProjectionList; + private List filterGamesDTOList; + private MockMultipartFile multipartFile; + private Expansion expansion; + private List usersGameRatingProjectionList; + private User userAdmin; + private User userModerator; + private User user; + private List ratingGameByUserDTOList; + + private SameGame sameGame; + private GameByDesigner gameByDesigner; + + @BeforeAll + public void setup() { + + objectMapper = new ObjectMapper(); + objectMapper.findAndRegisterModules(); + multipartFile = new MockMultipartFile( + "picture", + "hello.jpg", + MediaType.IMAGE_JPEG_VALUE, + "0x36".getBytes() + ); + + String instantExpected = "2014-12-22T10:15:30Z"; + + game = new Game(); + game.setId(1); + game.setTitle(" Игра номер 1"); + game.setDescription("Отличная игра войнушка номер 1"); + game.setAnnotation("Отличная игра номер 1"); + game.setPicture(null); + game.setPlayerAge("14"); + game.setPlayersMin(3); + game.setPlayersMax(5); + game.setTimeToPlayMin(120); + game.setTimeToPlayMax(360); + game.setYearOfRelease(OffsetDateTime.parse(instantExpected)); + + + game2 = new Game(); + game2.setId(1); + game2.setTitle(" Игра номер 2"); + game2.setDescription("Отличная игра войнушка номер 2"); + game2.setAnnotation("Отличная игра номер 2"); + game2.setPicture(null); + game2.setPlayerAge("16"); + game2.setPlayersMin(2); + game2.setPlayersMax(4); + game2.setTimeToPlayMin(30); + game2.setTimeToPlayMax(120); + game2.setYearOfRelease(OffsetDateTime.parse(instantExpected)); + + games = new ArrayList<>(); + games.add(game); + games.add(game2); + + expansion = new Expansion(); + expansion.setId(1); + expansion.setParentGame(game); + expansion.setDaughterGame(game2); + + sameGame = new SameGame(); + sameGame.setId(1); + sameGame.setSourceGame(game); + sameGame.setReferenceGame(game2); + + gameProjection = new GamePOJO(game, 8.0); + gameProjectionList = new ArrayList<>(); + gameProjectionList.add(gameProjection); + + designer = new Designer(); + designer.setId(1); + designer.setName("Designer number one"); + + Designer designer2 = new Designer(); + designer2.setId(2); + designer2.setName("Designer number two"); + + List designers = new ArrayList<>(); + designers.add(designer.getName()); + designers.add(designer2.getName()); + + designersProjectionList = new ArrayList<>(); + designersProjectionList.add(new DesignerPOJO(designer.getName())); + designersProjectionList.add(new DesignerPOJO(designer2.getName())); + + gameDataDTO = new GameDataDTO(gameMapper.gameToGameDTO(game), 8.4, designers); + designers.remove(1); + GameDataDTO gameDataDTO1 = new GameDataDTO(gameMapper.gameToGameDTO(game), 7.9, designers); + + gamesDataDTO = new ArrayList<>(); + gamesDataDTO.add(gameDataDTO); + gamesDataDTO.add(gameDataDTO1); + + gamesFilterByTitleProjectionList = new ArrayList<>(); + gamesFilterByTitleProjectionList.add(new GameTitlePOJO("some title", 2)); + gamesFilterByTitleProjectionList.add(new GameTitlePOJO("some title 2", 3)); + + filterGamesDTOList = new ArrayList<>(); + filterGamesDTOList.add(new FilterGamesDTO(2, "some title")); + filterGamesDTOList.add(new FilterGamesDTO(3, "some title 2")); + + + userAdmin = new User(); + userAdmin.setId(11); + userAdmin.setName("Alice"); + userAdmin.setPassword("pswd"); + userAdmin.setRole("ADMIN"); + userAdmin.setMail("alicealisson@ggogle.com"); + userAdmin.setRating(1.0); + userAdmin.setRegistrationDate(OffsetDateTime.now()); + + userModerator = new User(); + userModerator.setId(14); + userModerator.setName("Sam"); + userModerator.setPassword("pswdsam"); + userModerator.setRole("MODERATOR"); + userModerator.setMail("samwinchester@ggogle.com"); + userModerator.setRating(1.0); + userModerator.setRegistrationDate(OffsetDateTime.now()); + + user = new User(); + user.setId(34); + user.setName("Bobby"); + user.setPassword("1234qwer"); + user.setRole("USER"); + user.setMail("bobby@ggogle.com"); + user.setRating(1.0); + user.setRegistrationDate(OffsetDateTime.now()); + + usersGameRatingProjectionList = new ArrayList<>(); + usersGameRatingProjectionList.add(new UsersGameRatingProjectionPOJO(user, 8.0)); + usersGameRatingProjectionList.add(new UsersGameRatingProjectionPOJO(userAdmin, 10.0)); + usersGameRatingProjectionList.add(new UsersGameRatingProjectionPOJO(userModerator, 3.0)); + + ratingGameByUserDTOList = new ArrayList<>(); + ratingGameByUserDTOList.add(new RatingGameByUserDTO(user.getId(), 8.0)); + ratingGameByUserDTOList.add(new RatingGameByUserDTO(userModerator.getId(), 10.0)); + ratingGameByUserDTOList.add(new RatingGameByUserDTO(userAdmin.getId(), 3.0)); + + gameByDesigner = new GameByDesigner(); + gameByDesigner.setId(1); + gameByDesigner.setGame(game); + gameByDesigner.setDesigner(designer); + } + + @Test + public void getGamesShouldReturnOk() throws Exception { + + when(gameRepository.findGames()).thenReturn(gameProjectionList); + when(gameService.projectionsToGameDTO(gameProjectionList)).thenReturn(gamesDataDTO); + + var mvcRes = this.mockMvc.perform(MockMvcRequestBuilders.get(Gateway)).andDo(print()).andExpect(status().isOk()).andReturn(); + + var res = objectMapper.readValue(mvcRes.getResponse().getContentAsByteArray(), GameDataDTO[].class); + + verify(gameRepository).findGames(); + verify(gameService).projectionsToGameDTO(gameProjectionList); + + Assertions.assertEquals(res.length, 2); + + } + + @Test + public void getGamesShouldReturnOk_BlankList() throws Exception { + + when(gameRepository.findGames()).thenReturn(new ArrayList<>()); + when(gameService.projectionsToGameDTO(new ArrayList<>())).thenReturn(new ArrayList<>()); + + var mvcRes = this.mockMvc.perform(MockMvcRequestBuilders.get(Gateway)).andDo(print()).andExpect(status().isOk()).andReturn(); + + var res = objectMapper.readValue(mvcRes.getResponse().getContentAsByteArray(), GameDataDTO[].class); + + verify(gameRepository).findGames(); + verify(gameService).projectionsToGameDTO(new ArrayList<>()); + + Assertions.assertEquals(res.length, 0); + + } + + @Test + public void getGameByCriteriaShouldReturnOk() throws Exception { + when(gameRepository.findGameWithRating(1)).thenReturn(gameProjection); + when(designerRepository.findDesignersUsingGame(1)).thenReturn(designersProjectionList); + when(gameService.projectionsToGameDTO(gameProjection, designersProjectionList)).thenReturn(gameDataDTO); + + var mvcRes = this.mockMvc.perform(MockMvcRequestBuilders.get(Gateway + "/get-game/1")).andDo(print()).andExpect(status().isOk()).andReturn(); + + var res = objectMapper.readValue(mvcRes.getResponse().getContentAsByteArray(), GameDataDTO.class); + + verify(gameRepository).findGameWithRating(1); + verify(designerRepository).findDesignersUsingGame(1); + verify(gameService).projectionsToGameDTO(gameProjection, designersProjectionList); + + Assertions.assertEquals(res.getGame().id(), gameDataDTO.getGame().id()); + } + + @Test + public void getGameByCriteriaShouldReturnNotFound() throws Exception { + when(gameRepository.findGameWithRating(-1)).thenReturn(null); + when(designerRepository.findDesignersUsingGame(-1)).thenReturn(null); + when(gameService.projectionsToGameDTO(null, null)).thenReturn(null); + + this.mockMvc.perform(MockMvcRequestBuilders.get(Gateway + "/get-game/-1")).andDo(print()).andExpect(status().isNotFound()); + + verify(gameRepository).findGameWithRating(-1); + verify(designerRepository).findDesignersUsingGame(-1); + verify(gameService).projectionsToGameDTO(null, null); + } + + @Test + public void getGamesByTitleShouldReturnOk() throws Exception { + when(gameRepository.findGamesUsingTitle("title")).thenReturn(gamesFilterByTitleProjectionList); + when(gameService.getTitlesFromProjections(gamesFilterByTitleProjectionList)).thenReturn(filterGamesDTOList); + + var mvcRes = this.mockMvc.perform(MockMvcRequestBuilders.get(Gateway + "/get-games-by-filter/title")).andDo(print()).andExpect(status().isOk()).andReturn(); + var res = objectMapper.readValue(mvcRes.getResponse().getContentAsByteArray(), FilterGamesDTO[].class); + + verify(gameRepository).findGamesUsingTitle("title"); + verify(gameService).getTitlesFromProjections(gamesFilterByTitleProjectionList); + + Assertions.assertEquals(gamesFilterByTitleProjectionList.size(), res.length); + } + + @Test + public void getGamesByTitleShouldReturnOk_BlankArray() throws Exception { + when(gameRepository.findGamesUsingTitle("title not exist")).thenReturn(new ArrayList<>()); + when(gameService.getTitlesFromProjections(new ArrayList<>())).thenReturn(new ArrayList<>()); + + var mvcRes = this.mockMvc.perform(MockMvcRequestBuilders.get(Gateway + "/get-games-by-filter/title not exist")).andDo(print()).andExpect(status().isOk()).andReturn(); + var res = objectMapper.readValue(mvcRes.getResponse().getContentAsByteArray(), FilterGamesDTO[].class); + + verify(gameRepository).findGamesUsingTitle("title not exist"); + verify(gameService).getTitlesFromProjections(new ArrayList<>()); + + Assertions.assertEquals(0, res.length); + } + + @Test + @WithMockUser(roles = "MODERATOR") + public void addGameShouldReturnOk() throws Exception { + game.setId(null); + when(gameRepository.save(game)).thenReturn(game); + when(gameService.entityToGameDTO(game)).thenReturn(gameDataDTO); + + this.mockMvc.perform(MockMvcRequestBuilders.post(Gateway + "/add").contentType(MediaType.APPLICATION_JSON) + .accept(MediaType.APPLICATION_JSON) + .content(objectMapper.writeValueAsString(game))).andExpect(status().isOk()); + + verify(gameRepository).save(refEq(game)); + verify(gameService).entityToGameDTO(refEq(game)); + game.setId(1); + } + + @Test + @WithMockUser(roles = "MODERATOR") + public void addGameShouldReturnBadRequest() throws Exception { + this.mockMvc.perform(MockMvcRequestBuilders.post(Gateway + "/add").contentType(MediaType.APPLICATION_JSON) + .accept(MediaType.APPLICATION_JSON) + .content(objectMapper.writeValueAsString(game))).andExpect(status().isBadRequest()); + } + + @Test + @WithMockUser(roles = "MODERATOR") + public void addGameShouldReturnBadRequest_BadModel() throws Exception { + game.setTimeToPlayMax(null); + this.mockMvc.perform(MockMvcRequestBuilders.post(Gateway + "/add").contentType(MediaType.APPLICATION_JSON) + .accept(MediaType.APPLICATION_JSON) + .content(objectMapper.writeValueAsString(game))).andExpect(status().isBadRequest()); + game.setTimeToPlayMax(360); + } + + @Test + @WithMockUser(roles = "USER") + public void addGameShouldReturnForbidden() throws Exception { + this.mockMvc.perform(MockMvcRequestBuilders.post(Gateway + "/add").contentType(MediaType.APPLICATION_JSON) + .accept(MediaType.APPLICATION_JSON) + .content(objectMapper.writeValueAsString(game))).andExpect(status().isForbidden()); + } + + @Test + public void addGameShouldReturnUnauthorized() throws Exception { + this.mockMvc.perform(MockMvcRequestBuilders.post(Gateway + "/add").contentType(MediaType.APPLICATION_JSON) + .accept(MediaType.APPLICATION_JSON) + .content(objectMapper.writeValueAsString(game))).andExpect(status().isUnauthorized()); + } + + @Test + @WithMockUser(roles = "USER") + public void uploadImageShouldReturnIsOk() throws Exception { + when(gameRepository.findGameById(1)).thenReturn(game); + when(gameRepository.save(game)).thenReturn(null); + when(gameRepository.findGameWithRating(1)).thenReturn(gameProjection); + when(designerRepository.findDesignersUsingGame(1)).thenReturn(designersProjectionList); + when(gameService.projectionsToGameDTO(gameProjection, designersProjectionList)).thenReturn(gameDataDTO); + + MockMultipartHttpServletRequestBuilder multipartRequest = + MockMvcRequestBuilders.multipart(Gateway + "/upload-image/1"); + mockMvc.perform(multipartRequest.file(multipartFile)) + .andExpect(status().isOk()); + + verify(gameRepository).findGameById(1); + verify(gameRepository).save(game); + verify(gameRepository).findGameWithRating(1); + verify(designerRepository).findDesignersUsingGame(1); + verify(gameService).projectionsToGameDTO(gameProjection, designersProjectionList); + } + + @Test + @WithMockUser(roles = "USER") + public void uploadImageShouldReturnNotFound() throws Exception { + when(gameRepository.findGameById(-1)).thenReturn(null); + + MockMultipartHttpServletRequestBuilder multipartRequest = + MockMvcRequestBuilders.multipart(Gateway + "/upload-image/-1"); + mockMvc.perform(multipartRequest.file(multipartFile)) + .andExpect(status().isNotFound()); + + verify(gameRepository).findGameById(-1); + } + + @Test + @WithMockUser(roles = "USER") + public void uploadImageShouldReturnBadRequest() throws Exception { + multipartFile = new MockMultipartFile( + "not-picture", + "hello.jpg", + MediaType.IMAGE_JPEG_VALUE, + "0x36".getBytes() + ); + MockMultipartHttpServletRequestBuilder multipartRequest = + MockMvcRequestBuilders.multipart(Gateway + "/upload-image/-1"); + mockMvc.perform(multipartRequest.file(multipartFile)) + .andExpect(status().isBadRequest()); + + multipartFile = new MockMultipartFile( + "picture", + "hello.jpg", + MediaType.IMAGE_JPEG_VALUE, + "0x36".getBytes() + ); + } + + @Test + public void uploadImageShouldReturnUnauthorized() throws Exception { + MockMultipartHttpServletRequestBuilder multipartRequest = + MockMvcRequestBuilders.multipart(Gateway + "/upload-image/-1"); + mockMvc.perform(multipartRequest.file(multipartFile)) + .andExpect(status().isUnauthorized()); + } + + @Test + @WithMockUser(roles = "MODERATOR") + public void updateGameShouldReturnIsOk() throws Exception { + when(gameRepository.save(game)).thenReturn(null); + when(gameService.entityToGameDTO(game)).thenReturn(gameDataDTO); + + this.mockMvc.perform(MockMvcRequestBuilders.put(Gateway + "/update").contentType(MediaType.APPLICATION_JSON) + .accept(MediaType.APPLICATION_JSON) + .content(objectMapper.writeValueAsString(game))).andExpect(status().isOk()); + + verify(gameRepository).save(refEq(game)); + verify(gameService).entityToGameDTO(refEq(game)); + } + + @Test + @WithMockUser(roles = "MODERATOR") + public void updateGameShouldReturnIsBadRequest() throws Exception { + game.setTimeToPlayMax(null); + + this.mockMvc.perform(MockMvcRequestBuilders.put(Gateway + "/update").contentType(MediaType.APPLICATION_JSON) + .accept(MediaType.APPLICATION_JSON) + .content(objectMapper.writeValueAsString(game))).andExpect(status().isBadRequest()); + + game.setTimeToPlayMax(360); + } + + @Test + @WithMockUser(roles = "USER") + public void updateGameShouldReturnIsForbidden() throws Exception { + + this.mockMvc.perform(MockMvcRequestBuilders.put(Gateway + "/update").contentType(MediaType.APPLICATION_JSON) + .accept(MediaType.APPLICATION_JSON) + .content(objectMapper.writeValueAsString(game))).andExpect(status().isForbidden()); + + } + + @Test + public void updateGameShouldReturnIsUnauthorized() throws Exception { + + this.mockMvc.perform(MockMvcRequestBuilders.put(Gateway + "/update").contentType(MediaType.APPLICATION_JSON) + .accept(MediaType.APPLICATION_JSON) + .content(objectMapper.writeValueAsString(game))).andExpect(status().isUnauthorized()); + + } + + @Test + @WithMockUser(roles = "MODERATOR") + public void removeGameFromSiteShouldReturnIsOk() throws Exception { + doNothing().when(gameRepository).delete(game); + + this.mockMvc.perform(MockMvcRequestBuilders.delete(Gateway + "/remove").contentType(MediaType.APPLICATION_JSON) + .accept(MediaType.APPLICATION_JSON) + .content(objectMapper.writeValueAsString(game))).andExpect(status().isOk()); + + verify(gameRepository).delete(refEq(game)); + } + + @Test + @WithMockUser(roles = "MODERATOR") + public void removeGameFromSiteShouldReturnNotFound() throws Exception { + game.setId(null); + + this.mockMvc.perform(MockMvcRequestBuilders.delete(Gateway + "/remove").contentType(MediaType.APPLICATION_JSON) + .accept(MediaType.APPLICATION_JSON) + .content(objectMapper.writeValueAsString(game))).andExpect(status().isNotFound()); + + game.setId(1); + } + + @Test + @WithMockUser(roles = "USER") + public void removeGameFromSiteShouldReturnNotForbidden() throws Exception { + this.mockMvc.perform(MockMvcRequestBuilders.delete(Gateway + "/remove").contentType(MediaType.APPLICATION_JSON) + .accept(MediaType.APPLICATION_JSON) + .content(objectMapper.writeValueAsString(game))).andExpect(status().isForbidden()); + } + + @Test + public void removeGameFromSiteShouldReturnIsUnauthorized() throws Exception { + this.mockMvc.perform(MockMvcRequestBuilders.delete(Gateway + "/remove").contentType(MediaType.APPLICATION_JSON) + .accept(MediaType.APPLICATION_JSON) + .content(objectMapper.writeValueAsString(game))).andExpect(status().isUnauthorized()); + } + + @Test + public void getExpansionsShouldReturnIsOk() throws Exception { + when(gameRepository.getExpansions(1)).thenReturn(games); + when(gameService.entitiesToGameDTO(games)).thenReturn(gamesDataDTO); + + var mvsRes = this.mockMvc.perform(MockMvcRequestBuilders.get(Gateway + "/expansions/1")).andExpect(status().isOk()).andReturn(); + var res = objectMapper.readValue(mvsRes.getResponse().getContentAsByteArray(), GameDataDTO[].class); + + verify(gameRepository).getExpansions(1); + verify(gameService).entitiesToGameDTO(games); + + Assertions.assertEquals(gamesDataDTO.size(), res.length); + } + + @Test + public void getExpansionsShouldReturnIsOk_BlankArray() throws Exception { + when(gameRepository.getExpansions(-1)).thenReturn(new ArrayList<>()); + when(gameService.entitiesToGameDTO(new ArrayList<>())).thenReturn(new ArrayList<>()); + + var mvsRes = this.mockMvc.perform(MockMvcRequestBuilders.get(Gateway + "/expansions/-1")).andExpect(status().isOk()).andReturn(); + var res = objectMapper.readValue(mvsRes.getResponse().getContentAsByteArray(), GameDataDTO[].class); + + verify(gameRepository).getExpansions(-1); + verify(gameService).entitiesToGameDTO(new ArrayList<>()); + + Assertions.assertEquals(0, res.length); + } + + @Test + public void getExpansionsShouldReturnIsNotFound() throws Exception { + this.mockMvc.perform(MockMvcRequestBuilders.get(Gateway + "/expansions/")).andExpect(status().isNotFound()); + } + + @Test + @WithMockUser(roles = "USER") + public void addExpansionShouldReturnIsOk() throws Exception { + when(gameRepository.findGameById(1)).thenReturn(game); + when(gameRepository.findGameById(2)).thenReturn(game2); + when(expansionRepository.save(any(Expansion.class))).thenReturn(expansion); + when(gameRepository.getExpansions(1)).thenReturn(games); + when(gameService.entitiesToGameDTO(games)).thenReturn(gamesDataDTO); + + var mvsRes = this.mockMvc.perform(MockMvcRequestBuilders.post(Gateway + "/add-expansion/1/2")).andExpect(status().isOk()).andReturn(); + var res = objectMapper.readValue(mvsRes.getResponse().getContentAsByteArray(), GameDataDTO[].class); + + verify(gameRepository).findGameById(1); + verify(gameRepository).findGameById(2); + verify(expansionRepository).save(any(Expansion.class)); + verify(gameRepository).getExpansions(1); + verify(gameService).entitiesToGameDTO(games); + + Assertions.assertEquals(gamesDataDTO.size(), res.length); + } + + @Test + @WithMockUser(roles = "USER") + public void addExpansionShouldReturnIsBadRequest_ParentGame() throws Exception { + when(gameRepository.findGameById(-1)).thenReturn(null); + when(gameRepository.findGameById(2)).thenReturn(game2); + + this.mockMvc.perform(MockMvcRequestBuilders.post(Gateway + "/add-expansion/-1/2")).andExpect(status().isBadRequest()); + + verify(gameRepository).findGameById(-1); + verify(gameRepository).findGameById(2); + } + + @Test + @WithMockUser(roles = "USER") + public void addExpansionShouldReturnIsBadRequest_DaughterGame() throws Exception { + when(gameRepository.findGameById(1)).thenReturn(game); + when(gameRepository.findGameById(-2)).thenReturn(null); + + this.mockMvc.perform(MockMvcRequestBuilders.post(Gateway + "/add-expansion/1/-2")).andExpect(status().isBadRequest()); + + verify(gameRepository).findGameById(1); + verify(gameRepository).findGameById(-2); + } + + @Test + @WithMockUser(roles = "USER") + public void addExpansionShouldReturnIsBadRequest_BothGame() throws Exception { + when(gameRepository.findGameById(-1)).thenReturn(null); + when(gameRepository.findGameById(-2)).thenReturn(null); + + this.mockMvc.perform(MockMvcRequestBuilders.post(Gateway + "/add-expansion/-1/-2")).andExpect(status().isBadRequest()); + + verify(gameRepository).findGameById(-1); + verify(gameRepository).findGameById(-2); + } + + @Test + public void addExpansionShouldReturnIsUnauthorized() throws Exception { + this.mockMvc.perform(MockMvcRequestBuilders.post(Gateway + "/add-expansion/1/2")).andExpect(status().isUnauthorized()).andReturn(); + } + + @Test + @WithMockUser(roles = "USER") + public void deleteExpansionShouldReturnIsOk() throws Exception { + when(expansionRepository.findExpansion_ByParentGameIdAndDaughterGameId(1, 2)).thenReturn(expansion); + doNothing().when(expansionRepository).delete(expansion); + when(gameRepository.getExpansions(1)).thenReturn(games); + when(gameService.entitiesToGameDTO(games)).thenReturn(gamesDataDTO); + + var mvcRes = this.mockMvc.perform(MockMvcRequestBuilders.delete(Gateway + "/delete-expansion/1/2")).andExpect(status().isOk()).andReturn(); + var res = objectMapper.readValue(mvcRes.getResponse().getContentAsByteArray(), GameDataDTO[].class); + + verify(expansionRepository).findExpansion_ByParentGameIdAndDaughterGameId(1, 2); + verify(expansionRepository).delete(expansion); + verify(gameRepository).getExpansions(1); + verify(gameService).entitiesToGameDTO(games); + + Assertions.assertEquals(gamesDataDTO.size(), res.length); + } + + @Test + @WithMockUser(roles = "USER") + public void deleteExpansionShouldReturnIsNotFound() throws Exception { + when(expansionRepository.findExpansion_ByParentGameIdAndDaughterGameId(-1, -2)).thenReturn(null); + + this.mockMvc.perform(MockMvcRequestBuilders.delete(Gateway + "/delete-expansion/-1/-2")).andExpect(status().isNotFound()); + + verify(expansionRepository).findExpansion_ByParentGameIdAndDaughterGameId(-1, -2); + } + + @Test + public void deleteExpansionShouldReturnIsUnauthorized() throws Exception { + this.mockMvc.perform(MockMvcRequestBuilders.delete(Gateway + "/delete-expansion/1/2")).andExpect(status().isUnauthorized()); + } + + @Test + public void getSimilarGamesShouldReturnIsOk() throws Exception { + when(gameRepository.getSimilarGames(1)).thenReturn(games); + when(gameService.entitiesToGameDTO(games)).thenReturn(gamesDataDTO); + + var mvcRes = this.mockMvc.perform(MockMvcRequestBuilders.get(Gateway + "/similar/1")).andExpect(status().isOk()).andReturn(); + var res = objectMapper.readValue(mvcRes.getResponse().getContentAsByteArray(), GameDataDTO[].class); + + verify(gameRepository).getSimilarGames(1); + verify(gameService).entitiesToGameDTO(games); + + Assertions.assertEquals(games.size(), res.length); + + } + + @Test + public void getSimilarGamesShouldReturnIsOk_BlankArray() throws Exception { + when(gameRepository.getSimilarGames(-1)).thenReturn(new ArrayList<>()); + when(gameService.entitiesToGameDTO(new ArrayList<>())).thenReturn(new ArrayList<>()); + + var mvcRes = this.mockMvc.perform(MockMvcRequestBuilders.get(Gateway + "/similar/-1")).andExpect(status().isOk()).andReturn(); + var res = objectMapper.readValue(mvcRes.getResponse().getContentAsByteArray(), GameDataDTO[].class); + + verify(gameRepository).getSimilarGames(-1); + verify(gameService).entitiesToGameDTO(new ArrayList<>()); + + Assertions.assertEquals(0, res.length); + } + + @Test + public void getSimilarGamesShouldReturnIsNotFound() throws Exception { + this.mockMvc.perform(MockMvcRequestBuilders.get(Gateway + "/similar/")).andExpect(status().isNotFound()).andReturn(); + } + + + @Test + @WithMockUser(roles = "USER") + public void addSimilarGameShouldReturnIsOk() throws Exception { + when(gameRepository.findGameById(1)).thenReturn(game); + when(gameRepository.findGameById(2)).thenReturn(game2); + when(sameGameRepository.save(any(SameGame.class))).thenReturn(sameGame); + when(gameRepository.getSimilarGames(1)).thenReturn(games); + when(gameService.entitiesToGameDTO(games)).thenReturn(gamesDataDTO); + + var mvsRes = this.mockMvc.perform(MockMvcRequestBuilders.post(Gateway + "/add-similar/1/2")).andExpect(status().isOk()).andReturn(); + var res = objectMapper.readValue(mvsRes.getResponse().getContentAsByteArray(), GameDataDTO[].class); + + verify(gameRepository).findGameById(1); + verify(gameRepository).findGameById(2); + verify(sameGameRepository).save(any(SameGame.class)); + verify(gameRepository).getSimilarGames(1); + verify(gameService).entitiesToGameDTO(games); + + Assertions.assertEquals(gamesDataDTO.size(), res.length); + } + + @Test + @WithMockUser(roles = "USER") + public void addSimilarGameShouldReturnIsBadRequest_ReferenceGame() throws Exception { + when(gameRepository.findGameById(-1)).thenReturn(null); + when(gameRepository.findGameById(2)).thenReturn(game2); + + this.mockMvc.perform(MockMvcRequestBuilders.post(Gateway + "/add-similar/-1/2")).andExpect(status().isBadRequest()); + + verify(gameRepository).findGameById(-1); + verify(gameRepository).findGameById(2); + } + + @Test + @WithMockUser(roles = "USER") + public void addSimilarShouldGameReturnIsBadRequest_SourceGame() throws Exception { + when(gameRepository.findGameById(1)).thenReturn(game); + when(gameRepository.findGameById(-2)).thenReturn(null); + + this.mockMvc.perform(MockMvcRequestBuilders.post(Gateway + "/add-similar/1/-2")).andExpect(status().isBadRequest()); + + verify(gameRepository).findGameById(1); + verify(gameRepository).findGameById(-2); + } + + @Test + @WithMockUser(roles = "USER") + public void addSimilarGameShouldReturnIsBadRequest_BothGame() throws Exception { + when(gameRepository.findGameById(-1)).thenReturn(null); + when(gameRepository.findGameById(-2)).thenReturn(null); + + this.mockMvc.perform(MockMvcRequestBuilders.post(Gateway + "/add-similar/-1/-2")).andExpect(status().isBadRequest()); + + verify(gameRepository).findGameById(-1); + verify(gameRepository).findGameById(-2); + } + + @Test + public void addSimilarGameShouldReturnIsUnauthorized() throws Exception { + this.mockMvc.perform(MockMvcRequestBuilders.post(Gateway + "/add-similar/1/2")).andExpect(status().isUnauthorized()); + } + + @Test + @WithMockUser(roles = "USER") + public void deleteSameGameShouldReturnIsOk() throws Exception { + when(sameGameRepository.findSameGame_ByReferenceGameIdAndSourceGameId(1, 2)).thenReturn(sameGame); + doNothing().when(sameGameRepository).delete(sameGame); + when(gameRepository.getSimilarGames(1)).thenReturn(games); + when(gameService.entitiesToGameDTO(games)).thenReturn(gamesDataDTO); + + var mvcRes = this.mockMvc.perform(MockMvcRequestBuilders.delete(Gateway + "/delete-similar/1/2")).andExpect(status().isOk()).andReturn(); + var res = objectMapper.readValue(mvcRes.getResponse().getContentAsByteArray(), GameDataDTO[].class); + + verify(sameGameRepository).findSameGame_ByReferenceGameIdAndSourceGameId(1, 2); + verify(sameGameRepository).delete(sameGame); + verify(gameRepository).getSimilarGames(1); + verify(gameService).entitiesToGameDTO(games); + + Assertions.assertEquals(gamesDataDTO.size(), res.length); + } + + @Test + @WithMockUser(roles = "USER") + public void deleteSameGameShouldReturnIsNotFound_ReferenceGame() throws Exception { + when(sameGameRepository.findSameGame_ByReferenceGameIdAndSourceGameId(-1, 2)).thenReturn(null); + + this.mockMvc.perform(MockMvcRequestBuilders.delete(Gateway + "/delete-similar/-1/2")).andExpect(status().isNotFound()); + + verify(sameGameRepository).findSameGame_ByReferenceGameIdAndSourceGameId(-1, 2); + + } + + @Test + @WithMockUser(roles = "USER") + public void deleteSameGameShouldReturnIsNotFound_SourceGame() throws Exception { + when(sameGameRepository.findSameGame_ByReferenceGameIdAndSourceGameId(1, -2)).thenReturn(null); + + this.mockMvc.perform(MockMvcRequestBuilders.delete(Gateway + "/delete-similar/1/-2")).andExpect(status().isNotFound()); + + verify(sameGameRepository).findSameGame_ByReferenceGameIdAndSourceGameId(1, -2); + + } + + @Test + @WithMockUser(roles = "USER") + public void deleteSameGameShouldReturnIsNotFound_BothGame() throws Exception { + when(sameGameRepository.findSameGame_ByReferenceGameIdAndSourceGameId(-1, -2)).thenReturn(null); + + this.mockMvc.perform(MockMvcRequestBuilders.delete(Gateway + "/delete-similar/-1/-2")).andExpect(status().isNotFound()); + + verify(sameGameRepository).findSameGame_ByReferenceGameIdAndSourceGameId(-1, -2); + + } + + @Test + public void deleteSameGameShouldReturnIsUnauthorized() throws Exception { + this.mockMvc.perform(MockMvcRequestBuilders.delete(Gateway + "/delete-similar/1/2")).andExpect(status().isUnauthorized()); + } + + @Test + public void getUsersRatingShouldReturnIsOk() throws Exception { + when(userRepository.findGameRatings(1)).thenReturn(usersGameRatingProjectionList); + when(gameService.usersGameRatingToDTO(usersGameRatingProjectionList)).thenReturn(ratingGameByUserDTOList); + + var mvcRes = this.mockMvc.perform(MockMvcRequestBuilders.get(Gateway + "/1/users-rating")).andExpect(status().isOk()).andReturn(); + var res = objectMapper.readValue(mvcRes.getResponse().getContentAsByteArray(), RatingGameByUserDTO[].class); + + verify(userRepository).findGameRatings(1); + verify(gameService).usersGameRatingToDTO(usersGameRatingProjectionList); + + Assertions.assertEquals(ratingGameByUserDTOList.size(), res.length); + } + + @Test + public void getUsersRatingShouldReturnIsOk_BlankArray() throws Exception { + when(userRepository.findGameRatings(1)).thenReturn(new ArrayList<>()); + when(gameService.usersGameRatingToDTO(new ArrayList<>())).thenReturn(new ArrayList<>()); + + var mvcRes = this.mockMvc.perform(MockMvcRequestBuilders.get(Gateway + "/1/users-rating")).andExpect(status().isOk()).andReturn(); + var res = objectMapper.readValue(mvcRes.getResponse().getContentAsByteArray(), RatingGameByUserDTO[].class); + + verify(userRepository).findGameRatings(1); + verify(gameService).usersGameRatingToDTO(new ArrayList<>()); + + Assertions.assertEquals(0, res.length); + } + + @Test + @WithMockUser(roles = "USER") + public void addDesignerToGameRatingShouldReturnIsOk() throws Exception { + when(gameRepository.findGameById(1)).thenReturn(game); + when(designerRepository.findDesignerById(1)).thenReturn(designer); + when(gameByDesignerRepository.save(any(GameByDesigner.class))).thenReturn(null); + when(gameRepository.findGameWithRating(1)).thenReturn(gameProjection); + when(designerRepository.findDesignersUsingGame(1)).thenReturn(designersProjectionList); + when(gameService.projectionsToGameDTO(gameProjection, designersProjectionList)).thenReturn(gameDataDTO); + + + var mvcRes = this.mockMvc.perform(MockMvcRequestBuilders.post(Gateway + "/1/set-designer/1")).andExpect(status().isOk()).andReturn(); + var res = objectMapper.readValue(mvcRes.getResponse().getContentAsByteArray(), GameDataDTO.class); + + verify(gameRepository).findGameById(1); + verify(designerRepository).findDesignerById(1); + verify(gameByDesignerRepository).save(any(GameByDesigner.class)); + verify(gameRepository).findGameWithRating(1); + verify(designerRepository).findDesignersUsingGame(1); + verify(gameService).projectionsToGameDTO(gameProjection, designersProjectionList); + + Assertions.assertEquals(gameDataDTO.getGame().id(), res.getGame().id()); + } + + @Test + @WithMockUser(roles = "USER") + public void addDesignerToGameRatingShouldReturnIsNotFound_Game() throws Exception { + when(gameRepository.findGameById(-1)).thenReturn(null); + when(designerRepository.findDesignerById(1)).thenReturn(designer); + + this.mockMvc.perform(MockMvcRequestBuilders.post(Gateway + "/-1/set-designer/1")).andExpect(status().isNotFound()); + + verify(gameRepository).findGameById(-1); + verify(designerRepository).findDesignerById(1); + + } + + @Test + @WithMockUser(roles = "USER") + public void addDesignerToGameRatingShouldReturnIsNotFound_Designer() throws Exception { + when(gameRepository.findGameById(1)).thenReturn(game); + when(designerRepository.findDesignerById(-1)).thenReturn(null); + + this.mockMvc.perform(MockMvcRequestBuilders.post(Gateway + "/1/set-designer/-1")).andExpect(status().isNotFound()); + + verify(gameRepository).findGameById(1); + verify(designerRepository).findDesignerById(-1); + + } + + @Test + @WithMockUser(roles = "USER") + public void addDesignerToGameRatingShouldReturnIsNotFound_Both() throws Exception { + when(gameRepository.findGameById(-1)).thenReturn(null); + when(designerRepository.findDesignerById(-1)).thenReturn(null); + + this.mockMvc.perform(MockMvcRequestBuilders.post(Gateway + "/-1/set-designer/-1")).andExpect(status().isNotFound()); + + verify(gameRepository).findGameById(-1); + verify(designerRepository).findDesignerById(-1); + + } + + @Test + public void addDesignerToGameRatingShouldReturnIsUnauthorized() throws Exception { + this.mockMvc.perform(MockMvcRequestBuilders.post(Gateway + "/-1/set-designer/-1")).andExpect(status().isUnauthorized()); + } + + @Test + @WithMockUser(roles = "USER") + public void deleteDesignerFromGameShouldReturnIsOk() throws Exception { + doNothing().when(gameByDesignerRepository).deleteById(1); + when(gameRepository.findGameWithRating(1)).thenReturn(gameProjection); + when(designerRepository.findDesignersUsingGame(1)).thenReturn(designersProjectionList); + when(gameService.projectionsToGameDTO(gameProjection, designersProjectionList)).thenReturn(gameDataDTO); + + var mvcRes = this.mockMvc.perform(MockMvcRequestBuilders.delete(Gateway + "/1/remove-designer/1")).andExpect(status().isOk()).andReturn(); + var res = objectMapper.readValue(mvcRes.getResponse().getContentAsByteArray(), GameDataDTO.class); + + verify(gameByDesignerRepository).deleteById(1); + verify(gameRepository).findGameWithRating(1); + verify(designerRepository).findDesignersUsingGame(1); + verify(gameService).projectionsToGameDTO(gameProjection, designersProjectionList); + + Assertions.assertEquals(gameDataDTO.getGame().id(), res.getGame().id()); + } + + @Test + public void deleteDesignerFromGameShouldReturnIsUnauthorized() throws Exception { + this.mockMvc.perform(MockMvcRequestBuilders.delete(Gateway + "/1/remove-designer/1")).andExpect(status().isUnauthorized()); + } + + + //todo: union beforeAll method? +} +*/ diff --git a/src/test/java/com/petproject/boardgamefun/controller/GameSellControllerTests.java b/src/test/java/com/petproject/boardgamefun/controller/GameSellControllerTests.java new file mode 100644 index 0000000..31cacfa --- /dev/null +++ b/src/test/java/com/petproject/boardgamefun/controller/GameSellControllerTests.java @@ -0,0 +1,243 @@ +package com.petproject.boardgamefun.controller; + +import com.fasterxml.jackson.databind.ObjectMapper; +import com.petproject.boardgamefun.SpringSecurityWebTestConfig; +import com.petproject.boardgamefun.dto.GameDataDTO; +import com.petproject.boardgamefun.dto.GameSellDTO; +import com.petproject.boardgamefun.exception.BadRequestException; +import com.petproject.boardgamefun.exception.NoRecordFoundException; +import com.petproject.boardgamefun.model.Game; +import com.petproject.boardgamefun.model.GameSell; +import com.petproject.boardgamefun.model.User; +import com.petproject.boardgamefun.service.GameSellService; +import com.petproject.boardgamefun.service.mappers.GameMapper; +import com.petproject.boardgamefun.service.mappers.GameSellMapper; +import org.junit.jupiter.api.*; +import org.junit.jupiter.api.extension.ExtendWith; +import org.mockito.Matchers; +import org.mockito.junit.jupiter.MockitoExtension; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.boot.test.autoconfigure.web.servlet.AutoConfigureMockMvc; +import org.springframework.boot.test.context.SpringBootTest; +import org.springframework.boot.test.mock.mockito.MockBean; +import org.springframework.http.MediaType; +import org.springframework.security.test.context.support.WithMockUser; +import org.springframework.test.web.servlet.MockMvc; +import org.springframework.test.web.servlet.request.MockMvcRequestBuilders; +import org.springframework.web.context.WebApplicationContext; + +import java.time.OffsetDateTime; +import java.util.ArrayList; +import java.util.List; +import java.util.Objects; + +import static org.mockito.ArgumentMatchers.*; +import static org.mockito.Mockito.*; +import static org.springframework.test.web.servlet.result.MockMvcResultHandlers.print; +import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status; + +@ExtendWith(MockitoExtension.class) +@SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.MOCK, classes = SpringSecurityWebTestConfig.class) +@AutoConfigureMockMvc +@TestMethodOrder(MethodOrderer.OrderAnnotation.class) +@TestInstance(TestInstance.Lifecycle.PER_CLASS) +public class GameSellControllerTests { + @Autowired + private MockMvc mockMvc; + + @Autowired + private WebApplicationContext webApplicationContext; + + private final String Gateway = "/game-sell"; + + ObjectMapper objectMapper; + @Autowired + GameSellMapper gameSellMapper; + @MockBean + private GameSellService gameSellService; + + private GameSell gameSell; + private GameSell gameSell2; + private List gameSellDTOList; + + @BeforeAll + public void setup() { + objectMapper = new ObjectMapper(); + objectMapper.findAndRegisterModules(); + + String instantExpected = "2014-12-22T10:15:30Z"; + + Game game = new Game(); + game.setId(1); + game.setTitle(" Игра номер 1"); + game.setDescription("Отличная игра войнушка номер 1"); + game.setAnnotation("Отличная игра номер 1"); + game.setPicture(null); + game.setPlayerAge("14"); + game.setPlayersMin(3); + game.setPlayersMax(5); + game.setTimeToPlayMin(120); + game.setTimeToPlayMax(360); + game.setYearOfRelease(OffsetDateTime.parse(instantExpected)); + + Game game2 = new Game(); + game2.setId(1); + game2.setTitle(" Игра номер 2"); + game2.setDescription("Отличная игра войнушка номер 2"); + game2.setAnnotation("Отличная игра номер 2"); + game2.setPicture(null); + game2.setPlayerAge("16"); + game2.setPlayersMin(2); + game2.setPlayersMax(4); + game2.setTimeToPlayMin(30); + game2.setTimeToPlayMax(120); + game2.setYearOfRelease(OffsetDateTime.parse(instantExpected)); + + User user = new User(); + user.setId(34); + user.setName("Bobby"); + user.setPassword("1234qwer"); + user.setRole("USER"); + user.setMail("bobby@ggogle.com"); + user.setRating(1.0); + user.setRegistrationDate(OffsetDateTime.now()); + + gameSell = new GameSell(); + gameSell.setGame(game); + gameSell.setCondition("good"); + gameSell.setComment("so good"); + gameSell.setPrice(100); + gameSell.setUser(user); + + GameSell gameSell2 = new GameSell(); + gameSell2.setGame(game2); + gameSell2.setCondition("bad"); + gameSell2.setComment("so bad"); + gameSell2.setPrice(1); + gameSell2.setUser(user); + + gameSellDTOList = new ArrayList<>(); + gameSellDTOList.add(gameSellMapper.GameSellToGameSellDTO(gameSell)); + gameSellDTOList.add(gameSellMapper.GameSellToGameSellDTO(gameSell2)); + + } + + @Test + @WithMockUser(roles = "USER") + public void addGameToSellListShouldReturnOk() throws Exception { + when(gameSellService.addGameToSellList(eq(1), eq(1), any(GameSell.class))).thenReturn(gameSellDTOList); + var mvcRes = this.mockMvc.perform(MockMvcRequestBuilders.post(Gateway + "/1/1") + .contentType(MediaType.APPLICATION_JSON) + .accept(MediaType.APPLICATION_JSON) + .content(objectMapper.writeValueAsString(gameSell))).andExpect(status().isOk()).andReturn(); + var res = objectMapper.readValue(mvcRes.getResponse().getContentAsByteArray(), GameSellDTO[].class); + verify(gameSellService).addGameToSellList(eq(1), eq(1), any(GameSell.class)); + Assertions.assertEquals(res.length, 2); + } + + @Test + @WithMockUser(roles = "USER") + public void addGameToSellListShouldReturnNotFound() throws Exception { + when(gameSellService.addGameToSellList(eq(-1), eq(-1), any(GameSell.class))).thenThrow(NoRecordFoundException.class); + this.mockMvc.perform(MockMvcRequestBuilders.post(Gateway + "/-1/-1") + .contentType(MediaType.APPLICATION_JSON) + .accept(MediaType.APPLICATION_JSON) + .content(objectMapper.writeValueAsString(gameSell))).andExpect(status().isNotFound()); + verify(gameSellService).addGameToSellList(eq(-1), eq(-1), any(GameSell.class)); + Assertions.assertThrows(NoRecordFoundException.class, () -> gameSellService.addGameToSellList(-1, -1, gameSell)); + } + + @Test + @WithMockUser(roles = "USER") + public void addGameToSellListShouldReturnBadRequest() throws Exception { + when(gameSellService.addGameToSellList(eq(1), eq(1), any(GameSell.class))).thenThrow(BadRequestException.class); + this.mockMvc.perform(MockMvcRequestBuilders.post(Gateway + "/1/1") + .contentType(MediaType.APPLICATION_JSON) + .accept(MediaType.APPLICATION_JSON) + .content(objectMapper.writeValueAsString(gameSell))).andExpect(status().isBadRequest()); + verify(gameSellService).addGameToSellList(eq(1), eq(1), any(GameSell.class)); + Assertions.assertThrows(BadRequestException.class, () -> gameSellService.addGameToSellList(1, 1, gameSell)); + } + + @Test + public void addGameToSellListShouldReturnUnauthorized() throws Exception { + this.mockMvc.perform(MockMvcRequestBuilders.post(Gateway + "/1/1") + .contentType(MediaType.APPLICATION_JSON) + .accept(MediaType.APPLICATION_JSON) + .content(objectMapper.writeValueAsString(gameSell))).andExpect(status().isUnauthorized()); + } + + @Test + @WithMockUser(roles = "USER") + public void removeGameFromSellListShouldReturnOk() throws Exception { + doNothing().when(gameSellService).removeGameFromSell(1, 1); + this.mockMvc.perform(MockMvcRequestBuilders.delete(Gateway + "/1/1")).andDo(print()).andExpect(status().isOk()); + verify(gameSellService).removeGameFromSell(1, 1); + } + + @Test + @WithMockUser(roles = "USER") + public void removeGameFromSellListShouldReturnNotFound() throws Exception { + doThrow(NoRecordFoundException.class).when(gameSellService).removeGameFromSell(1, 1); + this.mockMvc.perform(MockMvcRequestBuilders.delete(Gateway + "/1/1")).andDo(print()).andExpect(status().isNotFound()); + verify(gameSellService).removeGameFromSell(1, 1); + Assertions.assertThrows(NoRecordFoundException.class, () -> gameSellService.removeGameFromSell(1, 1)); + } + + @Test + public void removeGameFromSellListShouldReturnUnauthorized() throws Exception { + this.mockMvc.perform(MockMvcRequestBuilders.delete(Gateway + "/1/1")).andDo(print()).andExpect(status().isUnauthorized()); + } + + @Test + @WithMockUser(roles = "USER") + public void updateSellGameListShouldReturnOk() throws Exception { + doNothing().when(gameSellService).updateGameSell(any(GameSell.class)); + this.mockMvc.perform(MockMvcRequestBuilders.put(Gateway) + .contentType(MediaType.APPLICATION_JSON) + .accept(MediaType.APPLICATION_JSON) + .content(objectMapper.writeValueAsString(gameSell))).andExpect(status().isOk()); + verify(gameSellService).updateGameSell( any(GameSell.class)); + } + + @Test + @WithMockUser(roles = "USER") + public void updateSellGameListShouldReturnBadRequest() throws Exception { + doThrow(BadRequestException.class).when(gameSellService).updateGameSell(any(GameSell.class)); + this.mockMvc.perform(MockMvcRequestBuilders.put(Gateway) + .contentType(MediaType.APPLICATION_JSON) + .accept(MediaType.APPLICATION_JSON) + .content(objectMapper.writeValueAsString(gameSell))).andExpect(status().isBadRequest()); + verify(gameSellService).updateGameSell( any(GameSell.class)); + Assertions.assertThrows(BadRequestException.class, () -> gameSellService.updateGameSell(gameSell)); + } + + @Test + @WithMockUser(roles = "USER") + public void getGameSellListShouldReturnOk() throws Exception { + when(gameSellService.getGameSellList(1)).thenReturn(gameSellDTOList); + var mvcRes = this.mockMvc.perform(MockMvcRequestBuilders.get(Gateway + "/1")).andDo(print()).andExpect(status().isOk()).andReturn(); + var res = objectMapper.readValue(mvcRes.getResponse().getContentAsByteArray(), GameSellDTO[].class); + verify(gameSellService).getGameSellList(1); + Assertions.assertEquals(res.length, 2); + } + + @Test + @WithMockUser(roles = "USER") + public void getGameSellListShouldReturnOk_BlankList() throws Exception { + when(gameSellService.getGameSellList(1)).thenReturn(new ArrayList<>()); + var mvcRes = this.mockMvc.perform(MockMvcRequestBuilders.get(Gateway + "/1")).andDo(print()).andExpect(status().isOk()).andReturn(); + var res = objectMapper.readValue(mvcRes.getResponse().getContentAsByteArray(), GameSellDTO[].class); + verify(gameSellService).getGameSellList(1); + Assertions.assertEquals(res.length, 0); + } + + @Test + @WithMockUser(roles = "USER") + public void getGameSellListShouldReturnNotFound() throws Exception { + when(gameSellService.getGameSellList(-1)).thenThrow(NoRecordFoundException.class); + this.mockMvc.perform(MockMvcRequestBuilders.get(Gateway + "/-1")).andDo(print()).andExpect(status().isNotFound()); + verify(gameSellService).getGameSellList(-1); + Assertions.assertThrows(NoRecordFoundException.class, () -> gameSellService.getGameSellList(-1)); + } +} diff --git a/src/test/java/com/petproject/boardgamefun/controller/UserControllerTests.java b/src/test/java/com/petproject/boardgamefun/controller/UserControllerTests.java new file mode 100644 index 0000000..1e9208f --- /dev/null +++ b/src/test/java/com/petproject/boardgamefun/controller/UserControllerTests.java @@ -0,0 +1,1937 @@ +package com.petproject.boardgamefun.controller; + +import static org.mockito.Mockito.when; +import static org.springframework.test.web.servlet.result.MockMvcResultHandlers.print; +import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status; + +import com.fasterxml.jackson.databind.ObjectMapper; +import com.petproject.boardgamefun.SpringSecurityWebTestConfig; +import com.petproject.boardgamefun.dto.*; +import com.petproject.boardgamefun.dto.projection.GameSellProjection; +import com.petproject.boardgamefun.dto.projection.UserGameRatingProjection; +import com.petproject.boardgamefun.dto.request.PasswordChangeRequest; +import com.petproject.boardgamefun.dto.request.UserEditRequest; +import com.petproject.boardgamefun.exception.BadRequestException; +import com.petproject.boardgamefun.exception.NoRecordFoundException; +import com.petproject.boardgamefun.model.*; + +import com.petproject.boardgamefun.repository.*; +import com.petproject.boardgamefun.security.jwt.JwtUtils; +import com.petproject.boardgamefun.security.model.LoginRequest; +import com.petproject.boardgamefun.security.model.RefreshTokenRequest; +import com.petproject.boardgamefun.security.model.RefreshTokenResponse; +import com.petproject.boardgamefun.security.services.RefreshTokenService; +import com.petproject.boardgamefun.security.services.UserDetailsImpl; +import com.petproject.boardgamefun.service.DiaryService; +import com.petproject.boardgamefun.service.GameSellService; +import com.petproject.boardgamefun.service.GameService; +import com.petproject.boardgamefun.service.UserService; +import com.petproject.boardgamefun.service.mappers.DiaryMapper; +import com.petproject.boardgamefun.service.mappers.GameMapper; +import com.petproject.boardgamefun.service.mappers.UserMapper; +import org.apache.maven.wagon.resource.Resource; +import org.junit.jupiter.api.*; +import org.junit.jupiter.api.extension.ExtendWith; + +import static org.mockito.Mockito.*; + +import org.mockito.ArgumentCaptor; +import org.mockito.Captor; +import org.mockito.junit.jupiter.MockitoExtension; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.boot.test.autoconfigure.web.servlet.AutoConfigureMockMvc; +import org.springframework.boot.test.context.SpringBootTest; +import org.springframework.boot.test.mock.mockito.MockBean; +import org.springframework.core.io.ClassPathResource; +import org.springframework.http.MediaType; +import org.springframework.mock.web.MockMultipartFile; +import org.springframework.security.authentication.AuthenticationManager; +import org.springframework.security.authentication.UsernamePasswordAuthenticationToken; +import org.springframework.security.core.Authentication; +import org.springframework.security.core.AuthenticationException; +import org.springframework.security.test.context.support.WithMockUser; +import org.springframework.test.web.servlet.MockMvc; +import org.springframework.test.web.servlet.MvcResult; +import org.springframework.test.web.servlet.request.MockMultipartHttpServletRequestBuilder; +import org.springframework.test.web.servlet.request.MockMvcRequestBuilders; +import org.springframework.web.multipart.MultipartFile; + +import java.time.OffsetDateTime; +import java.util.ArrayList; +import java.util.HexFormat; +import java.util.List; +import java.util.Optional; + + +@ExtendWith(MockitoExtension.class) +@SpringBootTest( + webEnvironment = SpringBootTest.WebEnvironment.MOCK, + classes = SpringSecurityWebTestConfig.class +) +@AutoConfigureMockMvc +@TestMethodOrder(MethodOrderer.OrderAnnotation.class) +@TestInstance(TestInstance.Lifecycle.PER_CLASS) +public class UserControllerTests { + + private final String Gateway = "/users"; + + @Autowired + UserMapper userMapper; + @Autowired + private MockMvc mockMvc; + @MockBean + private UserService userService; + @MockBean + private RefreshTokenService refreshTokenService; + + @MockBean + private AuthenticationManager authenticationManager; + + @MockBean + private Authentication authentication; + + @MockBean + private JwtUtils jwtUtils; + + @MockBean + private UserDetailsImpl userDetails; + @Captor + ArgumentCaptor> userListArgumentCaptor; + @Captor + ArgumentCaptor stringArgumentCaptor; + @Captor + ArgumentCaptor userArgumentCaptor; + + private List usersDTO; + private UserDTO userDTO; + private UserDTO userModeratorDTO; + private User userAdmin; + private User userModerator; + private User user; + private List users; + private UserEditRequest userEditRequest; + private PasswordChangeRequest passwordChangeRequest; + ObjectMapper objectMapper; + + @BeforeAll + public void setup() { + objectMapper = new ObjectMapper(); + objectMapper.findAndRegisterModules(); + userAdmin = new User(); + userAdmin.setId(11); + userAdmin.setName("Alice"); + userAdmin.setPassword("pswd"); + userAdmin.setRole("ADMIN"); + userAdmin.setMail("alicealisson@ggogle.com"); + userAdmin.setRating(1.0); + userAdmin.setRegistrationDate(OffsetDateTime.now()); + + userModerator = new User(); + userModerator.setId(14); + userModerator.setName("Sam"); + userModerator.setPassword("pswdsam"); + userModerator.setRole("MODERATOR"); + userModerator.setMail("samwinchester@ggogle.com"); + userModerator.setRating(1.0); + userModerator.setRegistrationDate(OffsetDateTime.now()); + + user = new User(); + user.setId(34); + user.setName("Bobby"); + user.setPassword("1234qwer"); + user.setRole("USER"); + user.setMail("bobby@ggogle.com"); + user.setRating(1.0); + user.setRegistrationDate(OffsetDateTime.now()); + + users = new ArrayList<>(); + users.add(userAdmin); + users.add(userModerator); + users.add(user); + + + userDTO = userMapper.userToUserDTO(user); + usersDTO = new ArrayList<>(); + usersDTO.add(userMapper.userToUserDTO(userAdmin)); + usersDTO.add(userMapper.userToUserDTO(userModerator)); + usersDTO.add(userMapper.userToUserDTO(user)); + + userModeratorDTO = userMapper.userToUserDTO(userModerator); + + userEditRequest = new UserEditRequest(); + userEditRequest.setRole(userModerator.getRole()); + userEditRequest.setName(userModerator.getName()); + + passwordChangeRequest = new PasswordChangeRequest(); + passwordChangeRequest.setPassword("bla-bla"); + + + } + + @Test + public void getUsersShouldReturnOk() throws Exception { + when(userService.getUsers()).thenReturn(usersDTO); + + var result = this.mockMvc.perform(MockMvcRequestBuilders.get(Gateway)).andDo(print()).andExpect(status().isOk()).andReturn(); + + var userList = objectMapper.readValue(result.getResponse().getContentAsByteArray(), UserDTO[].class); + + verify(userService).getUsers(); + Assertions.assertEquals(userList.length, 3); + } + + @Test + public void getUsersShouldReturnOk_BlankList() throws Exception { + when(userService.getUsers()).thenReturn(new ArrayList<>()); + + var mvcResult = this.mockMvc.perform(MockMvcRequestBuilders.get(Gateway)).andDo(print()).andExpect(status().isOk()).andReturn(); + UserDTO[] userResponse = objectMapper.readValue(mvcResult.getResponse().getContentAsByteArray(), UserDTO[].class); + verify(userService).getUsers(); + Assertions.assertEquals(userResponse.length, 0); + } + + @Test + @WithMockUser(roles = "USER") + public void authenticateUserShouldReturnOk() throws Exception { + LoginRequest loginRequest = new LoginRequest(user.getName(), user.getPassword()); + + when(authenticationManager.authenticate(new UsernamePasswordAuthenticationToken(user.getName(), user.getPassword()))).thenReturn(authentication); + when(userService.existsByName((user.getName()))).thenReturn(true); + when(refreshTokenService.createRefreshToken(user.getName())).thenReturn("token"); + when(authentication.isAuthenticated()).thenReturn(true); + when(authentication.getPrincipal()).thenReturn(userDetails); + when(jwtUtils.generateJwtToken(authentication)).thenReturn("124"); + when(userDetails.getId()).thenReturn(user.getId()); + when(userDetails.getUsername()).thenReturn(user.getName()); + when(userDetails.getEmail()).thenReturn(user.getMail()); + + this.mockMvc.perform(MockMvcRequestBuilders.post(Gateway + "/sign-in").contentType(MediaType.APPLICATION_JSON) + .accept(MediaType.APPLICATION_JSON) + .content(objectMapper.writeValueAsString(loginRequest))).andExpect(status().isOk()); + + verify(refreshTokenService).createRefreshToken(stringArgumentCaptor.capture()); + Assertions.assertEquals(stringArgumentCaptor.getValue(), user.getName()); + } + + @Test + public void authenticateUserShouldReturn415() throws Exception { + LoginRequest loginRequest = new LoginRequest("Admin", "123qweAdmin"); + this.mockMvc.perform(MockMvcRequestBuilders.post(Gateway + "/sign-in") + .contentType(MediaType.APPLICATION_XML) + .accept(MediaType.APPLICATION_XML) + .content(objectMapper.writeValueAsString(loginRequest))).andExpect(status().isUnsupportedMediaType()); + } + + @Test + public void authenticateUserShouldReturnNotFound() throws Exception { + LoginRequest loginRequest = new LoginRequest("-1Admin", "123qweAdmin"); + when(userService.existsByName(user.getName())).thenReturn(false); + this.mockMvc.perform(MockMvcRequestBuilders.post(Gateway + "/sign-in") + .contentType(MediaType.APPLICATION_JSON) + .accept(MediaType.APPLICATION_JSON) + .content(objectMapper.writeValueAsString(loginRequest))).andExpect(status().isNotFound()); + } + + @Test + public void authenticateUserShouldReturnNotAuthorized() throws Exception { + LoginRequest loginRequest = new LoginRequest(user.getName(), user.getPassword()); + + when(userService.existsByName(user.getName())).thenReturn(true); + when(authenticationManager.authenticate(new UsernamePasswordAuthenticationToken(user.getName(), user.getPassword()))).thenThrow(new AuthenticationException("auth failed") { + @Override + public String getMessage() { + return super.getMessage(); + } + }); + + this.mockMvc.perform(MockMvcRequestBuilders.post(Gateway + "/sign-in") + .contentType(MediaType.APPLICATION_JSON) + .accept(MediaType.APPLICATION_JSON) + .content(objectMapper.writeValueAsString(loginRequest))).andExpect(status().isUnauthorized()); + verify(userService).existsByName(user.getName()); + Assertions.assertThrows(AuthenticationException.class, () -> authenticationManager.authenticate(new UsernamePasswordAuthenticationToken(user.getName(), user.getPassword()))); + } + + @Test + public void authenticateUserShouldReturnBadRequest() throws Exception { + this.mockMvc.perform(MockMvcRequestBuilders.post(Gateway + "/sign-in") + .contentType(MediaType.APPLICATION_JSON) + .accept(MediaType.APPLICATION_JSON)) + .andExpect(status().isBadRequest()); + } + + @Test + public void refreshTokenShouldReturnNotAuthorizedBadAccessToken() throws Exception { + RefreshTokenRequest refreshTokenRequest = new RefreshTokenRequest("Admin", "bla-bla"); + when(refreshTokenService.verifyExpiration(refreshTokenRequest.getRefreshToken())).thenReturn(false); + this.mockMvc.perform(MockMvcRequestBuilders.post(Gateway + "/refresh-token") + .contentType(MediaType.APPLICATION_JSON) + .accept(MediaType.APPLICATION_JSON) + .content(objectMapper.writeValueAsString(refreshTokenRequest))) + .andExpect(status().isUnauthorized()); + verify(refreshTokenService, only()).verifyExpiration(refreshTokenRequest.getRefreshToken()); + } + + @Test + public void refreshTokenShouldReturnIsOk() throws Exception { + RefreshTokenRequest refreshTokenRequest = new RefreshTokenRequest("Admin", "bla-bla"); + + when(refreshTokenService.verifyExpiration(refreshTokenRequest.getRefreshToken())).thenReturn(true); + when(jwtUtils.generateJwtToken(refreshTokenRequest.getUserName())).thenReturn("new token"); + + var response = this.mockMvc.perform(MockMvcRequestBuilders.post(Gateway + "/refresh-token") + .contentType(MediaType.APPLICATION_JSON) + .accept(MediaType.APPLICATION_JSON) + .content(objectMapper.writeValueAsString(refreshTokenRequest))) + .andExpect(status().isOk()).andReturn(); + + RefreshTokenResponse refreshTokenResponse = objectMapper.readValue(response.getResponse().getContentAsByteArray(), RefreshTokenResponse.class); + + verify(refreshTokenService, only()).verifyExpiration(refreshTokenRequest.getRefreshToken()); + verify(jwtUtils, only()).generateJwtToken(refreshTokenRequest.getUserName()); + Assertions.assertEquals(refreshTokenResponse.getAccessToken(), "new token"); + } + + @Test + public void getUserShouldReturnStatusOkTest() throws Exception { + when(userService.getUser(1)).thenReturn(userDTO); + var mvcRes = this.mockMvc.perform(MockMvcRequestBuilders.get(Gateway + "/1")).andDo(print()).andExpect(status().isOk()).andReturn(); + var res = objectMapper.readValue(mvcRes.getResponse().getContentAsByteArray(), UserDTO.class); + verify(userService).getUser(1); + Assertions.assertEquals(res.name(), userDTO.name()); + } + + @Test + public void getUserShouldReturnStatusNotFound() throws Exception { + when(userService.getUser(-1)).thenThrow(new NoRecordFoundException("User not found")); + this.mockMvc.perform(MockMvcRequestBuilders.get(Gateway + "/-1")).andDo(print()).andExpect(status().isNotFound()); + verify(userService).getUser(-1); + } + + @Test + public void getUserWhenBadPathValueReturn400() throws Exception { + mockMvc.perform(MockMvcRequestBuilders.get(Gateway + "/{userId}", "userId")).andExpect(status().isBadRequest()); + } + + @Test + public void registerUserShouldReturnOK() throws Exception { + doNothing().when(userService).registerUser(any(User.class)); + mockMvc.perform(MockMvcRequestBuilders.post(Gateway + "/sign-up").contentType(MediaType.APPLICATION_JSON) + .accept(MediaType.APPLICATION_JSON) + .content(objectMapper.writeValueAsString(user))).andExpect(status().isOk()); + verify(userService).registerUser(any(User.class)); + } + + @Test + public void registerUserShouldReturnBadRequest() throws Exception { + doThrow(new BadRequestException()).when(userService).registerUser(user); + mockMvc.perform(MockMvcRequestBuilders.post(Gateway + "/sign-up").contentType(MediaType.APPLICATION_JSON) + .accept(MediaType.APPLICATION_JSON) + .content(objectMapper.writeValueAsString(user))).andExpect(status().isOk()); + verify(userService).registerUser(any(User.class)); + } + + @Test + public void uploadAvatarShouldReturnOk() throws Exception { + MockMultipartFile multipartFile = new MockMultipartFile( + "avatar", + "hello.jpg", + MediaType.MULTIPART_FORM_DATA_VALUE, + "0x36".getBytes() + ); + doNothing().when(userService).uploadAvatar(user.getName(), multipartFile); + MockMultipartHttpServletRequestBuilder multipartRequest = + MockMvcRequestBuilders.multipart(Gateway + "/upload-avatar/" + user.getName()); + mockMvc.perform(multipartRequest.file(multipartFile)) + .andExpect(status().isOk()); + + verify(userService).uploadAvatar(user.getName(), multipartFile); + } + + @Test + public void uploadAvatarShouldReturnNotFound() throws Exception { + MockMultipartFile multipartFile = new MockMultipartFile( + "avatar", + "hello.jpg", + MediaType.MULTIPART_FORM_DATA_VALUE, + "0x36".getBytes() + ); + doThrow(new NoRecordFoundException()).when(userService).uploadAvatar("user.getName()", multipartFile); + + MockMultipartHttpServletRequestBuilder multipartRequest = + MockMvcRequestBuilders.multipart(Gateway + "/upload-avatar/" + "user.getName()"); + mockMvc.perform(multipartRequest.file(multipartFile)) + .andExpect(status().isNotFound()); + Assertions.assertThrows(NoRecordFoundException.class, () -> userService.uploadAvatar("user.getName()", multipartFile)); + } + + @Test + public void uploadAvatarShouldReturnBadRequest() throws Exception { + MockMultipartFile multipartFile = new MockMultipartFile( + "avatar", + "hello.jpg", + MediaType.TEXT_PLAIN_VALUE, + "0x36".getBytes() + ); + doThrow(new BadRequestException()).when(userService).uploadAvatar(user.getName(), multipartFile); + MockMultipartHttpServletRequestBuilder multipartRequest = + MockMvcRequestBuilders.multipart(Gateway + "/upload-avatar/" + user.getName()); + mockMvc.perform(multipartRequest.file(multipartFile)) + .andExpect(status().isBadRequest()); + + Assertions.assertThrows(BadRequestException.class, () -> userService.uploadAvatar(user.getName(), multipartFile)); + } + + @Test + @WithMockUser(roles = "USER") + public void editUserShouldReturnOK() throws Exception { + when(userService.editUser(1, userEditRequest)).thenReturn(userModeratorDTO); + var mvcRes = mockMvc.perform(MockMvcRequestBuilders.patch(Gateway + "/1").contentType(MediaType.APPLICATION_JSON) + .accept(MediaType.APPLICATION_JSON) + .content(objectMapper.writeValueAsString(userEditRequest))).andExpect(status().isOk()).andReturn(); + var result = objectMapper.readValue(mvcRes.getResponse().getContentAsByteArray(), UserDTO.class); + verify(userService).editUser(1, userEditRequest); + Assertions.assertEquals(result.name(), userModeratorDTO.name()); + } + + @Test + @WithMockUser(roles = "USER") + public void editUserShouldReturnBadReqQuest() throws Exception { + when(userService.editUser(1, userEditRequest)).thenThrow(new BadRequestException("Nickname already exists")); + mockMvc.perform(MockMvcRequestBuilders.patch(Gateway + "/1").contentType(MediaType.APPLICATION_JSON) + .accept(MediaType.APPLICATION_JSON) + .content(objectMapper.writeValueAsString(userEditRequest))).andExpect(status().isBadRequest()); + Assertions.assertThrows(BadRequestException.class, () -> userService.editUser(1, userEditRequest)); + } + + @Test + public void editUserShouldReturnUnauthorized() throws Exception { + mockMvc.perform(MockMvcRequestBuilders.patch(Gateway + "/1").contentType(MediaType.APPLICATION_JSON) + .accept(MediaType.APPLICATION_JSON) + .content(objectMapper.writeValueAsString(userEditRequest))).andExpect(status().isUnauthorized()); + } + + @Test + public void changePasswordShouldReturnUnauthorized() throws Exception { + mockMvc.perform(MockMvcRequestBuilders.patch(Gateway + "/change-password/1").contentType(MediaType.APPLICATION_JSON) + .accept(MediaType.APPLICATION_JSON) + .content(objectMapper.writeValueAsString(passwordChangeRequest))).andExpect(status().isUnauthorized()); + } + + @Test + @WithMockUser(roles = "USER") + public void changePasswordShouldReturnBadRequest() throws Exception { + when(userService.changePassword(1, passwordChangeRequest)).thenThrow(new BadRequestException()); + mockMvc.perform(MockMvcRequestBuilders.patch(Gateway + "/change-password/1").contentType(MediaType.APPLICATION_JSON) + .accept(MediaType.APPLICATION_JSON) + .content(objectMapper.writeValueAsString(passwordChangeRequest))).andExpect(status().isBadRequest()); + Assertions.assertThrows(BadRequestException.class, () -> userService.changePassword(1, passwordChangeRequest)); + } + + @Test + @WithMockUser(roles = "USER") + public void changePasswordShouldReturnOk() throws Exception { + when(userService.changePassword(1, passwordChangeRequest)).thenReturn(userDTO); + var mvcRes = mockMvc.perform(MockMvcRequestBuilders.patch(Gateway + "/change-password/1").contentType(MediaType.APPLICATION_JSON) + .accept(MediaType.APPLICATION_JSON) + .content(objectMapper.writeValueAsString(passwordChangeRequest))).andExpect(status().isOk()).andReturn(); + var result = objectMapper.readValue(mvcRes.getResponse().getContentAsByteArray(), UserDTO.class); + verify(userService).changePassword(1, passwordChangeRequest); + Assertions.assertEquals(userDTO.name(), result.name()); + } +} + + +/*@ExtendWith(MockitoExtension.class) +@SpringBootTest( + webEnvironment = SpringBootTest.WebEnvironment.MOCK, + classes = SpringSecurityWebTestConfig.class +) +@AutoConfigureMockMvc +@TestMethodOrder(MethodOrderer.OrderAnnotation.class) +@TestInstance(TestInstance.Lifecycle.PER_CLASS) +public class UserControllerTests { + + private final String Gateway = "/users"; + + @Autowired + UserMapper userMapper; + + @Autowired + GameMapper gameMapper; + + @Autowired + DiaryMapper diaryMapper; + + @MockBean + private UserRepository userRepository; + + @MockBean + private UserService userService; + + @MockBean + private GameService gameService; + + @MockBean + private GameRepository gameRepository; + + @MockBean + private RatingGameByUserRepository ratingGameByUserRepository; + + @MockBean + private RefreshTokenService refreshTokenService; + + @MockBean + private AuthenticationManager authenticationManager; + + @MockBean + private Authentication authentication; + + @MockBean + private JwtUtils jwtUtils; + + @MockBean + private UserDetailsImpl userDetails; + + @MockBean + private UserOwnGameRepository userOwnGameRepository; + + @MockBean + private UserWishRepository userWishRepository; + + @MockBean + private GameSellRepository gameSellRepository; + + @MockBean + private GameSellService gameSellService; + + @MockBean + private DiaryRepository diaryRepository; + + @MockBean + private DiaryService diaryService; + + private List usersDTO; + private UserDTO userDTO; + private User userAdmin; + private User userModerator; + private User user; + private List users; + private List gamesDTO; + private GameDataDTO gameDataDTO; + private Game game; + private List games; + private List userGameRatingProjections; + private Designer designer; + private DesignerDTO designerDTO; + private RatingGameByUser ratingGameByUser; + private UserOwnGame userOwnGame; + private UserWish userWish; + private List gameSellProjectionList; + private List gameSellDTOList; + private GameSellDTO gameSellDTO; + private GameSell gameSell; + private Diary diary; + private DiaryDataDTO diaryDTO; + + @Autowired + private MockMvc mockMvc; + private static final int insertDataOrder = 1, checkOnDuplicate = 2, updateDataOrder = 3, deleteDataOrder = 4; + + @Captor + ArgumentCaptor> userListArgumentCaptor; + + @Captor + ArgumentCaptor userArgumentCaptor; + + @Captor + ArgumentCaptor> gameListArgumentCaptor; + + @Captor + ArgumentCaptor> userGameRatingProjectionCaptor; + + @Captor + ArgumentCaptor gameArgumentCaptor; + + @Captor + ArgumentCaptor ratingGameByUserArgumentCaptor; + + @Captor + ArgumentCaptor stringArgumentCaptor; + + ObjectMapper objectMapper; + + User admin; + + @BeforeAll + public void setup() { + objectMapper = new ObjectMapper(); + objectMapper.findAndRegisterModules(); + userAdmin = new User(); + userAdmin.setId(11); + userAdmin.setName("Alice"); + userAdmin.setPassword("pswd"); + userAdmin.setRole("ADMIN"); + userAdmin.setMail("alicealisson@ggogle.com"); + userAdmin.setRating(1.0); + userAdmin.setRegistrationDate(OffsetDateTime.now()); + + userModerator = new User(); + userModerator.setId(14); + userModerator.setName("Sam"); + userModerator.setPassword("pswdsam"); + userModerator.setRole("MODERATOR"); + userModerator.setMail("samwinchester@ggogle.com"); + userModerator.setRating(1.0); + userModerator.setRegistrationDate(OffsetDateTime.now()); + + user = new User(); + user.setId(34); + user.setName("Bobby"); + user.setPassword("1234qwer"); + user.setRole("USER"); + user.setMail("bobby@ggogle.com"); + user.setRating(1.0); + user.setRegistrationDate(OffsetDateTime.now()); + + users = new ArrayList<>(); + users.add(userAdmin); + users.add(userModerator); + users.add(user); + + + userDTO = userMapper.userToUserDTO(user); + usersDTO = new ArrayList<>(); + usersDTO.add(userMapper.userToUserDTO(userAdmin)); + usersDTO.add(userMapper.userToUserDTO(userModerator)); + usersDTO.add(userMapper.userToUserDTO(user)); + + + game = new Game(); + game.setId(1); + game.setTitle(" Игра номер 1"); + game.setDescription("Отличная игра войнушка номер 1"); + game.setAnnotation("Отличная игра номер 1"); + game.setPicture(null); + game.setPlayerAge("14"); + game.setPlayersMin(3); + game.setPlayersMax(5); + game.setTimeToPlayMin(120); + game.setTimeToPlayMax(360); + game.setYearOfRelease(OffsetDateTime.now()); + + + Game game1 = new Game(); + game1.setId(1); + game1.setTitle(" Игра номер 2"); + game1.setDescription("Отличная игра войнушка номер 2"); + game1.setAnnotation("Отличная игра номер 2"); + game1.setPicture(null); + game1.setPlayerAge("16"); + game1.setPlayersMin(2); + game1.setPlayersMax(4); + game1.setTimeToPlayMin(30); + game1.setTimeToPlayMax(120); + game1.setYearOfRelease(OffsetDateTime.now()); + + games = new ArrayList<>(); + games.add(game); + games.add(game1); + + designer = new Designer(); + designer.setId(1); + designer.setName("Designer number one"); + + Designer designer2 = new Designer(); + designer2.setId(2); + designer2.setName("Designer number two"); + + List designers = new ArrayList<>(); + designers.add(designer.getName()); + designers.add(designer2.getName()); + + gameDataDTO = new GameDataDTO(gameMapper.gameToGameDTO(game), 8.4, designers); + designers.remove(1); + GameDataDTO gameDataDTO1 = new GameDataDTO(gameMapper.gameToGameDTO(game), 7.9, designers); + + userGameRatingProjections = new ArrayList<>(); + userGameRatingProjections.add(new UserGameRatingPOJO(game, 3)); + userGameRatingProjections.add(new UserGameRatingPOJO(game, 10)); + + gamesDTO = new ArrayList<>(); + gamesDTO.add(gameDataDTO); + gamesDTO.add(gameDataDTO1); + + ratingGameByUser = new RatingGameByUser(); + ratingGameByUser.setUser(user); + ratingGameByUser.setGame(game); + ratingGameByUser.setRating(10.0); + + userOwnGame = new UserOwnGame(); + userOwnGame.setUser(user); + userOwnGame.setGame(game); + + userWish = new UserWish(); + userWish.setUser(user); + userWish.setGame(game); + userWish.setId(1); + + gameSell = new GameSell(); + gameSell.setGame(game); + gameSell.setCondition("good"); + gameSell.setComment("so good"); + gameSell.setPrice(100); + gameSell.setUser(user); + + gameSellProjectionList = new ArrayList<>(); + gameSellProjectionList.add(new GameSellPOJO(game, "good", "so good", 100)); + gameSellProjectionList.add(new GameSellPOJO(game1, "excellent", "not open", 300)); + + gameSellDTO = new GameSellDTO(); + gameSellDTO.setGame(gameMapper.gameToGameDTO(game)); + gameSellDTO.setCondition("good"); + gameSellDTO.setComment("so good"); + gameSellDTO.setPrice(100); + + gameSellDTOList = new ArrayList<>(); + gameSellDTOList.add(gameSellDTO); + gameSellDTOList.add(new GameSellDTO(gameMapper.gameToGameDTO(game1), "excellent", "not open", 300)); + + diary = new Diary(); + diary.setGame(game); + diary.setUser(user); + diary.setTitle("let's talk about" + game.getTitle()); + diary.setText("Not so good, but good"); + diary.setPublicationTime(OffsetDateTime.now()); + + diaryDTO = new DiaryDataDTO(diaryMapper.diaryToDiaryDTO(diary), 8.0); + } + + @Test + public void getUsersShouldReturnOk() throws Exception { + when(userRepository.findAll()).thenReturn(users); + when(userService.entitiesToUserDTO(users)).thenReturn(usersDTO); + + this.mockMvc.perform(MockMvcRequestBuilders.get(Gateway)).andDo(print()).andExpect(status().isOk()); + + + verify(userRepository, only()).findAll(); + verify(userService, only()).entitiesToUserDTO(userListArgumentCaptor.capture()); + Assertions.assertEquals(userListArgumentCaptor.getValue().size(), 3); + } + + @Test + public void getUsersShouldReturnOk_BlankList() throws Exception { + when(userRepository.findAll()).thenReturn(null); + when(userService.entitiesToUserDTO(new ArrayList<>())).thenReturn(new ArrayList<>()); + + MvcResult mvcResult = this.mockMvc.perform(MockMvcRequestBuilders.get(Gateway)).andDo(print()).andExpect(status().isOk()).andReturn(); + UserDTO[] userResponse = objectMapper.readValue(mvcResult.getResponse().getContentAsByteArray(), UserDTO[].class); + verify(userRepository, only()).findAll(); + verify(userService, only()).entitiesToUserDTO(userListArgumentCaptor.capture()); + Assertions.assertNull(userListArgumentCaptor.getValue()); + Assertions.assertEquals(userResponse.length, 0); + } + + @Test + @WithMockUser(roles = "USER") + public void authenticateUserShouldReturnOk() throws Exception { + LoginRequest loginRequest = new LoginRequest(user.getName(), user.getPassword()); + + when(userRepository.existsByName(user.getName())).thenReturn(true); + when(authenticationManager.authenticate(new UsernamePasswordAuthenticationToken(user.getName(), user.getPassword()))).thenReturn(authentication); + when(userRepository.findUserByName(user.getName())).thenReturn(user); + when(refreshTokenService.createRefreshToken(user.getName())).thenReturn("token"); + when(authentication.isAuthenticated()).thenReturn(true); + when(authentication.getPrincipal()).thenReturn(userDetails); + when(jwtUtils.generateJwtToken(authentication)).thenReturn("124"); + when(userDetails.getId()).thenReturn(user.getId()); + when(userDetails.getUsername()).thenReturn(user.getName()); + when(userDetails.getEmail()).thenReturn(user.getMail()); + + this.mockMvc.perform(MockMvcRequestBuilders.post(Gateway + "/sign-in").contentType(MediaType.APPLICATION_JSON) + .accept(MediaType.APPLICATION_JSON) + .content(objectMapper.writeValueAsString(loginRequest))).andExpect(status().isOk()); + + verify(userRepository).existsByName(user.getName()); + verify(refreshTokenService).createRefreshToken(stringArgumentCaptor.capture()); + Assertions.assertEquals(stringArgumentCaptor.getValue(), user.getName()); + } + + @Test + public void authenticateUserShouldReturn415() throws Exception { + LoginRequest loginRequest = new LoginRequest("Admin", "123qweAdmin"); + this.mockMvc.perform(MockMvcRequestBuilders.post(Gateway + "/sign-in") + .contentType(MediaType.APPLICATION_XML) + .accept(MediaType.APPLICATION_XML) + .content(objectMapper.writeValueAsString(loginRequest))).andExpect(status().isUnsupportedMediaType()); + } + + @Test + public void authenticateUserShouldReturnNotFound() throws Exception { + LoginRequest loginRequest = new LoginRequest("-1Admin", "123qweAdmin"); + when(userRepository.existsByName(user.getName())).thenReturn(false); + this.mockMvc.perform(MockMvcRequestBuilders.post(Gateway + "/sign-in") + .contentType(MediaType.APPLICATION_JSON) + .accept(MediaType.APPLICATION_JSON) + .content(objectMapper.writeValueAsString(loginRequest))).andExpect(status().isNotFound()); + } + + @Test + public void authenticateUserShouldReturnNotAuthorized() throws Exception { + LoginRequest loginRequest = new LoginRequest(user.getName(), user.getPassword()); + + when(userRepository.existsByName(user.getName())).thenReturn(true); + when(authenticationManager.authenticate(new UsernamePasswordAuthenticationToken(user.getName(), user.getPassword()))).thenThrow(new AuthenticationException("auth failed") { + @Override + public String getMessage() { + return super.getMessage(); + } + }); + + this.mockMvc.perform(MockMvcRequestBuilders.post(Gateway + "/sign-in") + .contentType(MediaType.APPLICATION_JSON) + .accept(MediaType.APPLICATION_JSON) + .content(objectMapper.writeValueAsString(loginRequest))).andExpect(status().isUnauthorized()); + } + + @Test + public void authenticateUserShouldReturnBadRequest() throws Exception { + this.mockMvc.perform(MockMvcRequestBuilders.post(Gateway + "/sign-in") + .contentType(MediaType.APPLICATION_JSON) + .accept(MediaType.APPLICATION_JSON)) + .andExpect(status().isBadRequest()); + } + + @Test + public void refreshTokenShouldReturnNotAuthorizedBadAccessToken() throws Exception { + RefreshTokenRequest refreshTokenRequest = new RefreshTokenRequest("Admin", "bla-bla"); + when(refreshTokenService.verifyExpiration(refreshTokenRequest.getRefreshToken())).thenReturn(false); + this.mockMvc.perform(MockMvcRequestBuilders.post(Gateway + "/refresh-token") + .contentType(MediaType.APPLICATION_JSON) + .accept(MediaType.APPLICATION_JSON) + .content(objectMapper.writeValueAsString(refreshTokenRequest))) + .andExpect(status().isUnauthorized()); + verify(refreshTokenService, only()).verifyExpiration(refreshTokenRequest.getRefreshToken()); + } + + @Test + public void refreshTokenShouldReturnIsOk() throws Exception { + RefreshTokenRequest refreshTokenRequest = new RefreshTokenRequest("Admin", "bla-bla"); + + when(refreshTokenService.verifyExpiration(refreshTokenRequest.getRefreshToken())).thenReturn(true); + when(jwtUtils.generateJwtToken(refreshTokenRequest.getUserName())).thenReturn("new token"); + + var response = this.mockMvc.perform(MockMvcRequestBuilders.post(Gateway + "/refresh-token") + .contentType(MediaType.APPLICATION_JSON) + .accept(MediaType.APPLICATION_JSON) + .content(objectMapper.writeValueAsString(refreshTokenRequest))) + .andExpect(status().isOk()).andReturn(); + + RefreshTokenResponse refreshTokenResponse = objectMapper.readValue(response.getResponse().getContentAsByteArray(), RefreshTokenResponse.class); + + verify(refreshTokenService, only()).verifyExpiration(refreshTokenRequest.getRefreshToken()); + verify(jwtUtils, only()).generateJwtToken(refreshTokenRequest.getUserName()); + Assertions.assertEquals(refreshTokenResponse.getAccessToken(), "new token"); + } + + @Test + public void getUserShouldReturnStatusOkTest() throws Exception { + when(userRepository.findUserById(1)).thenReturn(user); + when(userService.entityToUserDTO(user)).thenReturn(userDTO); + this.mockMvc.perform(MockMvcRequestBuilders.get(Gateway + "/1")).andDo(print()).andExpect(status().isOk()); + verify(userRepository, only()).findUserById(1); + verify(userService, only()).entityToUserDTO(userArgumentCaptor.capture()); + Assertions.assertEquals(userArgumentCaptor.getValue().getName(), userDTO.name()); + } + + @Test + public void getUserShouldReturnStatusNotFound() throws Exception { + when(userRepository.findUserById(-1)).thenReturn(null); + when(userService.entityToUserDTO(null)).thenReturn(null); + this.mockMvc.perform(MockMvcRequestBuilders.get(Gateway + "/-1")).andDo(print()).andExpect(status().isNotFound()); + verify(userRepository, only()).findUserById(-1); + verify(userService, only()).entityToUserDTO(null); + } + + @Test + public void getUserWhenBadPathValueReturn400() throws Exception { + mockMvc.perform(MockMvcRequestBuilders.get(Gateway + "/{userId}", "userId")).andExpect(status().isBadRequest()); + } + + @Test + public void getUserWhenValidInput_thenReturnUserResource() throws Exception { + + when(userRepository.findUserById(1)).thenReturn(user); + when(userService.entityToUserDTO(user)).thenReturn(userDTO); + MvcResult mvcResult = mockMvc.perform(MockMvcRequestBuilders.get(Gateway + "/{userId}", "1")).andExpect(status().isOk()).andReturn(); + + UserDTO userResponse = objectMapper.readValue(mvcResult.getResponse().getContentAsByteArray(), UserDTO.class); + + verify(userRepository, only()).findUserById(1); + verify(userService, only()).entityToUserDTO(userArgumentCaptor.capture()); + + Assertions.assertEquals(userArgumentCaptor.getValue().getName(), userDTO.name()); + + Assertions.assertEquals(userResponse.name(), user.getName()); + Assertions.assertEquals(userResponse.mail(), user.getMail()); + Assertions.assertEquals(userResponse.role(), user.getRole()); + } + + @Test + @WithMockUser(roles = "USER") + public void getUserCollectionShouldReturnIsOk() throws Exception { + when(gameRepository.findUserGames(1)).thenReturn(games); + when(gameService.entitiesToGameDTO(games)).thenReturn(gamesDTO); + + MvcResult mvcResult = this.mockMvc.perform(MockMvcRequestBuilders.get(Gateway + "/1/games")).andExpect(status().isOk()).andReturn(); + var userCollection = objectMapper.readValue(mvcResult.getResponse().getContentAsByteArray(), GameDataDTO[].class); + + verify(gameRepository, only()).findUserGames(1); + verify(gameService, only()).entitiesToGameDTO(gameListArgumentCaptor.capture()); + + Assertions.assertNotEquals(gameListArgumentCaptor.getValue().size(), 0); + Assertions.assertEquals(userCollection[0].getGame().id(), gamesDTO.get(0).getGame().id()); + } + + @Test + @WithMockUser(roles = "USER") + public void getUserCollectionShouldReturnBlankArray() throws Exception { + when(gameRepository.findUserGames(-1)).thenReturn(null); + when(gameService.entitiesToGameDTO(new ArrayList<>())).thenReturn(new ArrayList<>()); + MvcResult mvcResult = this.mockMvc.perform(MockMvcRequestBuilders.get(Gateway + "/-1/games")).andExpect(status().isOk()).andReturn(); + var gameDTOS = objectMapper.readValue(mvcResult.getResponse().getContentAsByteArray(), GameDataDTO[].class); + + verify(gameRepository, only()).findUserGames(-1); + verify(gameService, only()).entitiesToGameDTO(gameListArgumentCaptor.capture()); + + Assertions.assertNull(gameListArgumentCaptor.getValue()); + Assertions.assertEquals(gameDTOS.length, 0); + } + + @Test + @WithMockUser(roles = "USER") + public void getUserRatingListShouldReturnIsOk() throws Exception { + when(gameRepository.findUserGameRatingList(1)).thenReturn(userGameRatingProjections); + when(gameService.userGameRatingToGameDTO(userGameRatingProjections)).thenReturn(gamesDTO); + + MvcResult mvcResult = this.mockMvc.perform(MockMvcRequestBuilders.get(Gateway + "/1/games-rating").characterEncoding("UTF-8")) + .andExpect(status().isOk()).andReturn(); + var userRatingList = objectMapper.readValue(mvcResult.getResponse().getContentAsByteArray(), GameDataDTO[].class); + + verify(gameRepository, only()).findUserGameRatingList(1); + verify(gameService, only()).userGameRatingToGameDTO(userGameRatingProjectionCaptor.capture()); + + Assertions.assertNotEquals(userGameRatingProjectionCaptor.getValue().size(), 0); + Assertions.assertEquals(userRatingList[0].getGame().id(), gamesDTO.get(0).getGame().id()); + } + + @Test + @WithMockUser(roles = "USER") + public void getUserRatingListShouldReturnBlankArray() throws Exception { + when(gameRepository.findUserGameRatingList(-1)).thenReturn(null); + when(gameService.userGameRatingToGameDTO(new ArrayList<>())).thenReturn(new ArrayList<>()); + + MvcResult mvcResult = this.mockMvc.perform(MockMvcRequestBuilders.get(Gateway + "/-1/games-rating")).andExpect(status().isOk()).andReturn(); + var gameDTOS = objectMapper.readValue(mvcResult.getResponse().getContentAsByteArray(), GameDataDTO[].class); + + verify(gameRepository, only()).findUserGameRatingList(-1); + verify(gameService, only()).userGameRatingToGameDTO(userGameRatingProjectionCaptor.capture()); + + Assertions.assertNull(userGameRatingProjectionCaptor.getValue()); + Assertions.assertEquals(gameDTOS.length, 0); + } + + @Test + @WithMockUser(roles = "USER") + public void deleteGameRatingShouldReturnNotFound_FirstParameter() throws Exception { + when(ratingGameByUserRepository.findRatingGame_ByUserIdAndGameId(-1, 1)).thenReturn(null); + + this.mockMvc.perform(MockMvcRequestBuilders.delete(Gateway + "/-1/delete-game-rating/1")).andDo(print()).andExpect(status().isNotFound()); + + verify(ratingGameByUserRepository, only()).findRatingGame_ByUserIdAndGameId(-1, 1); + } + + @Test + @WithMockUser(roles = "USER") + public void deleteGameRatingShouldReturnNotFound_SecondParameter() throws Exception { + when(ratingGameByUserRepository.findRatingGame_ByUserIdAndGameId(1, -1)).thenReturn(null); + + this.mockMvc.perform(MockMvcRequestBuilders.delete(Gateway + "/1/delete-game-rating/-1")).andDo(print()).andExpect(status().isNotFound()); + + verify(ratingGameByUserRepository, only()).findRatingGame_ByUserIdAndGameId(1, -1); + } + + @Test + @WithMockUser(roles = "USER") + public void deleteGameRatingShouldReturnNotFound_BothParameters() throws Exception { + when(ratingGameByUserRepository.findRatingGame_ByUserIdAndGameId(-1, -1)).thenReturn(null); + + this.mockMvc.perform(MockMvcRequestBuilders.delete(Gateway + "/-1/delete-game-rating/-1")).andDo(print()).andExpect(status().isNotFound()); + + verify(ratingGameByUserRepository, only()).findRatingGame_ByUserIdAndGameId(-1, -1); + } + + @Test + @WithMockUser(roles = "USER") + public void deleteGameRatingShouldReturnOk() throws Exception { + when(ratingGameByUserRepository.findRatingGame_ByUserIdAndGameId(1, 1)).thenReturn(ratingGameByUser); + doNothing().when(ratingGameByUserRepository).delete(ratingGameByUser); + + var mvcResult = this.mockMvc.perform(MockMvcRequestBuilders.delete(Gateway + "/1/delete-game-rating/1") + .characterEncoding("UTF-8")).andDo(print()).andExpect(status().isOk()).andReturn().getResponse().getContentAsString(); + + verify(ratingGameByUserRepository).findRatingGame_ByUserIdAndGameId(1, 1); + verify(ratingGameByUserRepository).delete(ratingGameByUserArgumentCaptor.capture()); + + Assertions.assertEquals(ratingGameByUserArgumentCaptor.getValue().getId(), ratingGameByUser.getId()); + Assertions.assertEquals(mvcResult, "Оценка с текущей игры удалена"); + } + + @Test + @WithMockUser(roles = "USER") + public void setGameRatingShouldReturnOk() throws Exception { + when(ratingGameByUserRepository.findRatingGame_ByUserIdAndGameId(1, 1)).thenReturn(null); + when(userRepository.findUserById(1)).thenReturn(user); + when(gameRepository.findGameById(1)).thenReturn(game); + when(ratingGameByUserRepository.save(any(RatingGameByUser.class))).thenReturn(null); + + var mvcResult = this.mockMvc.perform(MockMvcRequestBuilders.post(Gateway + "/1/set-game-rating/1/10")) + .andDo(print()).andExpect(status().isOk()).andReturn(); + + var rating = objectMapper.readValue(mvcResult.getResponse().getContentAsByteArray(), Double.class); + + verify(ratingGameByUserRepository).findRatingGame_ByUserIdAndGameId(1, 1); + verify(userRepository).findUserById(1); + verify(gameRepository).findGameById(1); + verify(ratingGameByUserRepository).save(any(RatingGameByUser.class)); + Assertions.assertEquals(ratingGameByUser.getRating(), rating); + } + + @Test + @WithMockUser(roles = "USER") + public void setGameRatingShouldReturnBadRequest() throws Exception { + when(ratingGameByUserRepository.findRatingGame_ByUserIdAndGameId(1, 1)).thenReturn(ratingGameByUser); + + this.mockMvc.perform(MockMvcRequestBuilders.post(Gateway + "/1/set-game-rating/1/10")).andDo(print()).andExpect(status().isBadRequest()); + + verify(ratingGameByUserRepository).findRatingGame_ByUserIdAndGameId(1, 1); + + } + + @Test + @WithMockUser(roles = "USER") + public void setGameRatingShouldReturnBadRequestLessThanNormal() throws Exception { + this.mockMvc.perform(MockMvcRequestBuilders.post(Gateway + "/1/set-game-rating/1/0")).andDo(print()).andExpect(status().isBadRequest()); + } + + @Test + @WithMockUser(roles = "USER") + public void setGameRatingShouldReturnBadRequestMoreThanNormal() throws Exception { + this.mockMvc.perform(MockMvcRequestBuilders.post(Gateway + "/1/set-game-rating/1/11")).andDo(print()).andExpect(status().isBadRequest()); + } + + @Test + @WithMockUser(roles = "USER") + public void setGameRatingShouldReturnNotFound_FirstParameter() throws Exception { + when(ratingGameByUserRepository.findRatingGame_ByUserIdAndGameId(-1, 1)).thenReturn(null); + when(userRepository.findUserById(-1)).thenReturn(null); + when(gameRepository.findGameById(1)).thenReturn(game); + + this.mockMvc.perform(MockMvcRequestBuilders.post(Gateway + "/-1/set-game-rating/1/10")).andDo(print()).andExpect(status().isNotFound()); + + verify(ratingGameByUserRepository).findRatingGame_ByUserIdAndGameId(-1, 1); + verify(userRepository).findUserById(-1); + verify(gameRepository).findGameById(1); + } + + @Test + @WithMockUser(roles = "USER") + public void setGameRatingShouldReturnNotFound_SecondParameter() throws Exception { + when(ratingGameByUserRepository.findRatingGame_ByUserIdAndGameId(1, -1)).thenReturn(null); + when(userRepository.findUserById(1)).thenReturn(user); + when(gameRepository.findGameById(-1)).thenReturn(null); + + this.mockMvc.perform(MockMvcRequestBuilders.post(Gateway + "/1/set-game-rating/-1/1")) + .andDo(print()).andExpect(status().isNotFound()); + + verify(ratingGameByUserRepository).findRatingGame_ByUserIdAndGameId(1, -1); + verify(userRepository).findUserById(1); + verify(gameRepository).findGameById(-1); + } + + @Test + @WithMockUser(roles = "USER") + public void setGameRatingShouldReturnNotFound_BothParameters() throws Exception { + when(ratingGameByUserRepository.findRatingGame_ByUserIdAndGameId(-1, -1)).thenReturn(null); + when(userRepository.findUserById(-1)).thenReturn(null); + when(gameRepository.findGameById(-1)).thenReturn(null); + + this.mockMvc.perform(MockMvcRequestBuilders.post(Gateway + "/-1/set-game-rating/-1/1")) + .andDo(print()).andExpect(status().isNotFound()); + + verify(ratingGameByUserRepository).findRatingGame_ByUserIdAndGameId(-1, -1); + verify(userRepository).findUserById(-1); + verify(gameRepository).findGameById(-1); + } + + @Test + @WithMockUser(roles = "USER") + public void updateGameRatingShouldReturnOk() throws Exception { + + when(ratingGameByUserRepository.findRatingGame_ByUserIdAndGameId(1, 1)).thenReturn(ratingGameByUser); + when(ratingGameByUserRepository.save(ratingGameByUser)).thenReturn(null); + + var result = this.mockMvc.perform(MockMvcRequestBuilders.patch(Gateway + "/1/update-game-rating/1/10")) + .andDo(print()).andExpect(status().isOk()).andReturn(); + + var rating = objectMapper.readValue(result.getResponse().getContentAsByteArray(), Double.class); + + verify(ratingGameByUserRepository).findRatingGame_ByUserIdAndGameId(1, 1); + verify(ratingGameByUserRepository).save(ratingGameByUser); + Assertions.assertEquals(ratingGameByUser.getRating(), rating.doubleValue()); + } + + @Test + @WithMockUser(roles = "USER") + public void updateGameRatingShouldReturnBadRequestLessThanNormal() throws Exception { + this.mockMvc.perform(MockMvcRequestBuilders.patch(Gateway + "/1/update-game-rating/1/0")).andDo(print()).andExpect(status().isBadRequest()); + } + + @Test + @WithMockUser(roles = "USER") + public void updateGameRatingShouldReturnBadRequestMoreThanNormal() throws Exception { + this.mockMvc.perform(MockMvcRequestBuilders.patch(Gateway + "/1/update-game-rating/1/11")).andDo(print()).andExpect(status().isBadRequest()); + } + + @Test + @WithMockUser(roles = "USER") + public void updateGameRatingShouldReturnNotFound_FirstParameter() throws Exception { + when(ratingGameByUserRepository.findRatingGame_ByUserIdAndGameId(-1, 1)).thenReturn(null); + + this.mockMvc.perform(MockMvcRequestBuilders.patch(Gateway + "/-1/update-game-rating/1/1")) + .andDo(print()).andExpect(status().isNotFound()); + + verify(ratingGameByUserRepository).findRatingGame_ByUserIdAndGameId(-1, 1); + } + + @Test + @WithMockUser(roles = "USER") + public void updateGameRatingShouldReturnNotFound_SecondParameter() throws Exception { + when(ratingGameByUserRepository.findRatingGame_ByUserIdAndGameId(1, -1)).thenReturn(null); + + this.mockMvc.perform(MockMvcRequestBuilders.patch(Gateway + "/1/update-game-rating/-1/1")) + .andDo(print()).andExpect(status().isNotFound()); + + verify(ratingGameByUserRepository).findRatingGame_ByUserIdAndGameId(1, -1); + } + + @Test + @WithMockUser(roles = "USER") + public void updateGameRatingShouldReturnNotFound_BothParameters() throws Exception { + when(ratingGameByUserRepository.findRatingGame_ByUserIdAndGameId(-1, -1)).thenReturn(null); + + this.mockMvc.perform(MockMvcRequestBuilders.patch(Gateway + "/-1/update-game-rating/-1/1")) + .andDo(print()).andExpect(status().isNotFound()); + + verify(ratingGameByUserRepository).findRatingGame_ByUserIdAndGameId(-1, -1); + } + + @Test + @WithMockUser(roles = "USER") + public void addGameToUserShouldReturnOk() throws Exception { + + when(userRepository.findUserById(1)).thenReturn(user); + when(gameRepository.findGameById(1)).thenReturn(game); + when(gameRepository.findUserGames(1)).thenReturn(new ArrayList<>()); + when(userOwnGameRepository.save(any(UserOwnGame.class))).thenReturn(userOwnGame); + + var result = this.mockMvc.perform(MockMvcRequestBuilders.post(Gateway + "/1/add-game/1")) + .andDo(print()).andExpect(status().isOk()).andReturn().getResponse().getContentAsString(); + + verify(userRepository).findUserById(1); + verify(gameRepository).findGameById(1); + verify(gameRepository).findUserGames(1); + verify(userOwnGameRepository).save(any(UserOwnGame.class)); + + Assertions.assertNotEquals(0, result.length()); + } + + @Test + @WithMockUser(roles = "USER") + public void addGameToUserShouldReturnBadRequest() throws Exception { + when(userRepository.findUserById(1)).thenReturn(user); + when(gameRepository.findGameById(1)).thenReturn(game); + when(gameRepository.findUserGames(1)).thenReturn(games); + + this.mockMvc.perform(MockMvcRequestBuilders.post(Gateway + "/1/add-game/1")) + .andDo(print()).andExpect(status().isBadRequest()); + + verify(userRepository).findUserById(1); + verify(gameRepository).findGameById(1); + verify(gameRepository).findUserGames(1); + } + + @Test + @WithMockUser(roles = "USER") + public void addGameToUserShouldReturnStatusNotFound_FirstParameter() throws Exception { + when(userRepository.findUserById(-1)).thenReturn(null); + when(gameRepository.findGameById(1)).thenReturn(game); + + this.mockMvc.perform(MockMvcRequestBuilders.post(Gateway + "/-1/add-game/1")) + .andDo(print()).andExpect(status().isNotFound()); + + verify(userRepository).findUserById(-1); + verify(gameRepository).findGameById(1); + } + + @Test + @WithMockUser(roles = "USER") + public void addGameToUserShouldReturnStatusNotFound_SecondParameter() throws Exception { + when(userRepository.findUserById(1)).thenReturn(user); + when(gameRepository.findGameById(-1)).thenReturn(null); + + this.mockMvc.perform(MockMvcRequestBuilders.post(Gateway + "/1/add-game/-1")) + .andDo(print()).andExpect(status().isNotFound()); + + verify(userRepository).findUserById(1); + verify(gameRepository).findGameById(-1); + } + + @Test + @WithMockUser(roles = "USER") + public void addGameToUserShouldReturnStatusNotFound_BothParameters() throws Exception { + when(userRepository.findUserById(-1)).thenReturn(null); + when(gameRepository.findGameById(-1)).thenReturn(null); + + this.mockMvc.perform(MockMvcRequestBuilders.post(Gateway + "/-1/add-game/-1")) + .andDo(print()).andExpect(status().isNotFound()); + + verify(userRepository).findUserById(-1); + verify(gameRepository).findGameById(-1); + } + + @Test + @WithMockUser(roles = "USER") + public void addGameToUserShouldReturnStatusBadRequest_FirstParameter() throws Exception { + this.mockMvc.perform(MockMvcRequestBuilders.post(Gateway + "/bla/add-game/1")).andDo(print()).andExpect(status().isBadRequest()); + } + + @Test + @WithMockUser(roles = "USER") + public void addGameToUserShouldReturnStatusBadRequest_SecondParameter() throws Exception { + this.mockMvc.perform(MockMvcRequestBuilders.post(Gateway + "/1/add-game/bla")).andDo(print()).andExpect(status().isBadRequest()); + } + + @Test + @WithMockUser(roles = "USER") + public void addGameToUserShouldReturnStatusBadRequest_BothParameters() throws Exception { + this.mockMvc.perform(MockMvcRequestBuilders.post(Gateway + "/bla/add-game/bla")).andDo(print()).andExpect(status().isBadRequest()); + } + + @Test + @WithMockUser(roles = "USER") + public void deleteGameFromUserCollectionShouldReturnNotFound_FirstParameter() throws Exception { + when(userOwnGameRepository.findUserOwnGame_ByUserIdAndGameId(-1, 1)).thenReturn(null); + + this.mockMvc.perform(MockMvcRequestBuilders.delete(Gateway + "/-1/delete-game/1")) + .andDo(print()).andExpect(status().isNotFound()); + + verify(userOwnGameRepository).findUserOwnGame_ByUserIdAndGameId(-1, 1); + } + + @Test + @WithMockUser(roles = "USER") + public void deleteGameFromUserCollectionShouldReturnNotFound_SecondParameter() throws Exception { + when(userOwnGameRepository.findUserOwnGame_ByUserIdAndGameId(1, -1)).thenReturn(null); + + this.mockMvc.perform(MockMvcRequestBuilders.delete(Gateway + "/1/delete-game/-1")) + .andDo(print()).andExpect(status().isNotFound()); + + verify(userOwnGameRepository).findUserOwnGame_ByUserIdAndGameId(1, -1); + } + + @Test + @WithMockUser(roles = "USER") + public void deleteGameFromUserCollectionShouldReturnNotFound_BothParameters() throws Exception { + when(userOwnGameRepository.findUserOwnGame_ByUserIdAndGameId(-1, -1)).thenReturn(null); + + this.mockMvc.perform(MockMvcRequestBuilders.delete(Gateway + "/-1/delete-game/-1")) + .andDo(print()).andExpect(status().isNotFound()); + + verify(userOwnGameRepository).findUserOwnGame_ByUserIdAndGameId(-1, -1); + } + + @Test + @WithMockUser(roles = "USER") + public void deleteGameFromUserCollectionShouldReturnBadRequest_FirstParameter() throws Exception { + this.mockMvc.perform(MockMvcRequestBuilders.delete(Gateway + "/bla/delete-game/1")).andDo(print()).andExpect(status().isBadRequest()); + } + + @Test + @WithMockUser(roles = "USER") + public void deleteGameFromUserCollectionShouldReturnBadRequest_SecondParameter() throws Exception { + this.mockMvc.perform(MockMvcRequestBuilders.delete(Gateway + "/1/delete-game/bla")).andDo(print()).andExpect(status().isBadRequest()); + } + + @Test + @WithMockUser(roles = "USER") + public void deleteGameFromUserCollectionShouldReturnBadRequest_BothParameters() throws Exception { + this.mockMvc.perform(MockMvcRequestBuilders.delete(Gateway + "/bla/delete-game/bla")).andDo(print()).andExpect(status().isBadRequest()); + } + + @Test + @WithMockUser(roles = "USER") + public void deleteGameFromUserCollectionShouldReturnOk() throws Exception { + when(userOwnGameRepository.findUserOwnGame_ByUserIdAndGameId(1, 1)).thenReturn(userOwnGame); + doNothing().when(userOwnGameRepository).delete(userOwnGame); + + this.mockMvc.perform(MockMvcRequestBuilders.delete(Gateway + "/1/delete-game/1")) + .andDo(print()).andExpect(status().isOk()); + + verify(userOwnGameRepository).findUserOwnGame_ByUserIdAndGameId(1, 1); + verify(userOwnGameRepository).delete(userOwnGame); + } + + @Test + @WithMockUser(roles = "USER") + public void getUserWishlistShouldReturnIsOk() throws Exception { + when(gameRepository.findUserWishlist(1)).thenReturn(games); + when(gameService.entitiesToGameDTO(games)).thenReturn(gamesDTO); + + var mvcResult = this.mockMvc.perform(MockMvcRequestBuilders.get(Gateway + "/1/wishlist")) + .andExpect(status().isOk()).andReturn(); + + var response = objectMapper.readValue(mvcResult.getResponse().getContentAsByteArray(), GameDataDTO[].class); + + verify(gameRepository).findUserWishlist(1); + verify(gameService).entitiesToGameDTO(gameListArgumentCaptor.capture()); + + Assertions.assertEquals(response.length, gamesDTO.size()); + Assertions.assertEquals(response[0].getGame().id(), gamesDTO.get(0).getGame().id()); + Assertions.assertEquals(response[0].getRating(), gamesDTO.get(0).getRating()); + Assertions.assertEquals(gameListArgumentCaptor.getValue().size(), games.size()); + + } + + @Test + @WithMockUser(roles = "USER") + public void getUserWishlistShouldReturnBlankArray() throws Exception { + when(gameRepository.findUserWishlist(-1)).thenReturn(new ArrayList<>()); + when(gameService.entitiesToGameDTO(new ArrayList<>())).thenReturn(new ArrayList<>()); + var mvcResult = this.mockMvc.perform(MockMvcRequestBuilders.get(Gateway + "/-1/wishlist")).andExpect(status().isOk()).andReturn(); + var response = objectMapper.readValue(mvcResult.getResponse().getContentAsByteArray(), GameDataDTO[].class); + Assertions.assertEquals(0, response.length); + } + + @Test + @WithMockUser(roles = "USER") + public void getUserWishlistShouldReturnBadRequest() throws Exception { + this.mockMvc.perform(MockMvcRequestBuilders.get(Gateway + "/bla/wishlist")).andExpect(status().isBadRequest()); + } + + @Test + @WithMockUser(roles = "USER") + public void addGameToUserWishlistShouldReturnOk() throws Exception { + when(userRepository.findUserById(1)).thenReturn(user); + when(gameRepository.findGameById(1)).thenReturn(game); + when(userWishRepository.findByUserAndGame(user, game)).thenReturn(null); + when(userWishRepository.save(any(UserWish.class))).thenReturn(userWish); + + var response = this.mockMvc.perform(MockMvcRequestBuilders.post(Gateway + "/1/add-game-to-wishlist/1")) + .andDo(print()).andExpect(status().isOk()).andReturn().getResponse().getContentAsString(); + + verify(userRepository).findUserById(1); + verify(gameRepository).findGameById(1); + verify(userWishRepository).findByUserAndGame(user, game); + verify(userWishRepository).save(any(UserWish.class)); + + Assertions.assertNotEquals(response.length(), 0); + + } + + @Test + @WithMockUser(roles = "USER") + public void addGameToUserWishlistShouldReturnBadRequest_CheckOnDuplicates() throws Exception { + when(userRepository.findUserById(1)).thenReturn(user); + when(gameRepository.findGameById(1)).thenReturn(game); + when(userWishRepository.findByUserAndGame(user, game)).thenReturn(userWish); + + this.mockMvc.perform(MockMvcRequestBuilders.post(Gateway + "/1/add-game-to-wishlist/1")) + .andDo(print()).andExpect(status().isBadRequest()); + + verify(userRepository).findUserById(1); + verify(gameRepository).findGameById(1); + verify(userWishRepository).findByUserAndGame(user, game); + } + + @Test + @WithMockUser(roles = "USER") + public void addGameToUserWishlistShouldReturnStatusNotFound_FirstParameter() throws Exception { + when(userRepository.findUserById(-1)).thenReturn(null); + when(gameRepository.findGameById(1)).thenReturn(game); + + this.mockMvc.perform(MockMvcRequestBuilders.post(Gateway + "/-1/add-game-to-wishlist/1")) + .andDo(print()).andExpect(status().isNotFound()); + + verify(userRepository).findUserById(-1); + verify(gameRepository).findGameById(1); + } + + @Test + @WithMockUser(roles = "USER") + public void addGameToUserWishlistShouldReturnStatusNotFound_SecondParameter() throws Exception { + when(userRepository.findUserById(1)).thenReturn(user); + when(gameRepository.findGameById(-1)).thenReturn(null); + + this.mockMvc.perform(MockMvcRequestBuilders.post(Gateway + "/1/add-game-to-wishlist/-1")) + .andDo(print()).andExpect(status().isNotFound()); + + when(userRepository.findUserById(1)).thenReturn(user); + when(gameRepository.findGameById(-1)).thenReturn(null); + } + + @Test + @WithMockUser(roles = "USER") + public void addGameToUserWishlistShouldReturnStatusNotFound_BothParameters() throws Exception { + when(userRepository.findUserById(-1)).thenReturn(null); + when(gameRepository.findGameById(-1)).thenReturn(null); + + this.mockMvc.perform(MockMvcRequestBuilders.post(Gateway + "/-1/add-game-to-wishlist/-1")) + .andDo(print()).andExpect(status().isNotFound()); + + when(userRepository.findUserById(-1)).thenReturn(user); + when(gameRepository.findGameById(-1)).thenReturn(null); + } + + @Test + @WithMockUser(roles = "USER") + public void addGameToUserWishlistShouldReturnStatusBadRequest_FirstParameter() throws Exception { + this.mockMvc.perform(MockMvcRequestBuilders.post(Gateway + "/bla/add-game-to-wishlist/1")).andDo(print()).andExpect(status().isBadRequest()); + } + + @Test + @WithMockUser(roles = "USER") + public void addGameToUserWishlistShouldReturnStatusBadRequest_SecondParameter() throws Exception { + this.mockMvc.perform(MockMvcRequestBuilders.post(Gateway + "/1/add-game-to-wishlist/bla")).andDo(print()).andExpect(status().isBadRequest()); + } + + @Test + @WithMockUser(roles = "USER") + public void addGameToUserWishlistShouldReturnStatusBadRequest_BothParameters() throws Exception { + this.mockMvc.perform(MockMvcRequestBuilders.post(Gateway + "/bla/add-game-to-wishlist/bla")).andDo(print()).andExpect(status().isBadRequest()); + } + + @Test + @WithMockUser(roles = "USER") + public void deleteGameFromUserWishlistShouldReturnOk() throws Exception { + when(userWishRepository.findById(1)).thenReturn(java.util.Optional.ofNullable(userWish)); + doNothing().when(userWishRepository).delete(userWish); + + var result = this.mockMvc.perform(MockMvcRequestBuilders.delete(Gateway + "/delete-game-from-wishlist/1")) + .andDo(print()).andExpect(status().isOk()).andReturn(); + + var response = objectMapper.readValue(result.getResponse().getContentAsByteArray(), boolean.class); + + verify(userWishRepository).findById(1); + verify(userWishRepository).delete(userWish); + + Assertions.assertEquals(true, response); + + } + + @Test + @WithMockUser(roles = "USER") + public void deleteGameFromUserWishlistShouldReturnNotFound() throws Exception { + when(userWishRepository.findById(1)).thenReturn(Optional.empty()); + + var result = this.mockMvc.perform(MockMvcRequestBuilders.delete(Gateway + "/delete-game-from-wishlist/1")) + .andDo(print()).andExpect(status().isNotFound()).andReturn(); + + var response = objectMapper.readValue(result.getResponse().getContentAsByteArray(), boolean.class); + + verify(userWishRepository).findById(1); + + Assertions.assertEquals(false, response); + + } + + @Test + @WithMockUser(roles = "USER") + public void deleteGameFromUserWishlistShouldReturnBadRequest() throws Exception { + this.mockMvc.perform(MockMvcRequestBuilders.delete(Gateway + "/delete-game-from-wishlist/bla-bla")) + .andDo(print()).andExpect(status().isBadRequest()); + + } + + @Test + @WithMockUser(roles = "USER") + public void addGameToSellListShouldReturnOk() throws Exception { + + when(userRepository.findUserById(1)).thenReturn(user); + when(gameRepository.findGameById(1)).thenReturn(game); + when(gameSellRepository.save(any(GameSell.class))).thenReturn(null); + when(gameRepository.getGameSellList(1)).thenReturn(gameSellProjectionList); + when(gameSellService.projectionsToGameSellDTO(gameSellProjectionList)).thenReturn(gameSellDTOList); + + var mvcResult = this.mockMvc.perform(MockMvcRequestBuilders.post(Gateway + "/1/add-game-to-sell/1") + .contentType(MediaType.APPLICATION_JSON) + .accept(MediaType.APPLICATION_JSON) + .content(objectMapper.writeValueAsString(gameSell))) + .andDo(print()).andExpect(status().isOk()).andReturn(); + + var response = objectMapper.readValue(mvcResult.getResponse().getContentAsByteArray(), GameSellDTO[].class); + + verify(userRepository).findUserById(1); + verify(gameRepository).findGameById(1); + verify(gameSellRepository).save(any(GameSell.class)); + verify(gameRepository).getGameSellList(1); + verify(gameSellService).projectionsToGameSellDTO(gameSellProjectionList); + + Assertions.assertEquals(response.length, gameSellDTOList.size()); + Assertions.assertEquals(response[0].getGame().id(), gameSellDTOList.get(0).getGame().id()); + } + + @Test + @WithMockUser(roles = "USER") + public void addGameToSellListShouldReturnBadRequest_Duplicates() throws Exception { + + gameSell.setId(1); + this.mockMvc.perform(MockMvcRequestBuilders.post(Gateway + "/1/add-game-to-sell/1") + .contentType(MediaType.APPLICATION_JSON) + .accept(MediaType.APPLICATION_JSON) + .content(objectMapper.writeValueAsString(gameSell))) + .andDo(print()).andExpect(status().isBadRequest()); + gameSell.setId(null); + } + + @Test + @WithMockUser(roles = "USER") + public void addGameToSellListShouldReturnNotFound_FirstParameter() throws Exception { + + when(userRepository.findUserById(-1)).thenReturn(null); + when(gameRepository.findGameById(1)).thenReturn(game); + + this.mockMvc.perform(MockMvcRequestBuilders.post(Gateway + "/-1/add-game-to-sell/1") + .contentType(MediaType.APPLICATION_JSON) + .accept(MediaType.APPLICATION_JSON) + .content(objectMapper.writeValueAsString(gameSell))) + .andDo(print()).andExpect(status().isNotFound()); + + verify(userRepository).findUserById(-1); + verify(gameRepository).findGameById(1); + } + + @Test + @WithMockUser(roles = "USER") + public void addGameToSellListShouldReturnNotFound_SecondParameter() throws Exception { + + when(userRepository.findUserById(1)).thenReturn(user); + when(gameRepository.findGameById(-1)).thenReturn(null); + + this.mockMvc.perform(MockMvcRequestBuilders.post(Gateway + "/1/add-game-to-sell/-1") + .contentType(MediaType.APPLICATION_JSON) + .accept(MediaType.APPLICATION_JSON) + .content(objectMapper.writeValueAsString(gameSell))) + .andDo(print()).andExpect(status().isNotFound()); + + verify(userRepository).findUserById(1); + verify(gameRepository).findGameById(-1); + } + + @Test + @WithMockUser(roles = "USER") + public void addGameToSellListShouldReturnNotFound_BothParameters() throws Exception { + + when(userRepository.findUserById(-1)).thenReturn(null); + when(gameRepository.findGameById(-1)).thenReturn(null); + + this.mockMvc.perform(MockMvcRequestBuilders.post(Gateway + "/-1/add-game-to-sell/-1") + .contentType(MediaType.APPLICATION_JSON) + .accept(MediaType.APPLICATION_JSON) + .content(objectMapper.writeValueAsString(gameSell))) + .andDo(print()).andExpect(status().isNotFound()); + + verify(userRepository).findUserById(-1); + verify(gameRepository).findGameById(-1); + } + + @Test + public void getGameSellListShouldReturnOk() throws Exception { + + when(gameRepository.getGameSellList(1)).thenReturn(gameSellProjectionList); + when(gameSellService.projectionsToGameSellDTO(gameSellProjectionList)).thenReturn(gameSellDTOList); + + var result = this.mockMvc.perform(MockMvcRequestBuilders.get(Gateway + "/1/games-to-sell")) + .andDo(print()).andExpect(status().isOk()).andReturn(); + + var response = objectMapper.readValue(result.getResponse().getContentAsByteArray(), GameSellDTO[].class); + + verify(gameRepository).getGameSellList(1); + verify(gameSellService).projectionsToGameSellDTO(gameSellProjectionList); + + Assertions.assertEquals(response.length, gameSellDTOList.size()); + Assertions.assertEquals(response[0].getGame().id(), gameSellDTOList.get(0).getGame().id()); + + } + + @Test + public void getGameSellListShouldReturnBlankArray() throws Exception { + + when(gameRepository.getGameSellList(1)).thenReturn(new ArrayList<>()); + when(gameSellService.projectionsToGameSellDTO(new ArrayList<>())).thenReturn(new ArrayList<>()); + + var result = this.mockMvc.perform(MockMvcRequestBuilders.get(Gateway + "/1/games-to-sell")) + .andDo(print()).andExpect(status().isOk()).andReturn(); + + var response = objectMapper.readValue(result.getResponse().getContentAsByteArray(), GameSellDTO[].class); + + verify(gameRepository).getGameSellList(1); + verify(gameSellService).projectionsToGameSellDTO(new ArrayList<>()); + + Assertions.assertEquals(response.length, 0); + } + + @Test + @WithMockUser(roles = "USER") + public void removeGameFromSellShouldReturnOk() throws Exception { + when(gameSellRepository.findGameSell_ByUserIdAndGameId(1, 1)).thenReturn(gameSell); + doNothing().when(gameSellRepository).delete(gameSell); + + this.mockMvc.perform(MockMvcRequestBuilders.delete(Gateway + "/1/remove-game-from-sell/1")) + .andDo(print()).andExpect(status().isOk()); + + verify(gameSellRepository).findGameSell_ByUserIdAndGameId(1, 1); + verify(gameSellRepository).delete(gameSell); + } + + @Test + @WithMockUser(roles = "USER") + public void removeGameFromSellShouldReturnNotFound_FirstParameter() throws Exception { + when(gameSellRepository.findGameSell_ByUserIdAndGameId(-1, 1)).thenReturn(null); + + this.mockMvc.perform(MockMvcRequestBuilders.delete(Gateway + "/-1/remove-game-from-sell/1")) + .andDo(print()).andExpect(status().isNotFound()); + + verify(gameSellRepository).findGameSell_ByUserIdAndGameId(-1, 1); + } + + @Test + @WithMockUser(roles = "USER") + public void removeGameFromSellShouldReturnNotFound_SecondParameter() throws Exception { + when(gameSellRepository.findGameSell_ByUserIdAndGameId(1, -1)).thenReturn(null); + + this.mockMvc.perform(MockMvcRequestBuilders.delete(Gateway + "/1/remove-game-from-sell/-1")) + .andDo(print()).andExpect(status().isNotFound()); + + verify(gameSellRepository).findGameSell_ByUserIdAndGameId(1, -1); + } + + @Test + @WithMockUser(roles = "USER") + public void removeGameFromSellShouldReturnNotFound_BothParameters() throws Exception { + when(gameSellRepository.findGameSell_ByUserIdAndGameId(-1, -1)).thenReturn(null); + + this.mockMvc.perform(MockMvcRequestBuilders.delete(Gateway + "/-1/remove-game-from-sell/-1")) + .andDo(print()).andExpect(status().isNotFound()); + + verify(gameSellRepository).findGameSell_ByUserIdAndGameId(-1, -1); + } + + @Test + @WithMockUser(roles = "USER") + public void updateSellGameShouldReturnOk() throws Exception { + when(gameSellRepository.save(any(GameSell.class))).thenReturn(null); + gameSell.setId(1); + + var res = this.mockMvc.perform(MockMvcRequestBuilders.put(Gateway + "/update-game-to-sell") + .contentType(MediaType.APPLICATION_JSON) + .accept(MediaType.APPLICATION_JSON) + .content(objectMapper.writeValueAsString(gameSell))) + .andDo(print()).andExpect(status().isOk()).andReturn().getResponse().getContentAsString(); + + verify(gameSellRepository).save(any(GameSell.class)); + + gameSell.setId(null); + + Assertions.assertNotEquals(0, res.length()); + + } + + @Test + @WithMockUser(roles = "USER") + public void updateSellGameShouldReturnBadRequest_IdIsNull() throws Exception { + + this.mockMvc.perform(MockMvcRequestBuilders.put(Gateway + "/update-game-to-sell") + .contentType(MediaType.APPLICATION_JSON) + .accept(MediaType.APPLICATION_JSON) + .content(objectMapper.writeValueAsString(gameSell))) + .andDo(print()).andExpect(status().isBadRequest()); + + } + + @Test + @WithMockUser(roles = "USER") + public void updateSellGameShouldReturnBadRequest_GameIsNull() throws Exception { + + this.gameSell.setGame(null); + + this.mockMvc.perform(MockMvcRequestBuilders.put(Gateway + "/update-game-to-sell") + .contentType(MediaType.APPLICATION_JSON) + .accept(MediaType.APPLICATION_JSON) + .content(objectMapper.writeValueAsString(gameSell))) + .andDo(print()).andExpect(status().isBadRequest()); + + this.gameSell.setGame(game); + + } + + @Test + @WithMockUser(roles = "USER") + public void updateSellGameShouldReturnBadRequest_UserIsNull() throws Exception { + + this.gameSell.setUser(null); + + this.mockMvc.perform(MockMvcRequestBuilders.put(Gateway + "/update-game-to-sell") + .contentType(MediaType.APPLICATION_JSON) + .accept(MediaType.APPLICATION_JSON) + .content(objectMapper.writeValueAsString(gameSell))) + .andDo(print()).andExpect(status().isBadRequest()); + + this.gameSell.setUser(user); + + } + + @Test + @WithMockUser(roles = "USER") + public void addDiaryShouldReturnIsOk() throws Exception { + when(userRepository.findUserById(1)).thenReturn(user); + when(gameRepository.findGameById(1)).thenReturn(game); + when(diaryRepository.save(any(Diary.class))).thenReturn(diary); + when(diaryService.entityToDiaryDTO(any(Diary.class))).thenReturn(diaryDTO); + + + var mvcRes = this.mockMvc.perform(MockMvcRequestBuilders.post(Gateway + "/1/add-diary/1") + .contentType(MediaType.APPLICATION_JSON) + .accept(MediaType.APPLICATION_JSON) + .content(objectMapper.writeValueAsString(diary))) + .andDo(print()).andExpect(status().isOk()).andReturn(); + + var response = objectMapper.readValue(mvcRes.getResponse().getContentAsByteArray(), DiaryDataDTO.class); + + verify(userRepository).findUserById(1); + verify(gameRepository).findGameById(1); + verify(diaryRepository).save(any(Diary.class)); + verify(diaryService).entityToDiaryDTO(any(Diary.class)); + + Assertions.assertEquals(diaryDTO.getDiary().id(), response.getDiary().id()); + + } + + @Test + @WithMockUser(roles = "USER") + public void addDiaryShouldReturnNotFound_FirstParameter() throws Exception { + when(userRepository.findUserById(-1)).thenReturn(null); + when(gameRepository.findGameById(1)).thenReturn(game); + + this.mockMvc.perform(MockMvcRequestBuilders.post(Gateway + "/-1/add-diary/1") + .contentType(MediaType.APPLICATION_JSON) + .accept(MediaType.APPLICATION_JSON) + .content(objectMapper.writeValueAsString(diary))) + .andDo(print()).andExpect(status().isNotFound()); + + verify(userRepository).findUserById(-1); + verify(gameRepository).findGameById(1); + + } + + @Test + @WithMockUser(roles = "USER") + public void addDiaryShouldReturnNotFound_SecondParameter() throws Exception { + when(userRepository.findUserById(1)).thenReturn(user); + when(gameRepository.findGameById(-1)).thenReturn(null); + + this.mockMvc.perform(MockMvcRequestBuilders.post(Gateway + "/1/add-diary/-1") + .contentType(MediaType.APPLICATION_JSON) + .accept(MediaType.APPLICATION_JSON) + .content(objectMapper.writeValueAsString(diary))) + .andDo(print()).andExpect(status().isNotFound()); + + verify(userRepository).findUserById(1); + verify(gameRepository).findGameById(-1); + + } + + @Test + @WithMockUser(roles = "USER") + public void addDiaryShouldReturnNotFound_BothParameters() throws Exception { + when(userRepository.findUserById(-1)).thenReturn(null); + when(gameRepository.findGameById(-1)).thenReturn(null); + + this.mockMvc.perform(MockMvcRequestBuilders.post(Gateway + "/-1/add-diary/-1") + .contentType(MediaType.APPLICATION_JSON) + .accept(MediaType.APPLICATION_JSON) + .content(objectMapper.writeValueAsString(diary))) + .andDo(print()).andExpect(status().isNotFound()); + + verify(userRepository).findUserById(-1); + verify(gameRepository).findGameById(-1); + + } + + @Test + @WithMockUser(roles = "USER") + public void addDiaryShouldReturnBadRequest_InvalidInput() throws Exception { + + this.mockMvc.perform(MockMvcRequestBuilders.post(Gateway + "/1/add-diary/1") + .contentType(MediaType.APPLICATION_JSON) + .accept(MediaType.APPLICATION_JSON) + .content(objectMapper.writeValueAsString(null))) + .andDo(print()).andExpect(status().isBadRequest()); + + } + + @Test + @WithMockUser(roles = "USER") + public void deleteDiaryShouldReturnOk() throws Exception { + when(diaryRepository.findDiary_ByUserIdAndId(1, 1)).thenReturn(diary); + doNothing().when(diaryRepository).delete(diary); + + var res = this.mockMvc.perform(MockMvcRequestBuilders.delete(Gateway + "/1/remove-diary/1")) + .andDo(print()).andExpect(status().isOk()).andReturn().getResponse().getContentAsString(); + + verify(diaryRepository).findDiary_ByUserIdAndId(1, 1); + verify(diaryRepository).delete(diary); + + Assertions.assertNotEquals(0, res.length()); + } + + @Test + public void deleteDiaryShouldReturnUnauthorized() throws Exception { + this.mockMvc.perform(MockMvcRequestBuilders.delete(Gateway + "/1/remove-diary/1")) + .andDo(print()).andExpect(status().isUnauthorized()); + } + + @Test + @WithMockUser(roles = "USER") + public void deleteDiaryShouldReturnNotFound_FirstParameter() throws Exception { + when(diaryRepository.findDiary_ByUserIdAndId(-1, 1)).thenReturn(null); + this.mockMvc.perform(MockMvcRequestBuilders.delete(Gateway + "/-1/remove-diary/1")) + .andDo(print()).andExpect(status().isNotFound()).andReturn().getResponse().getContentAsString(); + + verify(diaryRepository).findDiary_ByUserIdAndId(-1, 1); + } + + @Test + @WithMockUser(roles = "USER") + public void deleteDiaryShouldReturnNotFound_SecondParameter() throws Exception { + when(diaryRepository.findDiary_ByUserIdAndId(1, -1)).thenReturn(null); + this.mockMvc.perform(MockMvcRequestBuilders.delete(Gateway + "/1/remove-diary/-1")) + .andDo(print()).andExpect(status().isNotFound()).andReturn().getResponse().getContentAsString(); + + verify(diaryRepository).findDiary_ByUserIdAndId(1, -1); + } + + @Test + @WithMockUser(roles = "USER") + public void deleteDiaryShouldReturnNotFound_BothParameters() throws Exception { + when(diaryRepository.findDiary_ByUserIdAndId(-1, -1)).thenReturn(null); + this.mockMvc.perform(MockMvcRequestBuilders.delete(Gateway + "/-1/remove-diary/-1")) + .andDo(print()).andExpect(status().isNotFound()).andReturn().getResponse().getContentAsString(); + + verify(diaryRepository).findDiary_ByUserIdAndId(-1, -1); + } + + @Test + @WithMockUser(roles = "USER") + public void updateDiaryShouldReturnIsOk() throws Exception { + when(diaryRepository.findDiary_ByUserIdAndId(1, 1)).thenReturn(diary); + when(diaryRepository.save(any(Diary.class))).thenReturn(diary); + when(diaryService.entityToDiaryDTO(any(Diary.class))).thenReturn(diaryDTO); + + diary.setId(1); + var mvcRes = this.mockMvc.perform(MockMvcRequestBuilders.put(Gateway + "/1/update-diary/1") + .contentType(MediaType.APPLICATION_JSON) + .accept(MediaType.APPLICATION_JSON) + .content(objectMapper.writeValueAsString(diary))) + .andDo(print()).andExpect(status().isOk()).andReturn(); + + var response = objectMapper.readValue(mvcRes.getResponse().getContentAsByteArray(), DiaryDataDTO.class); + + verify(diaryRepository).findDiary_ByUserIdAndId(1, 1); + verify(diaryRepository).save(any(Diary.class)); + verify(diaryService).entityToDiaryDTO(any(Diary.class)); + + Assertions.assertEquals(diaryDTO.getDiary().id(), response.getDiary().id()); + + diary.setId(null); + } + + @Test + public void updateDiaryShouldReturnUnauthorized() throws Exception { + this.mockMvc.perform(MockMvcRequestBuilders.put(Gateway + "/1/update-diary/1") + .contentType(MediaType.APPLICATION_JSON) + .accept(MediaType.APPLICATION_JSON) + .content(objectMapper.writeValueAsString(diary))) + .andDo(print()).andExpect(status().isUnauthorized()); + } + + @Test + @WithMockUser(roles = "USER") + public void updateDiaryShouldReturnBadRequest_NotValidInput() throws Exception { + this.mockMvc.perform(MockMvcRequestBuilders.put(Gateway + "/1/update-diary/1") + .contentType(MediaType.APPLICATION_JSON) + .accept(MediaType.APPLICATION_JSON) + .content(objectMapper.writeValueAsString(diary))) + .andDo(print()).andExpect(status().isBadRequest()); + } + + @Test + @WithMockUser(roles = "USER") + public void updateDiaryShouldReturnIsNotFound_FirstParameter() throws Exception { + when(diaryRepository.findDiary_ByUserIdAndId(-1, 1)).thenReturn(null); + + diary.setId(1); + this.mockMvc.perform(MockMvcRequestBuilders.put(Gateway + "/-1/update-diary/1") + .contentType(MediaType.APPLICATION_JSON) + .accept(MediaType.APPLICATION_JSON) + .content(objectMapper.writeValueAsString(diary))) + .andDo(print()).andExpect(status().isNotFound()); + + verify(diaryRepository).findDiary_ByUserIdAndId(-1, 1); + diary.setId(null); + } + + @Test + @WithMockUser(roles = "USER") + public void updateDiaryShouldReturnIsNotFound_SecondParameter() throws Exception { + when(diaryRepository.findDiary_ByUserIdAndId(1, -1)).thenReturn(null); + + diary.setId(1); + this.mockMvc.perform(MockMvcRequestBuilders.put(Gateway + "/1/update-diary/-1") + .contentType(MediaType.APPLICATION_JSON) + .accept(MediaType.APPLICATION_JSON) + .content(objectMapper.writeValueAsString(diary))) + .andDo(print()).andExpect(status().isNotFound()); + + verify(diaryRepository).findDiary_ByUserIdAndId(1, -1); + diary.setId(null); + } + + @Test + @WithMockUser(roles = "USER") + public void updateDiaryShouldReturnIsNotFound_BothParameters() throws Exception { + when(diaryRepository.findDiary_ByUserIdAndId(-1, -1)).thenReturn(null); + + diary.setId(1); + this.mockMvc.perform(MockMvcRequestBuilders.put(Gateway + "/-1/update-diary/-1") + .contentType(MediaType.APPLICATION_JSON) + .accept(MediaType.APPLICATION_JSON) + .content(objectMapper.writeValueAsString(diary))) + .andDo(print()).andExpect(status().isNotFound()); + + verify(diaryRepository).findDiary_ByUserIdAndId(-1, -1); + diary.setId(null); + } + +}*/ diff --git a/src/test/java/com/petproject/boardgamefun/model/DesignerPOJO.java b/src/test/java/com/petproject/boardgamefun/model/DesignerPOJO.java new file mode 100644 index 0000000..1a9d1f4 --- /dev/null +++ b/src/test/java/com/petproject/boardgamefun/model/DesignerPOJO.java @@ -0,0 +1,15 @@ +package com.petproject.boardgamefun.model; + +import com.petproject.boardgamefun.dto.projection.DesignersProjection; +import lombok.AllArgsConstructor; + +@AllArgsConstructor +public class DesignerPOJO implements DesignersProjection { + + private String designer; + + @Override + public String getDesigner() { + return designer; + } +} diff --git a/src/test/java/com/petproject/boardgamefun/model/GamePOJO.java b/src/test/java/com/petproject/boardgamefun/model/GamePOJO.java new file mode 100644 index 0000000..d72464e --- /dev/null +++ b/src/test/java/com/petproject/boardgamefun/model/GamePOJO.java @@ -0,0 +1,22 @@ +package com.petproject.boardgamefun.model; + +import com.petproject.boardgamefun.dto.projection.GameProjection; +import lombok.AllArgsConstructor; + +@AllArgsConstructor +public class GamePOJO implements GameProjection { + private Game game; + + private Double rating; + + + @Override + public Game getGame() { + return game; + } + + @Override + public Double getRating() { + return rating; + } +} diff --git a/src/test/java/com/petproject/boardgamefun/model/GameSellPOJO.java b/src/test/java/com/petproject/boardgamefun/model/GameSellPOJO.java new file mode 100644 index 0000000..4e1899d --- /dev/null +++ b/src/test/java/com/petproject/boardgamefun/model/GameSellPOJO.java @@ -0,0 +1,33 @@ +package com.petproject.boardgamefun.model; + +import com.petproject.boardgamefun.dto.projection.GameSellProjection; +import lombok.AllArgsConstructor; + +@AllArgsConstructor +public class GameSellPOJO implements GameSellProjection { + + private Game game; + private String condition; + private String comment; + private Integer price; + + @Override + public Game getGame() { + return game; + } + + @Override + public String getCondition() { + return condition; + } + + @Override + public String getComment() { + return comment; + } + + @Override + public Integer getPrice() { + return price; + } +} diff --git a/src/test/java/com/petproject/boardgamefun/model/GameTitlePOJO.java b/src/test/java/com/petproject/boardgamefun/model/GameTitlePOJO.java new file mode 100644 index 0000000..e2d4770 --- /dev/null +++ b/src/test/java/com/petproject/boardgamefun/model/GameTitlePOJO.java @@ -0,0 +1,21 @@ +package com.petproject.boardgamefun.model; + +import com.petproject.boardgamefun.dto.projection.GamesFilterByTitleProjection; +import lombok.AllArgsConstructor; + +@AllArgsConstructor +public class GameTitlePOJO implements GamesFilterByTitleProjection { + + private String title; + private Integer id; + + @Override + public String getTitle() { + return title; + } + + @Override + public Integer getId() { + return id; + } +} diff --git a/src/test/java/com/petproject/boardgamefun/model/UserGameRatingPOJO.java b/src/test/java/com/petproject/boardgamefun/model/UserGameRatingPOJO.java new file mode 100644 index 0000000..0b12e34 --- /dev/null +++ b/src/test/java/com/petproject/boardgamefun/model/UserGameRatingPOJO.java @@ -0,0 +1,23 @@ +package com.petproject.boardgamefun.model; + +import com.petproject.boardgamefun.dto.projection.UserGameRatingProjection; +import lombok.AllArgsConstructor; +import lombok.Data; + +@Data +@AllArgsConstructor +public class UserGameRatingPOJO implements UserGameRatingProjection { + + Game game; + Integer rating; + + @Override + public Game getGame() { + return game; + } + + @Override + public Integer getRating() { + return rating; + } +} diff --git a/src/test/java/com/petproject/boardgamefun/model/UsersGameRatingProjectionPOJO.java b/src/test/java/com/petproject/boardgamefun/model/UsersGameRatingProjectionPOJO.java new file mode 100644 index 0000000..04d2c47 --- /dev/null +++ b/src/test/java/com/petproject/boardgamefun/model/UsersGameRatingProjectionPOJO.java @@ -0,0 +1,20 @@ +package com.petproject.boardgamefun.model; + +import com.petproject.boardgamefun.dto.projection.UsersGameRatingProjection; +import lombok.AllArgsConstructor; + +@AllArgsConstructor +public class UsersGameRatingProjectionPOJO implements UsersGameRatingProjection { + private User user; + private Double rating; + + @Override + public User getUser() { + return user; + } + + @Override + public Double getRating() { + return rating; + } +} diff --git a/src/test/resources/mockito-extensions/org.mockito.plugins.MockMaker b/src/test/resources/mockito-extensions/org.mockito.plugins.MockMaker new file mode 100644 index 0000000..ca6ee9c --- /dev/null +++ b/src/test/resources/mockito-extensions/org.mockito.plugins.MockMaker @@ -0,0 +1 @@ +mock-maker-inline \ No newline at end of file