From 6953a5c4bf44966cb66c942c14b5844fb611f536 Mon Sep 17 00:00:00 2001 From: "i.i.artamonov" Date: Tue, 16 Nov 2021 21:58:01 +0400 Subject: [PATCH 001/141] Entities added --- .jpb/jpb-settings.xml | 6 + pom.xml | 4 + .../boardgamefun/model/Category.java | 34 +++++ .../boardgamefun/model/Designer.java | 34 +++++ .../petproject/boardgamefun/model/Diary.java | 80 ++++++++++++ .../boardgamefun/model/DiaryComment.java | 68 ++++++++++ .../boardgamefun/model/DiaryRating.java | 55 ++++++++ .../boardgamefun/model/Expansion.java | 44 +++++++ .../petproject/boardgamefun/model/File.java | 55 ++++++++ .../petproject/boardgamefun/model/Forum.java | 80 ++++++++++++ .../boardgamefun/model/ForumMessage.java | 68 ++++++++++ .../petproject/boardgamefun/model/Game.java | 117 ++++++++++++++++++ .../boardgamefun/model/GameByDesigner.java | 44 +++++++ .../boardgamefun/model/GameCategory.java | 44 +++++++ .../boardgamefun/model/GameSell.java | 79 ++++++++++++ .../petproject/boardgamefun/model/Image.java | 31 +++++ .../boardgamefun/model/ImageBinder.java | 92 ++++++++++++++ .../boardgamefun/model/Messenger.java | 79 ++++++++++++ .../petproject/boardgamefun/model/News.java | 20 +++ .../boardgamefun/model/NewsComment.java | 68 ++++++++++ .../boardgamefun/model/NewsRating.java | 55 ++++++++ .../boardgamefun/model/RatingGameByUser.java | 55 ++++++++ .../boardgamefun/model/SameGame.java | 44 +++++++ .../petproject/boardgamefun/model/User.java | 113 +++++++++++++++++ .../boardgamefun/model/UserOwnGame.java | 44 +++++++ .../boardgamefun/model/UserRating.java | 67 ++++++++++ .../boardgamefun/model/UserWish.java | 44 +++++++ 27 files changed, 1524 insertions(+) create mode 100644 .jpb/jpb-settings.xml create mode 100644 src/main/java/com/petproject/boardgamefun/model/Category.java create mode 100644 src/main/java/com/petproject/boardgamefun/model/Designer.java create mode 100644 src/main/java/com/petproject/boardgamefun/model/Diary.java create mode 100644 src/main/java/com/petproject/boardgamefun/model/DiaryComment.java create mode 100644 src/main/java/com/petproject/boardgamefun/model/DiaryRating.java create mode 100644 src/main/java/com/petproject/boardgamefun/model/Expansion.java create mode 100644 src/main/java/com/petproject/boardgamefun/model/File.java create mode 100644 src/main/java/com/petproject/boardgamefun/model/Forum.java create mode 100644 src/main/java/com/petproject/boardgamefun/model/ForumMessage.java create mode 100644 src/main/java/com/petproject/boardgamefun/model/Game.java create mode 100644 src/main/java/com/petproject/boardgamefun/model/GameByDesigner.java create mode 100644 src/main/java/com/petproject/boardgamefun/model/GameCategory.java create mode 100644 src/main/java/com/petproject/boardgamefun/model/GameSell.java create mode 100644 src/main/java/com/petproject/boardgamefun/model/Image.java create mode 100644 src/main/java/com/petproject/boardgamefun/model/ImageBinder.java create mode 100644 src/main/java/com/petproject/boardgamefun/model/Messenger.java create mode 100644 src/main/java/com/petproject/boardgamefun/model/News.java create mode 100644 src/main/java/com/petproject/boardgamefun/model/NewsComment.java create mode 100644 src/main/java/com/petproject/boardgamefun/model/NewsRating.java create mode 100644 src/main/java/com/petproject/boardgamefun/model/RatingGameByUser.java create mode 100644 src/main/java/com/petproject/boardgamefun/model/SameGame.java create mode 100644 src/main/java/com/petproject/boardgamefun/model/User.java create mode 100644 src/main/java/com/petproject/boardgamefun/model/UserOwnGame.java create mode 100644 src/main/java/com/petproject/boardgamefun/model/UserRating.java create mode 100644 src/main/java/com/petproject/boardgamefun/model/UserWish.java 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..09be647 100644 --- a/pom.xml +++ b/pom.xml @@ -21,6 +21,10 @@ + + + + org.springframework.boot 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..9af5c94 --- /dev/null +++ b/src/main/java/com/petproject/boardgamefun/model/Category.java @@ -0,0 +1,34 @@ +package com.petproject.boardgamefun.model; + +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 + @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..59efe1a --- /dev/null +++ b/src/main/java/com/petproject/boardgamefun/model/Designer.java @@ -0,0 +1,34 @@ +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; + + @Lob + @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..3ffd3d8 --- /dev/null +++ b/src/main/java/com/petproject/boardgamefun/model/Diary.java @@ -0,0 +1,80 @@ +package com.petproject.boardgamefun.model; + +import javax.persistence.*; +import java.time.OffsetTime; + +@Table(name = "diary") +@Entity +public class Diary { + @Id + @GeneratedValue(strategy = GenerationType.IDENTITY) + @Column(name = "id", nullable = false) + private Integer id; + + @Lob + @Column(name = "title", nullable = false) + private String title; + + @Lob + @Column(name = "text", nullable = false) + private String text; + + @Column(name = "publication_time", nullable = false) + private OffsetTime 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 OffsetTime getPublicationTime() { + return publicationTime; + } + + public void setPublicationTime(OffsetTime 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..be62aaf --- /dev/null +++ b/src/main/java/com/petproject/boardgamefun/model/DiaryComment.java @@ -0,0 +1,68 @@ +package com.petproject.boardgamefun.model; + +import javax.persistence.*; +import java.time.OffsetTime; + +@Table(name = "diary_comment") +@Entity +public class DiaryComment { + @Id + @GeneratedValue(strategy = GenerationType.IDENTITY) + @Column(name = "id", nullable = false) + private Integer id; + + @Lob + @Column(name = "comment", nullable = false) + private String comment; + + @Column(name = "comment_time", nullable = false) + private OffsetTime 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 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/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..e5f6745 --- /dev/null +++ b/src/main/java/com/petproject/boardgamefun/model/Forum.java @@ -0,0 +1,80 @@ +package com.petproject.boardgamefun.model; + +import javax.persistence.*; +import java.time.OffsetTime; + +@Table(name = "forum") +@Entity +public class Forum { + @Id + @GeneratedValue(strategy = GenerationType.IDENTITY) + @Column(name = "id", nullable = false) + private Integer id; + + @Lob + @Column(name = "title", nullable = false) + private String title; + + @Lob + @Column(name = "text", nullable = false) + private String text; + + @Column(name = "publication_time", nullable = false) + private OffsetTime 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 OffsetTime getPublicationTime() { + return publicationTime; + } + + public void setPublicationTime(OffsetTime 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..b64c39f --- /dev/null +++ b/src/main/java/com/petproject/boardgamefun/model/ForumMessage.java @@ -0,0 +1,68 @@ +package com.petproject.boardgamefun.model; + +import javax.persistence.*; +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 + @Column(name = "comment", nullable = false) + private String comment; + + @ManyToOne(optional = false) + @JoinColumn(name = "\"user\"", nullable = false) + private User user; + + @Column(name = "\"time\"", nullable = false) + private OffsetTime time; + + public OffsetTime getTime() { + return time; + } + + public void setTime(OffsetTime 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/Game.java b/src/main/java/com/petproject/boardgamefun/model/Game.java new file mode 100644 index 0000000..c2ae84e --- /dev/null +++ b/src/main/java/com/petproject/boardgamefun/model/Game.java @@ -0,0 +1,117 @@ +package com.petproject.boardgamefun.model; + +import javax.persistence.*; +import java.time.OffsetTime; + +@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; + + @Lob + @Column(name = "title", nullable = false) + private String title; + + @Column(name = "year_of_release", nullable = false) + private OffsetTime yearOfRelease; + + @Lob + @Column(name = "annotanion", nullable = false) + private String annotanion; + + @Lob + @Column(name = "description", nullable = false) + private String description; + + @Lob + @Column(name = "players_number", nullable = false) + private String playersNumber; + + @Lob + @Column(name = "time_to_play") + private String timeToPlay; + + @Lob + @Column(name = "age") + private String age; + + @Column(name = "picture") + private byte[] picture; + + public byte[] getPicture() { + return picture; + } + + public void setPicture(byte[] picture) { + this.picture = picture; + } + + public String getAge() { + return age; + } + + public void setAge(String age) { + this.age = age; + } + + public String getTimeToPlay() { + return timeToPlay; + } + + public void setTimeToPlay(String timeToPlay) { + this.timeToPlay = timeToPlay; + } + + public String getPlayersNumber() { + return playersNumber; + } + + public void setPlayersNumber(String playersNumber) { + this.playersNumber = playersNumber; + } + + public String getDescription() { + return description; + } + + public void setDescription(String description) { + this.description = description; + } + + public String getAnnotanion() { + return annotanion; + } + + public void setAnnotanion(String annotanion) { + this.annotanion = annotanion; + } + + public OffsetTime getYearOfRelease() { + return yearOfRelease; + } + + public void setYearOfRelease(OffsetTime 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..221b2fd --- /dev/null +++ b/src/main/java/com/petproject/boardgamefun/model/GameSell.java @@ -0,0 +1,79 @@ +package com.petproject.boardgamefun.model; + +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 + @Column(name = "condition", nullable = false) + private String condition; + + @Column(name = "price", nullable = false) + private Integer price; + + @Lob + @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..e1cf312 --- /dev/null +++ b/src/main/java/com/petproject/boardgamefun/model/Messenger.java @@ -0,0 +1,79 @@ +package com.petproject.boardgamefun.model; + +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 + @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..e832d85 --- /dev/null +++ b/src/main/java/com/petproject/boardgamefun/model/News.java @@ -0,0 +1,20 @@ +package com.petproject.boardgamefun.model; + +import javax.persistence.*; + +@Table(name = "news") +@Entity +public class News { + @Id + @GeneratedValue(strategy = GenerationType.IDENTITY) + @Column(name = "id", nullable = false) + private Integer id; + + 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..df9f08f --- /dev/null +++ b/src/main/java/com/petproject/boardgamefun/model/NewsComment.java @@ -0,0 +1,68 @@ +package com.petproject.boardgamefun.model; + +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 + @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..20ec37b --- /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 Integer 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 Integer getRating() { + return rating; + } + + public void setRating(Integer 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..0af3ff2 --- /dev/null +++ b/src/main/java/com/petproject/boardgamefun/model/User.java @@ -0,0 +1,113 @@ +package com.petproject.boardgamefun.model; + +import javax.persistence.*; +import java.time.OffsetTime; + +@Table(name = "user") +@Entity +public class User { + @Id + @GeneratedValue(strategy = GenerationType.IDENTITY) + @Column(name = "id", nullable = false) + private Integer id; + + @Column(name = "name", nullable = false, length = 1) + private String name; + + @Lob + @Column(name = "password", nullable = false) + private String password; + + @Lob + @Column(name = "role", nullable = false) + private String role; + + @Lob + @Column(name = "mail", nullable = false) + private String mail; + + @Lob + @Column(name = "town") + private String town; + + @Column(name = "registration_date", nullable = false) + private OffsetTime registrationDate; + + @Column(name = "rating") + private Double rating; + + @Column(name = "avatar") + private byte[] avatar; + + 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 OffsetTime getRegistrationDate() { + return registrationDate; + } + + public void setRegistrationDate(OffsetTime registrationDate) { + this.registrationDate = registrationDate; + } + + 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..831a9f9 --- /dev/null +++ b/src/main/java/com/petproject/boardgamefun/model/UserRating.java @@ -0,0 +1,67 @@ +package com.petproject.boardgamefun.model; + +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 + @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 From c4c659411ca34e2590c2ca492e5bbc173ef5adac Mon Sep 17 00:00:00 2001 From: "i.i.artamonov" Date: Wed, 17 Nov 2021 22:27:04 +0400 Subject: [PATCH 002/141] Repositories draft added --- pom.xml | 1 + .../boardgamefun/repository/CategoryRepository.java | 7 +++++++ .../boardgamefun/repository/DesignerRepository.java | 7 +++++++ .../boardgamefun/repository/DiaryCommentRepository.java | 7 +++++++ .../boardgamefun/repository/DiaryRatingRepository.java | 7 +++++++ .../boardgamefun/repository/DiaryRepository.java | 7 +++++++ .../boardgamefun/repository/ExpansionRepository.java | 7 +++++++ .../petproject/boardgamefun/repository/FileRepository.java | 7 +++++++ .../boardgamefun/repository/ForumMessageRepository.java | 7 +++++++ .../boardgamefun/repository/ForumRepository.java | 7 +++++++ .../boardgamefun/repository/GameByDesignerRepository.java | 7 +++++++ .../boardgamefun/repository/GameCategoryRepository.java | 7 +++++++ .../petproject/boardgamefun/repository/GameRepository.java | 7 +++++++ .../boardgamefun/repository/GameSellRepository.java | 7 +++++++ .../boardgamefun/repository/ImageRepository.java | 7 +++++++ .../boardgamefun/repository/MessengerRepository.java | 7 +++++++ .../boardgamefun/repository/NewsCommentRepository.java | 7 +++++++ .../boardgamefun/repository/NewsRatingRepository.java | 7 +++++++ .../petproject/boardgamefun/repository/NewsRepository.java | 7 +++++++ .../repository/RatingGameByUserRepository.java | 7 +++++++ .../boardgamefun/repository/SameGameRepository.java | 7 +++++++ .../boardgamefun/repository/UserRatingRepository.java | 7 +++++++ .../petproject/boardgamefun/repository/UserRepository.java | 7 +++++++ .../boardgamefun/repository/UserWishRepository.java | 7 +++++++ 24 files changed, 162 insertions(+) create mode 100644 src/main/java/com/petproject/boardgamefun/repository/CategoryRepository.java create mode 100644 src/main/java/com/petproject/boardgamefun/repository/DesignerRepository.java create mode 100644 src/main/java/com/petproject/boardgamefun/repository/DiaryCommentRepository.java create mode 100644 src/main/java/com/petproject/boardgamefun/repository/DiaryRatingRepository.java create mode 100644 src/main/java/com/petproject/boardgamefun/repository/DiaryRepository.java create mode 100644 src/main/java/com/petproject/boardgamefun/repository/ExpansionRepository.java create mode 100644 src/main/java/com/petproject/boardgamefun/repository/FileRepository.java create mode 100644 src/main/java/com/petproject/boardgamefun/repository/ForumMessageRepository.java create mode 100644 src/main/java/com/petproject/boardgamefun/repository/ForumRepository.java create mode 100644 src/main/java/com/petproject/boardgamefun/repository/GameByDesignerRepository.java create mode 100644 src/main/java/com/petproject/boardgamefun/repository/GameCategoryRepository.java create mode 100644 src/main/java/com/petproject/boardgamefun/repository/GameRepository.java create mode 100644 src/main/java/com/petproject/boardgamefun/repository/GameSellRepository.java create mode 100644 src/main/java/com/petproject/boardgamefun/repository/ImageRepository.java create mode 100644 src/main/java/com/petproject/boardgamefun/repository/MessengerRepository.java create mode 100644 src/main/java/com/petproject/boardgamefun/repository/NewsCommentRepository.java create mode 100644 src/main/java/com/petproject/boardgamefun/repository/NewsRatingRepository.java create mode 100644 src/main/java/com/petproject/boardgamefun/repository/NewsRepository.java create mode 100644 src/main/java/com/petproject/boardgamefun/repository/RatingGameByUserRepository.java create mode 100644 src/main/java/com/petproject/boardgamefun/repository/SameGameRepository.java create mode 100644 src/main/java/com/petproject/boardgamefun/repository/UserRatingRepository.java create mode 100644 src/main/java/com/petproject/boardgamefun/repository/UserRepository.java create mode 100644 src/main/java/com/petproject/boardgamefun/repository/UserWishRepository.java diff --git a/pom.xml b/pom.xml index 09be647..c52aa9c 100644 --- a/pom.xml +++ b/pom.xml @@ -25,6 +25,7 @@ + org.springframework.boot 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..77e7efa --- /dev/null +++ b/src/main/java/com/petproject/boardgamefun/repository/DesignerRepository.java @@ -0,0 +1,7 @@ +package com.petproject.boardgamefun.repository; + +import com.petproject.boardgamefun.model.Designer; +import org.springframework.data.jpa.repository.JpaRepository; + +public interface DesignerRepository extends JpaRepository { +} \ 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..ce9b7e7 --- /dev/null +++ b/src/main/java/com/petproject/boardgamefun/repository/DiaryCommentRepository.java @@ -0,0 +1,7 @@ +package com.petproject.boardgamefun.repository; + +import com.petproject.boardgamefun.model.DiaryComment; +import org.springframework.data.jpa.repository.JpaRepository; + +public interface DiaryCommentRepository extends JpaRepository { +} \ 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..d93dfc7 --- /dev/null +++ b/src/main/java/com/petproject/boardgamefun/repository/DiaryRatingRepository.java @@ -0,0 +1,7 @@ +package com.petproject.boardgamefun.repository; + +import com.petproject.boardgamefun.model.DiaryRating; +import org.springframework.data.jpa.repository.JpaRepository; + +public interface DiaryRatingRepository extends JpaRepository { +} \ 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..2a07591 --- /dev/null +++ b/src/main/java/com/petproject/boardgamefun/repository/DiaryRepository.java @@ -0,0 +1,7 @@ +package com.petproject.boardgamefun.repository; + +import com.petproject.boardgamefun.model.Diary; +import org.springframework.data.jpa.repository.JpaRepository; + +public interface DiaryRepository extends JpaRepository { +} \ 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..7faf8ba --- /dev/null +++ b/src/main/java/com/petproject/boardgamefun/repository/ExpansionRepository.java @@ -0,0 +1,7 @@ +package com.petproject.boardgamefun.repository; + +import com.petproject.boardgamefun.model.Expansion; +import org.springframework.data.jpa.repository.JpaRepository; + +public interface ExpansionRepository extends JpaRepository { +} \ 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..e12a47c --- /dev/null +++ b/src/main/java/com/petproject/boardgamefun/repository/ForumMessageRepository.java @@ -0,0 +1,7 @@ +package com.petproject.boardgamefun.repository; + +import com.petproject.boardgamefun.model.ForumMessage; +import org.springframework.data.jpa.repository.JpaRepository; + +public interface ForumMessageRepository extends JpaRepository { +} \ 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..88e192c --- /dev/null +++ b/src/main/java/com/petproject/boardgamefun/repository/ForumRepository.java @@ -0,0 +1,7 @@ +package com.petproject.boardgamefun.repository; + +import com.petproject.boardgamefun.model.Forum; +import org.springframework.data.jpa.repository.JpaRepository; + +public interface ForumRepository extends JpaRepository { +} \ 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..76052eb --- /dev/null +++ b/src/main/java/com/petproject/boardgamefun/repository/GameRepository.java @@ -0,0 +1,7 @@ +package com.petproject.boardgamefun.repository; + +import com.petproject.boardgamefun.model.Game; +import org.springframework.data.jpa.repository.JpaRepository; + +public interface GameRepository extends JpaRepository { +} \ 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..b714a85 --- /dev/null +++ b/src/main/java/com/petproject/boardgamefun/repository/GameSellRepository.java @@ -0,0 +1,7 @@ +package com.petproject.boardgamefun.repository; + +import com.petproject.boardgamefun.model.GameSell; +import org.springframework.data.jpa.repository.JpaRepository; + +public interface GameSellRepository extends JpaRepository { +} \ 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..3c23b42 --- /dev/null +++ b/src/main/java/com/petproject/boardgamefun/repository/RatingGameByUserRepository.java @@ -0,0 +1,7 @@ +package com.petproject.boardgamefun.repository; + +import com.petproject.boardgamefun.model.RatingGameByUser; +import org.springframework.data.jpa.repository.JpaRepository; + +public interface RatingGameByUserRepository extends JpaRepository { +} \ 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..381d96f --- /dev/null +++ b/src/main/java/com/petproject/boardgamefun/repository/SameGameRepository.java @@ -0,0 +1,7 @@ +package com.petproject.boardgamefun.repository; + +import com.petproject.boardgamefun.model.SameGame; +import org.springframework.data.jpa.repository.JpaRepository; + +public interface SameGameRepository extends JpaRepository { +} \ No newline at end of file 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..3983c09 --- /dev/null +++ b/src/main/java/com/petproject/boardgamefun/repository/UserRepository.java @@ -0,0 +1,7 @@ +package com.petproject.boardgamefun.repository; + +import com.petproject.boardgamefun.model.User; +import org.springframework.data.jpa.repository.JpaRepository; + +public interface UserRepository extends JpaRepository { +} \ 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..46ea0f5 --- /dev/null +++ b/src/main/java/com/petproject/boardgamefun/repository/UserWishRepository.java @@ -0,0 +1,7 @@ +package com.petproject.boardgamefun.repository; + +import com.petproject.boardgamefun.model.UserWish; +import org.springframework.data.jpa.repository.JpaRepository; + +public interface UserWishRepository extends JpaRepository { +} \ No newline at end of file From 2f4a0f4a8454654f48c631483fa4e9e7a60546b6 Mon Sep 17 00:00:00 2001 From: "i.i.artamonov" Date: Fri, 19 Nov 2021 13:15:24 +0400 Subject: [PATCH 003/141] Draft controllers for games and images added. Changes in Game Entity For testing connection and application added drafts controllers. --- pom.xml | 3 +- .../controller/GameController.java | 32 +++++++ .../controller/ImageController.java | 31 +++++++ .../petproject/boardgamefun/model/Game.java | 90 ++++++++++++------- 4 files changed, 121 insertions(+), 35 deletions(-) create mode 100644 src/main/java/com/petproject/boardgamefun/controller/GameController.java create mode 100644 src/main/java/com/petproject/boardgamefun/controller/ImageController.java diff --git a/pom.xml b/pom.xml index c52aa9c..718625a 100644 --- a/pom.xml +++ b/pom.xml @@ -16,7 +16,7 @@ 17 - + @@ -26,6 +26,7 @@ + org.springframework.boot 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..0e9df39 --- /dev/null +++ b/src/main/java/com/petproject/boardgamefun/controller/GameController.java @@ -0,0 +1,32 @@ +package com.petproject.boardgamefun.controller; + +import com.petproject.boardgamefun.model.Game; +import com.petproject.boardgamefun.repository.GameRepository; +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("/games") +public class GameController { + + final GameRepository gameRepository; + + public GameController(GameRepository gameRepository) { + this.gameRepository = gameRepository; + } + + @GetMapping() + ResponseEntity> getGames(){ + var games = gameRepository.findAll(); + if (games.size() != 0) { + return new ResponseEntity<>(games, HttpStatus.OK); + } + return new ResponseEntity<>(games, HttpStatus.NOT_FOUND); + + } +} 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..1880a9b --- /dev/null +++ b/src/main/java/com/petproject/boardgamefun/controller/ImageController.java @@ -0,0 +1,31 @@ +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 org.springframework.web.servlet.function.EntityResponse; + +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(); + if (images.size() != 0) { + return new ResponseEntity<>(images, HttpStatus.OK); + } + return new ResponseEntity<>(images, HttpStatus.NOT_FOUND); + } +} diff --git a/src/main/java/com/petproject/boardgamefun/model/Game.java b/src/main/java/com/petproject/boardgamefun/model/Game.java index c2ae84e..e56b179 100644 --- a/src/main/java/com/petproject/boardgamefun/model/Game.java +++ b/src/main/java/com/petproject/boardgamefun/model/Game.java @@ -1,5 +1,7 @@ package com.petproject.boardgamefun.model; +import org.hibernate.annotations.Type; + import javax.persistence.*; import java.time.OffsetTime; @@ -13,7 +15,6 @@ public class Game { @Column(name = "id", nullable = false) private Integer id; - @Lob @Column(name = "title", nullable = false) private String title; @@ -21,58 +22,79 @@ public class Game { private OffsetTime yearOfRelease; @Lob - @Column(name = "annotanion", nullable = false) - private String annotanion; + @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; - @Lob - @Column(name = "players_number", nullable = false) - private String playersNumber; + @Column(name = "picture") + private byte[] picture; - @Lob - @Column(name = "time_to_play") - private String timeToPlay; + @Column(name = "player_age") + private String playerAge; - @Lob - @Column(name = "age") - private String age; + @Column(name = "players_min", nullable = false) + private Integer playersMin; - @Column(name = "picture") - private byte[] picture; + @Column(name = "players_max", nullable = false) + private Integer playersMax; - public byte[] getPicture() { - return picture; + @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 setPicture(byte[] picture) { - this.picture = picture; + 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 String getAge() { - return age; + public void setPlayersMax(Integer playersMax) { + this.playersMax = playersMax; } - public void setAge(String age) { - this.age = age; + public Integer getPlayersMin() { + return playersMin; } - public String getTimeToPlay() { - return timeToPlay; + public void setPlayersMin(Integer playersMin) { + this.playersMin = playersMin; } - public void setTimeToPlay(String timeToPlay) { - this.timeToPlay = timeToPlay; + public String getPlayerAge() { + return playerAge; } - public String getPlayersNumber() { - return playersNumber; + public void setPlayerAge(String playerAge) { + this.playerAge = playerAge; } - public void setPlayersNumber(String playersNumber) { - this.playersNumber = playersNumber; + public byte[] getPicture() { + return picture; + } + + public void setPicture(byte[] picture) { + this.picture = picture; } public String getDescription() { @@ -83,12 +105,12 @@ public void setDescription(String description) { this.description = description; } - public String getAnnotanion() { - return annotanion; + public String getAnnotation() { + return annotation; } - public void setAnnotanion(String annotanion) { - this.annotanion = annotanion; + public void setAnnotation(String annotation) { + this.annotation = annotation; } public OffsetTime getYearOfRelease() { From 6dc0b6d7d3871105c04ea1ae819636a47a6f150d Mon Sep 17 00:00:00 2001 From: "i.i.artamonov" Date: Sat, 20 Nov 2021 12:35:30 +0400 Subject: [PATCH 004/141] Http status changes in Game and Image controllers Wrong http status if we get null from db --- pom.xml | 1 + .../petproject/boardgamefun/controller/GameController.java | 7 +++---- .../boardgamefun/controller/ImageController.java | 7 ++----- 3 files changed, 6 insertions(+), 9 deletions(-) diff --git a/pom.xml b/pom.xml index 718625a..604f5fb 100644 --- a/pom.xml +++ b/pom.xml @@ -27,6 +27,7 @@ + org.springframework.boot diff --git a/src/main/java/com/petproject/boardgamefun/controller/GameController.java b/src/main/java/com/petproject/boardgamefun/controller/GameController.java index 0e9df39..9fd7995 100644 --- a/src/main/java/com/petproject/boardgamefun/controller/GameController.java +++ b/src/main/java/com/petproject/boardgamefun/controller/GameController.java @@ -23,10 +23,9 @@ public GameController(GameRepository gameRepository) { @GetMapping() ResponseEntity> getGames(){ var games = gameRepository.findAll(); - if (games.size() != 0) { - return new ResponseEntity<>(games, HttpStatus.OK); - } - return new ResponseEntity<>(games, HttpStatus.NOT_FOUND); + return new ResponseEntity<>(games, HttpStatus.OK); + + } } diff --git a/src/main/java/com/petproject/boardgamefun/controller/ImageController.java b/src/main/java/com/petproject/boardgamefun/controller/ImageController.java index 1880a9b..15b919f 100644 --- a/src/main/java/com/petproject/boardgamefun/controller/ImageController.java +++ b/src/main/java/com/petproject/boardgamefun/controller/ImageController.java @@ -7,7 +7,6 @@ import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RestController; -import org.springframework.web.servlet.function.EntityResponse; import java.util.List; @@ -23,9 +22,7 @@ public ImageController(ImageRepository imageRepository) { @GetMapping() ResponseEntity> getImages() { var images = imageRepository.findAll(); - if (images.size() != 0) { - return new ResponseEntity<>(images, HttpStatus.OK); - } - return new ResponseEntity<>(images, HttpStatus.NOT_FOUND); + return new ResponseEntity<>(images, HttpStatus.OK); + } } From 27d1799de8596960b42ef00056a516de2dd92cb5 Mon Sep 17 00:00:00 2001 From: "i.i.artamonov" Date: Fri, 26 Nov 2021 11:15:15 +0400 Subject: [PATCH 005/141] Security added In application properties added fields for jwt token generation. User details folder added for work with user. Added models to request and response for login. Jwt classes added for authentication and generation, validate tokens. Enum Roles added for privileges requests. Web security config added. Some basic requests added to Game and User controller for testing security. Change name of table in postgres, because user is a keyword and exception was handling during request --- pom.xml | 10 ++ .../controller/GameController.java | 12 ++- .../controller/UserController.java | 71 ++++++++++++++ .../petproject/boardgamefun/model/User.java | 31 +++--- .../repository/GameRepository.java | 1 + .../repository/UserRepository.java | 3 + .../security/WebSecurityConfig.java | 65 +++++++++++++ .../boardgamefun/security/enums/Role.java | 7 ++ .../security/jwt/AuthEntryPointJwt.java | 24 +++++ .../security/jwt/AuthTokenFilter.java | 61 ++++++++++++ .../boardgamefun/security/jwt/JwtUtils.java | 57 +++++++++++ .../security/model/JwtResponse.java | 13 +++ .../security/model/LoginRequest.java | 14 +++ .../security/services/UserDetailsImpl.java | 95 +++++++++++++++++++ .../services/UserDetailsServiceImpl.java | 27 ++++++ src/main/resources/application.properties | 4 + 16 files changed, 476 insertions(+), 19 deletions(-) create mode 100644 src/main/java/com/petproject/boardgamefun/controller/UserController.java create mode 100644 src/main/java/com/petproject/boardgamefun/security/WebSecurityConfig.java create mode 100644 src/main/java/com/petproject/boardgamefun/security/enums/Role.java create mode 100644 src/main/java/com/petproject/boardgamefun/security/jwt/AuthEntryPointJwt.java create mode 100644 src/main/java/com/petproject/boardgamefun/security/jwt/AuthTokenFilter.java create mode 100644 src/main/java/com/petproject/boardgamefun/security/jwt/JwtUtils.java create mode 100644 src/main/java/com/petproject/boardgamefun/security/model/JwtResponse.java create mode 100644 src/main/java/com/petproject/boardgamefun/security/model/LoginRequest.java create mode 100644 src/main/java/com/petproject/boardgamefun/security/services/UserDetailsImpl.java create mode 100644 src/main/java/com/petproject/boardgamefun/security/services/UserDetailsServiceImpl.java diff --git a/pom.xml b/pom.xml index 604f5fb..fae6cae 100644 --- a/pom.xml +++ b/pom.xml @@ -24,6 +24,7 @@ + @@ -49,6 +50,15 @@ 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 diff --git a/src/main/java/com/petproject/boardgamefun/controller/GameController.java b/src/main/java/com/petproject/boardgamefun/controller/GameController.java index 9fd7995..22b061a 100644 --- a/src/main/java/com/petproject/boardgamefun/controller/GameController.java +++ b/src/main/java/com/petproject/boardgamefun/controller/GameController.java @@ -4,12 +4,11 @@ import com.petproject.boardgamefun.repository.GameRepository; 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 org.springframework.web.bind.annotation.*; import java.util.List; +@CrossOrigin(origins = "*", maxAge = 3600) @RestController @RequestMapping("/games") public class GameController { @@ -24,8 +23,11 @@ public GameController(GameRepository gameRepository) { ResponseEntity> getGames(){ var games = gameRepository.findAll(); return new ResponseEntity<>(games, HttpStatus.OK); + } - - + @GetMapping("{title}") + ResponseEntity getGame(@PathVariable String title){ + var game = gameRepository.findGameByTitle(title); + return new ResponseEntity<>(game, 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..017c6d4 --- /dev/null +++ b/src/main/java/com/petproject/boardgamefun/controller/UserController.java @@ -0,0 +1,71 @@ +package com.petproject.boardgamefun.controller; + +import com.petproject.boardgamefun.model.User; +import com.petproject.boardgamefun.repository.UserRepository; +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.services.UserDetailsImpl; +import org.springframework.http.HttpStatus; +import org.springframework.http.ResponseEntity; +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.security.crypto.password.PasswordEncoder; +import org.springframework.web.bind.annotation.*; + +import java.util.List; + +@RestController +@CrossOrigin(origins = "*", maxAge = 3600) +@RequestMapping("/users") +public class UserController { + final UserRepository userRepository; + final PasswordEncoder passwordEncoder; + final JwtUtils jwtUtils; + final AuthenticationManager authenticationManager; + + public UserController(UserRepository userRepository, PasswordEncoder passwordEncoder, JwtUtils jwtUtils, AuthenticationManager authenticationManager) { + this.userRepository = userRepository; + this.passwordEncoder = passwordEncoder; + this.jwtUtils = jwtUtils; + this.authenticationManager = authenticationManager; + } + + @GetMapping() + public ResponseEntity> getUsers(){ + var users = userRepository.findAll(); + return new ResponseEntity<>(users, HttpStatus.OK); + } + + @PostMapping("sign-in") + public ResponseEntity authenticateUser(@RequestBody LoginRequest loginRequest){ + if (!userRepository.existsUserByName(loginRequest.getName())){ + return new ResponseEntity<>("Пользователя с таким никнеймом не существует", HttpStatus.BAD_REQUEST); + } + Authentication authentication = authenticationManager.authenticate(new UsernamePasswordAuthenticationToken(loginRequest.getName(), loginRequest.getPassword())); + + SecurityContextHolder.getContext().setAuthentication(authentication); + String jwt = jwtUtils.generateJwtToken(authentication); + UserDetailsImpl userDetails = (UserDetailsImpl) authentication.getPrincipal(); + + return new ResponseEntity<>(new JwtResponse(jwt, userDetails.getUsername(), userDetails.getEmail()), HttpStatus.OK); + } + + @PostMapping("/sign-up") + public ResponseEntity registerUser(@RequestBody User user){ + + if (userRepository.existsUserByName(user.getName())){ + return new ResponseEntity<>("Пользователь с таким никнеймом уже существует", HttpStatus.BAD_REQUEST); + } + + if (userRepository.existsUserByMail(user.getMail())){ + return new ResponseEntity<>("Пользователь с такой почтой уже существует", HttpStatus.BAD_REQUEST); + } + + user.setPassword(passwordEncoder.encode(user.getPassword())); + userRepository.save(user); + return new ResponseEntity<>(user, HttpStatus.OK); + } +} diff --git a/src/main/java/com/petproject/boardgamefun/model/User.java b/src/main/java/com/petproject/boardgamefun/model/User.java index 0af3ff2..af39b50 100644 --- a/src/main/java/com/petproject/boardgamefun/model/User.java +++ b/src/main/java/com/petproject/boardgamefun/model/User.java @@ -1,9 +1,12 @@ package com.petproject.boardgamefun.model; import javax.persistence.*; -import java.time.OffsetTime; +import java.time.OffsetDateTime; -@Table(name = "user") +@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 @@ -30,15 +33,23 @@ public class User { @Column(name = "town") private String town; - @Column(name = "registration_date", nullable = false) - private OffsetTime registrationDate; - @Column(name = "rating") private Double rating; - @Column(name = "avatar") + @Column(name = "avatar", nullable = false) 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; } @@ -55,14 +66,6 @@ public void setRating(Double rating) { this.rating = rating; } - public OffsetTime getRegistrationDate() { - return registrationDate; - } - - public void setRegistrationDate(OffsetTime registrationDate) { - this.registrationDate = registrationDate; - } - public String getTown() { return town; } diff --git a/src/main/java/com/petproject/boardgamefun/repository/GameRepository.java b/src/main/java/com/petproject/boardgamefun/repository/GameRepository.java index 76052eb..97e7dd8 100644 --- a/src/main/java/com/petproject/boardgamefun/repository/GameRepository.java +++ b/src/main/java/com/petproject/boardgamefun/repository/GameRepository.java @@ -4,4 +4,5 @@ import org.springframework.data.jpa.repository.JpaRepository; public interface GameRepository extends JpaRepository { + Game findGameByTitle(String title); } \ 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 index 3983c09..61cd326 100644 --- a/src/main/java/com/petproject/boardgamefun/repository/UserRepository.java +++ b/src/main/java/com/petproject/boardgamefun/repository/UserRepository.java @@ -4,4 +4,7 @@ import org.springframework.data.jpa.repository.JpaRepository; public interface UserRepository extends JpaRepository { + User findUserByName(String name); + Boolean existsUserByName(String username); + Boolean existsUserByMail(String email); } \ 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..72890d0 --- /dev/null +++ b/src/main/java/com/petproject/boardgamefun/security/WebSecurityConfig.java @@ -0,0 +1,65 @@ +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; + +@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); + } + +} 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/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..3e85272 --- /dev/null +++ b/src/main/java/com/petproject/boardgamefun/security/jwt/JwtUtils.java @@ -0,0 +1,57 @@ +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 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/JwtResponse.java b/src/main/java/com/petproject/boardgamefun/security/model/JwtResponse.java new file mode 100644 index 0000000..5c7481b --- /dev/null +++ b/src/main/java/com/petproject/boardgamefun/security/model/JwtResponse.java @@ -0,0 +1,13 @@ +package com.petproject.boardgamefun.security.model; + +public class JwtResponse { + private final String token; + private final String userName; + private final String email; + + public JwtResponse(String token, String userName, String email){ + this.token = token; + this.userName = userName; + this.email = email; + } +} 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..18427ba --- /dev/null +++ b/src/main/java/com/petproject/boardgamefun/security/model/LoginRequest.java @@ -0,0 +1,14 @@ +package com.petproject.boardgamefun.security.model; + +import lombok.Data; +import lombok.Getter; +import lombok.Setter; + +@Data +@Getter +@Setter +public class LoginRequest { + + private String name; + private String password; +} 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..87f0901 --- /dev/null +++ b/src/main/java/com/petproject/boardgamefun/security/services/UserDetailsServiceImpl.java @@ -0,0 +1,27 @@ +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; + +@Service +public class UserDetailsServiceImpl implements UserDetailsService { + private final UserRepository userRepository; + + public UserDetailsServiceImpl(UserRepository userRepository){ + this.userRepository = userRepository; + } + + + @Override + 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/resources/application.properties b/src/main/resources/application.properties index 66180dd..757cfe9 100644 --- a/src/main/resources/application.properties +++ b/src/main/resources/application.properties @@ -3,3 +3,7 @@ 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 = 86400000 \ No newline at end of file From 5d8778b77db7cb648696be385e30ebf250810ea9 Mon Sep 17 00:00:00 2001 From: "i.i.artamonov" Date: Mon, 29 Nov 2021 20:40:52 +0400 Subject: [PATCH 006/141] Requests for user collection in UserController added Added next requests: add to collection, show all games from collection, delete from collection. Added request for getting specific user. --- .../controller/UserController.java | 67 +++++++++++++++++-- .../petproject/boardgamefun/model/User.java | 9 ++- .../repository/GameRepository.java | 10 +++ .../repository/UserOwnGameRepository.java | 10 +++ .../repository/UserRepository.java | 5 +- 5 files changed, 87 insertions(+), 14 deletions(-) create mode 100644 src/main/java/com/petproject/boardgamefun/repository/UserOwnGameRepository.java diff --git a/src/main/java/com/petproject/boardgamefun/controller/UserController.java b/src/main/java/com/petproject/boardgamefun/controller/UserController.java index 017c6d4..8c7c901 100644 --- a/src/main/java/com/petproject/boardgamefun/controller/UserController.java +++ b/src/main/java/com/petproject/boardgamefun/controller/UserController.java @@ -1,6 +1,10 @@ package com.petproject.boardgamefun.controller; +import com.petproject.boardgamefun.model.Game; import com.petproject.boardgamefun.model.User; +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 com.petproject.boardgamefun.security.jwt.JwtUtils; import com.petproject.boardgamefun.security.model.JwtResponse; @@ -15,33 +19,39 @@ import org.springframework.security.crypto.password.PasswordEncoder; import org.springframework.web.bind.annotation.*; +import javax.transaction.Transactional; +import java.time.OffsetDateTime; import java.util.List; @RestController @CrossOrigin(origins = "*", maxAge = 3600) @RequestMapping("/users") public class UserController { + final GameRepository gameRepository; final UserRepository userRepository; + final UserOwnGameRepository userOwnGameRepository; final PasswordEncoder passwordEncoder; final JwtUtils jwtUtils; final AuthenticationManager authenticationManager; - public UserController(UserRepository userRepository, PasswordEncoder passwordEncoder, JwtUtils jwtUtils, AuthenticationManager authenticationManager) { + public UserController(GameRepository gameRepository, UserRepository userRepository, UserOwnGameRepository userOwnGameRepository, PasswordEncoder passwordEncoder, JwtUtils jwtUtils, AuthenticationManager authenticationManager) { + this.gameRepository = gameRepository; this.userRepository = userRepository; + this.userOwnGameRepository = userOwnGameRepository; this.passwordEncoder = passwordEncoder; this.jwtUtils = jwtUtils; this.authenticationManager = authenticationManager; } @GetMapping() - public ResponseEntity> getUsers(){ + public ResponseEntity> getUsers() { var users = userRepository.findAll(); return new ResponseEntity<>(users, HttpStatus.OK); } @PostMapping("sign-in") - public ResponseEntity authenticateUser(@RequestBody LoginRequest loginRequest){ - if (!userRepository.existsUserByName(loginRequest.getName())){ + public ResponseEntity authenticateUser(@RequestBody LoginRequest loginRequest) { + if (!userRepository.existsByName(loginRequest.getName())) { return new ResponseEntity<>("Пользователя с таким никнеймом не существует", HttpStatus.BAD_REQUEST); } Authentication authentication = authenticationManager.authenticate(new UsernamePasswordAuthenticationToken(loginRequest.getName(), loginRequest.getPassword())); @@ -54,18 +64,61 @@ public ResponseEntity authenticateUser(@RequestBody LoginRequest loginRequest } @PostMapping("/sign-up") - public ResponseEntity registerUser(@RequestBody User user){ + public ResponseEntity registerUser(@RequestBody User user) { - if (userRepository.existsUserByName(user.getName())){ + if (userRepository.existsByName(user.getName())) { return new ResponseEntity<>("Пользователь с таким никнеймом уже существует", HttpStatus.BAD_REQUEST); } - if (userRepository.existsUserByMail(user.getMail())){ + if (userRepository.existsByMail(user.getMail())) { return new ResponseEntity<>("Пользователь с такой почтой уже существует", HttpStatus.BAD_REQUEST); } user.setPassword(passwordEncoder.encode(user.getPassword())); + user.setRegistrationDate(OffsetDateTime.now()); userRepository.save(user); return new ResponseEntity<>(user, HttpStatus.OK); } + + @GetMapping("{id}") + public ResponseEntity getUser(@PathVariable Integer id) { + var user = userRepository.findUserById(id); + return new ResponseEntity<>(user, HttpStatus.OK); + } + + @GetMapping("/{id}/games") + public ResponseEntity> getUserGames(@PathVariable Integer id) { + var games = gameRepository.findUserGames(id); + return new ResponseEntity<>(games, HttpStatus.OK); + } + + @Transactional + @PostMapping("{userId}/add-game/{gameId}") + public ResponseEntity addGameToUser(@PathVariable Integer userId, @PathVariable Integer gameId){ + + var user = userRepository.findUserById(userId); + var game = gameRepository.findGameById(gameId); + + var userOwnGame = new UserOwnGame(); + userOwnGame.setGame(game); + userOwnGame.setUser(user); + + userOwnGameRepository.save(userOwnGame); + + return new ResponseEntity<>(game.getTitle() + " добавлена в вашу коллекцию", HttpStatus.OK); + } + + @Transactional + @DeleteMapping("{userId}/delete-game/{gameId}") + public ResponseEntity deleteGameFromUserCollection(@PathVariable Integer userId, @PathVariable Integer gameId){ + + var user = userRepository.findUserById(userId); + var game = gameRepository.findGameById(gameId); + + var userOwnGame = userOwnGameRepository.findByGameAndUser(game, user); + + userOwnGameRepository.delete(userOwnGame); + + return new ResponseEntity<>(game.getTitle() + " удалена из вашей коллекции", HttpStatus.OK); + } } diff --git a/src/main/java/com/petproject/boardgamefun/model/User.java b/src/main/java/com/petproject/boardgamefun/model/User.java index af39b50..7a8a957 100644 --- a/src/main/java/com/petproject/boardgamefun/model/User.java +++ b/src/main/java/com/petproject/boardgamefun/model/User.java @@ -1,5 +1,7 @@ package com.petproject.boardgamefun.model; +import org.hibernate.annotations.Type; + import javax.persistence.*; import java.time.OffsetDateTime; @@ -14,29 +16,26 @@ public class User { @Column(name = "id", nullable = false) private Integer id; - @Column(name = "name", nullable = false, length = 1) + @Column(name = "name", nullable = false) private String name; @Lob @Column(name = "password", nullable = false) private String password; - @Lob @Column(name = "role", nullable = false) private String role; - @Lob @Column(name = "mail", nullable = false) private String mail; - @Lob @Column(name = "town") private String town; @Column(name = "rating") private Double rating; - @Column(name = "avatar", nullable = false) + @Column(name = "avatar") private byte[] avatar; @Column(name = "registration_date", nullable = false) diff --git a/src/main/java/com/petproject/boardgamefun/repository/GameRepository.java b/src/main/java/com/petproject/boardgamefun/repository/GameRepository.java index 97e7dd8..ffec446 100644 --- a/src/main/java/com/petproject/boardgamefun/repository/GameRepository.java +++ b/src/main/java/com/petproject/boardgamefun/repository/GameRepository.java @@ -2,7 +2,17 @@ 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 findGameByTitle(String title); + Game findGameById(Integer id); + + @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); } \ 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..00545f3 --- /dev/null +++ b/src/main/java/com/petproject/boardgamefun/repository/UserOwnGameRepository.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.UserOwnGame; +import org.springframework.data.jpa.repository.JpaRepository; + +public interface UserOwnGameRepository extends JpaRepository { + UserOwnGame findByGameAndUser(Game game, User user); +} \ 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 index 61cd326..05c9dc7 100644 --- a/src/main/java/com/petproject/boardgamefun/repository/UserRepository.java +++ b/src/main/java/com/petproject/boardgamefun/repository/UserRepository.java @@ -4,7 +4,8 @@ import org.springframework.data.jpa.repository.JpaRepository; public interface UserRepository extends JpaRepository { + User findUserById(Integer id); User findUserByName(String name); - Boolean existsUserByName(String username); - Boolean existsUserByMail(String email); + Boolean existsByName(String username); + Boolean existsByMail(String email); } \ No newline at end of file From adddb9d7dcd564c9fd404bebaa048bae9b229429 Mon Sep 17 00:00:00 2001 From: "i.i.artamonov" Date: Wed, 1 Dec 2021 09:04:12 +0400 Subject: [PATCH 007/141] Manipulation with rating for games added In UserController added next requests - save/update, get, delete rating game of the user. For list of game ratings GameRatingDTO added --- .../controller/UserController.java | 62 +++++++++++++++++-- .../boardgamefun/dto/GameRatingDTO.java | 8 +++ .../repository/GameRepository.java | 8 +++ .../RatingGameByUserRepository.java | 3 + 4 files changed, 77 insertions(+), 4 deletions(-) create mode 100644 src/main/java/com/petproject/boardgamefun/dto/GameRatingDTO.java diff --git a/src/main/java/com/petproject/boardgamefun/controller/UserController.java b/src/main/java/com/petproject/boardgamefun/controller/UserController.java index 8c7c901..a31f7df 100644 --- a/src/main/java/com/petproject/boardgamefun/controller/UserController.java +++ b/src/main/java/com/petproject/boardgamefun/controller/UserController.java @@ -1,9 +1,12 @@ package com.petproject.boardgamefun.controller; +import com.petproject.boardgamefun.dto.GameRatingDTO; import com.petproject.boardgamefun.model.Game; +import com.petproject.boardgamefun.model.RatingGameByUser; import com.petproject.boardgamefun.model.User; import com.petproject.boardgamefun.model.UserOwnGame; import com.petproject.boardgamefun.repository.GameRepository; +import com.petproject.boardgamefun.repository.RatingGameByUserRepository; import com.petproject.boardgamefun.repository.UserOwnGameRepository; import com.petproject.boardgamefun.repository.UserRepository; import com.petproject.boardgamefun.security.jwt.JwtUtils; @@ -27,17 +30,21 @@ @CrossOrigin(origins = "*", maxAge = 3600) @RequestMapping("/users") public class UserController { + final GameRepository gameRepository; final UserRepository userRepository; final UserOwnGameRepository userOwnGameRepository; + final RatingGameByUserRepository ratingGameByUserRepository; + final PasswordEncoder passwordEncoder; final JwtUtils jwtUtils; final AuthenticationManager authenticationManager; - public UserController(GameRepository gameRepository, UserRepository userRepository, UserOwnGameRepository userOwnGameRepository, PasswordEncoder passwordEncoder, JwtUtils jwtUtils, AuthenticationManager authenticationManager) { + public UserController(GameRepository gameRepository, UserRepository userRepository, UserOwnGameRepository userOwnGameRepository, RatingGameByUserRepository ratingGameByUserRepository, PasswordEncoder passwordEncoder, JwtUtils jwtUtils, AuthenticationManager authenticationManager) { this.gameRepository = gameRepository; this.userRepository = userRepository; this.userOwnGameRepository = userOwnGameRepository; + this.ratingGameByUserRepository = ratingGameByUserRepository; this.passwordEncoder = passwordEncoder; this.jwtUtils = jwtUtils; this.authenticationManager = authenticationManager; @@ -94,7 +101,7 @@ public ResponseEntity> getUserGames(@PathVariable Integer id) { @Transactional @PostMapping("{userId}/add-game/{gameId}") - public ResponseEntity addGameToUser(@PathVariable Integer userId, @PathVariable Integer gameId){ + public ResponseEntity addGameToUser(@PathVariable Integer userId, @PathVariable Integer gameId) { var user = userRepository.findUserById(userId); var game = gameRepository.findGameById(gameId); @@ -110,7 +117,7 @@ public ResponseEntity addGameToUser(@PathVariable Integer userId, @PathVariab @Transactional @DeleteMapping("{userId}/delete-game/{gameId}") - public ResponseEntity deleteGameFromUserCollection(@PathVariable Integer userId, @PathVariable Integer gameId){ + public ResponseEntity deleteGameFromUserCollection(@PathVariable Integer userId, @PathVariable Integer gameId) { var user = userRepository.findUserById(userId); var game = gameRepository.findGameById(gameId); @@ -119,6 +126,53 @@ public ResponseEntity deleteGameFromUserCollection(@PathVariable Integer user userOwnGameRepository.delete(userOwnGame); - return new ResponseEntity<>(game.getTitle() + " удалена из вашей коллекции", HttpStatus.OK); + return new ResponseEntity<>(game.getTitle() + " удалена из вашей коллекции", HttpStatus.OK); } + + @GetMapping("/{userId}/games-rating") + public ResponseEntity> getUserRatingList(@PathVariable Integer userId) { + + var ratingGamesByUser = gameRepository.findGameRatingList(userId); + + return new ResponseEntity<>(ratingGamesByUser, HttpStatus.OK); + } + + @Transactional + @DeleteMapping("/{userId}/delete-game-rating/{gameId}") + public ResponseEntity deleteGameRating(@PathVariable Integer userId, @PathVariable Integer gameId) { + + var user = userRepository.findUserById(userId); + var game = gameRepository.findGameById(gameId); + + var ratingGameByUser = ratingGameByUserRepository.findByGameAndUser(game, user); + + ratingGameByUserRepository.delete(ratingGameByUser); + + return new ResponseEntity<>("Оценка с текущей игры удалена", HttpStatus.OK); + } + + @Transactional + @PostMapping("/{userId}/set-game-rating/{gameId}/{rating}") + public ResponseEntity setGameRating(@PathVariable Integer userId, @PathVariable Integer gameId, @PathVariable Integer rating) { + + var user = userRepository.findUserById(userId); + var game = gameRepository.findGameById(gameId); + + var ratingGameByUser = ratingGameByUserRepository.findByGameAndUser(game, user); + + if (ratingGameByUser != null) { + ratingGameByUser.setRating(rating); + ratingGameByUserRepository.save(ratingGameByUser); + } else { + var gameRating = new RatingGameByUser(); + gameRating.setGame(game); + gameRating.setUser(user); + gameRating.setRating(rating); + + ratingGameByUserRepository.save(gameRating); + } + + return new ResponseEntity<>(rating, HttpStatus.OK); + } + } diff --git a/src/main/java/com/petproject/boardgamefun/dto/GameRatingDTO.java b/src/main/java/com/petproject/boardgamefun/dto/GameRatingDTO.java new file mode 100644 index 0000000..11bea2c --- /dev/null +++ b/src/main/java/com/petproject/boardgamefun/dto/GameRatingDTO.java @@ -0,0 +1,8 @@ +package com.petproject.boardgamefun.dto; + +import com.petproject.boardgamefun.model.Game; + +public interface GameRatingDTO { + Game getGame(); + Integer getRating(); +} \ 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 index ffec446..437d77c 100644 --- a/src/main/java/com/petproject/boardgamefun/repository/GameRepository.java +++ b/src/main/java/com/petproject/boardgamefun/repository/GameRepository.java @@ -1,5 +1,6 @@ package com.petproject.boardgamefun.repository; +import com.petproject.boardgamefun.dto.GameRatingDTO; import com.petproject.boardgamefun.model.Game; import org.springframework.data.jpa.repository.JpaRepository; import org.springframework.data.jpa.repository.Query; @@ -15,4 +16,11 @@ public interface GameRepository extends JpaRepository { "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 findGameRatingList(Integer id); } \ 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 index 3c23b42..b2f3067 100644 --- a/src/main/java/com/petproject/boardgamefun/repository/RatingGameByUserRepository.java +++ b/src/main/java/com/petproject/boardgamefun/repository/RatingGameByUserRepository.java @@ -1,7 +1,10 @@ package com.petproject.boardgamefun.repository; +import com.petproject.boardgamefun.model.Game; import com.petproject.boardgamefun.model.RatingGameByUser; +import com.petproject.boardgamefun.model.User; import org.springframework.data.jpa.repository.JpaRepository; public interface RatingGameByUserRepository extends JpaRepository { + RatingGameByUser findByGameAndUser(Game game, User user); } \ No newline at end of file From b9b2577d58919509e0f1c9f5b75576389ade651b Mon Sep 17 00:00:00 2001 From: "i.i.artamonov" Date: Wed, 1 Dec 2021 20:15:25 +0400 Subject: [PATCH 008/141] Wishlist requests in UserController added Added next requests - add, delete, get wishlist in UserController --- .../controller/UserController.java | 65 ++++++++++++++++--- .../repository/GameRepository.java | 6 ++ .../repository/UserWishRepository.java | 3 + 3 files changed, 64 insertions(+), 10 deletions(-) diff --git a/src/main/java/com/petproject/boardgamefun/controller/UserController.java b/src/main/java/com/petproject/boardgamefun/controller/UserController.java index a31f7df..e62ff52 100644 --- a/src/main/java/com/petproject/boardgamefun/controller/UserController.java +++ b/src/main/java/com/petproject/boardgamefun/controller/UserController.java @@ -1,14 +1,8 @@ package com.petproject.boardgamefun.controller; import com.petproject.boardgamefun.dto.GameRatingDTO; -import com.petproject.boardgamefun.model.Game; -import com.petproject.boardgamefun.model.RatingGameByUser; -import com.petproject.boardgamefun.model.User; -import com.petproject.boardgamefun.model.UserOwnGame; -import com.petproject.boardgamefun.repository.GameRepository; -import com.petproject.boardgamefun.repository.RatingGameByUserRepository; -import com.petproject.boardgamefun.repository.UserOwnGameRepository; -import com.petproject.boardgamefun.repository.UserRepository; +import com.petproject.boardgamefun.model.*; +import com.petproject.boardgamefun.repository.*; import com.petproject.boardgamefun.security.jwt.JwtUtils; import com.petproject.boardgamefun.security.model.JwtResponse; import com.petproject.boardgamefun.security.model.LoginRequest; @@ -35,16 +29,25 @@ public class UserController { final UserRepository userRepository; final UserOwnGameRepository userOwnGameRepository; final RatingGameByUserRepository ratingGameByUserRepository; + final UserWishRepository userWishRepository; final PasswordEncoder passwordEncoder; final JwtUtils jwtUtils; final AuthenticationManager authenticationManager; - public UserController(GameRepository gameRepository, UserRepository userRepository, UserOwnGameRepository userOwnGameRepository, RatingGameByUserRepository ratingGameByUserRepository, PasswordEncoder passwordEncoder, JwtUtils jwtUtils, AuthenticationManager authenticationManager) { + public UserController(GameRepository gameRepository, + UserRepository userRepository, + UserOwnGameRepository userOwnGameRepository, + RatingGameByUserRepository ratingGameByUserRepository, + UserWishRepository userWishRepository, + PasswordEncoder passwordEncoder, + JwtUtils jwtUtils, + AuthenticationManager authenticationManager) { this.gameRepository = gameRepository; this.userRepository = userRepository; this.userOwnGameRepository = userOwnGameRepository; this.ratingGameByUserRepository = ratingGameByUserRepository; + this.userWishRepository = userWishRepository; this.passwordEncoder = passwordEncoder; this.jwtUtils = jwtUtils; this.authenticationManager = authenticationManager; @@ -94,7 +97,8 @@ public ResponseEntity getUser(@PathVariable Integer id) { } @GetMapping("/{id}/games") - public ResponseEntity> getUserGames(@PathVariable Integer id) { + public ResponseEntity> getUserCollectionByType(@PathVariable Integer id) { + var games = gameRepository.findUserGames(id); return new ResponseEntity<>(games, HttpStatus.OK); } @@ -175,4 +179,45 @@ public ResponseEntity setGameRating(@PathVariable Integer userId, @Path return new ResponseEntity<>(rating, HttpStatus.OK); } + @GetMapping("/{id}/wishlist") + public ResponseEntity> getUserWishlist(@PathVariable Integer id) { + var games = gameRepository.findUserWishlist(id); + return new ResponseEntity<>(games, HttpStatus.OK); + } + + @Transactional + @PostMapping("{userId}/add-game-to-wishlist/{gameId}") + public ResponseEntity addGameToUserWishlist(@PathVariable Integer userId, @PathVariable Integer gameId) { + + var user = userRepository.findUserById(userId); + var game = gameRepository.findGameById(gameId); + + var userWish = new UserWish(); + userWish.setGame(game); + userWish.setUser(user); + + userWishRepository.save(userWish); + + return new ResponseEntity<>(game.getTitle() + " добавлена в ваши желания", HttpStatus.OK); + } + + @Transactional + @DeleteMapping("{userId}/delete-game-from-wishlist/{gameId}") + public ResponseEntity deleteGameFromUserWishlist(@PathVariable Integer userId, @PathVariable Integer gameId) { + + var user = userRepository.findUserById(userId); + var game = gameRepository.findGameById(gameId); + + var userWish = userWishRepository.findByGameAndUser(game, user); + + userWishRepository.delete(userWish); + + return new ResponseEntity<>(game.getTitle() + " удалена из вашего списка желаемого", HttpStatus.OK); + } + + //todo: sell games + //todo: diary + //todo: edit user + //todo: add game + } diff --git a/src/main/java/com/petproject/boardgamefun/repository/GameRepository.java b/src/main/java/com/petproject/boardgamefun/repository/GameRepository.java index 437d77c..c148837 100644 --- a/src/main/java/com/petproject/boardgamefun/repository/GameRepository.java +++ b/src/main/java/com/petproject/boardgamefun/repository/GameRepository.java @@ -23,4 +23,10 @@ public interface GameRepository extends JpaRepository { "where u.id = :id " + "order by rgbu.rating desc") List findGameRatingList(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); } \ 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 index 46ea0f5..931c4dd 100644 --- a/src/main/java/com/petproject/boardgamefun/repository/UserWishRepository.java +++ b/src/main/java/com/petproject/boardgamefun/repository/UserWishRepository.java @@ -1,7 +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 findByGameAndUser(Game game, User user); } \ No newline at end of file From 072430b3c95ef8cf086310693f70a113e1c446da Mon Sep 17 00:00:00 2001 From: "i.i.artamonov" Date: Thu, 2 Dec 2021 08:55:30 +0400 Subject: [PATCH 009/141] Sell list added to UserController Added next requests for sell list - add/update, delete, get in UserController --- .../controller/UserController.java | 73 ++++++++++++++++++- .../boardgamefun/dto/GameSellDTO.java | 10 +++ .../boardgamefun/dto/RequestGameSell.java | 17 +++++ .../repository/GameRepository.java | 8 ++ .../repository/GameSellRepository.java | 3 + 5 files changed, 109 insertions(+), 2 deletions(-) create mode 100644 src/main/java/com/petproject/boardgamefun/dto/GameSellDTO.java create mode 100644 src/main/java/com/petproject/boardgamefun/dto/RequestGameSell.java diff --git a/src/main/java/com/petproject/boardgamefun/controller/UserController.java b/src/main/java/com/petproject/boardgamefun/controller/UserController.java index e62ff52..0a7923e 100644 --- a/src/main/java/com/petproject/boardgamefun/controller/UserController.java +++ b/src/main/java/com/petproject/boardgamefun/controller/UserController.java @@ -1,6 +1,8 @@ package com.petproject.boardgamefun.controller; import com.petproject.boardgamefun.dto.GameRatingDTO; +import com.petproject.boardgamefun.dto.GameSellDTO; +import com.petproject.boardgamefun.dto.RequestGameSell; import com.petproject.boardgamefun.model.*; import com.petproject.boardgamefun.repository.*; import com.petproject.boardgamefun.security.jwt.JwtUtils; @@ -30,6 +32,7 @@ public class UserController { final UserOwnGameRepository userOwnGameRepository; final RatingGameByUserRepository ratingGameByUserRepository; final UserWishRepository userWishRepository; + final GameSellRepository gameSellRepository; final PasswordEncoder passwordEncoder; final JwtUtils jwtUtils; @@ -40,7 +43,7 @@ public UserController(GameRepository gameRepository, UserOwnGameRepository userOwnGameRepository, RatingGameByUserRepository ratingGameByUserRepository, UserWishRepository userWishRepository, - PasswordEncoder passwordEncoder, + GameSellRepository gameSellRepository, PasswordEncoder passwordEncoder, JwtUtils jwtUtils, AuthenticationManager authenticationManager) { this.gameRepository = gameRepository; @@ -48,6 +51,7 @@ public UserController(GameRepository gameRepository, this.userOwnGameRepository = userOwnGameRepository; this.ratingGameByUserRepository = ratingGameByUserRepository; this.userWishRepository = userWishRepository; + this.gameSellRepository = gameSellRepository; this.passwordEncoder = passwordEncoder; this.jwtUtils = jwtUtils; this.authenticationManager = authenticationManager; @@ -215,7 +219,72 @@ public ResponseEntity deleteGameFromUserWishlist(@PathVariable Integer userId return new ResponseEntity<>(game.getTitle() + " удалена из вашего списка желаемого", HttpStatus.OK); } - //todo: sell games + @Transactional + @PostMapping("{userId}/add-game-to-sell/{gameId}") + public ResponseEntity addGameToSellList(@PathVariable Integer userId, @PathVariable Integer gameId, @RequestBody RequestGameSell requestGameSell){ + + var user = userRepository.findUserById(userId); + var game = gameRepository.findGameById(gameId); + + var gameSell = new GameSell(); + gameSell.setGame(game); + gameSell.setUser(user); + gameSell.setCondition(requestGameSell.getCondition()); + gameSell.setComment(requestGameSell.getComment()); + gameSell.setPrice(requestGameSell.getPrice()); + + gameSellRepository.save(gameSell); + + return new ResponseEntity<>(gameSell, HttpStatus.OK); + } + + @Transactional + @GetMapping("{userId}/games-to-sell") + public ResponseEntity> getGameSellList(@PathVariable Integer userId){ + + var gameSellList = gameRepository.getGameSellList(userId); + + return new ResponseEntity<>(gameSellList,HttpStatus.OK); + } + + + @Transactional + @DeleteMapping("{userId}/remove-game-from-sell/{gameId}") + public ResponseEntity removeGameFromSell(@PathVariable Integer userId, @PathVariable Integer gameId){ + + var user = userRepository.findUserById(userId); + var game = gameRepository.findGameById(gameId); + + var gameSell = gameSellRepository.findByGameAndUser(game, user); + gameSellRepository.delete(gameSell); + + return new ResponseEntity<>(game.getTitle() + " убрана из списка продаж", HttpStatus.OK); + } + + @Transactional + @PutMapping("{userId}/update-game-to-sell/{gameId}") + public ResponseEntity updateSellGame(@PathVariable Integer userId, @PathVariable Integer gameId, @RequestBody RequestGameSell requestGameSell){ + + var user = userRepository.findUserById(userId); + var game = gameRepository.findGameById(gameId); + + var gameSell = gameSellRepository.findByGameAndUser(game, user); + + if (requestGameSell.getComment() != null){ + gameSell.setComment(requestGameSell.getComment()); + } + if (requestGameSell.getPrice() != null){ + gameSell.setPrice(requestGameSell.getPrice()); + } + if (requestGameSell.getCondition() != null){ + gameSell.setCondition(requestGameSell.getCondition()); + } + + gameSellRepository.save(gameSell); + + return new ResponseEntity<>(game.getTitle() + " обновлена", HttpStatus.OK); + } + //todo: diary //todo: edit user //todo: add game 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..ff90084 --- /dev/null +++ b/src/main/java/com/petproject/boardgamefun/dto/GameSellDTO.java @@ -0,0 +1,10 @@ +package com.petproject.boardgamefun.dto; + +import com.petproject.boardgamefun.model.Game; + +public interface GameSellDTO { + Game getGame(); + String getCondition(); + String getComment(); + Integer getPrice(); +} diff --git a/src/main/java/com/petproject/boardgamefun/dto/RequestGameSell.java b/src/main/java/com/petproject/boardgamefun/dto/RequestGameSell.java new file mode 100644 index 0000000..b1170d4 --- /dev/null +++ b/src/main/java/com/petproject/boardgamefun/dto/RequestGameSell.java @@ -0,0 +1,17 @@ +package com.petproject.boardgamefun.dto; + +import lombok.AllArgsConstructor; +import lombok.Data; +import lombok.Getter; +import lombok.Setter; + +@Data +@Getter +@Setter +@AllArgsConstructor +public class RequestGameSell { + private Integer gameId; + private String condition; + private String comment; + private Integer price; +} diff --git a/src/main/java/com/petproject/boardgamefun/repository/GameRepository.java b/src/main/java/com/petproject/boardgamefun/repository/GameRepository.java index c148837..bc35226 100644 --- a/src/main/java/com/petproject/boardgamefun/repository/GameRepository.java +++ b/src/main/java/com/petproject/boardgamefun/repository/GameRepository.java @@ -1,6 +1,7 @@ package com.petproject.boardgamefun.repository; import com.petproject.boardgamefun.dto.GameRatingDTO; +import com.petproject.boardgamefun.dto.GameSellDTO; import com.petproject.boardgamefun.model.Game; import org.springframework.data.jpa.repository.JpaRepository; import org.springframework.data.jpa.repository.Query; @@ -29,4 +30,11 @@ public interface GameRepository extends JpaRepository { "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); } \ 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 index b714a85..d2be19f 100644 --- a/src/main/java/com/petproject/boardgamefun/repository/GameSellRepository.java +++ b/src/main/java/com/petproject/boardgamefun/repository/GameSellRepository.java @@ -1,7 +1,10 @@ package com.petproject.boardgamefun.repository; +import com.petproject.boardgamefun.model.Game; import com.petproject.boardgamefun.model.GameSell; +import com.petproject.boardgamefun.model.User; import org.springframework.data.jpa.repository.JpaRepository; public interface GameSellRepository extends JpaRepository { + GameSell findByGameAndUser(Game game, User user); } \ No newline at end of file From 0adb5b0ec5e6c2d3a3246ed5741eaf814faec446 Mon Sep 17 00:00:00 2001 From: "i.i.artamonov" Date: Sat, 4 Dec 2021 13:16:58 +0400 Subject: [PATCH 010/141] Diary requests for UserConroller added Added next requests for diaries - add/update/delete/getlist. Change type of publication_date in Diary model --- .../controller/UserController.java | 92 +++++++++++++++---- .../boardgamefun/dto/RequestGameSell.java | 17 ---- .../petproject/boardgamefun/model/Diary.java | 8 +- .../repository/DiaryRepository.java | 13 +++ 4 files changed, 89 insertions(+), 41 deletions(-) delete mode 100644 src/main/java/com/petproject/boardgamefun/dto/RequestGameSell.java diff --git a/src/main/java/com/petproject/boardgamefun/controller/UserController.java b/src/main/java/com/petproject/boardgamefun/controller/UserController.java index 0a7923e..cb7ce0d 100644 --- a/src/main/java/com/petproject/boardgamefun/controller/UserController.java +++ b/src/main/java/com/petproject/boardgamefun/controller/UserController.java @@ -2,7 +2,6 @@ import com.petproject.boardgamefun.dto.GameRatingDTO; import com.petproject.boardgamefun.dto.GameSellDTO; -import com.petproject.boardgamefun.dto.RequestGameSell; import com.petproject.boardgamefun.model.*; import com.petproject.boardgamefun.repository.*; import com.petproject.boardgamefun.security.jwt.JwtUtils; @@ -21,6 +20,7 @@ import javax.transaction.Transactional; import java.time.OffsetDateTime; import java.util.List; +import java.util.Objects; @RestController @CrossOrigin(origins = "*", maxAge = 3600) @@ -33,6 +33,7 @@ public class UserController { final RatingGameByUserRepository ratingGameByUserRepository; final UserWishRepository userWishRepository; final GameSellRepository gameSellRepository; + final DiaryRepository diaryRepository; final PasswordEncoder passwordEncoder; final JwtUtils jwtUtils; @@ -43,7 +44,7 @@ public UserController(GameRepository gameRepository, UserOwnGameRepository userOwnGameRepository, RatingGameByUserRepository ratingGameByUserRepository, UserWishRepository userWishRepository, - GameSellRepository gameSellRepository, PasswordEncoder passwordEncoder, + GameSellRepository gameSellRepository, DiaryRepository diaryRepository, PasswordEncoder passwordEncoder, JwtUtils jwtUtils, AuthenticationManager authenticationManager) { this.gameRepository = gameRepository; @@ -52,6 +53,7 @@ public UserController(GameRepository gameRepository, this.ratingGameByUserRepository = ratingGameByUserRepository; this.userWishRepository = userWishRepository; this.gameSellRepository = gameSellRepository; + this.diaryRepository = diaryRepository; this.passwordEncoder = passwordEncoder; this.jwtUtils = jwtUtils; this.authenticationManager = authenticationManager; @@ -221,17 +223,13 @@ public ResponseEntity deleteGameFromUserWishlist(@PathVariable Integer userId @Transactional @PostMapping("{userId}/add-game-to-sell/{gameId}") - public ResponseEntity addGameToSellList(@PathVariable Integer userId, @PathVariable Integer gameId, @RequestBody RequestGameSell requestGameSell){ + public ResponseEntity addGameToSellList(@PathVariable Integer userId, @PathVariable Integer gameId, @RequestBody GameSell gameSell){ var user = userRepository.findUserById(userId); var game = gameRepository.findGameById(gameId); - var gameSell = new GameSell(); gameSell.setGame(game); gameSell.setUser(user); - gameSell.setCondition(requestGameSell.getCondition()); - gameSell.setComment(requestGameSell.getComment()); - gameSell.setPrice(requestGameSell.getPrice()); gameSellRepository.save(gameSell); @@ -262,29 +260,83 @@ public ResponseEntity removeGameFromSell(@PathVariable Integer userId, @ } @Transactional - @PutMapping("{userId}/update-game-to-sell/{gameId}") - public ResponseEntity updateSellGame(@PathVariable Integer userId, @PathVariable Integer gameId, @RequestBody RequestGameSell requestGameSell){ + @PutMapping("/update-game-to-sell") + public ResponseEntity updateSellGame(@RequestBody GameSell gameSell){ - var user = userRepository.findUserById(userId); - var game = gameRepository.findGameById(gameId); + if (gameSell.getComment() != null){ + gameSell.setComment(gameSell.getComment()); + } + if (gameSell.getPrice() != null){ + gameSell.setPrice(gameSell.getPrice()); + } + if (gameSell.getCondition() != null){ + gameSell.setCondition(gameSell.getCondition()); + } - var gameSell = gameSellRepository.findByGameAndUser(game, user); + gameSellRepository.save(gameSell); + + return new ResponseEntity<>(gameSell.getGame().getTitle() + " обновлена", HttpStatus.OK); + } + + @Transactional + @PostMapping("{userId}/add-diary") + public ResponseEntity addDiary(@PathVariable Integer userId, @RequestBody Diary diary){ - if (requestGameSell.getComment() != null){ - gameSell.setComment(requestGameSell.getComment()); + var user = userRepository.findUserById(userId); + diary.setUser(user); + diary.setPublicationTime(OffsetDateTime.now()); + // todo: в будущем переделать без поиска в репозитории, а сразу получать весь объект, пока нет фронта - заглушка + if (diary.getGame() != null){ + var game = gameRepository.findGameById(diary.getGame().getId()); + diary.setGame(game); } - if (requestGameSell.getPrice() != null){ - gameSell.setPrice(requestGameSell.getPrice()); + + diaryRepository.save(diary); + + return new ResponseEntity<>(diary, HttpStatus.OK); + } + + @Transactional + @DeleteMapping("{userId}/remove-diary/{diaryId}") + public ResponseEntity deleteDiary(@PathVariable Integer userId, @PathVariable Integer diaryId){ + + var diary = diaryRepository.findDiary_ByUserIdAndId(userId, diaryId); + + diaryRepository.delete(diary); + + return new ResponseEntity<>("Дневник " + diary.getTitle() + " удален из ваших дневников", HttpStatus.OK); + } + + @Transactional + @GetMapping({"{userId}/diary-list"}) + public ResponseEntity> getListDiary(@PathVariable Integer userId){ + var diaries = diaryRepository.findDiary_ByUserId(userId); + + return new ResponseEntity<>(diaries, HttpStatus.OK); + } + + @Transactional + @PutMapping({"{userId}/update-diary/{diaryId}"}) + public ResponseEntity updateDiary(@PathVariable Integer diaryId, @PathVariable Integer userId, @RequestBody Diary diaryRequest){ + //посмотреть на обновление продаваемой игры + + var diary = diaryRepository.findDiary_ByUserIdAndId(userId, diaryId); + if (diaryRequest.getTitle() != null && !Objects.equals(diary.getTitle(), diaryRequest.getTitle())){ + diary.setTitle(diaryRequest.getTitle()); } - if (requestGameSell.getCondition() != null){ - gameSell.setCondition(requestGameSell.getCondition()); + if (diaryRequest.getText() != null && !Objects.equals(diary.getText(), diaryRequest.getText())) { + diary.setText(diaryRequest.getText()); } - gameSellRepository.save(gameSell); + diaryRepository.save(diary); - return new ResponseEntity<>(game.getTitle() + " обновлена", HttpStatus.OK); + return new ResponseEntity<>(diary, HttpStatus.OK); } + + + //todo: optimize response - not whole model, only needed fields + //todo: add news //todo: diary //todo: edit user //todo: add game diff --git a/src/main/java/com/petproject/boardgamefun/dto/RequestGameSell.java b/src/main/java/com/petproject/boardgamefun/dto/RequestGameSell.java deleted file mode 100644 index b1170d4..0000000 --- a/src/main/java/com/petproject/boardgamefun/dto/RequestGameSell.java +++ /dev/null @@ -1,17 +0,0 @@ -package com.petproject.boardgamefun.dto; - -import lombok.AllArgsConstructor; -import lombok.Data; -import lombok.Getter; -import lombok.Setter; - -@Data -@Getter -@Setter -@AllArgsConstructor -public class RequestGameSell { - private Integer gameId; - private String condition; - private String comment; - private Integer price; -} diff --git a/src/main/java/com/petproject/boardgamefun/model/Diary.java b/src/main/java/com/petproject/boardgamefun/model/Diary.java index 3ffd3d8..107900f 100644 --- a/src/main/java/com/petproject/boardgamefun/model/Diary.java +++ b/src/main/java/com/petproject/boardgamefun/model/Diary.java @@ -1,7 +1,7 @@ package com.petproject.boardgamefun.model; import javax.persistence.*; -import java.time.OffsetTime; +import java.time.OffsetDateTime; @Table(name = "diary") @Entity @@ -20,7 +20,7 @@ public class Diary { private String text; @Column(name = "publication_time", nullable = false) - private OffsetTime publicationTime; + private OffsetDateTime publicationTime; @ManyToOne @JoinColumn(name = "game") @@ -46,11 +46,11 @@ public void setGame(Game game) { this.game = game; } - public OffsetTime getPublicationTime() { + public OffsetDateTime getPublicationTime() { return publicationTime; } - public void setPublicationTime(OffsetTime publicationTime) { + public void setPublicationTime(OffsetDateTime publicationTime) { this.publicationTime = publicationTime; } diff --git a/src/main/java/com/petproject/boardgamefun/repository/DiaryRepository.java b/src/main/java/com/petproject/boardgamefun/repository/DiaryRepository.java index 2a07591..0626ae4 100644 --- a/src/main/java/com/petproject/boardgamefun/repository/DiaryRepository.java +++ b/src/main/java/com/petproject/boardgamefun/repository/DiaryRepository.java @@ -1,7 +1,20 @@ package com.petproject.boardgamefun.repository; import com.petproject.boardgamefun.model.Diary; +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 DiaryRepository extends JpaRepository { + Diary findByUserAndId(User user, Integer id); + + + Diary findDiary_ByUserIdAndId(Integer userId, Integer id); + + + ListfindDiary_ByUserId(Integer userId); + + } \ No newline at end of file From 0747658d0482b52f717ca5167654f293aaaebe27 Mon Sep 17 00:00:00 2001 From: "i.i.artamonov" Date: Sat, 4 Dec 2021 13:39:50 +0400 Subject: [PATCH 011/141] Optimize searchinh queries Now, instead of query of whole models user and game, the search is performed by userId and gameId --- .../controller/UserController.java | 30 +++++++------------ .../repository/DiaryRepository.java | 1 - .../repository/GameSellRepository.java | 4 +-- .../RatingGameByUserRepository.java | 4 +-- .../repository/UserOwnGameRepository.java | 6 ++-- 5 files changed, 14 insertions(+), 31 deletions(-) diff --git a/src/main/java/com/petproject/boardgamefun/controller/UserController.java b/src/main/java/com/petproject/boardgamefun/controller/UserController.java index cb7ce0d..3f12be4 100644 --- a/src/main/java/com/petproject/boardgamefun/controller/UserController.java +++ b/src/main/java/com/petproject/boardgamefun/controller/UserController.java @@ -127,16 +127,13 @@ public ResponseEntity addGameToUser(@PathVariable Integer userId, @PathVariab @Transactional @DeleteMapping("{userId}/delete-game/{gameId}") - public ResponseEntity deleteGameFromUserCollection(@PathVariable Integer userId, @PathVariable Integer gameId) { + public ResponseEntity deleteGameFromUserCollection(@PathVariable Integer userId, @PathVariable Integer gameId) { - var user = userRepository.findUserById(userId); - var game = gameRepository.findGameById(gameId); - - var userOwnGame = userOwnGameRepository.findByGameAndUser(game, user); + var userOwnGame = userOwnGameRepository.findUserOwnGame_ByGameIdAndUserId(gameId, userId); userOwnGameRepository.delete(userOwnGame); - return new ResponseEntity<>(game.getTitle() + " удалена из вашей коллекции", HttpStatus.OK); + return new ResponseEntity<>(gameId, HttpStatus.OK); } @GetMapping("/{userId}/games-rating") @@ -151,10 +148,7 @@ public ResponseEntity> getUserRatingList(@PathVariable Integ @DeleteMapping("/{userId}/delete-game-rating/{gameId}") public ResponseEntity deleteGameRating(@PathVariable Integer userId, @PathVariable Integer gameId) { - var user = userRepository.findUserById(userId); - var game = gameRepository.findGameById(gameId); - - var ratingGameByUser = ratingGameByUserRepository.findByGameAndUser(game, user); + var ratingGameByUser = ratingGameByUserRepository.findRatingGame_ByGameIdAndUserId(gameId, userId); ratingGameByUserRepository.delete(ratingGameByUser); @@ -165,16 +159,15 @@ public ResponseEntity deleteGameRating(@PathVariable Integer userId, @Pa @PostMapping("/{userId}/set-game-rating/{gameId}/{rating}") public ResponseEntity setGameRating(@PathVariable Integer userId, @PathVariable Integer gameId, @PathVariable Integer rating) { - var user = userRepository.findUserById(userId); - var game = gameRepository.findGameById(gameId); - - var ratingGameByUser = ratingGameByUserRepository.findByGameAndUser(game, user); + var ratingGameByUser = ratingGameByUserRepository.findRatingGame_ByGameIdAndUserId(gameId, userId); if (ratingGameByUser != null) { ratingGameByUser.setRating(rating); ratingGameByUserRepository.save(ratingGameByUser); } else { var gameRating = new RatingGameByUser(); + var game = gameRepository.findGameById(gameId); + var user = userRepository.findUserById(userId); gameRating.setGame(game); gameRating.setUser(user); gameRating.setRating(rating); @@ -248,15 +241,12 @@ public ResponseEntity> getGameSellList(@PathVariable Integer u @Transactional @DeleteMapping("{userId}/remove-game-from-sell/{gameId}") - public ResponseEntity removeGameFromSell(@PathVariable Integer userId, @PathVariable Integer gameId){ - - var user = userRepository.findUserById(userId); - var game = gameRepository.findGameById(gameId); + public ResponseEntity removeGameFromSell(@PathVariable Integer userId, @PathVariable Integer gameId){ - var gameSell = gameSellRepository.findByGameAndUser(game, user); + var gameSell = gameSellRepository.findGameSell_ByGameIdAndUserId(gameId, userId); gameSellRepository.delete(gameSell); - return new ResponseEntity<>(game.getTitle() + " убрана из списка продаж", HttpStatus.OK); + return new ResponseEntity<>(gameId, HttpStatus.OK); } @Transactional diff --git a/src/main/java/com/petproject/boardgamefun/repository/DiaryRepository.java b/src/main/java/com/petproject/boardgamefun/repository/DiaryRepository.java index 0626ae4..09abe90 100644 --- a/src/main/java/com/petproject/boardgamefun/repository/DiaryRepository.java +++ b/src/main/java/com/petproject/boardgamefun/repository/DiaryRepository.java @@ -3,7 +3,6 @@ import com.petproject.boardgamefun.model.Diary; import com.petproject.boardgamefun.model.User; import org.springframework.data.jpa.repository.JpaRepository; -import org.springframework.data.jpa.repository.Query; import java.util.List; diff --git a/src/main/java/com/petproject/boardgamefun/repository/GameSellRepository.java b/src/main/java/com/petproject/boardgamefun/repository/GameSellRepository.java index d2be19f..f1c33b0 100644 --- a/src/main/java/com/petproject/boardgamefun/repository/GameSellRepository.java +++ b/src/main/java/com/petproject/boardgamefun/repository/GameSellRepository.java @@ -1,10 +1,8 @@ package com.petproject.boardgamefun.repository; -import com.petproject.boardgamefun.model.Game; import com.petproject.boardgamefun.model.GameSell; -import com.petproject.boardgamefun.model.User; import org.springframework.data.jpa.repository.JpaRepository; public interface GameSellRepository extends JpaRepository { - GameSell findByGameAndUser(Game game, User user); + GameSell findGameSell_ByGameIdAndUserId(Integer gameId, Integer userId); } \ 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 index b2f3067..5b3ea03 100644 --- a/src/main/java/com/petproject/boardgamefun/repository/RatingGameByUserRepository.java +++ b/src/main/java/com/petproject/boardgamefun/repository/RatingGameByUserRepository.java @@ -1,10 +1,8 @@ package com.petproject.boardgamefun.repository; -import com.petproject.boardgamefun.model.Game; import com.petproject.boardgamefun.model.RatingGameByUser; -import com.petproject.boardgamefun.model.User; import org.springframework.data.jpa.repository.JpaRepository; public interface RatingGameByUserRepository extends JpaRepository { - RatingGameByUser findByGameAndUser(Game game, User user); + RatingGameByUser findRatingGame_ByGameIdAndUserId(Integer gameId, Integer userId); } \ 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 index 00545f3..9a6824b 100644 --- a/src/main/java/com/petproject/boardgamefun/repository/UserOwnGameRepository.java +++ b/src/main/java/com/petproject/boardgamefun/repository/UserOwnGameRepository.java @@ -1,10 +1,8 @@ package com.petproject.boardgamefun.repository; -import com.petproject.boardgamefun.model.Game; -import com.petproject.boardgamefun.model.User; import com.petproject.boardgamefun.model.UserOwnGame; import org.springframework.data.jpa.repository.JpaRepository; public interface UserOwnGameRepository extends JpaRepository { - UserOwnGame findByGameAndUser(Game game, User user); -} \ No newline at end of file + UserOwnGame findUserOwnGame_ByGameIdAndUserId(Integer gameId, Integer userId); +} From 14f6cfb98bca369024b190c8776bcb6e6048c955 Mon Sep 17 00:00:00 2001 From: "i.i.artamonov" Date: Mon, 6 Dec 2021 09:50:32 +0400 Subject: [PATCH 012/141] Requests for DiaryComents in DiaryController added Added next requests for comments - add, update, get, delete for DiaryController. Change data type of publication time as well as in db. DiaryComment Request added. Delete unused method in diaryRepository --- .../controller/DiaryController.java | 102 ++++++++++++++++++ .../boardgamefun/dto/DiaryCommentRequest.java | 12 +++ .../boardgamefun/model/DiaryComment.java | 9 +- .../repository/DiaryCommentRepository.java | 4 + .../repository/DiaryRepository.java | 6 +- 5 files changed, 125 insertions(+), 8 deletions(-) create mode 100644 src/main/java/com/petproject/boardgamefun/controller/DiaryController.java create mode 100644 src/main/java/com/petproject/boardgamefun/dto/DiaryCommentRequest.java 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..f28b185 --- /dev/null +++ b/src/main/java/com/petproject/boardgamefun/controller/DiaryController.java @@ -0,0 +1,102 @@ +package com.petproject.boardgamefun.controller; + +import com.petproject.boardgamefun.dto.DiaryCommentRequest; +import com.petproject.boardgamefun.model.DiaryComment; +import com.petproject.boardgamefun.model.DiaryRating; +import com.petproject.boardgamefun.repository.DiaryCommentRepository; +import com.petproject.boardgamefun.repository.DiaryRepository; +import com.petproject.boardgamefun.repository.UserRepository; +import org.springframework.http.HttpStatus; +import org.springframework.http.ResponseEntity; +import org.springframework.web.bind.annotation.*; + +import javax.transaction.Transactional; +import java.time.OffsetDateTime; +import java.util.List; + + +@RestController +@CrossOrigin(origins = "*", maxAge = 3600) +@RequestMapping("/diaries") +public class DiaryController { + final DiaryCommentRepository diaryCommentRepository; + final UserRepository userRepository; + final DiaryRepository diaryRepository; + + public DiaryController(DiaryCommentRepository diaryCommentRepository, UserRepository userRepository, DiaryRepository diaryRepository) { + this.diaryCommentRepository = diaryCommentRepository; + this.userRepository = userRepository; + this.diaryRepository = diaryRepository; + } + + @Transactional + @GetMapping("/{diaryId}/comments") + public ResponseEntity> getDiaryComments(@PathVariable Integer diaryId){ + var diaryComments = diaryCommentRepository.findDiaryComment_ByDiaryId(diaryId); + + return new ResponseEntity<>(diaryComments, HttpStatus.OK); + } + + @Transactional + @PostMapping(value = "{diaryId}/add-comment/{userId}") + 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 = diaryCommentRepository.findDiaryComment_ByDiaryId(diaryId); + + return new ResponseEntity<>(diaryComments, HttpStatus.OK); + } + + @Transactional + @PatchMapping(value = "{diaryId}/update-comment/{diaryCommentId}") + 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 = diaryCommentRepository.findDiaryComment_ByDiaryId(diaryId); + + return new ResponseEntity<>(diaryComments, HttpStatus.OK); + } + + @Transactional + @DeleteMapping("{diaryId}/delete-comment/{diaryCommentId}") + public ResponseEntity> deleteComment(@PathVariable Integer diaryId, @PathVariable Integer diaryCommentId){ + + var diaryComment = diaryCommentRepository.findDiaryCommentById(diaryCommentId); + diaryCommentRepository.delete(diaryComment); + var diaryComments = diaryCommentRepository.findDiaryComment_ByDiaryId(diaryId); + + return new ResponseEntity<>(diaryComments, HttpStatus.OK); + } + + @PostMapping("/{diaryId}/set-rating/{userId}") + public ResponseEntity setDiaryRating(@PathVariable Integer diaryId, @PathVariable Integer userId, @RequestBody Integer rating){ + return null; + } + + @PutMapping("/{diaryId}/update-rating/{userId}") + public ResponseEntity updateDiaryRating(@PathVariable Integer diaryId, @PathVariable Integer userId, @RequestBody Integer rating){ + return null; + } + + @DeleteMapping("/{diaryId}/delete-rating/{userId}") + public ResponseEntity deleteDiaryRating(@PathVariable Integer diaryId, @PathVariable Integer userId, @RequestBody Integer rating){ + return null; + } + + + //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/dto/DiaryCommentRequest.java b/src/main/java/com/petproject/boardgamefun/dto/DiaryCommentRequest.java new file mode 100644 index 0000000..8de0d9a --- /dev/null +++ b/src/main/java/com/petproject/boardgamefun/dto/DiaryCommentRequest.java @@ -0,0 +1,12 @@ +package com.petproject.boardgamefun.dto; + +import lombok.*; + +@Data +@Getter +@Setter +@AllArgsConstructor +@NoArgsConstructor +public class DiaryCommentRequest { + private String comment; +} diff --git a/src/main/java/com/petproject/boardgamefun/model/DiaryComment.java b/src/main/java/com/petproject/boardgamefun/model/DiaryComment.java index be62aaf..04a47ef 100644 --- a/src/main/java/com/petproject/boardgamefun/model/DiaryComment.java +++ b/src/main/java/com/petproject/boardgamefun/model/DiaryComment.java @@ -1,7 +1,8 @@ package com.petproject.boardgamefun.model; import javax.persistence.*; -import java.time.OffsetTime; +import java.time.OffsetDateTime; + @Table(name = "diary_comment") @Entity @@ -16,7 +17,7 @@ public class DiaryComment { private String comment; @Column(name = "comment_time", nullable = false) - private OffsetTime commentTime; + private OffsetDateTime commentTime; @ManyToOne(optional = false) @JoinColumn(name = "diary", nullable = false) @@ -42,11 +43,11 @@ public void setDiary(Diary diary) { this.diary = diary; } - public OffsetTime getCommentTime() { + public OffsetDateTime getCommentTime() { return commentTime; } - public void setCommentTime(OffsetTime commentTime) { + public void setCommentTime(OffsetDateTime commentTime) { this.commentTime = commentTime; } diff --git a/src/main/java/com/petproject/boardgamefun/repository/DiaryCommentRepository.java b/src/main/java/com/petproject/boardgamefun/repository/DiaryCommentRepository.java index ce9b7e7..7ba526f 100644 --- a/src/main/java/com/petproject/boardgamefun/repository/DiaryCommentRepository.java +++ b/src/main/java/com/petproject/boardgamefun/repository/DiaryCommentRepository.java @@ -3,5 +3,9 @@ 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/DiaryRepository.java b/src/main/java/com/petproject/boardgamefun/repository/DiaryRepository.java index 09abe90..2e9a246 100644 --- a/src/main/java/com/petproject/boardgamefun/repository/DiaryRepository.java +++ b/src/main/java/com/petproject/boardgamefun/repository/DiaryRepository.java @@ -7,13 +7,11 @@ import java.util.List; public interface DiaryRepository extends JpaRepository { - Diary findByUserAndId(User user, Integer id); - - Diary findDiary_ByUserIdAndId(Integer userId, Integer id); - ListfindDiary_ByUserId(Integer userId); + Diary findDiaryById(Integer id); + } \ No newline at end of file From 154ace1920dc0f50abe8650b5ca3b10086130c05 Mon Sep 17 00:00:00 2001 From: "i.i.artamonov" Date: Mon, 6 Dec 2021 20:33:29 +0400 Subject: [PATCH 013/141] Requests for diaries rating in DiaryContorller added Added next requests for rating - update/delete/set rating in DiaryController --- pom.xml | 2 +- .../controller/DiaryController.java | 45 +++++++++++++++---- .../boardgamefun/dto/DiaryRatingRequest.java | 12 +++++ .../repository/DiaryRatingRepository.java | 1 + 4 files changed, 50 insertions(+), 10 deletions(-) create mode 100644 src/main/java/com/petproject/boardgamefun/dto/DiaryRatingRequest.java diff --git a/pom.xml b/pom.xml index fae6cae..036a6b5 100644 --- a/pom.xml +++ b/pom.xml @@ -23,7 +23,7 @@ - + diff --git a/src/main/java/com/petproject/boardgamefun/controller/DiaryController.java b/src/main/java/com/petproject/boardgamefun/controller/DiaryController.java index f28b185..924a42a 100644 --- a/src/main/java/com/petproject/boardgamefun/controller/DiaryController.java +++ b/src/main/java/com/petproject/boardgamefun/controller/DiaryController.java @@ -1,9 +1,11 @@ package com.petproject.boardgamefun.controller; import com.petproject.boardgamefun.dto.DiaryCommentRequest; +import com.petproject.boardgamefun.dto.DiaryRatingRequest; 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 org.springframework.http.HttpStatus; @@ -13,6 +15,7 @@ import javax.transaction.Transactional; import java.time.OffsetDateTime; import java.util.List; +import java.util.Objects; @RestController @@ -22,11 +25,13 @@ public class DiaryController { final DiaryCommentRepository diaryCommentRepository; final UserRepository userRepository; final DiaryRepository diaryRepository; + final DiaryRatingRepository diaryRatingRepository; - public DiaryController(DiaryCommentRepository diaryCommentRepository, UserRepository userRepository, DiaryRepository diaryRepository) { + public DiaryController(DiaryCommentRepository diaryCommentRepository, UserRepository userRepository, DiaryRepository diaryRepository, DiaryRatingRepository diaryRatingRepository) { this.diaryCommentRepository = diaryCommentRepository; this.userRepository = userRepository; this.diaryRepository = diaryRepository; + this.diaryRatingRepository = diaryRatingRepository; } @Transactional @@ -81,19 +86,41 @@ public ResponseEntity> deleteComment(@PathVariable Integer di return new ResponseEntity<>(diaryComments, HttpStatus.OK); } + @Transactional @PostMapping("/{diaryId}/set-rating/{userId}") - public ResponseEntity setDiaryRating(@PathVariable Integer diaryId, @PathVariable Integer userId, @RequestBody Integer rating){ - return null; + 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); + + return new ResponseEntity<>(diaryRating, HttpStatus.OK); } - @PutMapping("/{diaryId}/update-rating/{userId}") - public ResponseEntity updateDiaryRating(@PathVariable Integer diaryId, @PathVariable Integer userId, @RequestBody Integer rating){ - return null; + @Transactional + @PatchMapping("/update-rating/{ratingId}") + 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); + + return new ResponseEntity<>(diaryRating, HttpStatus.OK); } - @DeleteMapping("/{diaryId}/delete-rating/{userId}") - public ResponseEntity deleteDiaryRating(@PathVariable Integer diaryId, @PathVariable Integer userId, @RequestBody Integer rating){ - return null; + @Transactional + @DeleteMapping("/delete-rating/{ratingId}") + public ResponseEntity deleteDiaryRating(@PathVariable Integer ratingId){ + var diaryRating = diaryRatingRepository.findDiaryRatingById(ratingId); + diaryRatingRepository.delete(diaryRating); + return new ResponseEntity<>("Рейтинг убран с игры", HttpStatus.OK); } diff --git a/src/main/java/com/petproject/boardgamefun/dto/DiaryRatingRequest.java b/src/main/java/com/petproject/boardgamefun/dto/DiaryRatingRequest.java new file mode 100644 index 0000000..7099b07 --- /dev/null +++ b/src/main/java/com/petproject/boardgamefun/dto/DiaryRatingRequest.java @@ -0,0 +1,12 @@ +package com.petproject.boardgamefun.dto; + +import lombok.*; + +@Data +@Setter +@Getter +@NoArgsConstructor +@AllArgsConstructor +public class DiaryRatingRequest { + private Double rating; +} diff --git a/src/main/java/com/petproject/boardgamefun/repository/DiaryRatingRepository.java b/src/main/java/com/petproject/boardgamefun/repository/DiaryRatingRepository.java index d93dfc7..4238e74 100644 --- a/src/main/java/com/petproject/boardgamefun/repository/DiaryRatingRepository.java +++ b/src/main/java/com/petproject/boardgamefun/repository/DiaryRatingRepository.java @@ -4,4 +4,5 @@ import org.springframework.data.jpa.repository.JpaRepository; public interface DiaryRatingRepository extends JpaRepository { + DiaryRating findDiaryRatingById(Integer id); } \ No newline at end of file From efed34e9cdef5ddc9278c254fdb61e518c86475d Mon Sep 17 00:00:00 2001 From: "i.i.artamonov" Date: Tue, 7 Dec 2021 08:49:16 +0400 Subject: [PATCH 014/141] Change response of list Diaries Now list diaries return with their ratings. Change the name of dto for more clearness. --- .../boardgamefun/controller/DiaryController.java | 9 +++++++++ .../boardgamefun/controller/UserController.java | 12 ++++++------ .../dto/DiariesWithRatingsResponse.java | 8 ++++++++ ...{GameRatingDTO.java => UserGameRatingDTO.java} | 2 +- .../boardgamefun/repository/DiaryRepository.java | 15 ++++++++++++--- .../boardgamefun/repository/GameRepository.java | 4 ++-- 6 files changed, 38 insertions(+), 12 deletions(-) create mode 100644 src/main/java/com/petproject/boardgamefun/dto/DiariesWithRatingsResponse.java rename src/main/java/com/petproject/boardgamefun/dto/{GameRatingDTO.java => UserGameRatingDTO.java} (78%) diff --git a/src/main/java/com/petproject/boardgamefun/controller/DiaryController.java b/src/main/java/com/petproject/boardgamefun/controller/DiaryController.java index 924a42a..c9dd316 100644 --- a/src/main/java/com/petproject/boardgamefun/controller/DiaryController.java +++ b/src/main/java/com/petproject/boardgamefun/controller/DiaryController.java @@ -1,5 +1,6 @@ package com.petproject.boardgamefun.controller; +import com.petproject.boardgamefun.dto.DiariesWithRatingsResponse; import com.petproject.boardgamefun.dto.DiaryCommentRequest; import com.petproject.boardgamefun.dto.DiaryRatingRequest; import com.petproject.boardgamefun.model.DiaryComment; @@ -34,6 +35,14 @@ public DiaryController(DiaryCommentRepository diaryCommentRepository, UserReposi this.diaryRatingRepository = diaryRatingRepository; } + @Transactional + @GetMapping("") + public ResponseEntity> getDiaries(){ + var diaries = diaryRepository.getAllDiaries(); + + return new ResponseEntity<>(diaries, HttpStatus.OK); + } + @Transactional @GetMapping("/{diaryId}/comments") public ResponseEntity> getDiaryComments(@PathVariable Integer diaryId){ diff --git a/src/main/java/com/petproject/boardgamefun/controller/UserController.java b/src/main/java/com/petproject/boardgamefun/controller/UserController.java index 3f12be4..206c465 100644 --- a/src/main/java/com/petproject/boardgamefun/controller/UserController.java +++ b/src/main/java/com/petproject/boardgamefun/controller/UserController.java @@ -1,6 +1,7 @@ package com.petproject.boardgamefun.controller; -import com.petproject.boardgamefun.dto.GameRatingDTO; +import com.petproject.boardgamefun.dto.DiariesWithRatingsResponse; +import com.petproject.boardgamefun.dto.UserGameRatingDTO; import com.petproject.boardgamefun.dto.GameSellDTO; import com.petproject.boardgamefun.model.*; import com.petproject.boardgamefun.repository.*; @@ -137,9 +138,9 @@ public ResponseEntity deleteGameFromUserCollection(@PathVariable Intege } @GetMapping("/{userId}/games-rating") - public ResponseEntity> getUserRatingList(@PathVariable Integer userId) { + public ResponseEntity> getUserRatingList(@PathVariable Integer userId) { - var ratingGamesByUser = gameRepository.findGameRatingList(userId); + var ratingGamesByUser = gameRepository.findUserGameRatingList(userId); return new ResponseEntity<>(ratingGamesByUser, HttpStatus.OK); } @@ -299,8 +300,8 @@ public ResponseEntity deleteDiary(@PathVariable Integer userId, @PathVar @Transactional @GetMapping({"{userId}/diary-list"}) - public ResponseEntity> getListDiary(@PathVariable Integer userId){ - var diaries = diaryRepository.findDiary_ByUserId(userId); + public ResponseEntity> getListDiary(@PathVariable Integer userId){ + var diaries = diaryRepository.findUserDiaries(userId); return new ResponseEntity<>(diaries, HttpStatus.OK); } @@ -308,7 +309,6 @@ public ResponseEntity> getListDiary(@PathVariable Integer userId){ @Transactional @PutMapping({"{userId}/update-diary/{diaryId}"}) public ResponseEntity updateDiary(@PathVariable Integer diaryId, @PathVariable Integer userId, @RequestBody Diary diaryRequest){ - //посмотреть на обновление продаваемой игры var diary = diaryRepository.findDiary_ByUserIdAndId(userId, diaryId); if (diaryRequest.getTitle() != null && !Objects.equals(diary.getTitle(), diaryRequest.getTitle())){ diff --git a/src/main/java/com/petproject/boardgamefun/dto/DiariesWithRatingsResponse.java b/src/main/java/com/petproject/boardgamefun/dto/DiariesWithRatingsResponse.java new file mode 100644 index 0000000..2b61172 --- /dev/null +++ b/src/main/java/com/petproject/boardgamefun/dto/DiariesWithRatingsResponse.java @@ -0,0 +1,8 @@ +package com.petproject.boardgamefun.dto; + +import com.petproject.boardgamefun.model.Diary; + +public interface DiariesWithRatingsResponse { + Diary getDiary(); + Double getRating(); +} diff --git a/src/main/java/com/petproject/boardgamefun/dto/GameRatingDTO.java b/src/main/java/com/petproject/boardgamefun/dto/UserGameRatingDTO.java similarity index 78% rename from src/main/java/com/petproject/boardgamefun/dto/GameRatingDTO.java rename to src/main/java/com/petproject/boardgamefun/dto/UserGameRatingDTO.java index 11bea2c..e5178ff 100644 --- a/src/main/java/com/petproject/boardgamefun/dto/GameRatingDTO.java +++ b/src/main/java/com/petproject/boardgamefun/dto/UserGameRatingDTO.java @@ -2,7 +2,7 @@ import com.petproject.boardgamefun.model.Game; -public interface GameRatingDTO { +public interface UserGameRatingDTO { Game getGame(); Integer getRating(); } \ 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 index 2e9a246..7b2f586 100644 --- a/src/main/java/com/petproject/boardgamefun/repository/DiaryRepository.java +++ b/src/main/java/com/petproject/boardgamefun/repository/DiaryRepository.java @@ -1,17 +1,26 @@ package com.petproject.boardgamefun.repository; +import com.petproject.boardgamefun.dto.DiariesWithRatingsResponse; import com.petproject.boardgamefun.model.Diary; -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 DiaryRepository extends JpaRepository { Diary findDiary_ByUserIdAndId(Integer userId, Integer id); - ListfindDiary_ByUserId(Integer userId); + @Query("select d as diary, avg(dr.rating) as rating from Diary d " + + "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); Diary findDiaryById(Integer id); - + @Query("select d as diary, avg(dr.rating) as rating from Diary d " + + "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/GameRepository.java b/src/main/java/com/petproject/boardgamefun/repository/GameRepository.java index bc35226..4b063ea 100644 --- a/src/main/java/com/petproject/boardgamefun/repository/GameRepository.java +++ b/src/main/java/com/petproject/boardgamefun/repository/GameRepository.java @@ -1,6 +1,6 @@ package com.petproject.boardgamefun.repository; -import com.petproject.boardgamefun.dto.GameRatingDTO; +import com.petproject.boardgamefun.dto.UserGameRatingDTO; import com.petproject.boardgamefun.dto.GameSellDTO; import com.petproject.boardgamefun.model.Game; import org.springframework.data.jpa.repository.JpaRepository; @@ -23,7 +23,7 @@ public interface GameRepository extends JpaRepository { "join User u on u.id = rgbu.user.id " + "where u.id = :id " + "order by rgbu.rating desc") - List findGameRatingList(Integer id); + List findUserGameRatingList(Integer id); @Query("Select g from Game g " + "join UserWish uw on g.id = uw.game.id " + From 918290ed15d178d1b2802da38142d9ff45777800 Mon Sep 17 00:00:00 2001 From: "i.i.artamonov" Date: Wed, 8 Dec 2021 08:56:58 +0400 Subject: [PATCH 015/141] Edit user functionality added to UserController Change user data and password added to UserController. DTO for this requests added. Added Transactional annotation to methods - getUser, getUserCollectionByType --- .../controller/UserController.java | 47 +++++++++++++++++-- .../dto/PasswordChangeRequest.java | 12 +++++ .../boardgamefun/dto/UserEditRequest.java | 16 +++++++ 3 files changed, 71 insertions(+), 4 deletions(-) create mode 100644 src/main/java/com/petproject/boardgamefun/dto/PasswordChangeRequest.java create mode 100644 src/main/java/com/petproject/boardgamefun/dto/UserEditRequest.java diff --git a/src/main/java/com/petproject/boardgamefun/controller/UserController.java b/src/main/java/com/petproject/boardgamefun/controller/UserController.java index 206c465..9eb77f9 100644 --- a/src/main/java/com/petproject/boardgamefun/controller/UserController.java +++ b/src/main/java/com/petproject/boardgamefun/controller/UserController.java @@ -1,8 +1,6 @@ package com.petproject.boardgamefun.controller; -import com.petproject.boardgamefun.dto.DiariesWithRatingsResponse; -import com.petproject.boardgamefun.dto.UserGameRatingDTO; -import com.petproject.boardgamefun.dto.GameSellDTO; +import com.petproject.boardgamefun.dto.*; import com.petproject.boardgamefun.model.*; import com.petproject.boardgamefun.repository.*; import com.petproject.boardgamefun.security.jwt.JwtUtils; @@ -20,6 +18,7 @@ import javax.transaction.Transactional; import java.time.OffsetDateTime; +import java.util.Arrays; import java.util.List; import java.util.Objects; @@ -97,12 +96,52 @@ public ResponseEntity registerUser(@RequestBody User user) { return new ResponseEntity<>(user, HttpStatus.OK); } + @Transactional + @PatchMapping("/edit/{userId}") + public ResponseEntity editUser(@PathVariable Integer userId, @RequestBody UserEditRequest userEditRequest){ + var user = userRepository.findUserById(userId); + if (userEditRequest.getName() != null && !userRepository.existsByName(userEditRequest.getName())) { + user.setName(userEditRequest.getName()); + } + else{ + return new ResponseEntity<>("Пользователь с таким никнеймом уже существует", HttpStatus.BAD_REQUEST); + } + if (userEditRequest.getRole() != null && !Objects.equals(userEditRequest.getRole(), user.getRole())){ + user.setRole(userEditRequest.getRole()); + } + if (userEditRequest.getAvatar() != null && !Arrays.equals(userEditRequest.getAvatar(), user.getAvatar())){ + user.setAvatar(userEditRequest.getAvatar()); + } + + userRepository.save(user); + + return new ResponseEntity<>(user, HttpStatus.OK); + } + + @Transactional + @PatchMapping("/change-password/{userId}") + public ResponseEntity changePassword(@PathVariable Integer userId, @RequestBody PasswordChangeRequest passwordRequest){ + var user = userRepository.findUserById(userId); + if (passwordRequest.getPassword() != null && passwordEncoder.matches(passwordRequest.getPassword(), user.getPassword())){ + user.setPassword(passwordEncoder.encode(passwordRequest.getPassword())); + } + else { + return new ResponseEntity<>("Вы ввели точно такой же пароль", HttpStatus.BAD_REQUEST); + } + userRepository.save(user); + + return new ResponseEntity<>(user, HttpStatus.OK); + } + + + @Transactional @GetMapping("{id}") public ResponseEntity getUser(@PathVariable Integer id) { var user = userRepository.findUserById(id); return new ResponseEntity<>(user, HttpStatus.OK); } + @Transactional @GetMapping("/{id}/games") public ResponseEntity> getUserCollectionByType(@PathVariable Integer id) { @@ -328,7 +367,7 @@ public ResponseEntity updateDiary(@PathVariable Integer diaryId, @PathVar //todo: optimize response - not whole model, only needed fields //todo: add news //todo: diary - //todo: edit user + //todo: add game } diff --git a/src/main/java/com/petproject/boardgamefun/dto/PasswordChangeRequest.java b/src/main/java/com/petproject/boardgamefun/dto/PasswordChangeRequest.java new file mode 100644 index 0000000..fea8b74 --- /dev/null +++ b/src/main/java/com/petproject/boardgamefun/dto/PasswordChangeRequest.java @@ -0,0 +1,12 @@ +package com.petproject.boardgamefun.dto; + +import lombok.*; + +@Data +@Setter +@Getter +@AllArgsConstructor +@NoArgsConstructor +public class PasswordChangeRequest { + private String password; +} diff --git a/src/main/java/com/petproject/boardgamefun/dto/UserEditRequest.java b/src/main/java/com/petproject/boardgamefun/dto/UserEditRequest.java new file mode 100644 index 0000000..da7aa23 --- /dev/null +++ b/src/main/java/com/petproject/boardgamefun/dto/UserEditRequest.java @@ -0,0 +1,16 @@ +package com.petproject.boardgamefun.dto; + +import lombok.AllArgsConstructor; +import lombok.Data; +import lombok.Getter; +import lombok.Setter; + +@Data +@Getter +@Setter +@AllArgsConstructor +public class UserEditRequest { + private String name; + private String role; + private byte[] avatar; +} From a59495e37faacd6ac7db8fc196614d27836917bf Mon Sep 17 00:00:00 2001 From: "i.i.artamonov" Date: Wed, 8 Dec 2021 10:03:02 +0400 Subject: [PATCH 016/141] Base requests for GameController added Added next requests - add/update/remove game from site in GameController. Change Game model field - release year. Edit todo's in UnitController. --- .../controller/GameController.java | 28 +++++++++++++++++++ .../controller/UserController.java | 7 ++--- .../petproject/boardgamefun/model/Game.java | 8 +++--- 3 files changed, 34 insertions(+), 9 deletions(-) diff --git a/src/main/java/com/petproject/boardgamefun/controller/GameController.java b/src/main/java/com/petproject/boardgamefun/controller/GameController.java index 22b061a..b455fb9 100644 --- a/src/main/java/com/petproject/boardgamefun/controller/GameController.java +++ b/src/main/java/com/petproject/boardgamefun/controller/GameController.java @@ -4,6 +4,7 @@ import com.petproject.boardgamefun.repository.GameRepository; import org.springframework.http.HttpStatus; import org.springframework.http.ResponseEntity; +import org.springframework.transaction.annotation.Transactional; import org.springframework.web.bind.annotation.*; import java.util.List; @@ -19,15 +20,42 @@ public GameController(GameRepository gameRepository) { this.gameRepository = gameRepository; } + @Transactional @GetMapping() ResponseEntity> getGames(){ var games = gameRepository.findAll(); return new ResponseEntity<>(games, HttpStatus.OK); } + @Transactional @GetMapping("{title}") ResponseEntity getGame(@PathVariable String title){ var game = gameRepository.findGameByTitle(title); return new ResponseEntity<>(game, HttpStatus.OK); } + + @Transactional + @PostMapping("/add") + public ResponseEntity addGame(@RequestBody Game newGame){ + gameRepository.save(newGame); + + return new ResponseEntity<>(newGame, HttpStatus.OK); + } + + @Transactional + @PutMapping("/update") + public ResponseEntity updateGame(@RequestBody Game updatedGame){ + gameRepository.save(updatedGame); + + return new ResponseEntity<>(updatedGame, HttpStatus.OK); + } + + @Transactional + @DeleteMapping("/remove") + public ResponseEntity removeGameFromSite(@RequestBody Game deleteGame){ + gameRepository.delete(deleteGame); + + return new ResponseEntity<>(deleteGame.getTitle() + " удалена из базы данных", HttpStatus.OK); + } + } diff --git a/src/main/java/com/petproject/boardgamefun/controller/UserController.java b/src/main/java/com/petproject/boardgamefun/controller/UserController.java index 9eb77f9..2663f20 100644 --- a/src/main/java/com/petproject/boardgamefun/controller/UserController.java +++ b/src/main/java/com/petproject/boardgamefun/controller/UserController.java @@ -362,12 +362,9 @@ public ResponseEntity updateDiary(@PathVariable Integer diaryId, @PathVar return new ResponseEntity<>(diary, HttpStatus.OK); } - - //todo: optimize response - not whole model, only needed fields //todo: add news - //todo: diary - - //todo: add game + //todo: add rights + //todo: unique repository??? } diff --git a/src/main/java/com/petproject/boardgamefun/model/Game.java b/src/main/java/com/petproject/boardgamefun/model/Game.java index e56b179..8712a29 100644 --- a/src/main/java/com/petproject/boardgamefun/model/Game.java +++ b/src/main/java/com/petproject/boardgamefun/model/Game.java @@ -3,7 +3,7 @@ import org.hibernate.annotations.Type; import javax.persistence.*; -import java.time.OffsetTime; +import java.time.OffsetDateTime; @Table(name = "game", indexes = { @Index(name = "game_un", columnList = "title", unique = true) @@ -19,7 +19,7 @@ public class Game { private String title; @Column(name = "year_of_release", nullable = false) - private OffsetTime yearOfRelease; + private OffsetDateTime yearOfRelease; @Lob @Type(type = "org.hibernate.type.TextType") @@ -113,11 +113,11 @@ public void setAnnotation(String annotation) { this.annotation = annotation; } - public OffsetTime getYearOfRelease() { + public OffsetDateTime getYearOfRelease() { return yearOfRelease; } - public void setYearOfRelease(OffsetTime yearOfRelease) { + public void setYearOfRelease(OffsetDateTime yearOfRelease) { this.yearOfRelease = yearOfRelease; } From 905a6c7a69a27b8a63c524f09d852c2dd66e710a Mon Sep 17 00:00:00 2001 From: "i.i.artamonov" Date: Thu, 9 Dec 2021 09:08:23 +0400 Subject: [PATCH 017/141] Expansions request for GameController added Next requests added - get,delete/add expansion link to GameController. Add todos. New methods for gamerepository and expansionrepository added. --- .../controller/GameController.java | 45 ++++++++++++++++++- .../repository/ExpansionRepository.java | 1 + .../repository/GameRepository.java | 5 +++ 3 files changed, 50 insertions(+), 1 deletion(-) diff --git a/src/main/java/com/petproject/boardgamefun/controller/GameController.java b/src/main/java/com/petproject/boardgamefun/controller/GameController.java index b455fb9..98b9101 100644 --- a/src/main/java/com/petproject/boardgamefun/controller/GameController.java +++ b/src/main/java/com/petproject/boardgamefun/controller/GameController.java @@ -1,6 +1,8 @@ package com.petproject.boardgamefun.controller; +import com.petproject.boardgamefun.model.Expansion; import com.petproject.boardgamefun.model.Game; +import com.petproject.boardgamefun.repository.ExpansionRepository; import com.petproject.boardgamefun.repository.GameRepository; import org.springframework.http.HttpStatus; import org.springframework.http.ResponseEntity; @@ -15,9 +17,11 @@ public class GameController { final GameRepository gameRepository; + final ExpansionRepository expansionRepository; - public GameController(GameRepository gameRepository) { + public GameController(GameRepository gameRepository, ExpansionRepository expansionRepository) { this.gameRepository = gameRepository; + this.expansionRepository = expansionRepository; } @Transactional @@ -58,4 +62,43 @@ public ResponseEntity removeGameFromSite(@RequestBody Game deleteGame){ return new ResponseEntity<>(deleteGame.getTitle() + " удалена из базы данных", HttpStatus.OK); } + @Transactional + @GetMapping("/expansions/{gameId}") + public ResponseEntity> getExpansions(@PathVariable Integer gameId){ + var gamesExpansions = gameRepository.getExpansions(gameId); + + return new ResponseEntity<>(gamesExpansions, HttpStatus.OK); + } + + @Transactional + @PostMapping("/add-expansion/{parentGameId}/{daughterGameId}") + public ResponseEntity> addExpansion(@PathVariable Integer parentGameId, @PathVariable Integer daughterGameId){ + var parentGame = gameRepository.findGameById(parentGameId); + var daughterGame = gameRepository.findGameById(daughterGameId); + + var expansion = new Expansion(); + expansion.setParentGame(parentGame); + expansion.setDaughterGame(daughterGame); + expansionRepository.save(expansion); + + var gamesExpansions = gameRepository.getExpansions(parentGameId); + + return new ResponseEntity<>(gamesExpansions, HttpStatus.OK); + } + + @Transactional + @DeleteMapping("/delete-expansion/{parentGameId}/{daughterGameId}") + public ResponseEntity> deleteExpansion(@PathVariable Integer daughterGameId, @PathVariable Integer parentGameId){ + var expansion = expansionRepository.findExpansion_ByDaughterGameIdAndParentGameId(daughterGameId, parentGameId); + expansionRepository.delete(expansion); + + var gamesExpansions = gameRepository.getExpansions(parentGameId); + + return new ResponseEntity<>(gamesExpansions, HttpStatus.OK); + } + + //todo: add same game + //todo: ratings list + //todo: forum + //todo: gat avg rating } diff --git a/src/main/java/com/petproject/boardgamefun/repository/ExpansionRepository.java b/src/main/java/com/petproject/boardgamefun/repository/ExpansionRepository.java index 7faf8ba..faed42d 100644 --- a/src/main/java/com/petproject/boardgamefun/repository/ExpansionRepository.java +++ b/src/main/java/com/petproject/boardgamefun/repository/ExpansionRepository.java @@ -4,4 +4,5 @@ import org.springframework.data.jpa.repository.JpaRepository; public interface ExpansionRepository extends JpaRepository { + Expansion findExpansion_ByDaughterGameIdAndParentGameId(Integer daughterId, Integer parentGameId); } \ 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 index 4b063ea..01b70a7 100644 --- a/src/main/java/com/petproject/boardgamefun/repository/GameRepository.java +++ b/src/main/java/com/petproject/boardgamefun/repository/GameRepository.java @@ -37,4 +37,9 @@ public interface GameRepository extends JpaRepository { "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); } \ No newline at end of file From 572ff59b6445b0bc0ee28c5417c3b44a2a0e3d2d Mon Sep 17 00:00:00 2001 From: "i.i.artamonov" Date: Thu, 9 Dec 2021 09:25:09 +0400 Subject: [PATCH 018/141] Similar games request for GameController added Next requests added - get,delete/add similar game link to GameController. New methods for gamerepository and sameGameRepository added. --- .../controller/GameController.java | 44 ++++++++++++++++++- .../repository/GameRepository.java | 5 +++ .../repository/SameGameRepository.java | 1 + 3 files changed, 48 insertions(+), 2 deletions(-) diff --git a/src/main/java/com/petproject/boardgamefun/controller/GameController.java b/src/main/java/com/petproject/boardgamefun/controller/GameController.java index 98b9101..fbefd70 100644 --- a/src/main/java/com/petproject/boardgamefun/controller/GameController.java +++ b/src/main/java/com/petproject/boardgamefun/controller/GameController.java @@ -2,8 +2,10 @@ import com.petproject.boardgamefun.model.Expansion; import com.petproject.boardgamefun.model.Game; +import com.petproject.boardgamefun.model.SameGame; import com.petproject.boardgamefun.repository.ExpansionRepository; import com.petproject.boardgamefun.repository.GameRepository; +import com.petproject.boardgamefun.repository.SameGameRepository; import org.springframework.http.HttpStatus; import org.springframework.http.ResponseEntity; import org.springframework.transaction.annotation.Transactional; @@ -18,10 +20,12 @@ public class GameController { final GameRepository gameRepository; final ExpansionRepository expansionRepository; + final SameGameRepository sameGameRepository; - public GameController(GameRepository gameRepository, ExpansionRepository expansionRepository) { + public GameController(GameRepository gameRepository, ExpansionRepository expansionRepository, SameGameRepository sameGameRepository) { this.gameRepository = gameRepository; this.expansionRepository = expansionRepository; + this.sameGameRepository = sameGameRepository; } @Transactional @@ -97,7 +101,43 @@ public ResponseEntity> deleteExpansion(@PathVariable Integer daughter return new ResponseEntity<>(gamesExpansions, HttpStatus.OK); } - //todo: add same game + @Transactional + @GetMapping("/similar/{gameId}") + public ResponseEntity> getSimilarGames(@PathVariable Integer gameId){ + var similarGames = gameRepository.getSimilarGames(gameId); + + return new ResponseEntity<>(similarGames, HttpStatus.OK); + } + + @Transactional + @PostMapping("/add-similar/{referenceGameId}/{sourceGameId}") + public ResponseEntity> addSimilarGame(@PathVariable Integer referenceGameId, @PathVariable Integer sourceGameId){ + var referenceGame = gameRepository.findGameById(referenceGameId); + var sourceGame = gameRepository.findGameById(sourceGameId); + + var sameGame = new SameGame(); + sameGame.setReferenceGame(referenceGame); + sameGame.setSourceGame(sourceGame); + sameGameRepository.save(sameGame); + + var sameGames = gameRepository.getSimilarGames(referenceGameId); + + return new ResponseEntity<>(sameGames, HttpStatus.OK); + } + + @Transactional + @DeleteMapping("/delete-similar/{referenceGameId}/{sourceGameId}") + public ResponseEntity> deleteSameGame(@PathVariable Integer referenceGameId, @PathVariable Integer sourceGameId){ + var sameGame = sameGameRepository.findSameGame_ByReferenceGameIdAndSourceGameId(referenceGameId, sourceGameId); + sameGameRepository.delete(sameGame); + + var sameGames = gameRepository.getSimilarGames(referenceGameId); + + return new ResponseEntity<>(sameGames, HttpStatus.OK); + } + + + //todo: ratings list //todo: forum //todo: gat avg rating diff --git a/src/main/java/com/petproject/boardgamefun/repository/GameRepository.java b/src/main/java/com/petproject/boardgamefun/repository/GameRepository.java index 01b70a7..05612aa 100644 --- a/src/main/java/com/petproject/boardgamefun/repository/GameRepository.java +++ b/src/main/java/com/petproject/boardgamefun/repository/GameRepository.java @@ -42,4 +42,9 @@ public interface GameRepository extends JpaRepository { "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/SameGameRepository.java b/src/main/java/com/petproject/boardgamefun/repository/SameGameRepository.java index 381d96f..69b9a11 100644 --- a/src/main/java/com/petproject/boardgamefun/repository/SameGameRepository.java +++ b/src/main/java/com/petproject/boardgamefun/repository/SameGameRepository.java @@ -4,4 +4,5 @@ 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 From 21a689a8209fe213e850712d00c70492619cdf7c Mon Sep 17 00:00:00 2001 From: "i.i.artamonov" Date: Thu, 9 Dec 2021 22:00:28 +0400 Subject: [PATCH 019/141] Added requests which return game with rating in GameController Added request for getting all users, who gave rating to game in UserRepository. Same with GameRepository. Added dto to this requests. --- .../controller/GameController.java | 46 +++++++++++++------ .../dto/GameWithAverageRatingDTO.java | 8 ++++ .../boardgamefun/dto/UsersGameRatingDTO.java | 8 ++++ .../repository/GameRepository.java | 11 +++++ .../repository/UserRepository.java | 10 ++++ 5 files changed, 70 insertions(+), 13 deletions(-) create mode 100644 src/main/java/com/petproject/boardgamefun/dto/GameWithAverageRatingDTO.java create mode 100644 src/main/java/com/petproject/boardgamefun/dto/UsersGameRatingDTO.java diff --git a/src/main/java/com/petproject/boardgamefun/controller/GameController.java b/src/main/java/com/petproject/boardgamefun/controller/GameController.java index fbefd70..7885296 100644 --- a/src/main/java/com/petproject/boardgamefun/controller/GameController.java +++ b/src/main/java/com/petproject/boardgamefun/controller/GameController.java @@ -1,11 +1,14 @@ package com.petproject.boardgamefun.controller; +import com.petproject.boardgamefun.dto.GameWithAverageRatingDTO; +import com.petproject.boardgamefun.dto.UsersGameRatingDTO; import com.petproject.boardgamefun.model.Expansion; import com.petproject.boardgamefun.model.Game; import com.petproject.boardgamefun.model.SameGame; import com.petproject.boardgamefun.repository.ExpansionRepository; import com.petproject.boardgamefun.repository.GameRepository; import com.petproject.boardgamefun.repository.SameGameRepository; +import com.petproject.boardgamefun.repository.UserRepository; import org.springframework.http.HttpStatus; import org.springframework.http.ResponseEntity; import org.springframework.transaction.annotation.Transactional; @@ -19,32 +22,34 @@ public class GameController { final GameRepository gameRepository; + final UserRepository userRepository; final ExpansionRepository expansionRepository; final SameGameRepository sameGameRepository; - public GameController(GameRepository gameRepository, ExpansionRepository expansionRepository, SameGameRepository sameGameRepository) { + public GameController(GameRepository gameRepository, UserRepository userRepository, ExpansionRepository expansionRepository, SameGameRepository sameGameRepository) { this.gameRepository = gameRepository; + this.userRepository = userRepository; this.expansionRepository = expansionRepository; this.sameGameRepository = sameGameRepository; } @Transactional @GetMapping() - ResponseEntity> getGames(){ + ResponseEntity> getGames() { var games = gameRepository.findAll(); return new ResponseEntity<>(games, HttpStatus.OK); } @Transactional @GetMapping("{title}") - ResponseEntity getGame(@PathVariable String title){ + ResponseEntity getGame(@PathVariable String title) { var game = gameRepository.findGameByTitle(title); return new ResponseEntity<>(game, HttpStatus.OK); } @Transactional @PostMapping("/add") - public ResponseEntity addGame(@RequestBody Game newGame){ + public ResponseEntity addGame(@RequestBody Game newGame) { gameRepository.save(newGame); return new ResponseEntity<>(newGame, HttpStatus.OK); @@ -52,7 +57,7 @@ public ResponseEntity addGame(@RequestBody Game newGame){ @Transactional @PutMapping("/update") - public ResponseEntity updateGame(@RequestBody Game updatedGame){ + public ResponseEntity updateGame(@RequestBody Game updatedGame) { gameRepository.save(updatedGame); return new ResponseEntity<>(updatedGame, HttpStatus.OK); @@ -60,7 +65,7 @@ public ResponseEntity updateGame(@RequestBody Game updatedGame){ @Transactional @DeleteMapping("/remove") - public ResponseEntity removeGameFromSite(@RequestBody Game deleteGame){ + public ResponseEntity removeGameFromSite(@RequestBody Game deleteGame) { gameRepository.delete(deleteGame); return new ResponseEntity<>(deleteGame.getTitle() + " удалена из базы данных", HttpStatus.OK); @@ -68,7 +73,7 @@ public ResponseEntity removeGameFromSite(@RequestBody Game deleteGame){ @Transactional @GetMapping("/expansions/{gameId}") - public ResponseEntity> getExpansions(@PathVariable Integer gameId){ + public ResponseEntity> getExpansions(@PathVariable Integer gameId) { var gamesExpansions = gameRepository.getExpansions(gameId); return new ResponseEntity<>(gamesExpansions, HttpStatus.OK); @@ -76,7 +81,7 @@ public ResponseEntity> getExpansions(@PathVariable Integer gameId){ @Transactional @PostMapping("/add-expansion/{parentGameId}/{daughterGameId}") - public ResponseEntity> addExpansion(@PathVariable Integer parentGameId, @PathVariable Integer daughterGameId){ + public ResponseEntity> addExpansion(@PathVariable Integer parentGameId, @PathVariable Integer daughterGameId) { var parentGame = gameRepository.findGameById(parentGameId); var daughterGame = gameRepository.findGameById(daughterGameId); @@ -92,7 +97,7 @@ public ResponseEntity> addExpansion(@PathVariable Integer parentGameI @Transactional @DeleteMapping("/delete-expansion/{parentGameId}/{daughterGameId}") - public ResponseEntity> deleteExpansion(@PathVariable Integer daughterGameId, @PathVariable Integer parentGameId){ + public ResponseEntity> deleteExpansion(@PathVariable Integer daughterGameId, @PathVariable Integer parentGameId) { var expansion = expansionRepository.findExpansion_ByDaughterGameIdAndParentGameId(daughterGameId, parentGameId); expansionRepository.delete(expansion); @@ -103,15 +108,15 @@ public ResponseEntity> deleteExpansion(@PathVariable Integer daughter @Transactional @GetMapping("/similar/{gameId}") - public ResponseEntity> getSimilarGames(@PathVariable Integer gameId){ - var similarGames = gameRepository.getSimilarGames(gameId); + public ResponseEntity> getSimilarGames(@PathVariable Integer gameId) { + var similarGames = gameRepository.getSimilarGames(gameId); return new ResponseEntity<>(similarGames, HttpStatus.OK); } @Transactional @PostMapping("/add-similar/{referenceGameId}/{sourceGameId}") - public ResponseEntity> addSimilarGame(@PathVariable Integer referenceGameId, @PathVariable Integer sourceGameId){ + public ResponseEntity> addSimilarGame(@PathVariable Integer referenceGameId, @PathVariable Integer sourceGameId) { var referenceGame = gameRepository.findGameById(referenceGameId); var sourceGame = gameRepository.findGameById(sourceGameId); @@ -127,7 +132,7 @@ public ResponseEntity> addSimilarGame(@PathVariable Integer reference @Transactional @DeleteMapping("/delete-similar/{referenceGameId}/{sourceGameId}") - public ResponseEntity> deleteSameGame(@PathVariable Integer referenceGameId, @PathVariable Integer sourceGameId){ + public ResponseEntity> deleteSameGame(@PathVariable Integer referenceGameId, @PathVariable Integer sourceGameId) { var sameGame = sameGameRepository.findSameGame_ByReferenceGameIdAndSourceGameId(referenceGameId, sourceGameId); sameGameRepository.delete(sameGame); @@ -136,6 +141,21 @@ public ResponseEntity> deleteSameGame(@PathVariable Integer reference return new ResponseEntity<>(sameGames, HttpStatus.OK); } + @Transactional + @GetMapping("/{gameId}/users-rating") + public ResponseEntity> getUsersRating(@PathVariable Integer gameId) { + + var ratings = userRepository.findGameRatings(gameId); + + return new ResponseEntity<>(ratings, HttpStatus.OK); + } + + @Transactional + @GetMapping("/with-rating") + public ResponseEntity> getGamesWithRating() { + var games = gameRepository.findGamesWithRating(); + return new ResponseEntity<>(games, HttpStatus.OK); + } //todo: ratings list diff --git a/src/main/java/com/petproject/boardgamefun/dto/GameWithAverageRatingDTO.java b/src/main/java/com/petproject/boardgamefun/dto/GameWithAverageRatingDTO.java new file mode 100644 index 0000000..36b003b --- /dev/null +++ b/src/main/java/com/petproject/boardgamefun/dto/GameWithAverageRatingDTO.java @@ -0,0 +1,8 @@ +package com.petproject.boardgamefun.dto; + +import com.petproject.boardgamefun.model.Game; + +public interface GameWithAverageRatingDTO { + Game getGame(); + Double getRating(); +} diff --git a/src/main/java/com/petproject/boardgamefun/dto/UsersGameRatingDTO.java b/src/main/java/com/petproject/boardgamefun/dto/UsersGameRatingDTO.java new file mode 100644 index 0000000..9ff4287 --- /dev/null +++ b/src/main/java/com/petproject/boardgamefun/dto/UsersGameRatingDTO.java @@ -0,0 +1,8 @@ +package com.petproject.boardgamefun.dto; + +import com.petproject.boardgamefun.model.User; + +public interface UsersGameRatingDTO { + User getUser(); + Double getRating(); +} diff --git a/src/main/java/com/petproject/boardgamefun/repository/GameRepository.java b/src/main/java/com/petproject/boardgamefun/repository/GameRepository.java index 05612aa..a4fa648 100644 --- a/src/main/java/com/petproject/boardgamefun/repository/GameRepository.java +++ b/src/main/java/com/petproject/boardgamefun/repository/GameRepository.java @@ -1,5 +1,6 @@ package com.petproject.boardgamefun.repository; +import com.petproject.boardgamefun.dto.GameWithAverageRatingDTO; import com.petproject.boardgamefun.dto.UserGameRatingDTO; import com.petproject.boardgamefun.dto.GameSellDTO; import com.petproject.boardgamefun.model.Game; @@ -12,6 +13,16 @@ public interface GameRepository extends JpaRepository { Game findGameByTitle(String title); Game findGameById(Integer id); + @Query("select g as game, avg(rgbu.rating) as rating from Game g " + + "join RatingGameByUser rgbu on rgbu.game.id = g.id " + + "where g.id = :id ") + GameWithAverageRatingDTO findGameWithRating(Integer id); + + @Query("select g as game, avg(rgbu.rating) as rating from Game g " + + "join RatingGameByUser rgbu on rgbu.game.id = g.id " + + "group by g") + List findGamesWithRating(); + @Query("Select g from Game g " + "join UserOwnGame uog on g.id = uog.game.id " + "join User u on u.id = uog.user.id " + diff --git a/src/main/java/com/petproject/boardgamefun/repository/UserRepository.java b/src/main/java/com/petproject/boardgamefun/repository/UserRepository.java index 05c9dc7..91e1095 100644 --- a/src/main/java/com/petproject/boardgamefun/repository/UserRepository.java +++ b/src/main/java/com/petproject/boardgamefun/repository/UserRepository.java @@ -1,11 +1,21 @@ package com.petproject.boardgamefun.repository; +import com.petproject.boardgamefun.dto.UsersGameRatingDTO; 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 From fb0311fa10d011586cc06afe6596f409207d1494 Mon Sep 17 00:00:00 2001 From: "i.i.artamonov" Date: Sat, 11 Dec 2021 16:18:09 +0400 Subject: [PATCH 020/141] Forum requests added for ForumController Next request added - get/getByUser/getByGame/update/delete forum. Change type of field in Forum Model - publicationTime. Add new entity - ForumRating. Edit todos in GameController. DTO for post and patch requests added. Add methods for repository. --- .../controller/ForumController.java | 96 +++++++++++++++++++ .../controller/GameController.java | 1 + .../boardgamefun/dto/ForumRequest.java | 15 +++ .../petproject/boardgamefun/model/Forum.java | 8 +- .../boardgamefun/model/ForumRating.java | 55 +++++++++++ .../repository/ForumRepository.java | 5 + 6 files changed, 176 insertions(+), 4 deletions(-) create mode 100644 src/main/java/com/petproject/boardgamefun/controller/ForumController.java create mode 100644 src/main/java/com/petproject/boardgamefun/dto/ForumRequest.java create mode 100644 src/main/java/com/petproject/boardgamefun/model/ForumRating.java 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..36c68fc --- /dev/null +++ b/src/main/java/com/petproject/boardgamefun/controller/ForumController.java @@ -0,0 +1,96 @@ +package com.petproject.boardgamefun.controller; + +import com.petproject.boardgamefun.dto.ForumRequest; +import com.petproject.boardgamefun.model.Forum; +import com.petproject.boardgamefun.repository.ForumRepository; +import com.petproject.boardgamefun.repository.GameRepository; +import com.petproject.boardgamefun.repository.UserRepository; +import org.springframework.http.HttpStatus; +import org.springframework.http.ResponseEntity; +import org.springframework.web.bind.annotation.*; + +import javax.transaction.Transactional; +import java.time.OffsetDateTime; +import java.util.List; +import java.util.Objects; + +@RestController +@CrossOrigin(origins = "*", maxAge = 3600) +@RequestMapping("/forum") +public class ForumController { + + private final ForumRepository forumRepository; + private final GameRepository gameRepository; + private final UserRepository userRepository; + + public ForumController(ForumRepository forumRepository, GameRepository gameRepository, UserRepository userRepository) { + this.forumRepository = forumRepository; + this.gameRepository = gameRepository; + this.userRepository = userRepository; + } + + @Transactional + @GetMapping("") + public ResponseEntity> getForums(@RequestParam(required = false) Integer gameId, @RequestParam(required = false) Integer userId) { + List forums; + if (gameId != null){ + forums = forumRepository.findForumsByGameId(gameId); + } + else if (userId != null){ + forums = forumRepository.findForumsByUserId(userId); + } + else { + forums = forumRepository.findAll(); + } + + return new ResponseEntity<>(forums, HttpStatus.OK); + } + + @Transactional + @PostMapping("add-forum/{gameId}/{userId}") + 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); + + return new ResponseEntity<>(forum, HttpStatus.OK); + } + + @Transactional + @PatchMapping("/update-forum/{forumId}") + 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); + + return new ResponseEntity<>(forum, HttpStatus.OK); + } + + @Transactional + @DeleteMapping("/delete-forum/{forumId}") + public ResponseEntity deleteForum(@PathVariable Integer forumId){ + + var forum = forumRepository.findForumById(forumId); + forumRepository.delete(forum); + + return new ResponseEntity<>("Топик " + forum.getTitle() + " удален из игры", 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 index 7885296..3350149 100644 --- a/src/main/java/com/petproject/boardgamefun/controller/GameController.java +++ b/src/main/java/com/petproject/boardgamefun/controller/GameController.java @@ -158,6 +158,7 @@ public ResponseEntity> getGamesWithRating() { } + //todo: designers //todo: ratings list //todo: forum //todo: gat avg rating diff --git a/src/main/java/com/petproject/boardgamefun/dto/ForumRequest.java b/src/main/java/com/petproject/boardgamefun/dto/ForumRequest.java new file mode 100644 index 0000000..162f1f9 --- /dev/null +++ b/src/main/java/com/petproject/boardgamefun/dto/ForumRequest.java @@ -0,0 +1,15 @@ +package com.petproject.boardgamefun.dto; + +import lombok.AllArgsConstructor; +import lombok.Data; +import lombok.Getter; +import lombok.Setter; + +@Data +@Getter +@Setter +@AllArgsConstructor +public class ForumRequest { + String title; + String text; +} diff --git a/src/main/java/com/petproject/boardgamefun/model/Forum.java b/src/main/java/com/petproject/boardgamefun/model/Forum.java index e5f6745..f39801d 100644 --- a/src/main/java/com/petproject/boardgamefun/model/Forum.java +++ b/src/main/java/com/petproject/boardgamefun/model/Forum.java @@ -1,7 +1,7 @@ package com.petproject.boardgamefun.model; import javax.persistence.*; -import java.time.OffsetTime; +import java.time.OffsetDateTime; @Table(name = "forum") @Entity @@ -20,7 +20,7 @@ public class Forum { private String text; @Column(name = "publication_time", nullable = false) - private OffsetTime publicationTime; + private OffsetDateTime publicationTime; @ManyToOne(optional = false) @JoinColumn(name = "game", nullable = false) @@ -46,11 +46,11 @@ public void setGame(Game game) { this.game = game; } - public OffsetTime getPublicationTime() { + public OffsetDateTime getPublicationTime() { return publicationTime; } - public void setPublicationTime(OffsetTime publicationTime) { + public void setPublicationTime(OffsetDateTime publicationTime) { this.publicationTime = publicationTime; } 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/repository/ForumRepository.java b/src/main/java/com/petproject/boardgamefun/repository/ForumRepository.java index 88e192c..bcda758 100644 --- a/src/main/java/com/petproject/boardgamefun/repository/ForumRepository.java +++ b/src/main/java/com/petproject/boardgamefun/repository/ForumRepository.java @@ -3,5 +3,10 @@ import com.petproject.boardgamefun.model.Forum; import org.springframework.data.jpa.repository.JpaRepository; +import java.util.List; + public interface ForumRepository extends JpaRepository { + List findForumsByGameId(Integer id); + List findForumsByUserId(Integer id); + Forum findForumById(Integer id); } \ No newline at end of file From 9e3badd2a4f4952b9dea411ecede077b2aee080b Mon Sep 17 00:00:00 2001 From: "i.i.artamonov" Date: Mon, 13 Dec 2021 09:27:31 +0400 Subject: [PATCH 021/141] Forum messages requests in ForumController added Added next requests for forumMessages - getAll/getByForum/getByUser/update/delete/add to ForumController. MessageRequest added. Update field of ForumMessage model - change to OffsetDateTime. Methods to forumMessageRepository added --- .../controller/ForumController.java | 86 ++++++++++++++++--- .../boardgamefun/dto/ForumMessageRequest.java | 12 +++ .../boardgamefun/model/ForumMessage.java | 9 +- 3 files changed, 91 insertions(+), 16 deletions(-) create mode 100644 src/main/java/com/petproject/boardgamefun/dto/ForumMessageRequest.java diff --git a/src/main/java/com/petproject/boardgamefun/controller/ForumController.java b/src/main/java/com/petproject/boardgamefun/controller/ForumController.java index 36c68fc..9081e35 100644 --- a/src/main/java/com/petproject/boardgamefun/controller/ForumController.java +++ b/src/main/java/com/petproject/boardgamefun/controller/ForumController.java @@ -1,7 +1,10 @@ package com.petproject.boardgamefun.controller; +import com.petproject.boardgamefun.dto.ForumMessageRequest; import com.petproject.boardgamefun.dto.ForumRequest; import com.petproject.boardgamefun.model.Forum; +import com.petproject.boardgamefun.model.ForumMessage; +import com.petproject.boardgamefun.repository.ForumMessageRepository; import com.petproject.boardgamefun.repository.ForumRepository; import com.petproject.boardgamefun.repository.GameRepository; import com.petproject.boardgamefun.repository.UserRepository; @@ -22,26 +25,26 @@ public class ForumController { private final ForumRepository forumRepository; private final GameRepository gameRepository; private final UserRepository userRepository; + private final ForumMessageRepository forumMessageRepository; - public ForumController(ForumRepository forumRepository, GameRepository gameRepository, UserRepository userRepository) { + public ForumController(ForumRepository forumRepository, GameRepository gameRepository, UserRepository userRepository, ForumMessageRepository forumMessageRepository) { this.forumRepository = forumRepository; this.gameRepository = gameRepository; this.userRepository = userRepository; + this.forumMessageRepository = forumMessageRepository; } @Transactional @GetMapping("") public ResponseEntity> getForums(@RequestParam(required = false) Integer gameId, @RequestParam(required = false) Integer userId) { - List forums; - if (gameId != null){ - forums = forumRepository.findForumsByGameId(gameId); - } - else if (userId != null){ - forums = forumRepository.findForumsByUserId(userId); - } - else { - forums = forumRepository.findAll(); - } + List forums; + if (gameId != null) { + forums = forumRepository.findForumsByGameId(gameId); + } else if (userId != null) { + forums = forumRepository.findForumsByUserId(userId); + } else { + forums = forumRepository.findAll(); + } return new ResponseEntity<>(forums, HttpStatus.OK); } @@ -83,7 +86,7 @@ public ResponseEntity updateForum(@PathVariable Integer forumId, @Request @Transactional @DeleteMapping("/delete-forum/{forumId}") - public ResponseEntity deleteForum(@PathVariable Integer forumId){ + public ResponseEntity deleteForum(@PathVariable Integer forumId) { var forum = forumRepository.findForumById(forumId); forumRepository.delete(forum); @@ -91,6 +94,65 @@ public ResponseEntity deleteForum(@PathVariable Integer forumId){ return new ResponseEntity<>("Топик " + forum.getTitle() + " удален из игры", HttpStatus.OK); } + @Transactional + @GetMapping("/messages") + public ResponseEntity> getComments(@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(); + + return new ResponseEntity<>(messages, HttpStatus.OK); + } + + @Transactional + @PostMapping("/{forumId}/add-comment/{userId}") + 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); + + return new ResponseEntity<>(messages, HttpStatus.OK); + } + + @Transactional + @PatchMapping("/{forumId}/update-message/{messageId}") + 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 = forumMessageRepository.findByForumId(forumId); + + return new ResponseEntity<>(messages, HttpStatus.OK); + } + + @Transactional + @DeleteMapping("/{forumId}/delete-message/{messageId}") + public ResponseEntity> deleteMessage(@PathVariable Integer forumId, @PathVariable Integer messageId ) { + var message = forumMessageRepository.findForumMessageById(messageId); + + forumMessageRepository.delete(message); + + var messages = forumMessageRepository.findByForumId(forumId); + return new ResponseEntity<>(messages, HttpStatus.OK); + } + //todo: union patch method??? //todo: forumDTO with rating and count messages } diff --git a/src/main/java/com/petproject/boardgamefun/dto/ForumMessageRequest.java b/src/main/java/com/petproject/boardgamefun/dto/ForumMessageRequest.java new file mode 100644 index 0000000..6c930d2 --- /dev/null +++ b/src/main/java/com/petproject/boardgamefun/dto/ForumMessageRequest.java @@ -0,0 +1,12 @@ +package com.petproject.boardgamefun.dto; + +import lombok.Data; +import lombok.Getter; +import lombok.Setter; + +@Data +@Getter +@Setter +public class ForumMessageRequest { + String comment; +} diff --git a/src/main/java/com/petproject/boardgamefun/model/ForumMessage.java b/src/main/java/com/petproject/boardgamefun/model/ForumMessage.java index b64c39f..eeab621 100644 --- a/src/main/java/com/petproject/boardgamefun/model/ForumMessage.java +++ b/src/main/java/com/petproject/boardgamefun/model/ForumMessage.java @@ -1,6 +1,7 @@ package com.petproject.boardgamefun.model; import javax.persistence.*; +import java.time.OffsetDateTime; import java.time.OffsetTime; @Table(name = "forum_message") @@ -23,14 +24,14 @@ public class ForumMessage { @JoinColumn(name = "\"user\"", nullable = false) private User user; - @Column(name = "\"time\"", nullable = false) - private OffsetTime time; + @Column(name = "\"time_message\"", nullable = false) + private OffsetDateTime time; - public OffsetTime getTime() { + public OffsetDateTime getTime() { return time; } - public void setTime(OffsetTime time) { + public void setTime(OffsetDateTime time) { this.time = time; } From 708aa6530e66e1f556bdb561044a5855055f0513 Mon Sep 17 00:00:00 2001 From: "i.i.artamonov" Date: Mon, 13 Dec 2021 09:28:44 +0400 Subject: [PATCH 022/141] Added a missing file from the previous commit commt 9e3badd2a4f4952b9dea411ecede077b2aee080b --- .../boardgamefun/repository/ForumMessageRepository.java | 5 +++++ 1 file changed, 5 insertions(+) diff --git a/src/main/java/com/petproject/boardgamefun/repository/ForumMessageRepository.java b/src/main/java/com/petproject/boardgamefun/repository/ForumMessageRepository.java index e12a47c..e7551bb 100644 --- a/src/main/java/com/petproject/boardgamefun/repository/ForumMessageRepository.java +++ b/src/main/java/com/petproject/boardgamefun/repository/ForumMessageRepository.java @@ -3,5 +3,10 @@ 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 From b14e15fff4f650f04b22a49fe308f9f88fea3f0a Mon Sep 17 00:00:00 2001 From: "i.i.artamonov" Date: Mon, 13 Dec 2021 10:44:57 +0400 Subject: [PATCH 023/141] Change of the route method in ForumController Change route of addMessage method. --- .../com/petproject/boardgamefun/controller/ForumController.java | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/main/java/com/petproject/boardgamefun/controller/ForumController.java b/src/main/java/com/petproject/boardgamefun/controller/ForumController.java index 9081e35..a12c7fd 100644 --- a/src/main/java/com/petproject/boardgamefun/controller/ForumController.java +++ b/src/main/java/com/petproject/boardgamefun/controller/ForumController.java @@ -109,7 +109,7 @@ else if (userId != null) } @Transactional - @PostMapping("/{forumId}/add-comment/{userId}") + @PostMapping("/{forumId}/add-message/{userId}") public ResponseEntity> addMessage(@PathVariable Integer forumId, @PathVariable Integer userId, @RequestBody ForumMessageRequest forumMessageRequest) { var forum = forumRepository.findForumById(forumId); var user = userRepository.findUserById(userId); From 0ab6aafc38d7f6d8054945c81b8d8a8ed155b0f0 Mon Sep 17 00:00:00 2001 From: "i.i.artamonov" Date: Mon, 13 Dec 2021 20:36:16 +0400 Subject: [PATCH 024/141] Forum rating requests added to ForumController Added next requests - set/update/delete rating. Added ForumRatingRequest. Added needed methods to forumRatingRepository --- .../controller/ForumController.java | 42 ++++++++++++++++--- .../boardgamefun/dto/ForumRatingRequest.java | 8 ++++ .../repository/ForumRatingRepository.java | 9 ++++ 3 files changed, 54 insertions(+), 5 deletions(-) create mode 100644 src/main/java/com/petproject/boardgamefun/dto/ForumRatingRequest.java create mode 100644 src/main/java/com/petproject/boardgamefun/repository/ForumRatingRepository.java diff --git a/src/main/java/com/petproject/boardgamefun/controller/ForumController.java b/src/main/java/com/petproject/boardgamefun/controller/ForumController.java index a12c7fd..4ffafe5 100644 --- a/src/main/java/com/petproject/boardgamefun/controller/ForumController.java +++ b/src/main/java/com/petproject/boardgamefun/controller/ForumController.java @@ -1,13 +1,12 @@ package com.petproject.boardgamefun.controller; import com.petproject.boardgamefun.dto.ForumMessageRequest; +import com.petproject.boardgamefun.dto.ForumRatingRequest; import com.petproject.boardgamefun.dto.ForumRequest; import com.petproject.boardgamefun.model.Forum; import com.petproject.boardgamefun.model.ForumMessage; -import com.petproject.boardgamefun.repository.ForumMessageRepository; -import com.petproject.boardgamefun.repository.ForumRepository; -import com.petproject.boardgamefun.repository.GameRepository; -import com.petproject.boardgamefun.repository.UserRepository; +import com.petproject.boardgamefun.model.ForumRating; +import com.petproject.boardgamefun.repository.*; import org.springframework.http.HttpStatus; import org.springframework.http.ResponseEntity; import org.springframework.web.bind.annotation.*; @@ -26,12 +25,14 @@ public class ForumController { private final GameRepository gameRepository; private final UserRepository userRepository; private final ForumMessageRepository forumMessageRepository; + private final ForumRatingRepository forumRatingRepository; - public ForumController(ForumRepository forumRepository, GameRepository gameRepository, UserRepository userRepository, ForumMessageRepository forumMessageRepository) { + public ForumController(ForumRepository forumRepository, GameRepository gameRepository, UserRepository userRepository, ForumMessageRepository forumMessageRepository, ForumRatingRepository forumRatingRepository) { this.forumRepository = forumRepository; this.gameRepository = gameRepository; this.userRepository = userRepository; this.forumMessageRepository = forumMessageRepository; + this.forumRatingRepository = forumRatingRepository; } @Transactional @@ -153,6 +154,37 @@ public ResponseEntity> deleteMessage(@PathVariable Integer fo return new ResponseEntity<>(messages, HttpStatus.OK); } + @Transactional + @PostMapping("/{forumId}/set-rating/{userId}") + 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 = forumRepository.findForumById(forumId); + return new ResponseEntity<>(forum, HttpStatus.OK); + } + + @Transactional + @DeleteMapping("/{forumId}/remove-rating/{ratingId}") + public ResponseEntity removeRatingFromForum(@PathVariable Integer forumId, @PathVariable Integer ratingId){ + var forumRating = forumRatingRepository.findForumRatingById(ratingId); + forumRatingRepository.delete(forumRating); + + var forum = forumRepository.findForumById(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/dto/ForumRatingRequest.java b/src/main/java/com/petproject/boardgamefun/dto/ForumRatingRequest.java new file mode 100644 index 0000000..e6bc75d --- /dev/null +++ b/src/main/java/com/petproject/boardgamefun/dto/ForumRatingRequest.java @@ -0,0 +1,8 @@ +package com.petproject.boardgamefun.dto; + +import lombok.Data; + +@Data +public class ForumRatingRequest { + Double rating; +} 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 From 1f019a32a896237bef7dff4c1852e5a66f9c348b Mon Sep 17 00:00:00 2001 From: "i.i.artamonov" Date: Mon, 13 Dec 2021 20:40:04 +0400 Subject: [PATCH 025/141] Remove unnecessary annotations from Request DTOs Data annotations already includes getter and setter methods --- .../petproject/boardgamefun/dto/DiaryCommentRequest.java | 6 +----- .../com/petproject/boardgamefun/dto/DiaryRatingRequest.java | 6 +----- .../petproject/boardgamefun/dto/ForumMessageRequest.java | 4 ---- .../java/com/petproject/boardgamefun/dto/ForumRequest.java | 6 ------ .../petproject/boardgamefun/dto/PasswordChangeRequest.java | 6 +----- .../com/petproject/boardgamefun/dto/UserEditRequest.java | 6 ------ 6 files changed, 3 insertions(+), 31 deletions(-) diff --git a/src/main/java/com/petproject/boardgamefun/dto/DiaryCommentRequest.java b/src/main/java/com/petproject/boardgamefun/dto/DiaryCommentRequest.java index 8de0d9a..e8fb3ca 100644 --- a/src/main/java/com/petproject/boardgamefun/dto/DiaryCommentRequest.java +++ b/src/main/java/com/petproject/boardgamefun/dto/DiaryCommentRequest.java @@ -1,12 +1,8 @@ package com.petproject.boardgamefun.dto; -import lombok.*; +import lombok.Data; @Data -@Getter -@Setter -@AllArgsConstructor -@NoArgsConstructor public class DiaryCommentRequest { private String comment; } diff --git a/src/main/java/com/petproject/boardgamefun/dto/DiaryRatingRequest.java b/src/main/java/com/petproject/boardgamefun/dto/DiaryRatingRequest.java index 7099b07..e5e390a 100644 --- a/src/main/java/com/petproject/boardgamefun/dto/DiaryRatingRequest.java +++ b/src/main/java/com/petproject/boardgamefun/dto/DiaryRatingRequest.java @@ -1,12 +1,8 @@ package com.petproject.boardgamefun.dto; -import lombok.*; +import lombok.Data; @Data -@Setter -@Getter -@NoArgsConstructor -@AllArgsConstructor public class DiaryRatingRequest { private Double rating; } diff --git a/src/main/java/com/petproject/boardgamefun/dto/ForumMessageRequest.java b/src/main/java/com/petproject/boardgamefun/dto/ForumMessageRequest.java index 6c930d2..d6fa925 100644 --- a/src/main/java/com/petproject/boardgamefun/dto/ForumMessageRequest.java +++ b/src/main/java/com/petproject/boardgamefun/dto/ForumMessageRequest.java @@ -1,12 +1,8 @@ package com.petproject.boardgamefun.dto; import lombok.Data; -import lombok.Getter; -import lombok.Setter; @Data -@Getter -@Setter public class ForumMessageRequest { String comment; } diff --git a/src/main/java/com/petproject/boardgamefun/dto/ForumRequest.java b/src/main/java/com/petproject/boardgamefun/dto/ForumRequest.java index 162f1f9..c762253 100644 --- a/src/main/java/com/petproject/boardgamefun/dto/ForumRequest.java +++ b/src/main/java/com/petproject/boardgamefun/dto/ForumRequest.java @@ -1,14 +1,8 @@ package com.petproject.boardgamefun.dto; -import lombok.AllArgsConstructor; import lombok.Data; -import lombok.Getter; -import lombok.Setter; @Data -@Getter -@Setter -@AllArgsConstructor public class ForumRequest { String title; String text; diff --git a/src/main/java/com/petproject/boardgamefun/dto/PasswordChangeRequest.java b/src/main/java/com/petproject/boardgamefun/dto/PasswordChangeRequest.java index fea8b74..28e032f 100644 --- a/src/main/java/com/petproject/boardgamefun/dto/PasswordChangeRequest.java +++ b/src/main/java/com/petproject/boardgamefun/dto/PasswordChangeRequest.java @@ -1,12 +1,8 @@ package com.petproject.boardgamefun.dto; -import lombok.*; +import lombok.Data; @Data -@Setter -@Getter -@AllArgsConstructor -@NoArgsConstructor public class PasswordChangeRequest { private String password; } diff --git a/src/main/java/com/petproject/boardgamefun/dto/UserEditRequest.java b/src/main/java/com/petproject/boardgamefun/dto/UserEditRequest.java index da7aa23..c5fd9b5 100644 --- a/src/main/java/com/petproject/boardgamefun/dto/UserEditRequest.java +++ b/src/main/java/com/petproject/boardgamefun/dto/UserEditRequest.java @@ -1,14 +1,8 @@ package com.petproject.boardgamefun.dto; -import lombok.AllArgsConstructor; import lombok.Data; -import lombok.Getter; -import lombok.Setter; @Data -@Getter -@Setter -@AllArgsConstructor public class UserEditRequest { private String name; private String role; From a3ef13632bf6fd58b45dc90d9375bce0c7626fb4 Mon Sep 17 00:00:00 2001 From: "i.i.artamonov" Date: Tue, 14 Dec 2021 08:36:10 +0400 Subject: [PATCH 026/141] Added ForumDTO for ForumController This DTO include forum and its rating. Removed unused methods from forumRepository --- .../controller/ForumController.java | 11 ++++---- .../petproject/boardgamefun/dto/ForumDTO.java | 8 ++++++ .../repository/ForumRepository.java | 25 ++++++++++++++++--- 3 files changed, 36 insertions(+), 8 deletions(-) create mode 100644 src/main/java/com/petproject/boardgamefun/dto/ForumDTO.java diff --git a/src/main/java/com/petproject/boardgamefun/controller/ForumController.java b/src/main/java/com/petproject/boardgamefun/controller/ForumController.java index 4ffafe5..ed00e9e 100644 --- a/src/main/java/com/petproject/boardgamefun/controller/ForumController.java +++ b/src/main/java/com/petproject/boardgamefun/controller/ForumController.java @@ -1,5 +1,6 @@ package com.petproject.boardgamefun.controller; +import com.petproject.boardgamefun.dto.ForumDTO; import com.petproject.boardgamefun.dto.ForumMessageRequest; import com.petproject.boardgamefun.dto.ForumRatingRequest; import com.petproject.boardgamefun.dto.ForumRequest; @@ -37,14 +38,14 @@ public ForumController(ForumRepository forumRepository, GameRepository gameRepos @Transactional @GetMapping("") - public ResponseEntity> getForums(@RequestParam(required = false) Integer gameId, @RequestParam(required = false) Integer userId) { - List forums; + public ResponseEntity> getForums(@RequestParam(required = false) Integer gameId, @RequestParam(required = false) Integer userId) { + List forums; if (gameId != null) { - forums = forumRepository.findForumsByGameId(gameId); + forums = forumRepository.findForumsGameWithRating(gameId); } else if (userId != null) { - forums = forumRepository.findForumsByUserId(userId); + forums = forumRepository.findForumsUserWithRating(userId); } else { - forums = forumRepository.findAll(); + forums = forumRepository.findForumsWithRating(); } return new ResponseEntity<>(forums, HttpStatus.OK); 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..dee9e92 --- /dev/null +++ b/src/main/java/com/petproject/boardgamefun/dto/ForumDTO.java @@ -0,0 +1,8 @@ +package com.petproject.boardgamefun.dto; + +import com.petproject.boardgamefun.model.Forum; + +public interface ForumDTO { + Forum getForum(); + Double getRating(); +} diff --git a/src/main/java/com/petproject/boardgamefun/repository/ForumRepository.java b/src/main/java/com/petproject/boardgamefun/repository/ForumRepository.java index bcda758..c7d9468 100644 --- a/src/main/java/com/petproject/boardgamefun/repository/ForumRepository.java +++ b/src/main/java/com/petproject/boardgamefun/repository/ForumRepository.java @@ -1,12 +1,31 @@ package com.petproject.boardgamefun.repository; +import com.petproject.boardgamefun.dto.ForumDTO; 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 { - List findForumsByGameId(Integer id); - List findForumsByUserId(Integer id); - Forum findForumById(Integer id); + @Query("select f as forum, avg(fr.rating) as rating from Forum f " + + "join Game g on g.id = f.game.id " + + "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 " + + "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 " + + "join ForumRating fr on fr.forum.id = f.id " + + "group by f") + List findForumsWithRating(); + + Forum findForumById(Integer id); } \ No newline at end of file From e6f2f6379800513194f27e4aa120aab16c623708 Mon Sep 17 00:00:00 2001 From: "i.i.artamonov" Date: Tue, 14 Dec 2021 08:55:10 +0400 Subject: [PATCH 027/141] Change getting Game to GameWithRating Removed getting game by title --- .../boardgamefun/controller/GameController.java | 9 ++++----- .../boardgamefun/repository/GameRepository.java | 4 ++-- 2 files changed, 6 insertions(+), 7 deletions(-) diff --git a/src/main/java/com/petproject/boardgamefun/controller/GameController.java b/src/main/java/com/petproject/boardgamefun/controller/GameController.java index 3350149..d92ebff 100644 --- a/src/main/java/com/petproject/boardgamefun/controller/GameController.java +++ b/src/main/java/com/petproject/boardgamefun/controller/GameController.java @@ -41,9 +41,10 @@ ResponseEntity> getGames() { } @Transactional - @GetMapping("{title}") - ResponseEntity getGame(@PathVariable String title) { - var game = gameRepository.findGameByTitle(title); + @GetMapping("{id}") + ResponseEntity getGameById(@PathVariable Integer id){ + var game = gameRepository.findGameWithRating(id); + return new ResponseEntity<>(game, HttpStatus.OK); } @@ -160,6 +161,4 @@ public ResponseEntity> getGamesWithRating() { //todo: designers //todo: ratings list - //todo: forum - //todo: gat avg rating } diff --git a/src/main/java/com/petproject/boardgamefun/repository/GameRepository.java b/src/main/java/com/petproject/boardgamefun/repository/GameRepository.java index a4fa648..27e99b6 100644 --- a/src/main/java/com/petproject/boardgamefun/repository/GameRepository.java +++ b/src/main/java/com/petproject/boardgamefun/repository/GameRepository.java @@ -10,12 +10,12 @@ import java.util.List; public interface GameRepository extends JpaRepository { - Game findGameByTitle(String title); Game findGameById(Integer id); @Query("select g as game, avg(rgbu.rating) as rating from Game g " + "join RatingGameByUser rgbu on rgbu.game.id = g.id " + - "where g.id = :id ") + "where g.id = :id " + + "group by g") GameWithAverageRatingDTO findGameWithRating(Integer id); @Query("select g as game, avg(rgbu.rating) as rating from Game g " + From 6d548ce68a3284143ae594650dca9a2367021eb7 Mon Sep 17 00:00:00 2001 From: "i.i.artamonov" Date: Tue, 14 Dec 2021 09:54:56 +0400 Subject: [PATCH 028/141] Added CRUD methods to DesignerController DesignerController class added with next requests - add/update/delete/get/getByName. DesignerRequest added. Remove Lob annotation, as so its convert string to number!!! Add methods to designer repository --- .../controller/DesignerController.java | 80 +++++++++++++++++++ .../boardgamefun/dto/DesignerRequest.java | 8 ++ .../boardgamefun/model/Designer.java | 1 - .../repository/DesignerRepository.java | 2 + 4 files changed, 90 insertions(+), 1 deletion(-) create mode 100644 src/main/java/com/petproject/boardgamefun/controller/DesignerController.java create mode 100644 src/main/java/com/petproject/boardgamefun/dto/DesignerRequest.java 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..0edb0a9 --- /dev/null +++ b/src/main/java/com/petproject/boardgamefun/controller/DesignerController.java @@ -0,0 +1,80 @@ +package com.petproject.boardgamefun.controller; + +import com.petproject.boardgamefun.dto.DesignerRequest; +import com.petproject.boardgamefun.model.Designer; +import com.petproject.boardgamefun.repository.DesignerRepository; +import org.springframework.http.HttpStatus; +import org.springframework.http.ResponseEntity; +import org.springframework.web.bind.annotation.*; + +import javax.transaction.Transactional; +import java.util.List; + +@RestController +@RequestMapping("/designer") +@CrossOrigin(origins = "*", maxAge = 3600) +public class DesignerController { + + private final DesignerRepository designerRepository; + + public DesignerController(DesignerRepository designerRepository) { + this.designerRepository = designerRepository; + } + + @Transactional + @GetMapping("") + public ResponseEntity> getDesigners(){ + var designers = designerRepository.findAll(); + + return new ResponseEntity<>(designers, HttpStatus.OK); + } + + @Transactional + @GetMapping("/{name}") + public ResponseEntity getDesignerByName(@PathVariable String name){ + var designers = designerRepository.findDesignerByName(name); + + return new ResponseEntity<>(designers, HttpStatus.OK); + } + + @Transactional + @PostMapping("/add") + public ResponseEntity> addDesigner(@RequestBody DesignerRequest designerRequest){ + var designer = new Designer(); + designer.setName(designerRequest.getName()); + designerRepository.save(designer); + + var designers = designerRepository.findAll(); + + return new ResponseEntity<>(designers, HttpStatus.OK); + } + + @Transactional + @PatchMapping("/update/{id}") + public ResponseEntity> updateDesigner(@PathVariable Integer id, @RequestBody DesignerRequest designerRequest){ + var designer = designerRepository.findDesignerById(id); + + designer.setName(designerRequest.getName()); + designerRepository.save(designer); + + var designers = designerRepository.findAll(); + + return new ResponseEntity<>(designers, HttpStatus.OK); + } + + @Transactional + @DeleteMapping("/delete/{id}") + public ResponseEntity> deleteDesigner(@PathVariable Integer id){ + + var designer = designerRepository.findDesignerById(id); + + designerRepository.delete(designer); + + var designers = designerRepository.findAll(); + + return new ResponseEntity<>(designers, HttpStatus.OK); + } + + + +} diff --git a/src/main/java/com/petproject/boardgamefun/dto/DesignerRequest.java b/src/main/java/com/petproject/boardgamefun/dto/DesignerRequest.java new file mode 100644 index 0000000..dab2528 --- /dev/null +++ b/src/main/java/com/petproject/boardgamefun/dto/DesignerRequest.java @@ -0,0 +1,8 @@ +package com.petproject.boardgamefun.dto; + +import lombok.Data; + +@Data +public class DesignerRequest { + String name; +} diff --git a/src/main/java/com/petproject/boardgamefun/model/Designer.java b/src/main/java/com/petproject/boardgamefun/model/Designer.java index 59efe1a..e8d4880 100644 --- a/src/main/java/com/petproject/boardgamefun/model/Designer.java +++ b/src/main/java/com/petproject/boardgamefun/model/Designer.java @@ -12,7 +12,6 @@ public class Designer { @Column(name = "id", nullable = false) private Integer id; - @Lob @Column(name = "name") private String name; diff --git a/src/main/java/com/petproject/boardgamefun/repository/DesignerRepository.java b/src/main/java/com/petproject/boardgamefun/repository/DesignerRepository.java index 77e7efa..dd1e22b 100644 --- a/src/main/java/com/petproject/boardgamefun/repository/DesignerRepository.java +++ b/src/main/java/com/petproject/boardgamefun/repository/DesignerRepository.java @@ -4,4 +4,6 @@ import org.springframework.data.jpa.repository.JpaRepository; public interface DesignerRepository extends JpaRepository { + Designer findDesignerById(Integer id); + Designer findDesignerByName(String name); } \ No newline at end of file From 1909eb2a96216ad238e990908faa9e017201c08e Mon Sep 17 00:00:00 2001 From: "i.i.artamonov" Date: Tue, 14 Dec 2021 21:45:47 +0400 Subject: [PATCH 029/141] Return getGameByTitle method in GameRepository. Change GameDTO Change name of GameDTO. Rewrite methods of getting games and gameBy. New request in GameController --- .../controller/GameController.java | 30 ++++++++++++++----- ...WithAverageRatingDTO.java => GameDTO.java} | 2 +- .../repository/GameRepository.java | 16 ++++++---- 3 files changed, 34 insertions(+), 14 deletions(-) rename src/main/java/com/petproject/boardgamefun/dto/{GameWithAverageRatingDTO.java => GameDTO.java} (75%) diff --git a/src/main/java/com/petproject/boardgamefun/controller/GameController.java b/src/main/java/com/petproject/boardgamefun/controller/GameController.java index d92ebff..039d3c1 100644 --- a/src/main/java/com/petproject/boardgamefun/controller/GameController.java +++ b/src/main/java/com/petproject/boardgamefun/controller/GameController.java @@ -1,6 +1,6 @@ package com.petproject.boardgamefun.controller; -import com.petproject.boardgamefun.dto.GameWithAverageRatingDTO; +import com.petproject.boardgamefun.dto.GameDTO; import com.petproject.boardgamefun.dto.UsersGameRatingDTO; import com.petproject.boardgamefun.model.Expansion; import com.petproject.boardgamefun.model.Game; @@ -35,19 +35,28 @@ public GameController(GameRepository gameRepository, UserRepository userReposito @Transactional @GetMapping() - ResponseEntity> getGames() { - var games = gameRepository.findAll(); + ResponseEntity> getGames() { + + var games = gameRepository.findGames(); + return new ResponseEntity<>(games, HttpStatus.OK); } @Transactional - @GetMapping("{id}") - ResponseEntity getGameById(@PathVariable Integer id){ - var game = gameRepository.findGameWithRating(id); + @GetMapping("/get-game") + public ResponseEntity getGameByCriteria(@RequestParam(required = false) Integer id, + @RequestParam(required = false) String title) { + GameDTO game = null; + + if (id != null) + game = gameRepository.findGame(id); + else if (title != null) + game = gameRepository.findGameUsingTitle(title); return new ResponseEntity<>(game, HttpStatus.OK); } + @Transactional @PostMapping("/add") public ResponseEntity addGame(@RequestBody Game newGame) { @@ -153,12 +162,17 @@ public ResponseEntity> getUsersRating(@PathVariable Int @Transactional @GetMapping("/with-rating") - public ResponseEntity> getGamesWithRating() { - var games = gameRepository.findGamesWithRating(); + public ResponseEntity> getGamesWithRating() { + var games = gameRepository.findGames(); return new ResponseEntity<>(games, HttpStatus.OK); } + //Поменять на тип текст либо убрать аннотацию + + + //todo: designers //todo: ratings list + //todo: get games by designer } diff --git a/src/main/java/com/petproject/boardgamefun/dto/GameWithAverageRatingDTO.java b/src/main/java/com/petproject/boardgamefun/dto/GameDTO.java similarity index 75% rename from src/main/java/com/petproject/boardgamefun/dto/GameWithAverageRatingDTO.java rename to src/main/java/com/petproject/boardgamefun/dto/GameDTO.java index 36b003b..9268c8e 100644 --- a/src/main/java/com/petproject/boardgamefun/dto/GameWithAverageRatingDTO.java +++ b/src/main/java/com/petproject/boardgamefun/dto/GameDTO.java @@ -2,7 +2,7 @@ import com.petproject.boardgamefun.model.Game; -public interface GameWithAverageRatingDTO { +public interface GameDTO { Game getGame(); Double getRating(); } diff --git a/src/main/java/com/petproject/boardgamefun/repository/GameRepository.java b/src/main/java/com/petproject/boardgamefun/repository/GameRepository.java index 27e99b6..ef8a7b4 100644 --- a/src/main/java/com/petproject/boardgamefun/repository/GameRepository.java +++ b/src/main/java/com/petproject/boardgamefun/repository/GameRepository.java @@ -1,6 +1,6 @@ package com.petproject.boardgamefun.repository; -import com.petproject.boardgamefun.dto.GameWithAverageRatingDTO; +import com.petproject.boardgamefun.dto.GameDTO; import com.petproject.boardgamefun.dto.UserGameRatingDTO; import com.petproject.boardgamefun.dto.GameSellDTO; import com.petproject.boardgamefun.model.Game; @@ -13,15 +13,21 @@ public interface GameRepository extends JpaRepository { Game findGameById(Integer id); @Query("select g as game, avg(rgbu.rating) as rating from Game g " + - "join RatingGameByUser rgbu on rgbu.game.id = g.id " + + "left join RatingGameByUser rgbu on rgbu.game.id = g.id " + "where g.id = :id " + "group by g") - GameWithAverageRatingDTO findGameWithRating(Integer id); + GameDTO findGame(Integer id); @Query("select g as game, avg(rgbu.rating) as rating from Game g " + - "join RatingGameByUser rgbu on rgbu.game.id = g.id " + + "left join RatingGameByUser rgbu on rgbu.game.id = g.id " + + "where g.title = :title " + + "group by g") + GameDTO findGameUsingTitle(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 findGamesWithRating(); + List findGames(); @Query("Select g from Game g " + "join UserOwnGame uog on g.id = uog.game.id " + From 8228ae25ac17bf334808de259f1cfd8363cea837 Mon Sep 17 00:00:00 2001 From: "i.i.artamonov" Date: Fri, 17 Dec 2021 08:58:19 +0400 Subject: [PATCH 030/141] Adding requests for designers in GameController Now we can add and remove disigner to game entity. Change the name of gameDTO to projections. GameDTO now include designer. Add gameService. add methods to DesignerRepository --- .../controller/GameController.java | 57 +++++++++++++++---- .../boardgamefun/dto/DesignersProjection.java | 6 ++ .../petproject/boardgamefun/dto/GameDTO.java | 13 ++++- .../boardgamefun/dto/GameProjection.java | 9 +++ .../repository/DesignerRepository.java | 8 +++ .../repository/GameRepository.java | 8 +-- .../boardgamefun/service/GameService.java | 18 ++++++ 7 files changed, 100 insertions(+), 19 deletions(-) create mode 100644 src/main/java/com/petproject/boardgamefun/dto/DesignersProjection.java create mode 100644 src/main/java/com/petproject/boardgamefun/dto/GameProjection.java create mode 100644 src/main/java/com/petproject/boardgamefun/service/GameService.java diff --git a/src/main/java/com/petproject/boardgamefun/controller/GameController.java b/src/main/java/com/petproject/boardgamefun/controller/GameController.java index 039d3c1..9ee5ed5 100644 --- a/src/main/java/com/petproject/boardgamefun/controller/GameController.java +++ b/src/main/java/com/petproject/boardgamefun/controller/GameController.java @@ -1,14 +1,14 @@ package com.petproject.boardgamefun.controller; import com.petproject.boardgamefun.dto.GameDTO; +import com.petproject.boardgamefun.dto.GameProjection; import com.petproject.boardgamefun.dto.UsersGameRatingDTO; import com.petproject.boardgamefun.model.Expansion; import com.petproject.boardgamefun.model.Game; +import com.petproject.boardgamefun.model.GameByDesigner; import com.petproject.boardgamefun.model.SameGame; -import com.petproject.boardgamefun.repository.ExpansionRepository; -import com.petproject.boardgamefun.repository.GameRepository; -import com.petproject.boardgamefun.repository.SameGameRepository; -import com.petproject.boardgamefun.repository.UserRepository; +import com.petproject.boardgamefun.repository.*; +import com.petproject.boardgamefun.service.GameService; import org.springframework.http.HttpStatus; import org.springframework.http.ResponseEntity; import org.springframework.transaction.annotation.Transactional; @@ -25,17 +25,23 @@ public class GameController { final UserRepository userRepository; final ExpansionRepository expansionRepository; final SameGameRepository sameGameRepository; + final DesignerRepository designerRepository; + final GameByDesignerRepository gameByDesignerRepository; + final GameService gameService; - public GameController(GameRepository gameRepository, UserRepository userRepository, ExpansionRepository expansionRepository, SameGameRepository sameGameRepository) { + public GameController(GameRepository gameRepository, UserRepository userRepository, ExpansionRepository expansionRepository, SameGameRepository sameGameRepository, DesignerRepository designerRepository, GameByDesignerRepository gameByDesignerRepository, GameService gameService) { this.gameRepository = gameRepository; this.userRepository = userRepository; this.expansionRepository = expansionRepository; this.sameGameRepository = sameGameRepository; + this.designerRepository = designerRepository; + this.gameByDesignerRepository = gameByDesignerRepository; + this.gameService = gameService; } @Transactional @GetMapping() - ResponseEntity> getGames() { + ResponseEntity> getGames() { var games = gameRepository.findGames(); @@ -44,9 +50,9 @@ ResponseEntity> getGames() { @Transactional @GetMapping("/get-game") - public ResponseEntity getGameByCriteria(@RequestParam(required = false) Integer id, - @RequestParam(required = false) String title) { - GameDTO game = null; + public ResponseEntity getGameByCriteria(@RequestParam(required = false) Integer id, + @RequestParam(required = false) String title) { + GameProjection game = null; if (id != null) game = gameRepository.findGame(id); @@ -162,17 +168,44 @@ public ResponseEntity> getUsersRating(@PathVariable Int @Transactional @GetMapping("/with-rating") - public ResponseEntity> getGamesWithRating() { + public ResponseEntity> getGamesWithRating() { var games = gameRepository.findGames(); return new ResponseEntity<>(games, HttpStatus.OK); } //Поменять на тип текст либо убрать аннотацию + @Transactional + @PostMapping("/{gameId}/set-designer/{designerId}") + public ResponseEntity addDesignerToGame(@PathVariable Integer gameId, @PathVariable Integer designerId){ + var game = gameRepository.findGameById(gameId); + var designer = designerRepository.findDesignerById(designerId); + + var gameByDesigner = new GameByDesigner(); + gameByDesigner.setDesigner(designer); + gameByDesigner.setGame(game); + + gameByDesignerRepository.save(gameByDesigner); + + var gameDTO = gameService.projectionsToGameDTO(gameRepository.findGame(gameId), + designerRepository.findDesignersUsingGame(gameId)); + + return new ResponseEntity<>(gameDTO, HttpStatus.OK); + } + @Transactional + @DeleteMapping("{gameId}/remove-designer/{gameByDesignerId}") + public ResponseEntity deleteDesignerFromGame(@PathVariable Integer gameId, @PathVariable Integer gameByDesignerId){ + + gameByDesignerRepository.deleteById(gameByDesignerId); + + var gameDTO = gameService.projectionsToGameDTO(gameRepository.findGame(gameId), + designerRepository.findDesignersUsingGame(gameId)); + + return new ResponseEntity<>(gameDTO, HttpStatus.OK); + } - //todo: designers + // todo: use standard hibernate deleteById and findById!!! //todo: ratings list - //todo: get games by designer } diff --git a/src/main/java/com/petproject/boardgamefun/dto/DesignersProjection.java b/src/main/java/com/petproject/boardgamefun/dto/DesignersProjection.java new file mode 100644 index 0000000..ea2898f --- /dev/null +++ b/src/main/java/com/petproject/boardgamefun/dto/DesignersProjection.java @@ -0,0 +1,6 @@ +package com.petproject.boardgamefun.dto; + + +public interface DesignersProjection { + String getDesigner(); +} diff --git a/src/main/java/com/petproject/boardgamefun/dto/GameDTO.java b/src/main/java/com/petproject/boardgamefun/dto/GameDTO.java index 9268c8e..c07e8b6 100644 --- a/src/main/java/com/petproject/boardgamefun/dto/GameDTO.java +++ b/src/main/java/com/petproject/boardgamefun/dto/GameDTO.java @@ -1,8 +1,15 @@ package com.petproject.boardgamefun.dto; import com.petproject.boardgamefun.model.Game; +import lombok.AllArgsConstructor; +import lombok.Data; -public interface GameDTO { - Game getGame(); - Double getRating(); +import java.util.List; + +@Data +@AllArgsConstructor +public class GameDTO { + private Game game; + private Double rating; + private List designers; } diff --git a/src/main/java/com/petproject/boardgamefun/dto/GameProjection.java b/src/main/java/com/petproject/boardgamefun/dto/GameProjection.java new file mode 100644 index 0000000..715dddc --- /dev/null +++ b/src/main/java/com/petproject/boardgamefun/dto/GameProjection.java @@ -0,0 +1,9 @@ +package com.petproject.boardgamefun.dto; + +import com.petproject.boardgamefun.model.Game; + + +public interface GameProjection { + Game getGame(); + Double getRating(); +} diff --git a/src/main/java/com/petproject/boardgamefun/repository/DesignerRepository.java b/src/main/java/com/petproject/boardgamefun/repository/DesignerRepository.java index dd1e22b..77f7772 100644 --- a/src/main/java/com/petproject/boardgamefun/repository/DesignerRepository.java +++ b/src/main/java/com/petproject/boardgamefun/repository/DesignerRepository.java @@ -1,9 +1,17 @@ package com.petproject.boardgamefun.repository; +import com.petproject.boardgamefun.dto.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/GameRepository.java b/src/main/java/com/petproject/boardgamefun/repository/GameRepository.java index ef8a7b4..91b68f9 100644 --- a/src/main/java/com/petproject/boardgamefun/repository/GameRepository.java +++ b/src/main/java/com/petproject/boardgamefun/repository/GameRepository.java @@ -1,6 +1,6 @@ package com.petproject.boardgamefun.repository; -import com.petproject.boardgamefun.dto.GameDTO; +import com.petproject.boardgamefun.dto.GameProjection; import com.petproject.boardgamefun.dto.UserGameRatingDTO; import com.petproject.boardgamefun.dto.GameSellDTO; import com.petproject.boardgamefun.model.Game; @@ -16,18 +16,18 @@ public interface GameRepository extends JpaRepository { "left join RatingGameByUser rgbu on rgbu.game.id = g.id " + "where g.id = :id " + "group by g") - GameDTO findGame(Integer id); + GameProjection findGame(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.title = :title " + "group by g") - GameDTO findGameUsingTitle(String title); + GameProjection findGameUsingTitle(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(); + List findGames(); @Query("Select g from Game g " + "join UserOwnGame uog on g.id = uog.game.id " + 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..49a1b28 --- /dev/null +++ b/src/main/java/com/petproject/boardgamefun/service/GameService.java @@ -0,0 +1,18 @@ +package com.petproject.boardgamefun.service; + +import com.petproject.boardgamefun.dto.DesignersProjection; +import com.petproject.boardgamefun.dto.GameDTO; +import com.petproject.boardgamefun.dto.GameProjection; +import org.springframework.stereotype.Service; + +import java.util.List; +import java.util.stream.Collectors; + +@Service +public class GameService { + public GameDTO projectionsToGameDTO(GameProjection gameProjection, List designersProjection){ + return new GameDTO(gameProjection.getGame(), + gameProjection.getRating(), + designersProjection.stream().map(DesignersProjection::getDesigner).collect(Collectors.toList())); + } +} From a4d82de1930972b653d84f743d50fd5863feef9a Mon Sep 17 00:00:00 2001 From: "i.i.artamonov" Date: Fri, 17 Dec 2021 09:32:33 +0400 Subject: [PATCH 031/141] Add filtering games by title in GameController Change requests get game by id and add request get games title by title search string. Add appropriate projection to this method. Add method to GameService fo convert to list title --- .../controller/GameController.java | 20 +++++++++---------- .../dto/GamesFilterByTitleProjection.java | 5 +++++ .../repository/GameRepository.java | 9 ++++----- .../boardgamefun/service/GameService.java | 5 +++++ 4 files changed, 24 insertions(+), 15 deletions(-) create mode 100644 src/main/java/com/petproject/boardgamefun/dto/GamesFilterByTitleProjection.java diff --git a/src/main/java/com/petproject/boardgamefun/controller/GameController.java b/src/main/java/com/petproject/boardgamefun/controller/GameController.java index 9ee5ed5..c1bdba1 100644 --- a/src/main/java/com/petproject/boardgamefun/controller/GameController.java +++ b/src/main/java/com/petproject/boardgamefun/controller/GameController.java @@ -49,17 +49,17 @@ ResponseEntity> getGames() { } @Transactional - @GetMapping("/get-game") - public ResponseEntity getGameByCriteria(@RequestParam(required = false) Integer id, - @RequestParam(required = false) String title) { - GameProjection game = null; - - if (id != null) - game = gameRepository.findGame(id); - else if (title != null) - game = gameRepository.findGameUsingTitle(title); + @GetMapping("/get-game/{id}") + public ResponseEntity getGameByCriteria(@PathVariable Integer id) { + var gameDTO = gameService.projectionsToGameDTO(gameRepository.findGame(id), designerRepository.findDesignersUsingGame(id)); + return new ResponseEntity<>(gameDTO, HttpStatus.OK); + } - return new ResponseEntity<>(game, HttpStatus.OK); + @Transactional + @GetMapping("/get-games-by-filter/{title}") + public ResponseEntity> getGamesByTitle(@PathVariable String title){ + var games = gameService.getTitlesFromProjections(gameRepository.findGamesUsingTitle(title)); + return new ResponseEntity<>(games, HttpStatus.OK); } diff --git a/src/main/java/com/petproject/boardgamefun/dto/GamesFilterByTitleProjection.java b/src/main/java/com/petproject/boardgamefun/dto/GamesFilterByTitleProjection.java new file mode 100644 index 0000000..e5ff071 --- /dev/null +++ b/src/main/java/com/petproject/boardgamefun/dto/GamesFilterByTitleProjection.java @@ -0,0 +1,5 @@ +package com.petproject.boardgamefun.dto; + +public interface GamesFilterByTitleProjection { + String getTitle(); +} diff --git a/src/main/java/com/petproject/boardgamefun/repository/GameRepository.java b/src/main/java/com/petproject/boardgamefun/repository/GameRepository.java index 91b68f9..9d574f9 100644 --- a/src/main/java/com/petproject/boardgamefun/repository/GameRepository.java +++ b/src/main/java/com/petproject/boardgamefun/repository/GameRepository.java @@ -1,6 +1,7 @@ package com.petproject.boardgamefun.repository; import com.petproject.boardgamefun.dto.GameProjection; +import com.petproject.boardgamefun.dto.GamesFilterByTitleProjection; import com.petproject.boardgamefun.dto.UserGameRatingDTO; import com.petproject.boardgamefun.dto.GameSellDTO; import com.petproject.boardgamefun.model.Game; @@ -18,11 +19,9 @@ public interface GameRepository extends JpaRepository { "group by g") GameProjection findGame(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.title = :title " + - "group by g") - GameProjection findGameUsingTitle(String title); + @Query("select g.title as title from Game g " + + "where 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 " + diff --git a/src/main/java/com/petproject/boardgamefun/service/GameService.java b/src/main/java/com/petproject/boardgamefun/service/GameService.java index 49a1b28..b6c1eca 100644 --- a/src/main/java/com/petproject/boardgamefun/service/GameService.java +++ b/src/main/java/com/petproject/boardgamefun/service/GameService.java @@ -2,6 +2,7 @@ import com.petproject.boardgamefun.dto.DesignersProjection; import com.petproject.boardgamefun.dto.GameDTO; +import com.petproject.boardgamefun.dto.GamesFilterByTitleProjection; import com.petproject.boardgamefun.dto.GameProjection; import org.springframework.stereotype.Service; @@ -15,4 +16,8 @@ public GameDTO projectionsToGameDTO(GameProjection gameProjection, List getTitlesFromProjections(List games){ + return games.stream().map(GamesFilterByTitleProjection::getTitle).collect(Collectors.toList()); + } } From 8b3470a0349ca17ffebcd163fe156cd62639b89a Mon Sep 17 00:00:00 2001 From: "i.i.artamonov" Date: Fri, 17 Dec 2021 10:02:03 +0400 Subject: [PATCH 032/141] Changing current DTO to projection Changing names to projection, because it's not the DTO. Grouping requests and projections by folders --- .../boardgamefun/controller/DesignerController.java | 2 +- .../boardgamefun/controller/DiaryController.java | 8 ++++---- .../boardgamefun/controller/ForumController.java | 12 ++++++------ .../boardgamefun/controller/GameController.java | 6 +++--- .../boardgamefun/controller/UserController.java | 12 ++++++++---- .../boardgamefun/dto/DiariesWithRatingsResponse.java | 8 -------- .../boardgamefun/dto/UserGameRatingDTO.java | 8 -------- .../boardgamefun/dto/UsersGameRatingDTO.java | 8 -------- .../dto/{ => projection}/DesignersProjection.java | 2 +- .../dto/projection/DiariesWithRatingsProjection.java | 8 ++++++++ .../ForumProjection.java} | 4 ++-- .../dto/{ => projection}/GameProjection.java | 2 +- .../GameSellProjection.java} | 4 ++-- .../GamesFilterByTitleProjection.java | 2 +- .../dto/projection/UserGameRatingProjection.java | 8 ++++++++ .../dto/projection/UsersGameRatingProjection.java | 8 ++++++++ .../dto/{ => request}/DesignerRequest.java | 2 +- .../dto/{ => request}/DiaryCommentRequest.java | 2 +- .../dto/{ => request}/DiaryRatingRequest.java | 2 +- .../dto/{ => request}/ForumMessageRequest.java | 2 +- .../dto/{ => request}/ForumRatingRequest.java | 2 +- .../boardgamefun/dto/{ => request}/ForumRequest.java | 2 +- .../dto/{ => request}/PasswordChangeRequest.java | 2 +- .../dto/{ => request}/UserEditRequest.java | 2 +- .../boardgamefun/repository/DesignerRepository.java | 2 +- .../boardgamefun/repository/DiaryRepository.java | 6 +++--- .../boardgamefun/repository/ForumRepository.java | 8 ++++---- .../boardgamefun/repository/GameRepository.java | 12 ++++++------ .../boardgamefun/repository/UserRepository.java | 4 ++-- .../petproject/boardgamefun/service/GameService.java | 6 +++--- 30 files changed, 80 insertions(+), 76 deletions(-) delete mode 100644 src/main/java/com/petproject/boardgamefun/dto/DiariesWithRatingsResponse.java delete mode 100644 src/main/java/com/petproject/boardgamefun/dto/UserGameRatingDTO.java delete mode 100644 src/main/java/com/petproject/boardgamefun/dto/UsersGameRatingDTO.java rename src/main/java/com/petproject/boardgamefun/dto/{ => projection}/DesignersProjection.java (57%) create mode 100644 src/main/java/com/petproject/boardgamefun/dto/projection/DiariesWithRatingsProjection.java rename src/main/java/com/petproject/boardgamefun/dto/{ForumDTO.java => projection/ForumProjection.java} (52%) rename src/main/java/com/petproject/boardgamefun/dto/{ => projection}/GameProjection.java (71%) rename src/main/java/com/petproject/boardgamefun/dto/{GameSellDTO.java => projection/GameSellProjection.java} (62%) rename src/main/java/com/petproject/boardgamefun/dto/{ => projection}/GamesFilterByTitleProjection.java (58%) create mode 100644 src/main/java/com/petproject/boardgamefun/dto/projection/UserGameRatingProjection.java create mode 100644 src/main/java/com/petproject/boardgamefun/dto/projection/UsersGameRatingProjection.java rename src/main/java/com/petproject/boardgamefun/dto/{ => request}/DesignerRequest.java (61%) rename src/main/java/com/petproject/boardgamefun/dto/{ => request}/DiaryCommentRequest.java (65%) rename src/main/java/com/petproject/boardgamefun/dto/{ => request}/DiaryRatingRequest.java (65%) rename src/main/java/com/petproject/boardgamefun/dto/{ => request}/ForumMessageRequest.java (63%) rename src/main/java/com/petproject/boardgamefun/dto/{ => request}/ForumRatingRequest.java (62%) rename src/main/java/com/petproject/boardgamefun/dto/{ => request}/ForumRequest.java (65%) rename src/main/java/com/petproject/boardgamefun/dto/{ => request}/PasswordChangeRequest.java (66%) rename src/main/java/com/petproject/boardgamefun/dto/{ => request}/UserEditRequest.java (73%) diff --git a/src/main/java/com/petproject/boardgamefun/controller/DesignerController.java b/src/main/java/com/petproject/boardgamefun/controller/DesignerController.java index 0edb0a9..f370993 100644 --- a/src/main/java/com/petproject/boardgamefun/controller/DesignerController.java +++ b/src/main/java/com/petproject/boardgamefun/controller/DesignerController.java @@ -1,6 +1,6 @@ package com.petproject.boardgamefun.controller; -import com.petproject.boardgamefun.dto.DesignerRequest; +import com.petproject.boardgamefun.dto.request.DesignerRequest; import com.petproject.boardgamefun.model.Designer; import com.petproject.boardgamefun.repository.DesignerRepository; import org.springframework.http.HttpStatus; diff --git a/src/main/java/com/petproject/boardgamefun/controller/DiaryController.java b/src/main/java/com/petproject/boardgamefun/controller/DiaryController.java index c9dd316..ef474cf 100644 --- a/src/main/java/com/petproject/boardgamefun/controller/DiaryController.java +++ b/src/main/java/com/petproject/boardgamefun/controller/DiaryController.java @@ -1,8 +1,8 @@ package com.petproject.boardgamefun.controller; -import com.petproject.boardgamefun.dto.DiariesWithRatingsResponse; -import com.petproject.boardgamefun.dto.DiaryCommentRequest; -import com.petproject.boardgamefun.dto.DiaryRatingRequest; +import com.petproject.boardgamefun.dto.projection.DiariesWithRatingsProjection; +import com.petproject.boardgamefun.dto.request.DiaryCommentRequest; +import com.petproject.boardgamefun.dto.request.DiaryRatingRequest; import com.petproject.boardgamefun.model.DiaryComment; import com.petproject.boardgamefun.model.DiaryRating; import com.petproject.boardgamefun.repository.DiaryCommentRepository; @@ -37,7 +37,7 @@ public DiaryController(DiaryCommentRepository diaryCommentRepository, UserReposi @Transactional @GetMapping("") - public ResponseEntity> getDiaries(){ + public ResponseEntity> getDiaries(){ var diaries = diaryRepository.getAllDiaries(); return new ResponseEntity<>(diaries, HttpStatus.OK); diff --git a/src/main/java/com/petproject/boardgamefun/controller/ForumController.java b/src/main/java/com/petproject/boardgamefun/controller/ForumController.java index ed00e9e..71516f7 100644 --- a/src/main/java/com/petproject/boardgamefun/controller/ForumController.java +++ b/src/main/java/com/petproject/boardgamefun/controller/ForumController.java @@ -1,9 +1,9 @@ package com.petproject.boardgamefun.controller; -import com.petproject.boardgamefun.dto.ForumDTO; -import com.petproject.boardgamefun.dto.ForumMessageRequest; -import com.petproject.boardgamefun.dto.ForumRatingRequest; -import com.petproject.boardgamefun.dto.ForumRequest; +import com.petproject.boardgamefun.dto.projection.ForumProjection; +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; @@ -38,8 +38,8 @@ public ForumController(ForumRepository forumRepository, GameRepository gameRepos @Transactional @GetMapping("") - public ResponseEntity> getForums(@RequestParam(required = false) Integer gameId, @RequestParam(required = false) Integer userId) { - List forums; + public ResponseEntity> getForums(@RequestParam(required = false) Integer gameId, @RequestParam(required = false) Integer userId) { + List forums; if (gameId != null) { forums = forumRepository.findForumsGameWithRating(gameId); } else if (userId != null) { diff --git a/src/main/java/com/petproject/boardgamefun/controller/GameController.java b/src/main/java/com/petproject/boardgamefun/controller/GameController.java index c1bdba1..cfdf16b 100644 --- a/src/main/java/com/petproject/boardgamefun/controller/GameController.java +++ b/src/main/java/com/petproject/boardgamefun/controller/GameController.java @@ -1,8 +1,8 @@ package com.petproject.boardgamefun.controller; import com.petproject.boardgamefun.dto.GameDTO; -import com.petproject.boardgamefun.dto.GameProjection; -import com.petproject.boardgamefun.dto.UsersGameRatingDTO; +import com.petproject.boardgamefun.dto.projection.GameProjection; +import com.petproject.boardgamefun.dto.projection.UsersGameRatingProjection; import com.petproject.boardgamefun.model.Expansion; import com.petproject.boardgamefun.model.Game; import com.petproject.boardgamefun.model.GameByDesigner; @@ -159,7 +159,7 @@ public ResponseEntity> deleteSameGame(@PathVariable Integer reference @Transactional @GetMapping("/{gameId}/users-rating") - public ResponseEntity> getUsersRating(@PathVariable Integer gameId) { + public ResponseEntity> getUsersRating(@PathVariable Integer gameId) { var ratings = userRepository.findGameRatings(gameId); diff --git a/src/main/java/com/petproject/boardgamefun/controller/UserController.java b/src/main/java/com/petproject/boardgamefun/controller/UserController.java index 2663f20..d1e31b6 100644 --- a/src/main/java/com/petproject/boardgamefun/controller/UserController.java +++ b/src/main/java/com/petproject/boardgamefun/controller/UserController.java @@ -1,6 +1,10 @@ package com.petproject.boardgamefun.controller; -import com.petproject.boardgamefun.dto.*; +import com.petproject.boardgamefun.dto.projection.DiariesWithRatingsProjection; +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.model.*; import com.petproject.boardgamefun.repository.*; import com.petproject.boardgamefun.security.jwt.JwtUtils; @@ -177,7 +181,7 @@ public ResponseEntity deleteGameFromUserCollection(@PathVariable Intege } @GetMapping("/{userId}/games-rating") - public ResponseEntity> getUserRatingList(@PathVariable Integer userId) { + public ResponseEntity> getUserRatingList(@PathVariable Integer userId) { var ratingGamesByUser = gameRepository.findUserGameRatingList(userId); @@ -271,7 +275,7 @@ public ResponseEntity addGameToSellList(@PathVariable Integer userId, @Transactional @GetMapping("{userId}/games-to-sell") - public ResponseEntity> getGameSellList(@PathVariable Integer userId){ + public ResponseEntity> getGameSellList(@PathVariable Integer userId){ var gameSellList = gameRepository.getGameSellList(userId); @@ -339,7 +343,7 @@ public ResponseEntity deleteDiary(@PathVariable Integer userId, @PathVar @Transactional @GetMapping({"{userId}/diary-list"}) - public ResponseEntity> getListDiary(@PathVariable Integer userId){ + public ResponseEntity> getListDiary(@PathVariable Integer userId){ var diaries = diaryRepository.findUserDiaries(userId); return new ResponseEntity<>(diaries, HttpStatus.OK); diff --git a/src/main/java/com/petproject/boardgamefun/dto/DiariesWithRatingsResponse.java b/src/main/java/com/petproject/boardgamefun/dto/DiariesWithRatingsResponse.java deleted file mode 100644 index 2b61172..0000000 --- a/src/main/java/com/petproject/boardgamefun/dto/DiariesWithRatingsResponse.java +++ /dev/null @@ -1,8 +0,0 @@ -package com.petproject.boardgamefun.dto; - -import com.petproject.boardgamefun.model.Diary; - -public interface DiariesWithRatingsResponse { - Diary getDiary(); - Double getRating(); -} diff --git a/src/main/java/com/petproject/boardgamefun/dto/UserGameRatingDTO.java b/src/main/java/com/petproject/boardgamefun/dto/UserGameRatingDTO.java deleted file mode 100644 index e5178ff..0000000 --- a/src/main/java/com/petproject/boardgamefun/dto/UserGameRatingDTO.java +++ /dev/null @@ -1,8 +0,0 @@ -package com.petproject.boardgamefun.dto; - -import com.petproject.boardgamefun.model.Game; - -public interface UserGameRatingDTO { - Game getGame(); - Integer getRating(); -} \ No newline at end of file diff --git a/src/main/java/com/petproject/boardgamefun/dto/UsersGameRatingDTO.java b/src/main/java/com/petproject/boardgamefun/dto/UsersGameRatingDTO.java deleted file mode 100644 index 9ff4287..0000000 --- a/src/main/java/com/petproject/boardgamefun/dto/UsersGameRatingDTO.java +++ /dev/null @@ -1,8 +0,0 @@ -package com.petproject.boardgamefun.dto; - -import com.petproject.boardgamefun.model.User; - -public interface UsersGameRatingDTO { - User getUser(); - Double getRating(); -} diff --git a/src/main/java/com/petproject/boardgamefun/dto/DesignersProjection.java b/src/main/java/com/petproject/boardgamefun/dto/projection/DesignersProjection.java similarity index 57% rename from src/main/java/com/petproject/boardgamefun/dto/DesignersProjection.java rename to src/main/java/com/petproject/boardgamefun/dto/projection/DesignersProjection.java index ea2898f..1cee152 100644 --- a/src/main/java/com/petproject/boardgamefun/dto/DesignersProjection.java +++ b/src/main/java/com/petproject/boardgamefun/dto/projection/DesignersProjection.java @@ -1,4 +1,4 @@ -package com.petproject.boardgamefun.dto; +package com.petproject.boardgamefun.dto.projection; public interface DesignersProjection { diff --git a/src/main/java/com/petproject/boardgamefun/dto/projection/DiariesWithRatingsProjection.java b/src/main/java/com/petproject/boardgamefun/dto/projection/DiariesWithRatingsProjection.java new file mode 100644 index 0000000..8d4fc1b --- /dev/null +++ b/src/main/java/com/petproject/boardgamefun/dto/projection/DiariesWithRatingsProjection.java @@ -0,0 +1,8 @@ +package com.petproject.boardgamefun.dto.projection; + +import com.petproject.boardgamefun.model.Diary; + +public interface DiariesWithRatingsProjection { + Diary getDiary(); + Double getRating(); +} diff --git a/src/main/java/com/petproject/boardgamefun/dto/ForumDTO.java b/src/main/java/com/petproject/boardgamefun/dto/projection/ForumProjection.java similarity index 52% rename from src/main/java/com/petproject/boardgamefun/dto/ForumDTO.java rename to src/main/java/com/petproject/boardgamefun/dto/projection/ForumProjection.java index dee9e92..fa34e00 100644 --- a/src/main/java/com/petproject/boardgamefun/dto/ForumDTO.java +++ b/src/main/java/com/petproject/boardgamefun/dto/projection/ForumProjection.java @@ -1,8 +1,8 @@ -package com.petproject.boardgamefun.dto; +package com.petproject.boardgamefun.dto.projection; import com.petproject.boardgamefun.model.Forum; -public interface ForumDTO { +public interface ForumProjection { Forum getForum(); Double getRating(); } diff --git a/src/main/java/com/petproject/boardgamefun/dto/GameProjection.java b/src/main/java/com/petproject/boardgamefun/dto/projection/GameProjection.java similarity index 71% rename from src/main/java/com/petproject/boardgamefun/dto/GameProjection.java rename to src/main/java/com/petproject/boardgamefun/dto/projection/GameProjection.java index 715dddc..428dc4e 100644 --- a/src/main/java/com/petproject/boardgamefun/dto/GameProjection.java +++ b/src/main/java/com/petproject/boardgamefun/dto/projection/GameProjection.java @@ -1,4 +1,4 @@ -package com.petproject.boardgamefun.dto; +package com.petproject.boardgamefun.dto.projection; import com.petproject.boardgamefun.model.Game; diff --git a/src/main/java/com/petproject/boardgamefun/dto/GameSellDTO.java b/src/main/java/com/petproject/boardgamefun/dto/projection/GameSellProjection.java similarity index 62% rename from src/main/java/com/petproject/boardgamefun/dto/GameSellDTO.java rename to src/main/java/com/petproject/boardgamefun/dto/projection/GameSellProjection.java index ff90084..4009b36 100644 --- a/src/main/java/com/petproject/boardgamefun/dto/GameSellDTO.java +++ b/src/main/java/com/petproject/boardgamefun/dto/projection/GameSellProjection.java @@ -1,8 +1,8 @@ -package com.petproject.boardgamefun.dto; +package com.petproject.boardgamefun.dto.projection; import com.petproject.boardgamefun.model.Game; -public interface GameSellDTO { +public interface GameSellProjection { Game getGame(); String getCondition(); String getComment(); diff --git a/src/main/java/com/petproject/boardgamefun/dto/GamesFilterByTitleProjection.java b/src/main/java/com/petproject/boardgamefun/dto/projection/GamesFilterByTitleProjection.java similarity index 58% rename from src/main/java/com/petproject/boardgamefun/dto/GamesFilterByTitleProjection.java rename to src/main/java/com/petproject/boardgamefun/dto/projection/GamesFilterByTitleProjection.java index e5ff071..5385d2e 100644 --- a/src/main/java/com/petproject/boardgamefun/dto/GamesFilterByTitleProjection.java +++ b/src/main/java/com/petproject/boardgamefun/dto/projection/GamesFilterByTitleProjection.java @@ -1,4 +1,4 @@ -package com.petproject.boardgamefun.dto; +package com.petproject.boardgamefun.dto.projection; public interface GamesFilterByTitleProjection { String getTitle(); 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/DesignerRequest.java b/src/main/java/com/petproject/boardgamefun/dto/request/DesignerRequest.java similarity index 61% rename from src/main/java/com/petproject/boardgamefun/dto/DesignerRequest.java rename to src/main/java/com/petproject/boardgamefun/dto/request/DesignerRequest.java index dab2528..e840f8d 100644 --- a/src/main/java/com/petproject/boardgamefun/dto/DesignerRequest.java +++ b/src/main/java/com/petproject/boardgamefun/dto/request/DesignerRequest.java @@ -1,4 +1,4 @@ -package com.petproject.boardgamefun.dto; +package com.petproject.boardgamefun.dto.request; import lombok.Data; diff --git a/src/main/java/com/petproject/boardgamefun/dto/DiaryCommentRequest.java b/src/main/java/com/petproject/boardgamefun/dto/request/DiaryCommentRequest.java similarity index 65% rename from src/main/java/com/petproject/boardgamefun/dto/DiaryCommentRequest.java rename to src/main/java/com/petproject/boardgamefun/dto/request/DiaryCommentRequest.java index e8fb3ca..7f3b989 100644 --- a/src/main/java/com/petproject/boardgamefun/dto/DiaryCommentRequest.java +++ b/src/main/java/com/petproject/boardgamefun/dto/request/DiaryCommentRequest.java @@ -1,4 +1,4 @@ -package com.petproject.boardgamefun.dto; +package com.petproject.boardgamefun.dto.request; import lombok.Data; diff --git a/src/main/java/com/petproject/boardgamefun/dto/DiaryRatingRequest.java b/src/main/java/com/petproject/boardgamefun/dto/request/DiaryRatingRequest.java similarity index 65% rename from src/main/java/com/petproject/boardgamefun/dto/DiaryRatingRequest.java rename to src/main/java/com/petproject/boardgamefun/dto/request/DiaryRatingRequest.java index e5e390a..db4a681 100644 --- a/src/main/java/com/petproject/boardgamefun/dto/DiaryRatingRequest.java +++ b/src/main/java/com/petproject/boardgamefun/dto/request/DiaryRatingRequest.java @@ -1,4 +1,4 @@ -package com.petproject.boardgamefun.dto; +package com.petproject.boardgamefun.dto.request; import lombok.Data; diff --git a/src/main/java/com/petproject/boardgamefun/dto/ForumMessageRequest.java b/src/main/java/com/petproject/boardgamefun/dto/request/ForumMessageRequest.java similarity index 63% rename from src/main/java/com/petproject/boardgamefun/dto/ForumMessageRequest.java rename to src/main/java/com/petproject/boardgamefun/dto/request/ForumMessageRequest.java index d6fa925..63593f7 100644 --- a/src/main/java/com/petproject/boardgamefun/dto/ForumMessageRequest.java +++ b/src/main/java/com/petproject/boardgamefun/dto/request/ForumMessageRequest.java @@ -1,4 +1,4 @@ -package com.petproject.boardgamefun.dto; +package com.petproject.boardgamefun.dto.request; import lombok.Data; diff --git a/src/main/java/com/petproject/boardgamefun/dto/ForumRatingRequest.java b/src/main/java/com/petproject/boardgamefun/dto/request/ForumRatingRequest.java similarity index 62% rename from src/main/java/com/petproject/boardgamefun/dto/ForumRatingRequest.java rename to src/main/java/com/petproject/boardgamefun/dto/request/ForumRatingRequest.java index e6bc75d..dfd46d3 100644 --- a/src/main/java/com/petproject/boardgamefun/dto/ForumRatingRequest.java +++ b/src/main/java/com/petproject/boardgamefun/dto/request/ForumRatingRequest.java @@ -1,4 +1,4 @@ -package com.petproject.boardgamefun.dto; +package com.petproject.boardgamefun.dto.request; import lombok.Data; diff --git a/src/main/java/com/petproject/boardgamefun/dto/ForumRequest.java b/src/main/java/com/petproject/boardgamefun/dto/request/ForumRequest.java similarity index 65% rename from src/main/java/com/petproject/boardgamefun/dto/ForumRequest.java rename to src/main/java/com/petproject/boardgamefun/dto/request/ForumRequest.java index c762253..2e73a06 100644 --- a/src/main/java/com/petproject/boardgamefun/dto/ForumRequest.java +++ b/src/main/java/com/petproject/boardgamefun/dto/request/ForumRequest.java @@ -1,4 +1,4 @@ -package com.petproject.boardgamefun.dto; +package com.petproject.boardgamefun.dto.request; import lombok.Data; diff --git a/src/main/java/com/petproject/boardgamefun/dto/PasswordChangeRequest.java b/src/main/java/com/petproject/boardgamefun/dto/request/PasswordChangeRequest.java similarity index 66% rename from src/main/java/com/petproject/boardgamefun/dto/PasswordChangeRequest.java rename to src/main/java/com/petproject/boardgamefun/dto/request/PasswordChangeRequest.java index 28e032f..311609c 100644 --- a/src/main/java/com/petproject/boardgamefun/dto/PasswordChangeRequest.java +++ b/src/main/java/com/petproject/boardgamefun/dto/request/PasswordChangeRequest.java @@ -1,4 +1,4 @@ -package com.petproject.boardgamefun.dto; +package com.petproject.boardgamefun.dto.request; import lombok.Data; diff --git a/src/main/java/com/petproject/boardgamefun/dto/UserEditRequest.java b/src/main/java/com/petproject/boardgamefun/dto/request/UserEditRequest.java similarity index 73% rename from src/main/java/com/petproject/boardgamefun/dto/UserEditRequest.java rename to src/main/java/com/petproject/boardgamefun/dto/request/UserEditRequest.java index c5fd9b5..2de0c99 100644 --- a/src/main/java/com/petproject/boardgamefun/dto/UserEditRequest.java +++ b/src/main/java/com/petproject/boardgamefun/dto/request/UserEditRequest.java @@ -1,4 +1,4 @@ -package com.petproject.boardgamefun.dto; +package com.petproject.boardgamefun.dto.request; import lombok.Data; diff --git a/src/main/java/com/petproject/boardgamefun/repository/DesignerRepository.java b/src/main/java/com/petproject/boardgamefun/repository/DesignerRepository.java index 77f7772..a3b984c 100644 --- a/src/main/java/com/petproject/boardgamefun/repository/DesignerRepository.java +++ b/src/main/java/com/petproject/boardgamefun/repository/DesignerRepository.java @@ -1,6 +1,6 @@ package com.petproject.boardgamefun.repository; -import com.petproject.boardgamefun.dto.DesignersProjection; +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; diff --git a/src/main/java/com/petproject/boardgamefun/repository/DiaryRepository.java b/src/main/java/com/petproject/boardgamefun/repository/DiaryRepository.java index 7b2f586..bfa0ec9 100644 --- a/src/main/java/com/petproject/boardgamefun/repository/DiaryRepository.java +++ b/src/main/java/com/petproject/boardgamefun/repository/DiaryRepository.java @@ -1,6 +1,6 @@ package com.petproject.boardgamefun.repository; -import com.petproject.boardgamefun.dto.DiariesWithRatingsResponse; +import com.petproject.boardgamefun.dto.projection.DiariesWithRatingsProjection; import com.petproject.boardgamefun.model.Diary; import org.springframework.data.jpa.repository.JpaRepository; import org.springframework.data.jpa.repository.Query; @@ -15,12 +15,12 @@ public interface DiaryRepository extends JpaRepository { "join User u on u.id = d.user.id " + "where u.id = :userId " + "group by d") - ListfindUserDiaries(Integer userId); + ListfindUserDiaries(Integer userId); Diary findDiaryById(Integer id); @Query("select d as diary, avg(dr.rating) as rating from Diary d " + "join DiaryRating dr on d.id = dr.diary.id" + " group by d") - List getAllDiaries(); + List getAllDiaries(); } \ 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 index c7d9468..cb31329 100644 --- a/src/main/java/com/petproject/boardgamefun/repository/ForumRepository.java +++ b/src/main/java/com/petproject/boardgamefun/repository/ForumRepository.java @@ -1,6 +1,6 @@ package com.petproject.boardgamefun.repository; -import com.petproject.boardgamefun.dto.ForumDTO; +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; @@ -13,19 +13,19 @@ public interface ForumRepository extends JpaRepository { "join ForumRating fr on fr.forum.id = f.id " + "where g.id = :gameId " + "group by f") - List findForumsGameWithRating(Integer gameId); + 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 " + "join ForumRating fr on fr.forum.id = f.id " + "where u.id = :userId " + "group by f") - List findForumsUserWithRating(Integer userId); + List findForumsUserWithRating(Integer userId); @Query("select f as forum, avg(fr.rating) as rating from Forum f " + "join ForumRating fr on fr.forum.id = f.id " + "group by f") - List findForumsWithRating(); + List findForumsWithRating(); Forum findForumById(Integer id); } \ 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 index 9d574f9..22b0b03 100644 --- a/src/main/java/com/petproject/boardgamefun/repository/GameRepository.java +++ b/src/main/java/com/petproject/boardgamefun/repository/GameRepository.java @@ -1,9 +1,9 @@ package com.petproject.boardgamefun.repository; -import com.petproject.boardgamefun.dto.GameProjection; -import com.petproject.boardgamefun.dto.GamesFilterByTitleProjection; -import com.petproject.boardgamefun.dto.UserGameRatingDTO; -import com.petproject.boardgamefun.dto.GameSellDTO; +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; @@ -39,7 +39,7 @@ public interface GameRepository extends JpaRepository { "join User u on u.id = rgbu.user.id " + "where u.id = :id " + "order by rgbu.rating desc") - List findUserGameRatingList(Integer id); + List findUserGameRatingList(Integer id); @Query("Select g from Game g " + "join UserWish uw on g.id = uw.game.id " + @@ -52,7 +52,7 @@ public interface GameRepository extends JpaRepository { "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); + List getGameSellList(Integer id); @Query("select g from Game g " + "join Expansion ex on ex.daughterGame.id = g.id " + diff --git a/src/main/java/com/petproject/boardgamefun/repository/UserRepository.java b/src/main/java/com/petproject/boardgamefun/repository/UserRepository.java index 91e1095..e721b9f 100644 --- a/src/main/java/com/petproject/boardgamefun/repository/UserRepository.java +++ b/src/main/java/com/petproject/boardgamefun/repository/UserRepository.java @@ -1,6 +1,6 @@ package com.petproject.boardgamefun.repository; -import com.petproject.boardgamefun.dto.UsersGameRatingDTO; +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; @@ -17,5 +17,5 @@ public interface UserRepository extends JpaRepository { "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); + List findGameRatings(Integer gameId); } \ No newline at end of file diff --git a/src/main/java/com/petproject/boardgamefun/service/GameService.java b/src/main/java/com/petproject/boardgamefun/service/GameService.java index b6c1eca..70ae655 100644 --- a/src/main/java/com/petproject/boardgamefun/service/GameService.java +++ b/src/main/java/com/petproject/boardgamefun/service/GameService.java @@ -1,9 +1,9 @@ package com.petproject.boardgamefun.service; -import com.petproject.boardgamefun.dto.DesignersProjection; +import com.petproject.boardgamefun.dto.projection.DesignersProjection; import com.petproject.boardgamefun.dto.GameDTO; -import com.petproject.boardgamefun.dto.GamesFilterByTitleProjection; -import com.petproject.boardgamefun.dto.GameProjection; +import com.petproject.boardgamefun.dto.projection.GamesFilterByTitleProjection; +import com.petproject.boardgamefun.dto.projection.GameProjection; import org.springframework.stereotype.Service; import java.util.List; From 822385ff85cbadb146756643bb1b828bfdc4462d Mon Sep 17 00:00:00 2001 From: "i.i.artamonov" Date: Fri, 17 Dec 2021 10:43:45 +0400 Subject: [PATCH 033/141] Adding type text to Lob annotations in models Because postgre save info in Lob annotations like digits we need add type text description to column --- .../boardgamefun/model/Category.java | 3 + .../petproject/boardgamefun/model/Diary.java | 4 ++ .../boardgamefun/model/DiaryComment.java | 3 + .../petproject/boardgamefun/model/Forum.java | 4 ++ .../boardgamefun/model/ForumMessage.java | 3 + .../boardgamefun/model/GameSell.java | 4 ++ .../boardgamefun/model/Messenger.java | 3 + .../petproject/boardgamefun/model/News.java | 64 +++++++++++++++++++ .../boardgamefun/model/NewsComment.java | 3 + .../boardgamefun/model/UserRating.java | 3 + .../repository/ForumRepository.java | 6 +- 11 files changed, 97 insertions(+), 3 deletions(-) diff --git a/src/main/java/com/petproject/boardgamefun/model/Category.java b/src/main/java/com/petproject/boardgamefun/model/Category.java index 9af5c94..db04f55 100644 --- a/src/main/java/com/petproject/boardgamefun/model/Category.java +++ b/src/main/java/com/petproject/boardgamefun/model/Category.java @@ -1,5 +1,7 @@ package com.petproject.boardgamefun.model; +import org.hibernate.annotations.Type; + import javax.persistence.*; @Table(name = "category", indexes = { @@ -13,6 +15,7 @@ public class Category { private Integer id; @Lob + @Type(type = "org.hibernate.type.TextType") @Column(name = "category") private String category; diff --git a/src/main/java/com/petproject/boardgamefun/model/Diary.java b/src/main/java/com/petproject/boardgamefun/model/Diary.java index 107900f..19107b5 100644 --- a/src/main/java/com/petproject/boardgamefun/model/Diary.java +++ b/src/main/java/com/petproject/boardgamefun/model/Diary.java @@ -1,5 +1,7 @@ package com.petproject.boardgamefun.model; +import org.hibernate.annotations.Type; + import javax.persistence.*; import java.time.OffsetDateTime; @@ -12,10 +14,12 @@ public class Diary { 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; diff --git a/src/main/java/com/petproject/boardgamefun/model/DiaryComment.java b/src/main/java/com/petproject/boardgamefun/model/DiaryComment.java index 04a47ef..c2f92bd 100644 --- a/src/main/java/com/petproject/boardgamefun/model/DiaryComment.java +++ b/src/main/java/com/petproject/boardgamefun/model/DiaryComment.java @@ -1,5 +1,7 @@ package com.petproject.boardgamefun.model; +import org.hibernate.annotations.Type; + import javax.persistence.*; import java.time.OffsetDateTime; @@ -13,6 +15,7 @@ public class DiaryComment { private Integer id; @Lob + @Type(type = "org.hibernate.type.TextType") @Column(name = "comment", nullable = false) private String comment; diff --git a/src/main/java/com/petproject/boardgamefun/model/Forum.java b/src/main/java/com/petproject/boardgamefun/model/Forum.java index f39801d..35e9577 100644 --- a/src/main/java/com/petproject/boardgamefun/model/Forum.java +++ b/src/main/java/com/petproject/boardgamefun/model/Forum.java @@ -1,5 +1,7 @@ package com.petproject.boardgamefun.model; +import org.hibernate.annotations.Type; + import javax.persistence.*; import java.time.OffsetDateTime; @@ -12,10 +14,12 @@ public class Forum { 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; diff --git a/src/main/java/com/petproject/boardgamefun/model/ForumMessage.java b/src/main/java/com/petproject/boardgamefun/model/ForumMessage.java index eeab621..825e0dc 100644 --- a/src/main/java/com/petproject/boardgamefun/model/ForumMessage.java +++ b/src/main/java/com/petproject/boardgamefun/model/ForumMessage.java @@ -1,5 +1,7 @@ package com.petproject.boardgamefun.model; +import org.hibernate.annotations.Type; + import javax.persistence.*; import java.time.OffsetDateTime; import java.time.OffsetTime; @@ -17,6 +19,7 @@ public class ForumMessage { private Forum forum; @Lob + @Type(type = "org.hibernate.type.TextType") @Column(name = "comment", nullable = false) private String comment; diff --git a/src/main/java/com/petproject/boardgamefun/model/GameSell.java b/src/main/java/com/petproject/boardgamefun/model/GameSell.java index 221b2fd..5598867 100644 --- a/src/main/java/com/petproject/boardgamefun/model/GameSell.java +++ b/src/main/java/com/petproject/boardgamefun/model/GameSell.java @@ -1,5 +1,7 @@ package com.petproject.boardgamefun.model; +import org.hibernate.annotations.Type; + import javax.persistence.*; @Table(name = "game_sell") @@ -11,6 +13,7 @@ public class GameSell { private Integer id; @Lob + @Type(type = "org.hibernate.type.TextType") @Column(name = "condition", nullable = false) private String condition; @@ -18,6 +21,7 @@ public class GameSell { private Integer price; @Lob + @Type(type = "org.hibernate.type.TextType") @Column(name = "comment", nullable = false) private String comment; diff --git a/src/main/java/com/petproject/boardgamefun/model/Messenger.java b/src/main/java/com/petproject/boardgamefun/model/Messenger.java index e1cf312..5a9c811 100644 --- a/src/main/java/com/petproject/boardgamefun/model/Messenger.java +++ b/src/main/java/com/petproject/boardgamefun/model/Messenger.java @@ -1,5 +1,7 @@ package com.petproject.boardgamefun.model; +import org.hibernate.annotations.Type; + import javax.persistence.*; import java.time.OffsetTime; @@ -12,6 +14,7 @@ public class Messenger { private Integer id; @Lob + @Type(type = "org.hibernate.type.TextType") @Column(name = "text", nullable = false) private String text; diff --git a/src/main/java/com/petproject/boardgamefun/model/News.java b/src/main/java/com/petproject/boardgamefun/model/News.java index e832d85..06d55e5 100644 --- a/src/main/java/com/petproject/boardgamefun/model/News.java +++ b/src/main/java/com/petproject/boardgamefun/model/News.java @@ -1,6 +1,9 @@ package com.petproject.boardgamefun.model; +import org.hibernate.annotations.Type; + import javax.persistence.*; +import java.time.OffsetDateTime; @Table(name = "news") @Entity @@ -10,6 +13,67 @@ public class News { @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; } diff --git a/src/main/java/com/petproject/boardgamefun/model/NewsComment.java b/src/main/java/com/petproject/boardgamefun/model/NewsComment.java index df9f08f..cd98d36 100644 --- a/src/main/java/com/petproject/boardgamefun/model/NewsComment.java +++ b/src/main/java/com/petproject/boardgamefun/model/NewsComment.java @@ -1,5 +1,7 @@ package com.petproject.boardgamefun.model; +import org.hibernate.annotations.Type; + import javax.persistence.*; import java.time.OffsetTime; @@ -12,6 +14,7 @@ public class NewsComment { private Integer id; @Lob + @Type(type = "org.hibernate.type.TextType") @Column(name = "comment", nullable = false) private String comment; diff --git a/src/main/java/com/petproject/boardgamefun/model/UserRating.java b/src/main/java/com/petproject/boardgamefun/model/UserRating.java index 831a9f9..9f9e0b5 100644 --- a/src/main/java/com/petproject/boardgamefun/model/UserRating.java +++ b/src/main/java/com/petproject/boardgamefun/model/UserRating.java @@ -1,5 +1,7 @@ package com.petproject.boardgamefun.model; +import org.hibernate.annotations.Type; + import javax.persistence.*; @Table(name = "user_ratings") @@ -11,6 +13,7 @@ public class UserRating { private Integer id; @Lob + @Type(type = "org.hibernate.type.TextType") @Column(name = "comment") private String comment; diff --git a/src/main/java/com/petproject/boardgamefun/repository/ForumRepository.java b/src/main/java/com/petproject/boardgamefun/repository/ForumRepository.java index cb31329..fd4fabd 100644 --- a/src/main/java/com/petproject/boardgamefun/repository/ForumRepository.java +++ b/src/main/java/com/petproject/boardgamefun/repository/ForumRepository.java @@ -10,20 +10,20 @@ 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 " + - "join ForumRating fr on fr.forum.id = f.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 " + - "join ForumRating fr on fr.forum.id = f.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 " + - "join ForumRating fr on fr.forum.id = f.id " + + "left join ForumRating fr on fr.forum.id = f.id " + "group by f") List findForumsWithRating(); From 06d8d8bad2f53859bfc9693a6ca32498809c04a3 Mon Sep 17 00:00:00 2001 From: "i.i.artamonov" Date: Tue, 21 Dec 2021 10:05:30 +0400 Subject: [PATCH 034/141] Add plugin to pom "typescript-generator" Add maven plugin to generate java models to typescript models. --- pom.xml | 28 ++++++++++++++++++++++++++++ 1 file changed, 28 insertions(+) diff --git a/pom.xml b/pom.xml index 036a6b5..5350b9e 100644 --- a/pom.xml +++ b/pom.xml @@ -95,6 +95,11 @@ reactor-test test + + com.fasterxml.jackson.jaxrs + jackson-jaxrs-json-provider + 2.13.0 + @@ -111,6 +116,29 @@ + + cz.habarta.typescript-generator + typescript-generator-maven-plugin + 2.34.976 + + + generate + + generate + + process-classes + + + + jackson2 + + com.petproject.boardgamefun.model.* + + target/rest.d.ts + module + + + From dcd64327ae129aec018de6d28ec80f6b8230d0a9 Mon Sep 17 00:00:00 2001 From: "i.i.artamonov" Date: Thu, 23 Dec 2021 14:43:24 +0400 Subject: [PATCH 035/141] Add cors policy Remove crossorigin annotation from controllers. Add Transactional annotation to UserDetailsServiceImpl --- .../controller/DesignerController.java | 1 - .../controller/DiaryController.java | 1 - .../controller/ForumController.java | 1 - .../controller/GameController.java | 1 - .../controller/UserController.java | 1 - .../security/WebSecurityConfig.java | 20 +++++++++++++++++++ .../services/UserDetailsServiceImpl.java | 4 ++++ 7 files changed, 24 insertions(+), 5 deletions(-) diff --git a/src/main/java/com/petproject/boardgamefun/controller/DesignerController.java b/src/main/java/com/petproject/boardgamefun/controller/DesignerController.java index f370993..26b0c18 100644 --- a/src/main/java/com/petproject/boardgamefun/controller/DesignerController.java +++ b/src/main/java/com/petproject/boardgamefun/controller/DesignerController.java @@ -12,7 +12,6 @@ @RestController @RequestMapping("/designer") -@CrossOrigin(origins = "*", maxAge = 3600) public class DesignerController { private final DesignerRepository designerRepository; diff --git a/src/main/java/com/petproject/boardgamefun/controller/DiaryController.java b/src/main/java/com/petproject/boardgamefun/controller/DiaryController.java index ef474cf..060d9aa 100644 --- a/src/main/java/com/petproject/boardgamefun/controller/DiaryController.java +++ b/src/main/java/com/petproject/boardgamefun/controller/DiaryController.java @@ -20,7 +20,6 @@ @RestController -@CrossOrigin(origins = "*", maxAge = 3600) @RequestMapping("/diaries") public class DiaryController { final DiaryCommentRepository diaryCommentRepository; diff --git a/src/main/java/com/petproject/boardgamefun/controller/ForumController.java b/src/main/java/com/petproject/boardgamefun/controller/ForumController.java index 71516f7..0d3c102 100644 --- a/src/main/java/com/petproject/boardgamefun/controller/ForumController.java +++ b/src/main/java/com/petproject/boardgamefun/controller/ForumController.java @@ -18,7 +18,6 @@ import java.util.Objects; @RestController -@CrossOrigin(origins = "*", maxAge = 3600) @RequestMapping("/forum") public class ForumController { diff --git a/src/main/java/com/petproject/boardgamefun/controller/GameController.java b/src/main/java/com/petproject/boardgamefun/controller/GameController.java index cfdf16b..9698bdc 100644 --- a/src/main/java/com/petproject/boardgamefun/controller/GameController.java +++ b/src/main/java/com/petproject/boardgamefun/controller/GameController.java @@ -16,7 +16,6 @@ import java.util.List; -@CrossOrigin(origins = "*", maxAge = 3600) @RestController @RequestMapping("/games") public class GameController { diff --git a/src/main/java/com/petproject/boardgamefun/controller/UserController.java b/src/main/java/com/petproject/boardgamefun/controller/UserController.java index d1e31b6..1cdf227 100644 --- a/src/main/java/com/petproject/boardgamefun/controller/UserController.java +++ b/src/main/java/com/petproject/boardgamefun/controller/UserController.java @@ -27,7 +27,6 @@ import java.util.Objects; @RestController -@CrossOrigin(origins = "*", maxAge = 3600) @RequestMapping("/users") public class UserController { diff --git a/src/main/java/com/petproject/boardgamefun/security/WebSecurityConfig.java b/src/main/java/com/petproject/boardgamefun/security/WebSecurityConfig.java index 72890d0..df941a7 100644 --- a/src/main/java/com/petproject/boardgamefun/security/WebSecurityConfig.java +++ b/src/main/java/com/petproject/boardgamefun/security/WebSecurityConfig.java @@ -15,6 +15,9 @@ 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 @@ -62,4 +65,21 @@ protected void configure(HttpSecurity httpSecurity) throws Exception{ 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("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/services/UserDetailsServiceImpl.java b/src/main/java/com/petproject/boardgamefun/security/services/UserDetailsServiceImpl.java index 87f0901..247842e 100644 --- a/src/main/java/com/petproject/boardgamefun/security/services/UserDetailsServiceImpl.java +++ b/src/main/java/com/petproject/boardgamefun/security/services/UserDetailsServiceImpl.java @@ -7,6 +7,8 @@ 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; @@ -16,7 +18,9 @@ public UserDetailsServiceImpl(UserRepository userRepository){ } + @Override + @Transactional public UserDetails loadUserByUsername(String userName) throws UsernameNotFoundException { User user = userRepository.findUserByName(userName); if(user == null) From 3484b0fda0ed5f14b9d8efbfadd205a60b1e269f Mon Sep 17 00:00:00 2001 From: "i.i.artamonov" Date: Thu, 23 Dec 2021 15:28:30 +0400 Subject: [PATCH 036/141] Add projections and dto to typescript interface generating --- pom.xml | 2 ++ 1 file changed, 2 insertions(+) diff --git a/pom.xml b/pom.xml index 5350b9e..f85a7cc 100644 --- a/pom.xml +++ b/pom.xml @@ -133,6 +133,8 @@ jackson2 com.petproject.boardgamefun.model.* + com.petproject.boardgamefun.dto.* + com.petproject.boardgamefun.dto.projection.* target/rest.d.ts module From a8567b4a3e35a35e1b9e634b1ca8f6657f9fe828 Mon Sep 17 00:00:00 2001 From: "i.i.artamonov" Date: Fri, 24 Dec 2021 09:29:56 +0400 Subject: [PATCH 037/141] Add left join to diary repository requests --- .../petproject/boardgamefun/repository/DiaryRepository.java | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/src/main/java/com/petproject/boardgamefun/repository/DiaryRepository.java b/src/main/java/com/petproject/boardgamefun/repository/DiaryRepository.java index bfa0ec9..85edc3b 100644 --- a/src/main/java/com/petproject/boardgamefun/repository/DiaryRepository.java +++ b/src/main/java/com/petproject/boardgamefun/repository/DiaryRepository.java @@ -11,7 +11,7 @@ public interface DiaryRepository extends JpaRepository { Diary findDiary_ByUserIdAndId(Integer userId, Integer id); @Query("select d as diary, avg(dr.rating) as rating from Diary d " + - "join DiaryRating dr on d.id = dr.diary.id " + + "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") @@ -20,7 +20,7 @@ public interface DiaryRepository extends JpaRepository { Diary findDiaryById(Integer id); @Query("select d as diary, avg(dr.rating) as rating from Diary d " + - "join DiaryRating dr on d.id = dr.diary.id" + + "left join DiaryRating dr on d.id = dr.diary.id" + " group by d") List getAllDiaries(); } \ No newline at end of file From 6b37ff7c281c635827f835bbae7f61e9c6b2eca2 Mon Sep 17 00:00:00 2001 From: "i.i.artamonov" Date: Fri, 24 Dec 2021 10:11:02 +0400 Subject: [PATCH 038/141] Add request for get diary with rating by id Change name of projection from DiariesWithRatingsProjection to DiaryWithRatingsProjection. Add request for getting diary by id in DiaryController and according method to DiaryRepository --- .../boardgamefun/controller/DiaryController.java | 13 +++++++++++-- .../boardgamefun/controller/UserController.java | 4 ++-- ...jection.java => DiaryWithRatingsProjection.java} | 2 +- .../boardgamefun/repository/DiaryRepository.java | 12 +++++++++--- 4 files changed, 23 insertions(+), 8 deletions(-) rename src/main/java/com/petproject/boardgamefun/dto/projection/{DiariesWithRatingsProjection.java => DiaryWithRatingsProjection.java} (75%) diff --git a/src/main/java/com/petproject/boardgamefun/controller/DiaryController.java b/src/main/java/com/petproject/boardgamefun/controller/DiaryController.java index 060d9aa..ba4d3ac 100644 --- a/src/main/java/com/petproject/boardgamefun/controller/DiaryController.java +++ b/src/main/java/com/petproject/boardgamefun/controller/DiaryController.java @@ -1,6 +1,6 @@ package com.petproject.boardgamefun.controller; -import com.petproject.boardgamefun.dto.projection.DiariesWithRatingsProjection; +import com.petproject.boardgamefun.dto.projection.DiaryWithRatingsProjection; import com.petproject.boardgamefun.dto.request.DiaryCommentRequest; import com.petproject.boardgamefun.dto.request.DiaryRatingRequest; import com.petproject.boardgamefun.model.DiaryComment; @@ -36,12 +36,21 @@ public DiaryController(DiaryCommentRepository diaryCommentRepository, UserReposi @Transactional @GetMapping("") - public ResponseEntity> getDiaries(){ + public ResponseEntity> getDiaries(){ var diaries = diaryRepository.getAllDiaries(); return new ResponseEntity<>(diaries, HttpStatus.OK); } + @Transactional + @GetMapping("/{diaryId}") + public ResponseEntity getDiary(@PathVariable Integer diaryId){ + var diaryProjection = diaryRepository.findDiaryUsingId(diaryId); + + return new ResponseEntity<>(diaryProjection, HttpStatus.OK); + } + + @Transactional @GetMapping("/{diaryId}/comments") public ResponseEntity> getDiaryComments(@PathVariable Integer diaryId){ diff --git a/src/main/java/com/petproject/boardgamefun/controller/UserController.java b/src/main/java/com/petproject/boardgamefun/controller/UserController.java index 1cdf227..005a6a0 100644 --- a/src/main/java/com/petproject/boardgamefun/controller/UserController.java +++ b/src/main/java/com/petproject/boardgamefun/controller/UserController.java @@ -1,6 +1,6 @@ package com.petproject.boardgamefun.controller; -import com.petproject.boardgamefun.dto.projection.DiariesWithRatingsProjection; +import com.petproject.boardgamefun.dto.projection.DiaryWithRatingsProjection; import com.petproject.boardgamefun.dto.projection.GameSellProjection; import com.petproject.boardgamefun.dto.projection.UserGameRatingProjection; import com.petproject.boardgamefun.dto.request.PasswordChangeRequest; @@ -342,7 +342,7 @@ public ResponseEntity deleteDiary(@PathVariable Integer userId, @PathVar @Transactional @GetMapping({"{userId}/diary-list"}) - public ResponseEntity> getListDiary(@PathVariable Integer userId){ + public ResponseEntity> getListDiary(@PathVariable Integer userId){ var diaries = diaryRepository.findUserDiaries(userId); return new ResponseEntity<>(diaries, HttpStatus.OK); diff --git a/src/main/java/com/petproject/boardgamefun/dto/projection/DiariesWithRatingsProjection.java b/src/main/java/com/petproject/boardgamefun/dto/projection/DiaryWithRatingsProjection.java similarity index 75% rename from src/main/java/com/petproject/boardgamefun/dto/projection/DiariesWithRatingsProjection.java rename to src/main/java/com/petproject/boardgamefun/dto/projection/DiaryWithRatingsProjection.java index 8d4fc1b..6139938 100644 --- a/src/main/java/com/petproject/boardgamefun/dto/projection/DiariesWithRatingsProjection.java +++ b/src/main/java/com/petproject/boardgamefun/dto/projection/DiaryWithRatingsProjection.java @@ -2,7 +2,7 @@ import com.petproject.boardgamefun.model.Diary; -public interface DiariesWithRatingsProjection { +public interface DiaryWithRatingsProjection { Diary getDiary(); Double getRating(); } diff --git a/src/main/java/com/petproject/boardgamefun/repository/DiaryRepository.java b/src/main/java/com/petproject/boardgamefun/repository/DiaryRepository.java index 85edc3b..f9f184c 100644 --- a/src/main/java/com/petproject/boardgamefun/repository/DiaryRepository.java +++ b/src/main/java/com/petproject/boardgamefun/repository/DiaryRepository.java @@ -1,6 +1,6 @@ package com.petproject.boardgamefun.repository; -import com.petproject.boardgamefun.dto.projection.DiariesWithRatingsProjection; +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; @@ -15,12 +15,18 @@ public interface DiaryRepository extends JpaRepository { "join User u on u.id = d.user.id " + "where u.id = :userId " + "group by d") - ListfindUserDiaries(Integer userId); + 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 " + + "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(); + List getAllDiaries(); } \ No newline at end of file From a4b076ac401798b133a11b5591ca5a2bd28840a4 Mon Sep 17 00:00:00 2001 From: "i.i.artamonov" Date: Fri, 24 Dec 2021 10:25:59 +0400 Subject: [PATCH 039/141] Add request for getting forum projection Add request for getting forum by id in ForumController and according method to ForumRepository --- .../boardgamefun/controller/ForumController.java | 9 +++++++++ .../boardgamefun/repository/ForumRepository.java | 6 ++++++ 2 files changed, 15 insertions(+) diff --git a/src/main/java/com/petproject/boardgamefun/controller/ForumController.java b/src/main/java/com/petproject/boardgamefun/controller/ForumController.java index 0d3c102..a1609bc 100644 --- a/src/main/java/com/petproject/boardgamefun/controller/ForumController.java +++ b/src/main/java/com/petproject/boardgamefun/controller/ForumController.java @@ -8,6 +8,7 @@ import com.petproject.boardgamefun.model.ForumMessage; import com.petproject.boardgamefun.model.ForumRating; import com.petproject.boardgamefun.repository.*; +import org.springframework.data.relational.core.sql.In; import org.springframework.http.HttpStatus; import org.springframework.http.ResponseEntity; import org.springframework.web.bind.annotation.*; @@ -50,6 +51,14 @@ public ResponseEntity> getForums(@RequestParam(required = return new ResponseEntity<>(forums, HttpStatus.OK); } + @Transactional + @GetMapping("/{forumId}") + public ResponseEntity getForum(@PathVariable Integer forumId){ + var forum = forumRepository.findForumWithRatingUsingId(forumId); + + return new ResponseEntity<>(forum, HttpStatus.OK); + } + @Transactional @PostMapping("add-forum/{gameId}/{userId}") public ResponseEntity addForum(@PathVariable Integer gameId, @PathVariable Integer userId, @RequestBody ForumRequest forumRequest) { diff --git a/src/main/java/com/petproject/boardgamefun/repository/ForumRepository.java b/src/main/java/com/petproject/boardgamefun/repository/ForumRepository.java index fd4fabd..e6a4ad8 100644 --- a/src/main/java/com/petproject/boardgamefun/repository/ForumRepository.java +++ b/src/main/java/com/petproject/boardgamefun/repository/ForumRepository.java @@ -27,5 +27,11 @@ public interface ForumRepository extends JpaRepository { "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 From 32462ada5a1e062c32a7d86992126ab994aa4d01 Mon Sep 17 00:00:00 2001 From: "i.i.artamonov" Date: Wed, 29 Dec 2021 14:32:54 +0400 Subject: [PATCH 040/141] Change Jwt Response model Due to 406 error in response getter methods added. Added new field type --- .../controller/UserController.java | 2 +- .../security/model/JwtResponse.java | 18 ++++++++++++------ 2 files changed, 13 insertions(+), 7 deletions(-) diff --git a/src/main/java/com/petproject/boardgamefun/controller/UserController.java b/src/main/java/com/petproject/boardgamefun/controller/UserController.java index 005a6a0..6595026 100644 --- a/src/main/java/com/petproject/boardgamefun/controller/UserController.java +++ b/src/main/java/com/petproject/boardgamefun/controller/UserController.java @@ -79,7 +79,7 @@ public ResponseEntity authenticateUser(@RequestBody LoginRequest loginRequest String jwt = jwtUtils.generateJwtToken(authentication); UserDetailsImpl userDetails = (UserDetailsImpl) authentication.getPrincipal(); - return new ResponseEntity<>(new JwtResponse(jwt, userDetails.getUsername(), userDetails.getEmail()), HttpStatus.OK); + return new ResponseEntity<>(new JwtResponse(jwt, userDetails.getId(), userDetails.getUsername(), userDetails.getEmail()), HttpStatus.OK); } @PostMapping("/sign-up") diff --git a/src/main/java/com/petproject/boardgamefun/security/model/JwtResponse.java b/src/main/java/com/petproject/boardgamefun/security/model/JwtResponse.java index 5c7481b..b4fca3f 100644 --- a/src/main/java/com/petproject/boardgamefun/security/model/JwtResponse.java +++ b/src/main/java/com/petproject/boardgamefun/security/model/JwtResponse.java @@ -1,13 +1,19 @@ package com.petproject.boardgamefun.security.model; +import lombok.Data; + +@Data public class JwtResponse { - private final String token; - private final String userName; - private final String email; + private String token; + private final String type = "Bearer"; + private Integer id; + private String userName; + private String email; - public JwtResponse(String token, String userName, String email){ - this.token = token; - this.userName = userName; + public JwtResponse(String jwt, Integer id, String username, String email) { + this.token = jwt; + this.id = id; + this.userName = username; this.email = email; } } From 319b66ba3f32956a2a06338a7901a52c2f832e7d Mon Sep 17 00:00:00 2001 From: "i.i.artamonov" Date: Thu, 30 Dec 2021 14:49:42 +0400 Subject: [PATCH 041/141] Add DiaryDTO and DesignerDTO To eliminate confusion projections change to DTO. Add diaryService --- .../controller/DiaryController.java | 15 ++++++---- .../boardgamefun/dto/DesignerDTO.java | 10 +++++++ .../petproject/boardgamefun/dto/DiaryDTO.java | 14 +++++++++ .../boardgamefun/service/DiaryService.java | 29 +++++++++++++++++++ 4 files changed, 62 insertions(+), 6 deletions(-) create mode 100644 src/main/java/com/petproject/boardgamefun/dto/DesignerDTO.java create mode 100644 src/main/java/com/petproject/boardgamefun/dto/DiaryDTO.java create mode 100644 src/main/java/com/petproject/boardgamefun/service/DiaryService.java diff --git a/src/main/java/com/petproject/boardgamefun/controller/DiaryController.java b/src/main/java/com/petproject/boardgamefun/controller/DiaryController.java index ba4d3ac..a2a2a81 100644 --- a/src/main/java/com/petproject/boardgamefun/controller/DiaryController.java +++ b/src/main/java/com/petproject/boardgamefun/controller/DiaryController.java @@ -1,6 +1,6 @@ package com.petproject.boardgamefun.controller; -import com.petproject.boardgamefun.dto.projection.DiaryWithRatingsProjection; +import com.petproject.boardgamefun.dto.DiaryDTO; import com.petproject.boardgamefun.dto.request.DiaryCommentRequest; import com.petproject.boardgamefun.dto.request.DiaryRatingRequest; import com.petproject.boardgamefun.model.DiaryComment; @@ -9,6 +9,7 @@ import com.petproject.boardgamefun.repository.DiaryRatingRepository; import com.petproject.boardgamefun.repository.DiaryRepository; import com.petproject.boardgamefun.repository.UserRepository; +import com.petproject.boardgamefun.service.DiaryService; import org.springframework.http.HttpStatus; import org.springframework.http.ResponseEntity; import org.springframework.web.bind.annotation.*; @@ -26,26 +27,28 @@ public class DiaryController { final UserRepository userRepository; final DiaryRepository diaryRepository; final DiaryRatingRepository diaryRatingRepository; + final DiaryService diaryService; - public DiaryController(DiaryCommentRepository diaryCommentRepository, UserRepository userRepository, DiaryRepository diaryRepository, DiaryRatingRepository diaryRatingRepository) { + public DiaryController(DiaryCommentRepository diaryCommentRepository, UserRepository userRepository, DiaryRepository diaryRepository, DiaryRatingRepository diaryRatingRepository, DiaryService diaryService) { this.diaryCommentRepository = diaryCommentRepository; this.userRepository = userRepository; this.diaryRepository = diaryRepository; this.diaryRatingRepository = diaryRatingRepository; + this.diaryService = diaryService; } @Transactional @GetMapping("") - public ResponseEntity> getDiaries(){ - var diaries = diaryRepository.getAllDiaries(); + public ResponseEntity> getDiaries(){ + var diaries = diaryService.projectionsToDiaryDTO(diaryRepository.getAllDiaries()); return new ResponseEntity<>(diaries, HttpStatus.OK); } @Transactional @GetMapping("/{diaryId}") - public ResponseEntity getDiary(@PathVariable Integer diaryId){ - var diaryProjection = diaryRepository.findDiaryUsingId(diaryId); + public ResponseEntity getDiary(@PathVariable Integer diaryId){ + var diaryProjection = diaryService.projectionToDiaryDTO(diaryRepository.findDiaryUsingId(diaryId)); return new ResponseEntity<>(diaryProjection, 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..f3f1238 --- /dev/null +++ b/src/main/java/com/petproject/boardgamefun/dto/DesignerDTO.java @@ -0,0 +1,10 @@ +package com.petproject.boardgamefun.dto; + +import lombok.AllArgsConstructor; +import lombok.Data; + +@Data +@AllArgsConstructor +public class DesignerDTO { + private String designer; +} 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..a226919 --- /dev/null +++ b/src/main/java/com/petproject/boardgamefun/dto/DiaryDTO.java @@ -0,0 +1,14 @@ +package com.petproject.boardgamefun.dto; + +import com.petproject.boardgamefun.model.Diary; +import lombok.AllArgsConstructor; +import lombok.Data; +import lombok.NoArgsConstructor; + +@Data +@NoArgsConstructor +@AllArgsConstructor +public class DiaryDTO { + private Diary diary; + private double rating; +} diff --git a/src/main/java/com/petproject/boardgamefun/service/DiaryService.java b/src/main/java/com/petproject/boardgamefun/service/DiaryService.java new file mode 100644 index 0000000..b395b68 --- /dev/null +++ b/src/main/java/com/petproject/boardgamefun/service/DiaryService.java @@ -0,0 +1,29 @@ +package com.petproject.boardgamefun.service; + +import com.petproject.boardgamefun.dto.DiaryDTO; +import com.petproject.boardgamefun.dto.projection.DiaryWithRatingsProjection; +import org.springframework.stereotype.Service; + +import java.util.ArrayList; +import java.util.List; + +@Service +public class DiaryService { + public List projectionsToDiaryDTO(List projections) { + List diaries = new ArrayList<>(); + for (var projection : projections) { + diaries.add(new DiaryDTO(projection.getDiary(), projection.getRating())); + } + + return diaries; + } + + public DiaryDTO projectionToDiaryDTO(DiaryWithRatingsProjection projection) { + DiaryDTO diary = new DiaryDTO(); + diary.setDiary(projection.getDiary()); + diary.setRating(projection.getRating()); + + return diary; + } +} + From c345aca568f3697d39ad314cd53e0b451a63b60d Mon Sep 17 00:00:00 2001 From: "i.i.artamonov" Date: Thu, 30 Dec 2021 15:22:01 +0400 Subject: [PATCH 042/141] Add ForumDTO Added ForumService --- .../controller/ForumController.java | 22 +++++++++------- .../controller/UserController.java | 11 +++++--- .../petproject/boardgamefun/dto/ForumDTO.java | 14 ++++++++++ .../boardgamefun/service/ForumService.java | 26 +++++++++++++++++++ 4 files changed, 59 insertions(+), 14 deletions(-) create mode 100644 src/main/java/com/petproject/boardgamefun/dto/ForumDTO.java create mode 100644 src/main/java/com/petproject/boardgamefun/service/ForumService.java diff --git a/src/main/java/com/petproject/boardgamefun/controller/ForumController.java b/src/main/java/com/petproject/boardgamefun/controller/ForumController.java index a1609bc..f0f0069 100644 --- a/src/main/java/com/petproject/boardgamefun/controller/ForumController.java +++ b/src/main/java/com/petproject/boardgamefun/controller/ForumController.java @@ -1,6 +1,6 @@ package com.petproject.boardgamefun.controller; -import com.petproject.boardgamefun.dto.projection.ForumProjection; +import com.petproject.boardgamefun.dto.ForumDTO; import com.petproject.boardgamefun.dto.request.ForumMessageRequest; import com.petproject.boardgamefun.dto.request.ForumRatingRequest; import com.petproject.boardgamefun.dto.request.ForumRequest; @@ -8,7 +8,7 @@ import com.petproject.boardgamefun.model.ForumMessage; import com.petproject.boardgamefun.model.ForumRating; import com.petproject.boardgamefun.repository.*; -import org.springframework.data.relational.core.sql.In; +import com.petproject.boardgamefun.service.ForumService; import org.springframework.http.HttpStatus; import org.springframework.http.ResponseEntity; import org.springframework.web.bind.annotation.*; @@ -27,25 +27,27 @@ public class ForumController { private final UserRepository userRepository; private final ForumMessageRepository forumMessageRepository; private final ForumRatingRepository forumRatingRepository; + private final ForumService forumService; - public ForumController(ForumRepository forumRepository, GameRepository gameRepository, UserRepository userRepository, ForumMessageRepository forumMessageRepository, ForumRatingRepository forumRatingRepository) { + public ForumController(ForumRepository forumRepository, GameRepository gameRepository, UserRepository userRepository, ForumMessageRepository forumMessageRepository, ForumRatingRepository forumRatingRepository, ForumService forumService) { this.forumRepository = forumRepository; this.gameRepository = gameRepository; this.userRepository = userRepository; this.forumMessageRepository = forumMessageRepository; this.forumRatingRepository = forumRatingRepository; + this.forumService = forumService; } @Transactional @GetMapping("") - public ResponseEntity> getForums(@RequestParam(required = false) Integer gameId, @RequestParam(required = false) Integer userId) { - List forums; + public ResponseEntity> getForums(@RequestParam(required = false) Integer gameId, @RequestParam(required = false) Integer userId) { + List forums; if (gameId != null) { - forums = forumRepository.findForumsGameWithRating(gameId); + forums = forumService.projectionsToForumDTO(forumRepository.findForumsGameWithRating(gameId)); } else if (userId != null) { - forums = forumRepository.findForumsUserWithRating(userId); + forums = forumService.projectionsToForumDTO(forumRepository.findForumsUserWithRating(userId)); } else { - forums = forumRepository.findForumsWithRating(); + forums = forumService.projectionsToForumDTO(forumRepository.findForumsWithRating()); } return new ResponseEntity<>(forums, HttpStatus.OK); @@ -53,8 +55,8 @@ public ResponseEntity> getForums(@RequestParam(required = @Transactional @GetMapping("/{forumId}") - public ResponseEntity getForum(@PathVariable Integer forumId){ - var forum = forumRepository.findForumWithRatingUsingId(forumId); + public ResponseEntity getForum(@PathVariable Integer forumId){ + var forum = forumService.projectionToForumDTO(forumRepository.findForumWithRatingUsingId(forumId)); return new ResponseEntity<>(forum, HttpStatus.OK); } diff --git a/src/main/java/com/petproject/boardgamefun/controller/UserController.java b/src/main/java/com/petproject/boardgamefun/controller/UserController.java index 6595026..c37bb78 100644 --- a/src/main/java/com/petproject/boardgamefun/controller/UserController.java +++ b/src/main/java/com/petproject/boardgamefun/controller/UserController.java @@ -1,6 +1,6 @@ package com.petproject.boardgamefun.controller; -import com.petproject.boardgamefun.dto.projection.DiaryWithRatingsProjection; +import com.petproject.boardgamefun.dto.DiaryDTO; import com.petproject.boardgamefun.dto.projection.GameSellProjection; import com.petproject.boardgamefun.dto.projection.UserGameRatingProjection; import com.petproject.boardgamefun.dto.request.PasswordChangeRequest; @@ -11,6 +11,7 @@ import com.petproject.boardgamefun.security.model.JwtResponse; import com.petproject.boardgamefun.security.model.LoginRequest; import com.petproject.boardgamefun.security.services.UserDetailsImpl; +import com.petproject.boardgamefun.service.DiaryService; import org.springframework.http.HttpStatus; import org.springframework.http.ResponseEntity; import org.springframework.security.authentication.AuthenticationManager; @@ -37,6 +38,7 @@ public class UserController { final UserWishRepository userWishRepository; final GameSellRepository gameSellRepository; final DiaryRepository diaryRepository; + final DiaryService diaryService; final PasswordEncoder passwordEncoder; final JwtUtils jwtUtils; @@ -47,7 +49,7 @@ public UserController(GameRepository gameRepository, UserOwnGameRepository userOwnGameRepository, RatingGameByUserRepository ratingGameByUserRepository, UserWishRepository userWishRepository, - GameSellRepository gameSellRepository, DiaryRepository diaryRepository, PasswordEncoder passwordEncoder, + GameSellRepository gameSellRepository, DiaryRepository diaryRepository, DiaryService diaryService, PasswordEncoder passwordEncoder, JwtUtils jwtUtils, AuthenticationManager authenticationManager) { this.gameRepository = gameRepository; @@ -57,6 +59,7 @@ public UserController(GameRepository gameRepository, this.userWishRepository = userWishRepository; this.gameSellRepository = gameSellRepository; this.diaryRepository = diaryRepository; + this.diaryService = diaryService; this.passwordEncoder = passwordEncoder; this.jwtUtils = jwtUtils; this.authenticationManager = authenticationManager; @@ -342,8 +345,8 @@ public ResponseEntity deleteDiary(@PathVariable Integer userId, @PathVar @Transactional @GetMapping({"{userId}/diary-list"}) - public ResponseEntity> getListDiary(@PathVariable Integer userId){ - var diaries = diaryRepository.findUserDiaries(userId); + public ResponseEntity> getListDiary(@PathVariable Integer userId){ + var diaries = diaryService.projectionsToDiaryDTO(diaryRepository.findUserDiaries(userId)); return new ResponseEntity<>(diaries, HttpStatus.OK); } 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..8819ff7 --- /dev/null +++ b/src/main/java/com/petproject/boardgamefun/dto/ForumDTO.java @@ -0,0 +1,14 @@ +package com.petproject.boardgamefun.dto; + +import com.petproject.boardgamefun.model.Forum; +import lombok.AllArgsConstructor; +import lombok.Data; +import lombok.NoArgsConstructor; + +@Data +@AllArgsConstructor +@NoArgsConstructor +public class ForumDTO { + private Forum forum; + private Double rating; +} 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..1e7fa54 --- /dev/null +++ b/src/main/java/com/petproject/boardgamefun/service/ForumService.java @@ -0,0 +1,26 @@ +package com.petproject.boardgamefun.service; + +import com.petproject.boardgamefun.dto.ForumDTO; +import com.petproject.boardgamefun.dto.projection.ForumProjection; +import org.springframework.stereotype.Service; + +import java.util.ArrayList; +import java.util.List; + +@Service +public class ForumService { + public List projectionsToForumDTO(List projections) { + ArrayList forums = new ArrayList<>(); + for (var projection : projections) { + forums.add(new ForumDTO(projection.getForum(), projection.getRating())); + } + return forums; + } + + public ForumDTO projectionToForumDTO(ForumProjection projection) { + ForumDTO forum = new ForumDTO(); + forum.setForum(projection.getForum()); + forum.setRating(projection.getRating()); + return forum; + } +} From fe3e1fa62b427ceaf8ec7386226015ecdf6d0868 Mon Sep 17 00:00:00 2001 From: "i.i.artamonov" Date: Thu, 30 Dec 2021 15:50:41 +0400 Subject: [PATCH 043/141] Add GameSellDTO To eliminate confusion projections change to DTO. Add GameSellService --- .../controller/UserController.java | 11 +++++--- .../boardgamefun/dto/GameSellDTO.java | 16 ++++++++++++ .../boardgamefun/service/GameSellService.java | 26 +++++++++++++++++++ 3 files changed, 49 insertions(+), 4 deletions(-) create mode 100644 src/main/java/com/petproject/boardgamefun/dto/GameSellDTO.java create mode 100644 src/main/java/com/petproject/boardgamefun/service/GameSellService.java diff --git a/src/main/java/com/petproject/boardgamefun/controller/UserController.java b/src/main/java/com/petproject/boardgamefun/controller/UserController.java index c37bb78..ac4c104 100644 --- a/src/main/java/com/petproject/boardgamefun/controller/UserController.java +++ b/src/main/java/com/petproject/boardgamefun/controller/UserController.java @@ -1,7 +1,7 @@ package com.petproject.boardgamefun.controller; import com.petproject.boardgamefun.dto.DiaryDTO; -import com.petproject.boardgamefun.dto.projection.GameSellProjection; +import com.petproject.boardgamefun.dto.GameSellDTO; import com.petproject.boardgamefun.dto.projection.UserGameRatingProjection; import com.petproject.boardgamefun.dto.request.PasswordChangeRequest; import com.petproject.boardgamefun.dto.request.UserEditRequest; @@ -12,6 +12,7 @@ import com.petproject.boardgamefun.security.model.LoginRequest; import com.petproject.boardgamefun.security.services.UserDetailsImpl; import com.petproject.boardgamefun.service.DiaryService; +import com.petproject.boardgamefun.service.GameSellService; import org.springframework.http.HttpStatus; import org.springframework.http.ResponseEntity; import org.springframework.security.authentication.AuthenticationManager; @@ -39,6 +40,7 @@ public class UserController { final GameSellRepository gameSellRepository; final DiaryRepository diaryRepository; final DiaryService diaryService; + final GameSellService gameSellService; final PasswordEncoder passwordEncoder; final JwtUtils jwtUtils; @@ -49,7 +51,7 @@ public UserController(GameRepository gameRepository, UserOwnGameRepository userOwnGameRepository, RatingGameByUserRepository ratingGameByUserRepository, UserWishRepository userWishRepository, - GameSellRepository gameSellRepository, DiaryRepository diaryRepository, DiaryService diaryService, PasswordEncoder passwordEncoder, + GameSellRepository gameSellRepository, DiaryRepository diaryRepository, DiaryService diaryService, GameSellService gameSellService, PasswordEncoder passwordEncoder, JwtUtils jwtUtils, AuthenticationManager authenticationManager) { this.gameRepository = gameRepository; @@ -60,6 +62,7 @@ public UserController(GameRepository gameRepository, this.gameSellRepository = gameSellRepository; this.diaryRepository = diaryRepository; this.diaryService = diaryService; + this.gameSellService = gameSellService; this.passwordEncoder = passwordEncoder; this.jwtUtils = jwtUtils; this.authenticationManager = authenticationManager; @@ -277,9 +280,9 @@ public ResponseEntity addGameToSellList(@PathVariable Integer userId, @Transactional @GetMapping("{userId}/games-to-sell") - public ResponseEntity> getGameSellList(@PathVariable Integer userId){ + public ResponseEntity> getGameSellList(@PathVariable Integer userId){ - var gameSellList = gameRepository.getGameSellList(userId); + var gameSellList = gameSellService.projectionsToGameSellDTO(gameRepository.getGameSellList(userId)); return new ResponseEntity<>(gameSellList,HttpStatus.OK); } 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..c5f0f14 --- /dev/null +++ b/src/main/java/com/petproject/boardgamefun/dto/GameSellDTO.java @@ -0,0 +1,16 @@ +package com.petproject.boardgamefun.dto; + +import com.petproject.boardgamefun.model.Game; +import lombok.AllArgsConstructor; +import lombok.Data; +import lombok.NoArgsConstructor; + +@Data +@AllArgsConstructor +@NoArgsConstructor +public class GameSellDTO { + private Game game; + private String condition; + private String comment; + private Integer price; +} 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..a442e6b --- /dev/null +++ b/src/main/java/com/petproject/boardgamefun/service/GameSellService.java @@ -0,0 +1,26 @@ +package com.petproject.boardgamefun.service; + +import com.petproject.boardgamefun.dto.GameSellDTO; +import com.petproject.boardgamefun.dto.projection.GameSellProjection; +import org.springframework.stereotype.Service; + +import java.util.ArrayList; +import java.util.List; + +@Service +public class GameSellService { + public List projectionsToGameSellDTO(List projections){ + ArrayList gamesForSell = new ArrayList<>(); + for (var projection : + projections) { + gamesForSell.add(new GameSellDTO(projection.getGame(), + projection.getCondition(), + projection.getComment(), + projection.getPrice() + )); + } + + return gamesForSell; + + } +} From 36fc5bb9f7dcf590c197bf900ce1b9c4ae08e0ca Mon Sep 17 00:00:00 2001 From: "i.i.artamonov" Date: Thu, 30 Dec 2021 16:08:58 +0400 Subject: [PATCH 044/141] Change returned type from projection to DTO in GameController In gameUserratingList change returned type --- .../boardgamefun/controller/UserController.java | 11 +++++++---- .../petproject/boardgamefun/service/GameService.java | 11 +++++++++++ 2 files changed, 18 insertions(+), 4 deletions(-) diff --git a/src/main/java/com/petproject/boardgamefun/controller/UserController.java b/src/main/java/com/petproject/boardgamefun/controller/UserController.java index ac4c104..198cb51 100644 --- a/src/main/java/com/petproject/boardgamefun/controller/UserController.java +++ b/src/main/java/com/petproject/boardgamefun/controller/UserController.java @@ -1,8 +1,8 @@ package com.petproject.boardgamefun.controller; import com.petproject.boardgamefun.dto.DiaryDTO; +import com.petproject.boardgamefun.dto.GameDTO; import com.petproject.boardgamefun.dto.GameSellDTO; -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.model.*; @@ -13,6 +13,7 @@ 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 org.springframework.http.HttpStatus; import org.springframework.http.ResponseEntity; import org.springframework.security.authentication.AuthenticationManager; @@ -41,6 +42,7 @@ public class UserController { final DiaryRepository diaryRepository; final DiaryService diaryService; final GameSellService gameSellService; + final GameService gameService; final PasswordEncoder passwordEncoder; final JwtUtils jwtUtils; @@ -51,7 +53,7 @@ public UserController(GameRepository gameRepository, UserOwnGameRepository userOwnGameRepository, RatingGameByUserRepository ratingGameByUserRepository, UserWishRepository userWishRepository, - GameSellRepository gameSellRepository, DiaryRepository diaryRepository, DiaryService diaryService, GameSellService gameSellService, PasswordEncoder passwordEncoder, + GameSellRepository gameSellRepository, DiaryRepository diaryRepository, DiaryService diaryService, GameSellService gameSellService, GameService gameService, PasswordEncoder passwordEncoder, JwtUtils jwtUtils, AuthenticationManager authenticationManager) { this.gameRepository = gameRepository; @@ -63,6 +65,7 @@ public UserController(GameRepository gameRepository, this.diaryRepository = diaryRepository; this.diaryService = diaryService; this.gameSellService = gameSellService; + this.gameService = gameService; this.passwordEncoder = passwordEncoder; this.jwtUtils = jwtUtils; this.authenticationManager = authenticationManager; @@ -186,9 +189,9 @@ public ResponseEntity deleteGameFromUserCollection(@PathVariable Intege } @GetMapping("/{userId}/games-rating") - public ResponseEntity> getUserRatingList(@PathVariable Integer userId) { + public ResponseEntity> getUserRatingList(@PathVariable Integer userId) { - var ratingGamesByUser = gameRepository.findUserGameRatingList(userId); + var ratingGamesByUser = gameService.userGameRatingToGameDTO(gameRepository.findUserGameRatingList(userId)); return new ResponseEntity<>(ratingGamesByUser, HttpStatus.OK); } diff --git a/src/main/java/com/petproject/boardgamefun/service/GameService.java b/src/main/java/com/petproject/boardgamefun/service/GameService.java index 70ae655..bddd837 100644 --- a/src/main/java/com/petproject/boardgamefun/service/GameService.java +++ b/src/main/java/com/petproject/boardgamefun/service/GameService.java @@ -4,8 +4,10 @@ import com.petproject.boardgamefun.dto.GameDTO; import com.petproject.boardgamefun.dto.projection.GamesFilterByTitleProjection; import com.petproject.boardgamefun.dto.projection.GameProjection; +import com.petproject.boardgamefun.dto.projection.UserGameRatingProjection; import org.springframework.stereotype.Service; +import java.util.ArrayList; import java.util.List; import java.util.stream.Collectors; @@ -20,4 +22,13 @@ public GameDTO projectionsToGameDTO(GameProjection gameProjection, List getTitlesFromProjections(List games){ return games.stream().map(GamesFilterByTitleProjection::getTitle).collect(Collectors.toList()); } + + public List userGameRatingToGameDTO(List projections){ + ArrayList games = new ArrayList<>(); + for (var projection : + projections) { + games.add(new GameDTO(projection.getGame(), (double)projection.getRating(), null)); + } + return games; + } } From 121fa85ca9cf2f1a9f0030a5740cde105ef95620 Mon Sep 17 00:00:00 2001 From: "i.i.artamonov" Date: Thu, 30 Dec 2021 16:16:09 +0400 Subject: [PATCH 045/141] Add UsersGameRatingDTO Change returning type in getUsersRating in GameController --- .../controller/GameController.java | 12 +++++----- .../boardgamefun/dto/UsersGameRatingDTO.java | 14 +++++++++++ .../boardgamefun/service/GameService.java | 23 ++++++++++++------- 3 files changed, 35 insertions(+), 14 deletions(-) create mode 100644 src/main/java/com/petproject/boardgamefun/dto/UsersGameRatingDTO.java diff --git a/src/main/java/com/petproject/boardgamefun/controller/GameController.java b/src/main/java/com/petproject/boardgamefun/controller/GameController.java index 9698bdc..0a54f16 100644 --- a/src/main/java/com/petproject/boardgamefun/controller/GameController.java +++ b/src/main/java/com/petproject/boardgamefun/controller/GameController.java @@ -1,8 +1,8 @@ package com.petproject.boardgamefun.controller; import com.petproject.boardgamefun.dto.GameDTO; +import com.petproject.boardgamefun.dto.UsersGameRatingDTO; import com.petproject.boardgamefun.dto.projection.GameProjection; -import com.petproject.boardgamefun.dto.projection.UsersGameRatingProjection; import com.petproject.boardgamefun.model.Expansion; import com.petproject.boardgamefun.model.Game; import com.petproject.boardgamefun.model.GameByDesigner; @@ -56,7 +56,7 @@ public ResponseEntity getGameByCriteria(@PathVariable Integer id) { @Transactional @GetMapping("/get-games-by-filter/{title}") - public ResponseEntity> getGamesByTitle(@PathVariable String title){ + public ResponseEntity> getGamesByTitle(@PathVariable String title) { var games = gameService.getTitlesFromProjections(gameRepository.findGamesUsingTitle(title)); return new ResponseEntity<>(games, HttpStatus.OK); } @@ -158,9 +158,9 @@ public ResponseEntity> deleteSameGame(@PathVariable Integer reference @Transactional @GetMapping("/{gameId}/users-rating") - public ResponseEntity> getUsersRating(@PathVariable Integer gameId) { + public ResponseEntity> getUsersRating(@PathVariable Integer gameId) { - var ratings = userRepository.findGameRatings(gameId); + var ratings = gameService.usersGameRatingToDTO(userRepository.findGameRatings(gameId)); return new ResponseEntity<>(ratings, HttpStatus.OK); } @@ -176,7 +176,7 @@ public ResponseEntity> getGamesWithRating() { @Transactional @PostMapping("/{gameId}/set-designer/{designerId}") - public ResponseEntity addDesignerToGame(@PathVariable Integer gameId, @PathVariable Integer designerId){ + public ResponseEntity addDesignerToGame(@PathVariable Integer gameId, @PathVariable Integer designerId) { var game = gameRepository.findGameById(gameId); var designer = designerRepository.findDesignerById(designerId); @@ -194,7 +194,7 @@ public ResponseEntity addDesignerToGame(@PathVariable Integer gameId, @ @Transactional @DeleteMapping("{gameId}/remove-designer/{gameByDesignerId}") - public ResponseEntity deleteDesignerFromGame(@PathVariable Integer gameId, @PathVariable Integer gameByDesignerId){ + public ResponseEntity deleteDesignerFromGame(@PathVariable Integer gameId, @PathVariable Integer gameByDesignerId) { gameByDesignerRepository.deleteById(gameByDesignerId); diff --git a/src/main/java/com/petproject/boardgamefun/dto/UsersGameRatingDTO.java b/src/main/java/com/petproject/boardgamefun/dto/UsersGameRatingDTO.java new file mode 100644 index 0000000..f4cce84 --- /dev/null +++ b/src/main/java/com/petproject/boardgamefun/dto/UsersGameRatingDTO.java @@ -0,0 +1,14 @@ +package com.petproject.boardgamefun.dto; + +import com.petproject.boardgamefun.model.User; +import lombok.AllArgsConstructor; +import lombok.Data; +import lombok.NoArgsConstructor; + +@Data +@AllArgsConstructor +@NoArgsConstructor +public class UsersGameRatingDTO { + private User user; + private Double rating; +} diff --git a/src/main/java/com/petproject/boardgamefun/service/GameService.java b/src/main/java/com/petproject/boardgamefun/service/GameService.java index bddd837..49e934b 100644 --- a/src/main/java/com/petproject/boardgamefun/service/GameService.java +++ b/src/main/java/com/petproject/boardgamefun/service/GameService.java @@ -1,10 +1,8 @@ package com.petproject.boardgamefun.service; -import com.petproject.boardgamefun.dto.projection.DesignersProjection; +import com.petproject.boardgamefun.dto.UsersGameRatingDTO; +import com.petproject.boardgamefun.dto.projection.*; import com.petproject.boardgamefun.dto.GameDTO; -import com.petproject.boardgamefun.dto.projection.GamesFilterByTitleProjection; -import com.petproject.boardgamefun.dto.projection.GameProjection; -import com.petproject.boardgamefun.dto.projection.UserGameRatingProjection; import org.springframework.stereotype.Service; import java.util.ArrayList; @@ -13,22 +11,31 @@ @Service public class GameService { - public GameDTO projectionsToGameDTO(GameProjection gameProjection, List designersProjection){ + public GameDTO projectionsToGameDTO(GameProjection gameProjection, List designersProjection) { return new GameDTO(gameProjection.getGame(), gameProjection.getRating(), designersProjection.stream().map(DesignersProjection::getDesigner).collect(Collectors.toList())); } - public List getTitlesFromProjections(List games){ + public List getTitlesFromProjections(List games) { return games.stream().map(GamesFilterByTitleProjection::getTitle).collect(Collectors.toList()); } - public List userGameRatingToGameDTO(List projections){ + public List userGameRatingToGameDTO(List projections) { ArrayList games = new ArrayList<>(); for (var projection : projections) { - games.add(new GameDTO(projection.getGame(), (double)projection.getRating(), null)); + games.add(new GameDTO(projection.getGame(), (double) projection.getRating(), null)); } return games; } + + public List usersGameRatingToDTO(List projections) { + ArrayList users = new ArrayList<>(); + for (var projection : + projections) { + users.add(new UsersGameRatingDTO(projection.getUser(), projection.getRating())); + } + return users; + } } From 3787d91dd426a4addaa173cfda22f0576aef86ee Mon Sep 17 00:00:00 2001 From: "i.i.artamonov" Date: Mon, 10 Jan 2022 10:04:19 +0400 Subject: [PATCH 046/141] Change the DesignerDTO Add Id to DTO. Adding designerService. Change returning type of methods in DesignerController --- .../controller/DesignerController.java | 28 +++++++++++-------- .../boardgamefun/dto/DesignerDTO.java | 1 + .../boardgamefun/service/DesignerService.java | 26 +++++++++++++++++ 3 files changed, 43 insertions(+), 12 deletions(-) create mode 100644 src/main/java/com/petproject/boardgamefun/service/DesignerService.java diff --git a/src/main/java/com/petproject/boardgamefun/controller/DesignerController.java b/src/main/java/com/petproject/boardgamefun/controller/DesignerController.java index 26b0c18..8ad26bd 100644 --- a/src/main/java/com/petproject/boardgamefun/controller/DesignerController.java +++ b/src/main/java/com/petproject/boardgamefun/controller/DesignerController.java @@ -1,8 +1,10 @@ package com.petproject.boardgamefun.controller; +import com.petproject.boardgamefun.dto.DesignerDTO; 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.web.bind.annotation.*; @@ -15,61 +17,63 @@ public class DesignerController { private final DesignerRepository designerRepository; + private final DesignerService designerService; - public DesignerController(DesignerRepository designerRepository) { + public DesignerController(DesignerRepository designerRepository, DesignerService designerService) { this.designerRepository = designerRepository; + this.designerService = designerService; } @Transactional @GetMapping("") - public ResponseEntity> getDesigners(){ - var designers = designerRepository.findAll(); + 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 designers = designerRepository.findDesignerByName(name); + public ResponseEntity getDesignerByName(@PathVariable String name){ + var designer = designerService.entityToDesignerDTO(designerRepository.findDesignerByName(name)); - return new ResponseEntity<>(designers, HttpStatus.OK); + return new ResponseEntity<>(designer, HttpStatus.OK); } @Transactional @PostMapping("/add") - public ResponseEntity> addDesigner(@RequestBody DesignerRequest designerRequest){ + public ResponseEntity> addDesigner(@RequestBody DesignerRequest designerRequest){ var designer = new Designer(); designer.setName(designerRequest.getName()); designerRepository.save(designer); - var designers = designerRepository.findAll(); + var designers = designerService.entitiesToDesignerDTO(designerRepository.findAll()); return new ResponseEntity<>(designers, HttpStatus.OK); } @Transactional @PatchMapping("/update/{id}") - public ResponseEntity> updateDesigner(@PathVariable Integer id, @RequestBody DesignerRequest designerRequest){ + public ResponseEntity> updateDesigner(@PathVariable Integer id, @RequestBody DesignerRequest designerRequest){ var designer = designerRepository.findDesignerById(id); designer.setName(designerRequest.getName()); designerRepository.save(designer); - var designers = designerRepository.findAll(); + var designers = designerService.entitiesToDesignerDTO(designerRepository.findAll()); return new ResponseEntity<>(designers, HttpStatus.OK); } @Transactional @DeleteMapping("/delete/{id}") - public ResponseEntity> deleteDesigner(@PathVariable Integer id){ + public ResponseEntity> deleteDesigner(@PathVariable Integer id){ var designer = designerRepository.findDesignerById(id); designerRepository.delete(designer); - var designers = designerRepository.findAll(); + var designers = designerService.entitiesToDesignerDTO(designerRepository.findAll()); return new ResponseEntity<>(designers, HttpStatus.OK); } diff --git a/src/main/java/com/petproject/boardgamefun/dto/DesignerDTO.java b/src/main/java/com/petproject/boardgamefun/dto/DesignerDTO.java index f3f1238..00f9f63 100644 --- a/src/main/java/com/petproject/boardgamefun/dto/DesignerDTO.java +++ b/src/main/java/com/petproject/boardgamefun/dto/DesignerDTO.java @@ -6,5 +6,6 @@ @Data @AllArgsConstructor public class DesignerDTO { + private Integer id; private String designer; } 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..e14cf62 --- /dev/null +++ b/src/main/java/com/petproject/boardgamefun/service/DesignerService.java @@ -0,0 +1,26 @@ +package com.petproject.boardgamefun.service; + +import com.petproject.boardgamefun.dto.DesignerDTO; +import com.petproject.boardgamefun.model.Designer; +import org.springframework.stereotype.Service; + +import java.util.ArrayList; +import java.util.List; + +@Service +public class DesignerService { + + 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()); + } +} From 5b684d6fdcf21876a6f17c94fe04d8f61bae08fb Mon Sep 17 00:00:00 2001 From: "i.i.artamonov" Date: Mon, 10 Jan 2022 10:39:25 +0400 Subject: [PATCH 047/141] Add User Service and User DTO Change returning type of methods in User Controller. Add user DTO. --- .../controller/UserController.java | 14 +++++++---- .../petproject/boardgamefun/dto/UserDTO.java | 11 +++++++++ .../boardgamefun/service/UserService.java | 24 +++++++++++++++++++ 3 files changed, 44 insertions(+), 5 deletions(-) create mode 100644 src/main/java/com/petproject/boardgamefun/dto/UserDTO.java create mode 100644 src/main/java/com/petproject/boardgamefun/service/UserService.java diff --git a/src/main/java/com/petproject/boardgamefun/controller/UserController.java b/src/main/java/com/petproject/boardgamefun/controller/UserController.java index 198cb51..8e65876 100644 --- a/src/main/java/com/petproject/boardgamefun/controller/UserController.java +++ b/src/main/java/com/petproject/boardgamefun/controller/UserController.java @@ -3,6 +3,7 @@ import com.petproject.boardgamefun.dto.DiaryDTO; import com.petproject.boardgamefun.dto.GameDTO; import com.petproject.boardgamefun.dto.GameSellDTO; +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.*; @@ -14,6 +15,7 @@ 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 org.springframework.http.HttpStatus; import org.springframework.http.ResponseEntity; import org.springframework.security.authentication.AuthenticationManager; @@ -43,6 +45,7 @@ public class UserController { final DiaryService diaryService; final GameSellService gameSellService; final GameService gameService; + final UserService userService; final PasswordEncoder passwordEncoder; final JwtUtils jwtUtils; @@ -53,7 +56,7 @@ public UserController(GameRepository gameRepository, UserOwnGameRepository userOwnGameRepository, RatingGameByUserRepository ratingGameByUserRepository, UserWishRepository userWishRepository, - GameSellRepository gameSellRepository, DiaryRepository diaryRepository, DiaryService diaryService, GameSellService gameSellService, GameService gameService, PasswordEncoder passwordEncoder, + GameSellRepository gameSellRepository, DiaryRepository diaryRepository, DiaryService diaryService, GameSellService gameSellService, GameService gameService, UserService userService, PasswordEncoder passwordEncoder, JwtUtils jwtUtils, AuthenticationManager authenticationManager) { this.gameRepository = gameRepository; @@ -66,14 +69,15 @@ public UserController(GameRepository gameRepository, this.diaryService = diaryService; this.gameSellService = gameSellService; this.gameService = gameService; + this.userService = userService; this.passwordEncoder = passwordEncoder; this.jwtUtils = jwtUtils; this.authenticationManager = authenticationManager; } @GetMapping() - public ResponseEntity> getUsers() { - var users = userRepository.findAll(); + public ResponseEntity> getUsers() { + var users = userService.entitiesToUserDTO(userRepository.findAll()); return new ResponseEntity<>(users, HttpStatus.OK); } @@ -148,8 +152,8 @@ public ResponseEntity changePassword(@PathVariable Integer userId, @RequestBo @Transactional @GetMapping("{id}") - public ResponseEntity getUser(@PathVariable Integer id) { - var user = userRepository.findUserById(id); + public ResponseEntity getUser(@PathVariable Integer id) { + var user = userService.entityToUserDTO(userRepository.findUserById(id)); return new ResponseEntity<>(user, HttpStatus.OK); } 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..1471958 --- /dev/null +++ b/src/main/java/com/petproject/boardgamefun/dto/UserDTO.java @@ -0,0 +1,11 @@ +package com.petproject.boardgamefun.dto; + +import com.petproject.boardgamefun.model.User; +import lombok.AllArgsConstructor; +import lombok.Data; + +@Data +@AllArgsConstructor +public class UserDTO { + private User user; +} 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..30e978b --- /dev/null +++ b/src/main/java/com/petproject/boardgamefun/service/UserService.java @@ -0,0 +1,24 @@ +package com.petproject.boardgamefun.service; + +import com.petproject.boardgamefun.dto.UserDTO; +import com.petproject.boardgamefun.model.User; +import org.springframework.stereotype.Service; + +import java.util.ArrayList; +import java.util.List; + +@Service +public class UserService { + public List entitiesToUserDTO(List users){ + List usersDTO = new ArrayList<>(); + for (var user : + users) { + usersDTO.add(new UserDTO(user)); + } + return usersDTO; + } + + public UserDTO entityToUserDTO(User user){ + return new UserDTO(user); + } +} From 5610a011eab220687ad5a416eabea7259c3c94bf Mon Sep 17 00:00:00 2001 From: "i.i.artamonov" Date: Mon, 10 Jan 2022 13:45:51 +0400 Subject: [PATCH 048/141] Add entities to GameDTO in GameService change returning type of getUserWishlist to GameDTO --- .../boardgamefun/controller/UserController.java | 4 ++-- .../petproject/boardgamefun/service/GameService.java | 10 ++++++++++ 2 files changed, 12 insertions(+), 2 deletions(-) diff --git a/src/main/java/com/petproject/boardgamefun/controller/UserController.java b/src/main/java/com/petproject/boardgamefun/controller/UserController.java index 8e65876..d707c05 100644 --- a/src/main/java/com/petproject/boardgamefun/controller/UserController.java +++ b/src/main/java/com/petproject/boardgamefun/controller/UserController.java @@ -235,8 +235,8 @@ public ResponseEntity setGameRating(@PathVariable Integer userId, @Path } @GetMapping("/{id}/wishlist") - public ResponseEntity> getUserWishlist(@PathVariable Integer id) { - var games = gameRepository.findUserWishlist(id); + public ResponseEntity> getUserWishlist(@PathVariable Integer id) { + var games = gameService.entitiesToGameDTO(gameRepository.findUserWishlist(id)); return new ResponseEntity<>(games, HttpStatus.OK); } diff --git a/src/main/java/com/petproject/boardgamefun/service/GameService.java b/src/main/java/com/petproject/boardgamefun/service/GameService.java index 49e934b..218905f 100644 --- a/src/main/java/com/petproject/boardgamefun/service/GameService.java +++ b/src/main/java/com/petproject/boardgamefun/service/GameService.java @@ -3,6 +3,7 @@ import com.petproject.boardgamefun.dto.UsersGameRatingDTO; import com.petproject.boardgamefun.dto.projection.*; import com.petproject.boardgamefun.dto.GameDTO; +import com.petproject.boardgamefun.model.Game; import org.springframework.stereotype.Service; import java.util.ArrayList; @@ -17,6 +18,15 @@ public GameDTO projectionsToGameDTO(GameProjection gameProjection, List entitiesToGameDTO(List games) { + ArrayList gamesDTO = new ArrayList<>(); + for (var game : + games) { + gamesDTO.add(new GameDTO(game, null, null)); + } + return gamesDTO; + } + public List getTitlesFromProjections(List games) { return games.stream().map(GamesFilterByTitleProjection::getTitle).collect(Collectors.toList()); } From 7e4caf0ef4b3cc2b454328d28cf3e1d0ab10c82a Mon Sep 17 00:00:00 2001 From: "i.i.artamonov" Date: Mon, 10 Jan 2022 13:54:57 +0400 Subject: [PATCH 049/141] Change returning type of method addGameToSellList in UserController Add entityToGameSellDTO to GameSellService --- .../petproject/boardgamefun/controller/UserController.java | 5 +++-- .../petproject/boardgamefun/service/GameSellService.java | 6 ++++++ 2 files changed, 9 insertions(+), 2 deletions(-) diff --git a/src/main/java/com/petproject/boardgamefun/controller/UserController.java b/src/main/java/com/petproject/boardgamefun/controller/UserController.java index d707c05..8bbc38a 100644 --- a/src/main/java/com/petproject/boardgamefun/controller/UserController.java +++ b/src/main/java/com/petproject/boardgamefun/controller/UserController.java @@ -272,7 +272,7 @@ public ResponseEntity deleteGameFromUserWishlist(@PathVariable Integer userId @Transactional @PostMapping("{userId}/add-game-to-sell/{gameId}") - public ResponseEntity addGameToSellList(@PathVariable Integer userId, @PathVariable Integer gameId, @RequestBody GameSell gameSell){ + public ResponseEntity> addGameToSellList(@PathVariable Integer userId, @PathVariable Integer gameId, @RequestBody GameSell gameSell){ var user = userRepository.findUserById(userId); var game = gameRepository.findGameById(gameId); @@ -281,8 +281,9 @@ public ResponseEntity addGameToSellList(@PathVariable Integer userId, gameSell.setUser(user); gameSellRepository.save(gameSell); + var gameSellList = gameSellService.projectionsToGameSellDTO(gameRepository.getGameSellList(userId)); - return new ResponseEntity<>(gameSell, HttpStatus.OK); + return new ResponseEntity<>(gameSellList, HttpStatus.OK); } @Transactional diff --git a/src/main/java/com/petproject/boardgamefun/service/GameSellService.java b/src/main/java/com/petproject/boardgamefun/service/GameSellService.java index a442e6b..30febbc 100644 --- a/src/main/java/com/petproject/boardgamefun/service/GameSellService.java +++ b/src/main/java/com/petproject/boardgamefun/service/GameSellService.java @@ -2,6 +2,7 @@ import com.petproject.boardgamefun.dto.GameSellDTO; import com.petproject.boardgamefun.dto.projection.GameSellProjection; +import com.petproject.boardgamefun.model.Game; import org.springframework.stereotype.Service; import java.util.ArrayList; @@ -9,6 +10,11 @@ @Service public class GameSellService { + + public GameSellDTO entityToGameSellDTO(Game game){ + return new GameSellDTO(game, null, null, null); + } + public List projectionsToGameSellDTO(List projections){ ArrayList gamesForSell = new ArrayList<>(); for (var projection : From ae99f2ccbe79a567e6e641490205db96904b78d3 Mon Sep 17 00:00:00 2001 From: "i.i.artamonov" Date: Mon, 10 Jan 2022 14:21:31 +0400 Subject: [PATCH 050/141] Change returning type of diary methods in UserController Change addDiary and updateDiary returning type. Add entityToDiaryDTO method in DiaryService --- .../boardgamefun/controller/UserController.java | 12 ++++++++---- .../boardgamefun/service/DiaryService.java | 5 +++++ 2 files changed, 13 insertions(+), 4 deletions(-) diff --git a/src/main/java/com/petproject/boardgamefun/controller/UserController.java b/src/main/java/com/petproject/boardgamefun/controller/UserController.java index 8bbc38a..7b79121 100644 --- a/src/main/java/com/petproject/boardgamefun/controller/UserController.java +++ b/src/main/java/com/petproject/boardgamefun/controller/UserController.java @@ -327,7 +327,7 @@ public ResponseEntity updateSellGame(@RequestBody GameSell gameSell){ @Transactional @PostMapping("{userId}/add-diary") - public ResponseEntity addDiary(@PathVariable Integer userId, @RequestBody Diary diary){ + public ResponseEntity addDiary(@PathVariable Integer userId, @RequestBody Diary diary){ var user = userRepository.findUserById(userId); diary.setUser(user); @@ -340,7 +340,9 @@ public ResponseEntity addDiary(@PathVariable Integer userId, @RequestBody diaryRepository.save(diary); - return new ResponseEntity<>(diary, HttpStatus.OK); + var diaryDTO = diaryService.entityToDiaryDTO(diary); + + return new ResponseEntity<>(diaryDTO, HttpStatus.OK); } @Transactional @@ -364,7 +366,7 @@ public ResponseEntity> getListDiary(@PathVariable Integer userId) @Transactional @PutMapping({"{userId}/update-diary/{diaryId}"}) - public ResponseEntity updateDiary(@PathVariable Integer diaryId, @PathVariable Integer userId, @RequestBody Diary diaryRequest){ + public ResponseEntity updateDiary(@PathVariable Integer diaryId, @PathVariable Integer userId, @RequestBody Diary diaryRequest){ var diary = diaryRepository.findDiary_ByUserIdAndId(userId, diaryId); if (diaryRequest.getTitle() != null && !Objects.equals(diary.getTitle(), diaryRequest.getTitle())){ @@ -376,7 +378,9 @@ public ResponseEntity updateDiary(@PathVariable Integer diaryId, @PathVar diaryRepository.save(diary); - return new ResponseEntity<>(diary, HttpStatus.OK); + var diaryDTO = diaryService.entityToDiaryDTO(diary); + + return new ResponseEntity<>(diaryDTO, HttpStatus.OK); } //todo: optimize response - not whole model, only needed fields diff --git a/src/main/java/com/petproject/boardgamefun/service/DiaryService.java b/src/main/java/com/petproject/boardgamefun/service/DiaryService.java index b395b68..920d374 100644 --- a/src/main/java/com/petproject/boardgamefun/service/DiaryService.java +++ b/src/main/java/com/petproject/boardgamefun/service/DiaryService.java @@ -2,6 +2,7 @@ import com.petproject.boardgamefun.dto.DiaryDTO; import com.petproject.boardgamefun.dto.projection.DiaryWithRatingsProjection; +import com.petproject.boardgamefun.model.Diary; import org.springframework.stereotype.Service; import java.util.ArrayList; @@ -18,6 +19,10 @@ public List projectionsToDiaryDTO(List pro return diaries; } + public DiaryDTO entityToDiaryDTO(Diary diary){ + return new DiaryDTO(diary, 0); + } + public DiaryDTO projectionToDiaryDTO(DiaryWithRatingsProjection projection) { DiaryDTO diary = new DiaryDTO(); diary.setDiary(projection.getDiary()); From fd54caa31e321bebbca07b363ed7157e25b57589 Mon Sep 17 00:00:00 2001 From: "i.i.artamonov" Date: Mon, 10 Jan 2022 14:41:44 +0400 Subject: [PATCH 051/141] Add DiaryCommentService and DiaryCommentDTO Change returning type of methods in DiaryController --- .../controller/DiaryController.java | 22 +++++++++------- .../boardgamefun/dto/DiaryCommentDTO.java | 14 +++++++++++ .../service/DiaryCommentService.java | 25 +++++++++++++++++++ 3 files changed, 52 insertions(+), 9 deletions(-) create mode 100644 src/main/java/com/petproject/boardgamefun/dto/DiaryCommentDTO.java create mode 100644 src/main/java/com/petproject/boardgamefun/service/DiaryCommentService.java diff --git a/src/main/java/com/petproject/boardgamefun/controller/DiaryController.java b/src/main/java/com/petproject/boardgamefun/controller/DiaryController.java index a2a2a81..e55b92e 100644 --- a/src/main/java/com/petproject/boardgamefun/controller/DiaryController.java +++ b/src/main/java/com/petproject/boardgamefun/controller/DiaryController.java @@ -1,5 +1,6 @@ package com.petproject.boardgamefun.controller; +import com.petproject.boardgamefun.dto.DiaryCommentDTO; import com.petproject.boardgamefun.dto.DiaryDTO; import com.petproject.boardgamefun.dto.request.DiaryCommentRequest; import com.petproject.boardgamefun.dto.request.DiaryRatingRequest; @@ -9,6 +10,7 @@ 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.DiaryService; import org.springframework.http.HttpStatus; import org.springframework.http.ResponseEntity; @@ -28,13 +30,15 @@ public class DiaryController { final DiaryRepository diaryRepository; final DiaryRatingRepository diaryRatingRepository; final DiaryService diaryService; + final DiaryCommentService diaryCommentService; - public DiaryController(DiaryCommentRepository diaryCommentRepository, UserRepository userRepository, DiaryRepository diaryRepository, DiaryRatingRepository diaryRatingRepository, DiaryService diaryService) { + public DiaryController(DiaryCommentRepository diaryCommentRepository, UserRepository userRepository, DiaryRepository diaryRepository, DiaryRatingRepository diaryRatingRepository, DiaryService diaryService, DiaryCommentService diaryCommentService) { this.diaryCommentRepository = diaryCommentRepository; this.userRepository = userRepository; this.diaryRepository = diaryRepository; this.diaryRatingRepository = diaryRatingRepository; this.diaryService = diaryService; + this.diaryCommentService = diaryCommentService; } @Transactional @@ -56,15 +60,15 @@ public ResponseEntity getDiary(@PathVariable Integer diaryId){ @Transactional @GetMapping("/{diaryId}/comments") - public ResponseEntity> getDiaryComments(@PathVariable Integer diaryId){ - var diaryComments = diaryCommentRepository.findDiaryComment_ByDiaryId(diaryId); + 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}") - public ResponseEntity> addComment(@PathVariable Integer diaryId, @PathVariable Integer userId, @RequestBody DiaryCommentRequest diaryCommentRequest){ + public ResponseEntity> addComment(@PathVariable Integer diaryId, @PathVariable Integer userId, @RequestBody DiaryCommentRequest diaryCommentRequest){ var user = userRepository.findUserById(userId); var diary = diaryRepository.findDiaryById(diaryId); @@ -76,32 +80,32 @@ public ResponseEntity> addComment(@PathVariable Integer diary diaryComment.setComment(diaryCommentRequest.getComment()); diaryCommentRepository.save(diaryComment); - var diaryComments = diaryCommentRepository.findDiaryComment_ByDiaryId(diaryId); + var diaryComments = diaryCommentService.entitiesToCommentDTO(diaryCommentRepository.findDiaryComment_ByDiaryId(diaryId)); return new ResponseEntity<>(diaryComments, HttpStatus.OK); } @Transactional @PatchMapping(value = "{diaryId}/update-comment/{diaryCommentId}") - public ResponseEntity> updateComment(@PathVariable Integer diaryId, @PathVariable Integer diaryCommentId, @RequestBody DiaryCommentRequest diaryCommentRequest){ + 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 = diaryCommentRepository.findDiaryComment_ByDiaryId(diaryId); + var diaryComments = diaryCommentService.entitiesToCommentDTO(diaryCommentRepository.findDiaryComment_ByDiaryId(diaryId)); return new ResponseEntity<>(diaryComments, HttpStatus.OK); } @Transactional @DeleteMapping("{diaryId}/delete-comment/{diaryCommentId}") - public ResponseEntity> deleteComment(@PathVariable Integer diaryId, @PathVariable Integer diaryCommentId){ + public ResponseEntity> deleteComment(@PathVariable Integer diaryId, @PathVariable Integer diaryCommentId){ var diaryComment = diaryCommentRepository.findDiaryCommentById(diaryCommentId); diaryCommentRepository.delete(diaryComment); - var diaryComments = diaryCommentRepository.findDiaryComment_ByDiaryId(diaryId); + var diaryComments = diaryCommentService.entitiesToCommentDTO(diaryCommentRepository.findDiaryComment_ByDiaryId(diaryId)); return new ResponseEntity<>(diaryComments, HttpStatus.OK); } 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..55d23f2 --- /dev/null +++ b/src/main/java/com/petproject/boardgamefun/dto/DiaryCommentDTO.java @@ -0,0 +1,14 @@ +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; +} 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..94b4354 --- /dev/null +++ b/src/main/java/com/petproject/boardgamefun/service/DiaryCommentService.java @@ -0,0 +1,25 @@ +package com.petproject.boardgamefun.service; + +import com.petproject.boardgamefun.dto.DiaryCommentDTO; +import com.petproject.boardgamefun.model.DiaryComment; +import org.springframework.stereotype.Service; + +import java.util.ArrayList; +import java.util.List; + +@Service +public class DiaryCommentService { + + public DiaryCommentDTO entityToDiaryCommentDTO(DiaryComment diaryComment) { + return new DiaryCommentDTO(diaryComment.getId(), diaryComment.getComment(), diaryComment.getCommentTime()); + } + + public List entitiesToCommentDTO(List diaryComments){ + ArrayList diaryCommentsDTO = new ArrayList<>(); + for (var diaryComment : + diaryComments) { + diaryCommentsDTO.add(new DiaryCommentDTO(diaryComment.getId(), diaryComment.getComment(), diaryComment.getCommentTime())); + } + return diaryCommentsDTO; + } +} From c519c55150aa836993557079b871b5f675f795b8 Mon Sep 17 00:00:00 2001 From: "i.i.artamonov" Date: Mon, 10 Jan 2022 15:02:04 +0400 Subject: [PATCH 052/141] Add DiaryRatingDTO and DiaryRatingService Change returning type of methods in DiaryController --- .../controller/DiaryController.java | 33 +++++++++++-------- .../boardgamefun/dto/DiaryRatingDTO.java | 11 +++++++ .../service/DiaryRatingService.java | 24 ++++++++++++++ 3 files changed, 55 insertions(+), 13 deletions(-) create mode 100644 src/main/java/com/petproject/boardgamefun/dto/DiaryRatingDTO.java create mode 100644 src/main/java/com/petproject/boardgamefun/service/DiaryRatingService.java diff --git a/src/main/java/com/petproject/boardgamefun/controller/DiaryController.java b/src/main/java/com/petproject/boardgamefun/controller/DiaryController.java index e55b92e..59cff9c 100644 --- a/src/main/java/com/petproject/boardgamefun/controller/DiaryController.java +++ b/src/main/java/com/petproject/boardgamefun/controller/DiaryController.java @@ -2,6 +2,7 @@ import com.petproject.boardgamefun.dto.DiaryCommentDTO; import com.petproject.boardgamefun.dto.DiaryDTO; +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.DiaryComment; @@ -11,6 +12,7 @@ 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; @@ -31,19 +33,21 @@ public class DiaryController { 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) { + 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(){ + public ResponseEntity> getDiaries() { var diaries = diaryService.projectionsToDiaryDTO(diaryRepository.getAllDiaries()); return new ResponseEntity<>(diaries, HttpStatus.OK); @@ -51,7 +55,7 @@ public ResponseEntity> getDiaries(){ @Transactional @GetMapping("/{diaryId}") - public ResponseEntity getDiary(@PathVariable Integer diaryId){ + public ResponseEntity getDiary(@PathVariable Integer diaryId) { var diaryProjection = diaryService.projectionToDiaryDTO(diaryRepository.findDiaryUsingId(diaryId)); return new ResponseEntity<>(diaryProjection, HttpStatus.OK); @@ -60,7 +64,7 @@ public ResponseEntity getDiary(@PathVariable Integer diaryId){ @Transactional @GetMapping("/{diaryId}/comments") - public ResponseEntity> getDiaryComments(@PathVariable Integer diaryId){ + public ResponseEntity> getDiaryComments(@PathVariable Integer diaryId) { var diaryComments = diaryCommentService.entitiesToCommentDTO(diaryCommentRepository.findDiaryComment_ByDiaryId(diaryId)); return new ResponseEntity<>(diaryComments, HttpStatus.OK); @@ -68,7 +72,7 @@ public ResponseEntity> getDiaryComments(@PathVariable Inte @Transactional @PostMapping(value = "{diaryId}/add-comment/{userId}") - public ResponseEntity> addComment(@PathVariable Integer diaryId, @PathVariable Integer userId, @RequestBody DiaryCommentRequest diaryCommentRequest){ + public ResponseEntity> addComment(@PathVariable Integer diaryId, @PathVariable Integer userId, @RequestBody DiaryCommentRequest diaryCommentRequest) { var user = userRepository.findUserById(userId); var diary = diaryRepository.findDiaryById(diaryId); @@ -87,7 +91,7 @@ public ResponseEntity> addComment(@PathVariable Integer di @Transactional @PatchMapping(value = "{diaryId}/update-comment/{diaryCommentId}") - public ResponseEntity> updateComment(@PathVariable Integer diaryId, @PathVariable Integer diaryCommentId, @RequestBody DiaryCommentRequest diaryCommentRequest){ + 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()); @@ -101,7 +105,7 @@ public ResponseEntity> updateComment(@PathVariable Integer @Transactional @DeleteMapping("{diaryId}/delete-comment/{diaryCommentId}") - public ResponseEntity> deleteComment(@PathVariable Integer diaryId, @PathVariable Integer diaryCommentId){ + public ResponseEntity> deleteComment(@PathVariable Integer diaryId, @PathVariable Integer diaryCommentId) { var diaryComment = diaryCommentRepository.findDiaryCommentById(diaryCommentId); diaryCommentRepository.delete(diaryComment); @@ -112,7 +116,7 @@ public ResponseEntity> deleteComment(@PathVariable Integer @Transactional @PostMapping("/{diaryId}/set-rating/{userId}") - public ResponseEntity setDiaryRating(@PathVariable Integer diaryId, @PathVariable Integer userId, @RequestBody DiaryRatingRequest ratingRequest){ + public ResponseEntity setDiaryRating(@PathVariable Integer diaryId, @PathVariable Integer userId, @RequestBody DiaryRatingRequest ratingRequest) { var diary = diaryRepository.findDiaryById(diaryId); var user = userRepository.findUserById(userId); @@ -122,26 +126,29 @@ public ResponseEntity setDiaryRating(@PathVariable Integer diaryId, diaryRating.setRating(ratingRequest.getRating()); diaryRatingRepository.save(diaryRating); - return new ResponseEntity<>(diaryRating, HttpStatus.OK); + var diaryRatingDTO = diaryRatingService.entityToDiaryRatingDTO(diaryRating); + + return new ResponseEntity<>(diaryRatingDTO, HttpStatus.OK); } @Transactional @PatchMapping("/update-rating/{ratingId}") - public ResponseEntity updateDiaryRating(@PathVariable Integer ratingId, @RequestBody DiaryRatingRequest ratingRequest){ + public ResponseEntity updateDiaryRating(@PathVariable Integer ratingId, @RequestBody DiaryRatingRequest ratingRequest) { var diaryRating = diaryRatingRepository.findDiaryRatingById(ratingId); - if (ratingRequest != null && !Objects.equals(diaryRating.getRating(), ratingRequest.getRating())){ + if (ratingRequest != null && !Objects.equals(diaryRating.getRating(), ratingRequest.getRating())) { diaryRating.setRating(ratingRequest.getRating()); } diaryRatingRepository.save(diaryRating); + var diaryRatingDTO = diaryRatingService.entityToDiaryRatingDTO(diaryRating); - return new ResponseEntity<>(diaryRating, HttpStatus.OK); + return new ResponseEntity<>(diaryRatingDTO, HttpStatus.OK); } @Transactional @DeleteMapping("/delete-rating/{ratingId}") - public ResponseEntity deleteDiaryRating(@PathVariable Integer ratingId){ + public ResponseEntity deleteDiaryRating(@PathVariable Integer ratingId) { var diaryRating = diaryRatingRepository.findDiaryRatingById(ratingId); diaryRatingRepository.delete(diaryRating); return new ResponseEntity<>("Рейтинг убран с игры", HttpStatus.OK); 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..88ec4bc --- /dev/null +++ b/src/main/java/com/petproject/boardgamefun/dto/DiaryRatingDTO.java @@ -0,0 +1,11 @@ +package com.petproject.boardgamefun.dto; + +import lombok.AllArgsConstructor; +import lombok.Data; + +@Data +@AllArgsConstructor +public class DiaryRatingDTO { + private Integer id; + private Double rating; +} 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()); + } +} From afa1e97e2a638df1dff081fda12bd5c380b9e745 Mon Sep 17 00:00:00 2001 From: "i.i.artamonov" Date: Mon, 10 Jan 2022 15:49:42 +0400 Subject: [PATCH 053/141] Add entity to ForumDTO methods Change returning types of ForumController. --- .../controller/ForumController.java | 20 +++++++++++-------- .../boardgamefun/service/ForumService.java | 14 +++++++++++++ 2 files changed, 26 insertions(+), 8 deletions(-) diff --git a/src/main/java/com/petproject/boardgamefun/controller/ForumController.java b/src/main/java/com/petproject/boardgamefun/controller/ForumController.java index f0f0069..9f4b453 100644 --- a/src/main/java/com/petproject/boardgamefun/controller/ForumController.java +++ b/src/main/java/com/petproject/boardgamefun/controller/ForumController.java @@ -63,7 +63,7 @@ public ResponseEntity getForum(@PathVariable Integer forumId){ @Transactional @PostMapping("add-forum/{gameId}/{userId}") - public ResponseEntity addForum(@PathVariable Integer gameId, @PathVariable Integer userId, @RequestBody ForumRequest forumRequest) { + public ResponseEntity addForum(@PathVariable Integer gameId, @PathVariable Integer userId, @RequestBody ForumRequest forumRequest) { var user = userRepository.findUserById(userId); var game = gameRepository.findGameById(gameId); @@ -77,12 +77,14 @@ public ResponseEntity addForum(@PathVariable Integer gameId, @PathVariabl forumRepository.save(forum); - return new ResponseEntity<>(forum, HttpStatus.OK); + var forumDTO = forumService.entityToForumDTO(forum); + + return new ResponseEntity<>(forumDTO, HttpStatus.OK); } @Transactional @PatchMapping("/update-forum/{forumId}") - public ResponseEntity updateForum(@PathVariable Integer forumId, @RequestBody ForumRequest forumRequest) { + public ResponseEntity updateForum(@PathVariable Integer forumId, @RequestBody ForumRequest forumRequest) { var forum = forumRepository.findForumById(forumId); if (forumRequest.getTitle() != null && !Objects.equals(forumRequest.getTitle(), forum.getTitle())) @@ -93,7 +95,9 @@ public ResponseEntity updateForum(@PathVariable Integer forumId, @Request forumRepository.save(forum); - return new ResponseEntity<>(forum, HttpStatus.OK); + var forumDTO = forumService.entityToForumDTO(forum); + + return new ResponseEntity<>(forumDTO, HttpStatus.OK); } @Transactional @@ -167,7 +171,7 @@ public ResponseEntity> deleteMessage(@PathVariable Integer fo @Transactional @PostMapping("/{forumId}/set-rating/{userId}") - public ResponseEntity setForumRating(@PathVariable Integer forumId, @PathVariable Integer userId, @RequestBody ForumRatingRequest forumRatingRequest){ + public ResponseEntity setForumRating(@PathVariable Integer forumId, @PathVariable Integer userId, @RequestBody ForumRatingRequest forumRatingRequest){ var forumRating = forumRatingRepository.findForumRating_ByForumIdAndUserId(forumId, userId); if (forumRating == null){ @@ -181,17 +185,17 @@ public ResponseEntity setForumRating(@PathVariable Integer forumId, @Path forumRating.setRating(forumRatingRequest.getRating()); forumRatingRepository.save(forumRating); - var forum = forumRepository.findForumById(forumId); + var forum = forumService.projectionToForumDTO(forumRepository.findForumWithRatingUsingId(userId)); return new ResponseEntity<>(forum, HttpStatus.OK); } @Transactional @DeleteMapping("/{forumId}/remove-rating/{ratingId}") - public ResponseEntity removeRatingFromForum(@PathVariable Integer forumId, @PathVariable Integer ratingId){ + public ResponseEntity removeRatingFromForum(@PathVariable Integer forumId, @PathVariable Integer ratingId){ var forumRating = forumRatingRepository.findForumRatingById(ratingId); forumRatingRepository.delete(forumRating); - var forum = forumRepository.findForumById(forumId); + var forum = forumService.projectionToForumDTO(forumRepository.findForumWithRatingUsingId(forumId)); return new ResponseEntity<>(forum, HttpStatus.OK); } diff --git a/src/main/java/com/petproject/boardgamefun/service/ForumService.java b/src/main/java/com/petproject/boardgamefun/service/ForumService.java index 1e7fa54..11f9fa2 100644 --- a/src/main/java/com/petproject/boardgamefun/service/ForumService.java +++ b/src/main/java/com/petproject/boardgamefun/service/ForumService.java @@ -2,6 +2,7 @@ import com.petproject.boardgamefun.dto.ForumDTO; import com.petproject.boardgamefun.dto.projection.ForumProjection; +import com.petproject.boardgamefun.model.Forum; import org.springframework.stereotype.Service; import java.util.ArrayList; @@ -23,4 +24,17 @@ public ForumDTO projectionToForumDTO(ForumProjection projection) { forum.setRating(projection.getRating()); return forum; } + + public List entitiesToForumDTO(List forums){ + ArrayList forumsDTO = new ArrayList<>(); + for (var forum : + forums) { + forumsDTO.add(new ForumDTO(forum, null)); + } + return forumsDTO; + } + + public ForumDTO entityToForumDTO(Forum forum){ + return new ForumDTO(forum, null); + } } From 0f2829b578416b3eb5e8bf5339522ab9a950c9aa Mon Sep 17 00:00:00 2001 From: "i.i.artamonov" Date: Mon, 10 Jan 2022 16:34:05 +0400 Subject: [PATCH 054/141] Added ForumMessageService and ForumMessageDTO Change returning type of methods in ForumController --- .../controller/ForumController.java | 35 +++++++++++-------- .../boardgamefun/dto/ForumMessageDTO.java | 14 ++++++++ .../service/ForumMessageService.java | 24 +++++++++++++ 3 files changed, 59 insertions(+), 14 deletions(-) create mode 100644 src/main/java/com/petproject/boardgamefun/dto/ForumMessageDTO.java create mode 100644 src/main/java/com/petproject/boardgamefun/service/ForumMessageService.java diff --git a/src/main/java/com/petproject/boardgamefun/controller/ForumController.java b/src/main/java/com/petproject/boardgamefun/controller/ForumController.java index 9f4b453..6a9d3a3 100644 --- a/src/main/java/com/petproject/boardgamefun/controller/ForumController.java +++ b/src/main/java/com/petproject/boardgamefun/controller/ForumController.java @@ -1,6 +1,7 @@ package com.petproject.boardgamefun.controller; import com.petproject.boardgamefun.dto.ForumDTO; +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; @@ -8,6 +9,7 @@ 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; @@ -28,14 +30,16 @@ public class ForumController { 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) { + 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 @@ -55,7 +59,7 @@ public ResponseEntity> getForums(@RequestParam(required = false) @Transactional @GetMapping("/{forumId}") - public ResponseEntity getForum(@PathVariable Integer forumId){ + public ResponseEntity getForum(@PathVariable Integer forumId) { var forum = forumService.projectionToForumDTO(forumRepository.findForumWithRatingUsingId(forumId)); return new ResponseEntity<>(forum, HttpStatus.OK); @@ -112,7 +116,7 @@ public ResponseEntity deleteForum(@PathVariable Integer forumId) { @Transactional @GetMapping("/messages") - public ResponseEntity> getComments(@RequestParam(required = false) Integer forumId, @RequestParam(required = false) Integer userId) { + public ResponseEntity> getComments(@RequestParam(required = false) Integer forumId, @RequestParam(required = false) Integer userId) { List messages; if (forumId != null) messages = forumMessageRepository.findByForumId(forumId); @@ -121,12 +125,13 @@ else if (userId != null) else messages = forumMessageRepository.findAll(); - return new ResponseEntity<>(messages, HttpStatus.OK); + var forumMessagesDTO = forumMessageService.entitiesToForumMessagesDTO(messages); + return new ResponseEntity<>(forumMessagesDTO, HttpStatus.OK); } @Transactional @PostMapping("/{forumId}/add-message/{userId}") - public ResponseEntity> addMessage(@PathVariable Integer forumId, @PathVariable Integer userId, @RequestBody ForumMessageRequest forumMessageRequest) { + public ResponseEntity> addMessage(@PathVariable Integer forumId, @PathVariable Integer userId, @RequestBody ForumMessageRequest forumMessageRequest) { var forum = forumRepository.findForumById(forumId); var user = userRepository.findUserById(userId); @@ -140,12 +145,14 @@ public ResponseEntity> addMessage(@PathVariable Integer forum var messages = forumMessageRepository.findByForumId(forumId); - return new ResponseEntity<>(messages, HttpStatus.OK); + var forumMessagesDTO = forumMessageService.entitiesToForumMessagesDTO(messages); + + return new ResponseEntity<>(forumMessagesDTO, HttpStatus.OK); } @Transactional @PatchMapping("/{forumId}/update-message/{messageId}") - public ResponseEntity> updateMessage(@PathVariable Integer messageId, @PathVariable Integer forumId, @RequestBody ForumMessageRequest forumMessageRequest) { + public ResponseEntity> updateMessage(@PathVariable Integer messageId, @PathVariable Integer forumId, @RequestBody ForumMessageRequest forumMessageRequest) { var message = forumMessageRepository.findForumMessageById(messageId); if (!Objects.equals(forumMessageRequest.getComment(), message.getComment())) @@ -153,28 +160,28 @@ public ResponseEntity> updateMessage(@PathVariable Integer me forumMessageRepository.save(message); - var messages = forumMessageRepository.findByForumId(forumId); + var messages = forumMessageService.entitiesToForumMessagesDTO(forumMessageRepository.findByForumId(forumId)); return new ResponseEntity<>(messages, HttpStatus.OK); } @Transactional @DeleteMapping("/{forumId}/delete-message/{messageId}") - public ResponseEntity> deleteMessage(@PathVariable Integer forumId, @PathVariable Integer messageId ) { + public ResponseEntity> deleteMessage(@PathVariable Integer forumId, @PathVariable Integer messageId) { var message = forumMessageRepository.findForumMessageById(messageId); forumMessageRepository.delete(message); - var messages = forumMessageRepository.findByForumId(forumId); + var messages = forumMessageService.entitiesToForumMessagesDTO(forumMessageRepository.findByForumId(forumId)); return new ResponseEntity<>(messages, HttpStatus.OK); } @Transactional @PostMapping("/{forumId}/set-rating/{userId}") - public ResponseEntity setForumRating(@PathVariable Integer forumId, @PathVariable Integer userId, @RequestBody ForumRatingRequest forumRatingRequest){ + public ResponseEntity setForumRating(@PathVariable Integer forumId, @PathVariable Integer userId, @RequestBody ForumRatingRequest forumRatingRequest) { - var forumRating = forumRatingRepository.findForumRating_ByForumIdAndUserId(forumId, userId); - if (forumRating == null){ + var forumRating = forumRatingRepository.findForumRating_ByForumIdAndUserId(forumId, userId); + if (forumRating == null) { var forum = forumRepository.findForumById(forumId); var user = userRepository.findUserById(userId); @@ -191,7 +198,7 @@ public ResponseEntity setForumRating(@PathVariable Integer forumId, @P @Transactional @DeleteMapping("/{forumId}/remove-rating/{ratingId}") - public ResponseEntity removeRatingFromForum(@PathVariable Integer forumId, @PathVariable Integer ratingId){ + public ResponseEntity removeRatingFromForum(@PathVariable Integer forumId, @PathVariable Integer ratingId) { var forumRating = forumRatingRepository.findForumRatingById(ratingId); forumRatingRepository.delete(forumRating); 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..5aa7136 --- /dev/null +++ b/src/main/java/com/petproject/boardgamefun/dto/ForumMessageDTO.java @@ -0,0 +1,14 @@ +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; +} 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..55afd00 --- /dev/null +++ b/src/main/java/com/petproject/boardgamefun/service/ForumMessageService.java @@ -0,0 +1,24 @@ +package com.petproject.boardgamefun.service; + +import com.petproject.boardgamefun.dto.ForumMessageDTO; +import com.petproject.boardgamefun.model.ForumMessage; +import org.springframework.stereotype.Service; + +import java.util.ArrayList; +import java.util.List; + +@Service +public class ForumMessageService { + public ForumMessageDTO entityToForumMessageDTO(ForumMessage forumMessage) { + return new ForumMessageDTO(forumMessage.getId(), forumMessage.getComment(), forumMessage.getTime()); + } + + public List entitiesToForumMessagesDTO(List forumMessages) { + ArrayList forumMessagesDTO = new ArrayList<>(); + for (var forumMessage : + forumMessages) { + forumMessagesDTO.add(new ForumMessageDTO(forumMessage.getId(), forumMessage.getComment(), forumMessage.getTime())); + } + return forumMessagesDTO; + } +} From bb244be3cf6be9068a3221f2e9f1ed2d9324094a Mon Sep 17 00:00:00 2001 From: "i.i.artamonov" Date: Tue, 11 Jan 2022 15:42:24 +0400 Subject: [PATCH 055/141] Change returning types to GameDTO of methods in GameController Add methods to GameService. Remove unnecessary method - getGamesWithRating. --- .../controller/GameController.java | 48 ++++++++----------- .../boardgamefun/service/GameService.java | 18 +++++++ 2 files changed, 39 insertions(+), 27 deletions(-) diff --git a/src/main/java/com/petproject/boardgamefun/controller/GameController.java b/src/main/java/com/petproject/boardgamefun/controller/GameController.java index 0a54f16..68dacbe 100644 --- a/src/main/java/com/petproject/boardgamefun/controller/GameController.java +++ b/src/main/java/com/petproject/boardgamefun/controller/GameController.java @@ -40,9 +40,9 @@ public GameController(GameRepository gameRepository, UserRepository userReposito @Transactional @GetMapping() - ResponseEntity> getGames() { + ResponseEntity> getGames() { - var games = gameRepository.findGames(); + var games = gameService.projectionsToGameDTO(gameRepository.findGames()); return new ResponseEntity<>(games, HttpStatus.OK); } @@ -64,18 +64,19 @@ public ResponseEntity> getGamesByTitle(@PathVariable String title) @Transactional @PostMapping("/add") - public ResponseEntity addGame(@RequestBody Game newGame) { + public ResponseEntity addGame(@RequestBody Game newGame) { gameRepository.save(newGame); + var game = gameService.entityToGameDTO(newGame); - return new ResponseEntity<>(newGame, HttpStatus.OK); + return new ResponseEntity<>(game, HttpStatus.OK); } @Transactional @PutMapping("/update") - public ResponseEntity updateGame(@RequestBody Game updatedGame) { + public ResponseEntity updateGame(@RequestBody Game updatedGame) { gameRepository.save(updatedGame); - - return new ResponseEntity<>(updatedGame, HttpStatus.OK); + var game = gameService.entityToGameDTO(updatedGame); + return new ResponseEntity<>(game, HttpStatus.OK); } @Transactional @@ -88,15 +89,15 @@ public ResponseEntity removeGameFromSite(@RequestBody Game deleteGame) { @Transactional @GetMapping("/expansions/{gameId}") - public ResponseEntity> getExpansions(@PathVariable Integer gameId) { - var gamesExpansions = gameRepository.getExpansions(gameId); + public ResponseEntity> getExpansions(@PathVariable Integer gameId) { + var gamesExpansions = gameService.entitiesToGameDTO(gameRepository.getExpansions(gameId)); return new ResponseEntity<>(gamesExpansions, HttpStatus.OK); } @Transactional @PostMapping("/add-expansion/{parentGameId}/{daughterGameId}") - public ResponseEntity> addExpansion(@PathVariable Integer parentGameId, @PathVariable Integer daughterGameId) { + public ResponseEntity> addExpansion(@PathVariable Integer parentGameId, @PathVariable Integer daughterGameId) { var parentGame = gameRepository.findGameById(parentGameId); var daughterGame = gameRepository.findGameById(daughterGameId); @@ -105,33 +106,33 @@ public ResponseEntity> addExpansion(@PathVariable Integer parentGameI expansion.setDaughterGame(daughterGame); expansionRepository.save(expansion); - var gamesExpansions = gameRepository.getExpansions(parentGameId); + var gamesExpansions = gameService.entitiesToGameDTO(gameRepository.getExpansions(parentGameId)); return new ResponseEntity<>(gamesExpansions, HttpStatus.OK); } @Transactional @DeleteMapping("/delete-expansion/{parentGameId}/{daughterGameId}") - public ResponseEntity> deleteExpansion(@PathVariable Integer daughterGameId, @PathVariable Integer parentGameId) { + public ResponseEntity> deleteExpansion(@PathVariable Integer daughterGameId, @PathVariable Integer parentGameId) { var expansion = expansionRepository.findExpansion_ByDaughterGameIdAndParentGameId(daughterGameId, parentGameId); expansionRepository.delete(expansion); - var gamesExpansions = gameRepository.getExpansions(parentGameId); + var gamesExpansions = gameService.entitiesToGameDTO(gameRepository.getExpansions(parentGameId)); return new ResponseEntity<>(gamesExpansions, HttpStatus.OK); } @Transactional @GetMapping("/similar/{gameId}") - public ResponseEntity> getSimilarGames(@PathVariable Integer gameId) { - var similarGames = gameRepository.getSimilarGames(gameId); + public ResponseEntity> getSimilarGames(@PathVariable Integer gameId) { + var similarGames = gameService.entitiesToGameDTO(gameRepository.getSimilarGames(gameId)); return new ResponseEntity<>(similarGames, HttpStatus.OK); } @Transactional @PostMapping("/add-similar/{referenceGameId}/{sourceGameId}") - public ResponseEntity> addSimilarGame(@PathVariable Integer referenceGameId, @PathVariable Integer sourceGameId) { + public ResponseEntity> addSimilarGame(@PathVariable Integer referenceGameId, @PathVariable Integer sourceGameId) { var referenceGame = gameRepository.findGameById(referenceGameId); var sourceGame = gameRepository.findGameById(sourceGameId); @@ -140,18 +141,18 @@ public ResponseEntity> addSimilarGame(@PathVariable Integer reference sameGame.setSourceGame(sourceGame); sameGameRepository.save(sameGame); - var sameGames = gameRepository.getSimilarGames(referenceGameId); + var sameGames = gameService.entitiesToGameDTO(gameRepository.getSimilarGames(referenceGameId)); return new ResponseEntity<>(sameGames, HttpStatus.OK); } @Transactional @DeleteMapping("/delete-similar/{referenceGameId}/{sourceGameId}") - public ResponseEntity> deleteSameGame(@PathVariable Integer referenceGameId, @PathVariable Integer sourceGameId) { + public ResponseEntity> deleteSameGame(@PathVariable Integer referenceGameId, @PathVariable Integer sourceGameId) { var sameGame = sameGameRepository.findSameGame_ByReferenceGameIdAndSourceGameId(referenceGameId, sourceGameId); sameGameRepository.delete(sameGame); - var sameGames = gameRepository.getSimilarGames(referenceGameId); + var sameGames = gameService.entitiesToGameDTO(gameRepository.getSimilarGames(referenceGameId)); return new ResponseEntity<>(sameGames, HttpStatus.OK); } @@ -165,14 +166,7 @@ public ResponseEntity> getUsersRating(@PathVariable Int return new ResponseEntity<>(ratings, HttpStatus.OK); } - @Transactional - @GetMapping("/with-rating") - public ResponseEntity> getGamesWithRating() { - var games = gameRepository.findGames(); - return new ResponseEntity<>(games, HttpStatus.OK); - } - - //Поменять на тип текст либо убрать аннотацию + //Поменять на тип текст либо убрать аннотацию @Transactional @PostMapping("/{gameId}/set-designer/{designerId}") diff --git a/src/main/java/com/petproject/boardgamefun/service/GameService.java b/src/main/java/com/petproject/boardgamefun/service/GameService.java index 218905f..2ce48a8 100644 --- a/src/main/java/com/petproject/boardgamefun/service/GameService.java +++ b/src/main/java/com/petproject/boardgamefun/service/GameService.java @@ -18,6 +18,20 @@ public GameDTO projectionsToGameDTO(GameProjection gameProjection, List projectionsToGameDTO(List gameProjections) { + List games = new ArrayList<>(); + for (var game : + gameProjections) { + games.add(new GameDTO(game.getGame(), game.getRating(), null)); + } + return games; + } + + public List entitiesToGameDTO(List games) { ArrayList gamesDTO = new ArrayList<>(); for (var game : @@ -27,6 +41,10 @@ public List entitiesToGameDTO(List games) { return gamesDTO; } + public GameDTO entityToGameDTO(Game game){ + return new GameDTO(game, null, null); + } + public List getTitlesFromProjections(List games) { return games.stream().map(GamesFilterByTitleProjection::getTitle).collect(Collectors.toList()); } From 60f25c448f33e38505369ac920d9dccf12f690d6 Mon Sep 17 00:00:00 2001 From: "i.i.artamonov" Date: Tue, 11 Jan 2022 15:46:36 +0400 Subject: [PATCH 056/141] Little fix - change returning type getUserCollection in UserController Not changed earlier due to inattention --- .../petproject/boardgamefun/controller/UserController.java | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/src/main/java/com/petproject/boardgamefun/controller/UserController.java b/src/main/java/com/petproject/boardgamefun/controller/UserController.java index 7b79121..4c08470 100644 --- a/src/main/java/com/petproject/boardgamefun/controller/UserController.java +++ b/src/main/java/com/petproject/boardgamefun/controller/UserController.java @@ -159,9 +159,9 @@ public ResponseEntity getUser(@PathVariable Integer id) { @Transactional @GetMapping("/{id}/games") - public ResponseEntity> getUserCollectionByType(@PathVariable Integer id) { + public ResponseEntity> getUserCollection(@PathVariable Integer id) { - var games = gameRepository.findUserGames(id); + var games = gameService.entitiesToGameDTO(gameRepository.findUserGames(id)); return new ResponseEntity<>(games, HttpStatus.OK); } From 7fbba8f996b38e5cbb1ce7a066ef6f26bc0b8329 Mon Sep 17 00:00:00 2001 From: "i.i.artamonov" Date: Tue, 11 Jan 2022 15:51:30 +0400 Subject: [PATCH 057/141] Change rest models files in pom.xml for typescript-generator --- pom.xml | 2 -- 1 file changed, 2 deletions(-) diff --git a/pom.xml b/pom.xml index f85a7cc..3101e49 100644 --- a/pom.xml +++ b/pom.xml @@ -132,9 +132,7 @@ jackson2 - com.petproject.boardgamefun.model.* com.petproject.boardgamefun.dto.* - com.petproject.boardgamefun.dto.projection.* target/rest.d.ts module From a3a28e1b020a91b1beebcce9fc0e020cc598d6ca Mon Sep 17 00:00:00 2001 From: "i.i.artamonov" Date: Tue, 11 Jan 2022 16:14:57 +0400 Subject: [PATCH 058/141] Add null safety check for projectionsToDiaryDTO in DiaryService --- .../java/com/petproject/boardgamefun/service/DiaryService.java | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/main/java/com/petproject/boardgamefun/service/DiaryService.java b/src/main/java/com/petproject/boardgamefun/service/DiaryService.java index 920d374..3fa64f9 100644 --- a/src/main/java/com/petproject/boardgamefun/service/DiaryService.java +++ b/src/main/java/com/petproject/boardgamefun/service/DiaryService.java @@ -13,7 +13,7 @@ public class DiaryService { public List projectionsToDiaryDTO(List projections) { List diaries = new ArrayList<>(); for (var projection : projections) { - diaries.add(new DiaryDTO(projection.getDiary(), projection.getRating())); + diaries.add(new DiaryDTO(projection.getDiary(), projection.getRating() != null ? projection.getRating() : 0 )); } return diaries; From 4b73e0a4fb54c8501dc3f1b05420d832bda86dc8 Mon Sep 17 00:00:00 2001 From: "i.i.artamonov" Date: Tue, 8 Feb 2022 09:46:56 +0400 Subject: [PATCH 059/141] Split sign up to personal data and avatar request Due to different kind of requests image upload in separate request. --- .../controller/UserController.java | 18 ++++++++++++++---- 1 file changed, 14 insertions(+), 4 deletions(-) diff --git a/src/main/java/com/petproject/boardgamefun/controller/UserController.java b/src/main/java/com/petproject/boardgamefun/controller/UserController.java index 4c08470..74717f4 100644 --- a/src/main/java/com/petproject/boardgamefun/controller/UserController.java +++ b/src/main/java/com/petproject/boardgamefun/controller/UserController.java @@ -8,6 +8,7 @@ import com.petproject.boardgamefun.dto.request.UserEditRequest; import com.petproject.boardgamefun.model.*; import com.petproject.boardgamefun.repository.*; +import com.petproject.boardgamefun.security.enums.Role; import com.petproject.boardgamefun.security.jwt.JwtUtils; import com.petproject.boardgamefun.security.model.JwtResponse; import com.petproject.boardgamefun.security.model.LoginRequest; @@ -24,10 +25,11 @@ import org.springframework.security.core.context.SecurityContextHolder; import org.springframework.security.crypto.password.PasswordEncoder; import org.springframework.web.bind.annotation.*; +import org.springframework.web.multipart.MultipartFile; import javax.transaction.Transactional; +import java.io.IOException; import java.time.OffsetDateTime; -import java.util.Arrays; import java.util.List; import java.util.Objects; @@ -106,12 +108,23 @@ public ResponseEntity registerUser(@RequestBody User user) { return new ResponseEntity<>("Пользователь с такой почтой уже существует", HttpStatus.BAD_REQUEST); } + user.setRole(Role.ROLE_USER.name()); user.setPassword(passwordEncoder.encode(user.getPassword())); user.setRegistrationDate(OffsetDateTime.now()); userRepository.save(user); return new ResponseEntity<>(user, HttpStatus.OK); } + @Transactional + @PostMapping("/upload-avatar/{userName}") + public ResponseEntity uploadAvatar(@PathVariable String userName, @RequestParam("avatar") MultipartFile file) throws IOException { + var user = userRepository.findUserByName(userName); + user.setAvatar(file.getBytes()); + userRepository.save(user); + return new ResponseEntity<>(HttpStatus.OK); + } + + @Transactional @PatchMapping("/edit/{userId}") public ResponseEntity editUser(@PathVariable Integer userId, @RequestBody UserEditRequest userEditRequest){ @@ -125,9 +138,6 @@ public ResponseEntity editUser(@PathVariable Integer userId, @RequestBody Use if (userEditRequest.getRole() != null && !Objects.equals(userEditRequest.getRole(), user.getRole())){ user.setRole(userEditRequest.getRole()); } - if (userEditRequest.getAvatar() != null && !Arrays.equals(userEditRequest.getAvatar(), user.getAvatar())){ - user.setAvatar(userEditRequest.getAvatar()); - } userRepository.save(user); From 0d166a1d7c73a8abb30c1ad0a927f82360cf2444 Mon Sep 17 00:00:00 2001 From: "i.i.artamonov" Date: Mon, 14 Feb 2022 16:05:23 +0400 Subject: [PATCH 060/141] Union get diaries request Now with request param we can get diaries - all; by user; by game. Add method to diary repository for retrieving game diaries. Remove method from UserController. --- pom.xml | 1 + .../boardgamefun/controller/DiaryController.java | 13 ++++++++++--- .../boardgamefun/controller/UserController.java | 8 -------- .../boardgamefun/repository/DiaryRepository.java | 8 ++++++++ 4 files changed, 19 insertions(+), 11 deletions(-) diff --git a/pom.xml b/pom.xml index 3101e49..8bfaf37 100644 --- a/pom.xml +++ b/pom.xml @@ -17,6 +17,7 @@ 17 + diff --git a/src/main/java/com/petproject/boardgamefun/controller/DiaryController.java b/src/main/java/com/petproject/boardgamefun/controller/DiaryController.java index 59cff9c..7089ce9 100644 --- a/src/main/java/com/petproject/boardgamefun/controller/DiaryController.java +++ b/src/main/java/com/petproject/boardgamefun/controller/DiaryController.java @@ -47,8 +47,16 @@ public DiaryController(DiaryCommentRepository diaryCommentRepository, UserReposi @Transactional @GetMapping("") - public ResponseEntity> getDiaries() { - var diaries = diaryService.projectionsToDiaryDTO(diaryRepository.getAllDiaries()); + 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); } @@ -61,7 +69,6 @@ public ResponseEntity getDiary(@PathVariable Integer diaryId) { return new ResponseEntity<>(diaryProjection, HttpStatus.OK); } - @Transactional @GetMapping("/{diaryId}/comments") public ResponseEntity> getDiaryComments(@PathVariable Integer diaryId) { diff --git a/src/main/java/com/petproject/boardgamefun/controller/UserController.java b/src/main/java/com/petproject/boardgamefun/controller/UserController.java index 74717f4..cc68d2b 100644 --- a/src/main/java/com/petproject/boardgamefun/controller/UserController.java +++ b/src/main/java/com/petproject/boardgamefun/controller/UserController.java @@ -366,14 +366,6 @@ public ResponseEntity deleteDiary(@PathVariable Integer userId, @PathVar return new ResponseEntity<>("Дневник " + diary.getTitle() + " удален из ваших дневников", HttpStatus.OK); } - @Transactional - @GetMapping({"{userId}/diary-list"}) - public ResponseEntity> getListDiary(@PathVariable Integer userId){ - var diaries = diaryService.projectionsToDiaryDTO(diaryRepository.findUserDiaries(userId)); - - return new ResponseEntity<>(diaries, HttpStatus.OK); - } - @Transactional @PutMapping({"{userId}/update-diary/{diaryId}"}) public ResponseEntity updateDiary(@PathVariable Integer diaryId, @PathVariable Integer userId, @RequestBody Diary diaryRequest){ diff --git a/src/main/java/com/petproject/boardgamefun/repository/DiaryRepository.java b/src/main/java/com/petproject/boardgamefun/repository/DiaryRepository.java index f9f184c..4fad768 100644 --- a/src/main/java/com/petproject/boardgamefun/repository/DiaryRepository.java +++ b/src/main/java/com/petproject/boardgamefun/repository/DiaryRepository.java @@ -8,6 +8,7 @@ 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 " + @@ -17,6 +18,13 @@ public interface DiaryRepository extends JpaRepository { "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 " + From 5d7fb0b2a4639a30c6d229f574463340e490b0ee Mon Sep 17 00:00:00 2001 From: "i.i.artamonov" Date: Tue, 15 Feb 2022 15:43:20 +0400 Subject: [PATCH 061/141] Add separate request for image in GameController Due image need multipart request param - made separate request. --- .../boardgamefun/controller/GameController.java | 15 +++++++++++++-- 1 file changed, 13 insertions(+), 2 deletions(-) diff --git a/src/main/java/com/petproject/boardgamefun/controller/GameController.java b/src/main/java/com/petproject/boardgamefun/controller/GameController.java index 68dacbe..d5344f1 100644 --- a/src/main/java/com/petproject/boardgamefun/controller/GameController.java +++ b/src/main/java/com/petproject/boardgamefun/controller/GameController.java @@ -2,7 +2,6 @@ import com.petproject.boardgamefun.dto.GameDTO; import com.petproject.boardgamefun.dto.UsersGameRatingDTO; -import com.petproject.boardgamefun.dto.projection.GameProjection; import com.petproject.boardgamefun.model.Expansion; import com.petproject.boardgamefun.model.Game; import com.petproject.boardgamefun.model.GameByDesigner; @@ -13,7 +12,9 @@ import org.springframework.http.ResponseEntity; import org.springframework.transaction.annotation.Transactional; import org.springframework.web.bind.annotation.*; +import org.springframework.web.multipart.MultipartFile; +import java.io.IOException; import java.util.List; @RestController @@ -71,6 +72,16 @@ public ResponseEntity addGame(@RequestBody Game newGame) { return new ResponseEntity<>(game, HttpStatus.OK); } + @Transactional + @PostMapping("/upload-image/{gameId}") + public ResponseEntity uploadImage(@PathVariable Integer gameId, @RequestParam("picture") MultipartFile file) throws IOException { + var game = gameRepository.findGameById(gameId); + game.setPicture(file.getBytes()); + gameRepository.save(game); + var gameDTO = gameService.projectionsToGameDTO(gameRepository.findGame(gameId), designerRepository.findDesignersUsingGame(gameId)); + return new ResponseEntity<>(gameDTO, HttpStatus.OK); + } + @Transactional @PutMapping("/update") public ResponseEntity updateGame(@RequestBody Game updatedGame) { @@ -166,7 +177,7 @@ public ResponseEntity> getUsersRating(@PathVariable Int return new ResponseEntity<>(ratings, HttpStatus.OK); } - //Поменять на тип текст либо убрать аннотацию + //Поменять на тип текст либо убрать аннотацию @Transactional @PostMapping("/{gameId}/set-designer/{designerId}") From 28ebfd409ce242692d553cefd25f75586238bd14 Mon Sep 17 00:00:00 2001 From: "i.i.artamonov" Date: Thu, 17 Feb 2022 10:36:26 +0400 Subject: [PATCH 062/141] Add FilterGamesDTO for getGamesByTitle in GameController Now with title of the game we send if of the game. Edit projection and service method for applying new logic. --- .../boardgamefun/controller/GameController.java | 3 ++- .../petproject/boardgamefun/dto/FilterGamesDTO.java | 11 +++++++++++ .../dto/projection/GamesFilterByTitleProjection.java | 1 + .../boardgamefun/repository/GameRepository.java | 4 ++-- .../petproject/boardgamefun/service/GameService.java | 9 +++++++-- 5 files changed, 23 insertions(+), 5 deletions(-) create mode 100644 src/main/java/com/petproject/boardgamefun/dto/FilterGamesDTO.java diff --git a/src/main/java/com/petproject/boardgamefun/controller/GameController.java b/src/main/java/com/petproject/boardgamefun/controller/GameController.java index d5344f1..be4eb27 100644 --- a/src/main/java/com/petproject/boardgamefun/controller/GameController.java +++ b/src/main/java/com/petproject/boardgamefun/controller/GameController.java @@ -1,5 +1,6 @@ package com.petproject.boardgamefun.controller; +import com.petproject.boardgamefun.dto.FilterGamesDTO; import com.petproject.boardgamefun.dto.GameDTO; import com.petproject.boardgamefun.dto.UsersGameRatingDTO; import com.petproject.boardgamefun.model.Expansion; @@ -57,7 +58,7 @@ public ResponseEntity getGameByCriteria(@PathVariable Integer id) { @Transactional @GetMapping("/get-games-by-filter/{title}") - public ResponseEntity> getGamesByTitle(@PathVariable String title) { + public ResponseEntity> getGamesByTitle(@PathVariable String title) { var games = gameService.getTitlesFromProjections(gameRepository.findGamesUsingTitle(title)); return new ResponseEntity<>(games, HttpStatus.OK); } 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/projection/GamesFilterByTitleProjection.java b/src/main/java/com/petproject/boardgamefun/dto/projection/GamesFilterByTitleProjection.java index 5385d2e..e9a5d5b 100644 --- a/src/main/java/com/petproject/boardgamefun/dto/projection/GamesFilterByTitleProjection.java +++ b/src/main/java/com/petproject/boardgamefun/dto/projection/GamesFilterByTitleProjection.java @@ -2,4 +2,5 @@ public interface GamesFilterByTitleProjection { String getTitle(); + Integer getId(); } diff --git a/src/main/java/com/petproject/boardgamefun/repository/GameRepository.java b/src/main/java/com/petproject/boardgamefun/repository/GameRepository.java index 22b0b03..c7bb9e0 100644 --- a/src/main/java/com/petproject/boardgamefun/repository/GameRepository.java +++ b/src/main/java/com/petproject/boardgamefun/repository/GameRepository.java @@ -19,8 +19,8 @@ public interface GameRepository extends JpaRepository { "group by g") GameProjection findGame(Integer id); - @Query("select g.title as title from Game g " + - "where g.title like :title%") + @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 " + diff --git a/src/main/java/com/petproject/boardgamefun/service/GameService.java b/src/main/java/com/petproject/boardgamefun/service/GameService.java index 2ce48a8..0cabf3e 100644 --- a/src/main/java/com/petproject/boardgamefun/service/GameService.java +++ b/src/main/java/com/petproject/boardgamefun/service/GameService.java @@ -1,5 +1,6 @@ package com.petproject.boardgamefun.service; +import com.petproject.boardgamefun.dto.FilterGamesDTO; import com.petproject.boardgamefun.dto.UsersGameRatingDTO; import com.petproject.boardgamefun.dto.projection.*; import com.petproject.boardgamefun.dto.GameDTO; @@ -45,8 +46,12 @@ public GameDTO entityToGameDTO(Game game){ return new GameDTO(game, null, null); } - public List getTitlesFromProjections(List games) { - return games.stream().map(GamesFilterByTitleProjection::getTitle).collect(Collectors.toList()); + 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) { From c1156b5d756e7a69f1fa078f4b5af520e0556b77 Mon Sep 17 00:00:00 2001 From: "i.i.artamonov" Date: Thu, 17 Feb 2022 11:20:25 +0400 Subject: [PATCH 063/141] Add user entity to ForumMessageDTO Edit methods in ForumMessageService for new dto. On frontend side doesn't enough info about message. --- .../java/com/petproject/boardgamefun/dto/ForumMessageDTO.java | 2 ++ .../petproject/boardgamefun/service/ForumMessageService.java | 4 ++-- 2 files changed, 4 insertions(+), 2 deletions(-) diff --git a/src/main/java/com/petproject/boardgamefun/dto/ForumMessageDTO.java b/src/main/java/com/petproject/boardgamefun/dto/ForumMessageDTO.java index 5aa7136..1e63d69 100644 --- a/src/main/java/com/petproject/boardgamefun/dto/ForumMessageDTO.java +++ b/src/main/java/com/petproject/boardgamefun/dto/ForumMessageDTO.java @@ -1,5 +1,6 @@ package com.petproject.boardgamefun.dto; +import com.petproject.boardgamefun.model.User; import lombok.AllArgsConstructor; import lombok.Data; @@ -11,4 +12,5 @@ public class ForumMessageDTO { private Integer id; private String message; private OffsetDateTime messageTime; + private User user; } diff --git a/src/main/java/com/petproject/boardgamefun/service/ForumMessageService.java b/src/main/java/com/petproject/boardgamefun/service/ForumMessageService.java index 55afd00..815b671 100644 --- a/src/main/java/com/petproject/boardgamefun/service/ForumMessageService.java +++ b/src/main/java/com/petproject/boardgamefun/service/ForumMessageService.java @@ -10,14 +10,14 @@ @Service public class ForumMessageService { public ForumMessageDTO entityToForumMessageDTO(ForumMessage forumMessage) { - return new ForumMessageDTO(forumMessage.getId(), forumMessage.getComment(), forumMessage.getTime()); + return new ForumMessageDTO(forumMessage.getId(), forumMessage.getComment(), forumMessage.getTime(), 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())); + forumMessagesDTO.add(new ForumMessageDTO(forumMessage.getId(), forumMessage.getComment(), forumMessage.getTime(), forumMessage.getUser())); } return forumMessagesDTO; } From 162d133ba3301718a0f40bcdb2b95fc677ef6867 Mon Sep 17 00:00:00 2001 From: "i.i.artamonov" Date: Fri, 18 Feb 2022 08:45:36 +0400 Subject: [PATCH 064/141] Add null checking in method in DiaryService In projectionToDiary add null checking --- .../com/petproject/boardgamefun/controller/ForumController.java | 2 +- .../java/com/petproject/boardgamefun/service/DiaryService.java | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/src/main/java/com/petproject/boardgamefun/controller/ForumController.java b/src/main/java/com/petproject/boardgamefun/controller/ForumController.java index 6a9d3a3..c3a6ecb 100644 --- a/src/main/java/com/petproject/boardgamefun/controller/ForumController.java +++ b/src/main/java/com/petproject/boardgamefun/controller/ForumController.java @@ -116,7 +116,7 @@ public ResponseEntity deleteForum(@PathVariable Integer forumId) { @Transactional @GetMapping("/messages") - public ResponseEntity> getComments(@RequestParam(required = false) Integer forumId, @RequestParam(required = false) Integer userId) { + public ResponseEntity> getMessages(@RequestParam(required = false) Integer forumId, @RequestParam(required = false) Integer userId) { List messages; if (forumId != null) messages = forumMessageRepository.findByForumId(forumId); diff --git a/src/main/java/com/petproject/boardgamefun/service/DiaryService.java b/src/main/java/com/petproject/boardgamefun/service/DiaryService.java index 3fa64f9..0aaacc6 100644 --- a/src/main/java/com/petproject/boardgamefun/service/DiaryService.java +++ b/src/main/java/com/petproject/boardgamefun/service/DiaryService.java @@ -26,7 +26,7 @@ public DiaryDTO entityToDiaryDTO(Diary diary){ public DiaryDTO projectionToDiaryDTO(DiaryWithRatingsProjection projection) { DiaryDTO diary = new DiaryDTO(); diary.setDiary(projection.getDiary()); - diary.setRating(projection.getRating()); + diary.setRating(projection.getRating() != null ? projection.getRating() : 0 ); return diary; } From 73bbffdee1bee73a7848271780b3d35835fa7d5c Mon Sep 17 00:00:00 2001 From: "i.i.artamonov" Date: Fri, 18 Feb 2022 10:13:46 +0400 Subject: [PATCH 065/141] Add kotlin support. Convert some classes associated with diary Convert DiaryService, DiaryDTO, DiaryWithRatingsProjection to kotlin. --- pom.xml | 56 +++++++++++++++++++ .../petproject/boardgamefun/dto/DiaryDTO.java | 14 ----- .../petproject/boardgamefun/dto/DiaryDTO.kt | 5 ++ .../DiaryWithRatingsProjection.java | 8 --- .../projection/DiaryWithRatingsProjection.kt | 8 +++ .../boardgamefun/service/DiaryService.java | 34 ----------- .../boardgamefun/service/DiaryService.kt | 26 +++++++++ 7 files changed, 95 insertions(+), 56 deletions(-) delete mode 100644 src/main/java/com/petproject/boardgamefun/dto/DiaryDTO.java create mode 100644 src/main/java/com/petproject/boardgamefun/dto/DiaryDTO.kt delete mode 100644 src/main/java/com/petproject/boardgamefun/dto/projection/DiaryWithRatingsProjection.java create mode 100644 src/main/java/com/petproject/boardgamefun/dto/projection/DiaryWithRatingsProjection.kt delete mode 100644 src/main/java/com/petproject/boardgamefun/service/DiaryService.java create mode 100644 src/main/java/com/petproject/boardgamefun/service/DiaryService.kt diff --git a/pom.xml b/pom.xml index 8bfaf37..8234ca0 100644 --- a/pom.xml +++ b/pom.xml @@ -15,6 +15,7 @@ Boardgamefun 17 + 1.6.20-M1 @@ -101,6 +102,17 @@ jackson-jaxrs-json-provider 2.13.0 + + org.jetbrains.kotlin + kotlin-stdlib-jdk8 + ${kotlin.version} + + + org.jetbrains.kotlin + kotlin-test + ${kotlin.version} + test + @@ -139,6 +151,50 @@ module + + org.jetbrains.kotlin + kotlin-maven-plugin + ${kotlin.version} + + + compile + compile + + compile + + + + test-compile + test-compile + + test-compile + + + + + 1.8 + + + + org.apache.maven.plugins + maven-compiler-plugin + + + compile + compile + + compile + + + + testCompile + test-compile + + testCompile + + + + diff --git a/src/main/java/com/petproject/boardgamefun/dto/DiaryDTO.java b/src/main/java/com/petproject/boardgamefun/dto/DiaryDTO.java deleted file mode 100644 index a226919..0000000 --- a/src/main/java/com/petproject/boardgamefun/dto/DiaryDTO.java +++ /dev/null @@ -1,14 +0,0 @@ -package com.petproject.boardgamefun.dto; - -import com.petproject.boardgamefun.model.Diary; -import lombok.AllArgsConstructor; -import lombok.Data; -import lombok.NoArgsConstructor; - -@Data -@NoArgsConstructor -@AllArgsConstructor -public class DiaryDTO { - private Diary diary; - private double rating; -} diff --git a/src/main/java/com/petproject/boardgamefun/dto/DiaryDTO.kt b/src/main/java/com/petproject/boardgamefun/dto/DiaryDTO.kt new file mode 100644 index 0000000..a053d47 --- /dev/null +++ b/src/main/java/com/petproject/boardgamefun/dto/DiaryDTO.kt @@ -0,0 +1,5 @@ +package com.petproject.boardgamefun.dto + +import com.petproject.boardgamefun.model.Diary + +data class DiaryDTO(val diary: Diary, val rating: Double?) \ No newline at end of file diff --git a/src/main/java/com/petproject/boardgamefun/dto/projection/DiaryWithRatingsProjection.java b/src/main/java/com/petproject/boardgamefun/dto/projection/DiaryWithRatingsProjection.java deleted file mode 100644 index 6139938..0000000 --- a/src/main/java/com/petproject/boardgamefun/dto/projection/DiaryWithRatingsProjection.java +++ /dev/null @@ -1,8 +0,0 @@ -package com.petproject.boardgamefun.dto.projection; - -import com.petproject.boardgamefun.model.Diary; - -public interface DiaryWithRatingsProjection { - Diary getDiary(); - Double getRating(); -} 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/service/DiaryService.java b/src/main/java/com/petproject/boardgamefun/service/DiaryService.java deleted file mode 100644 index 0aaacc6..0000000 --- a/src/main/java/com/petproject/boardgamefun/service/DiaryService.java +++ /dev/null @@ -1,34 +0,0 @@ -package com.petproject.boardgamefun.service; - -import com.petproject.boardgamefun.dto.DiaryDTO; -import com.petproject.boardgamefun.dto.projection.DiaryWithRatingsProjection; -import com.petproject.boardgamefun.model.Diary; -import org.springframework.stereotype.Service; - -import java.util.ArrayList; -import java.util.List; - -@Service -public class DiaryService { - public List projectionsToDiaryDTO(List projections) { - List diaries = new ArrayList<>(); - for (var projection : projections) { - diaries.add(new DiaryDTO(projection.getDiary(), projection.getRating() != null ? projection.getRating() : 0 )); - } - - return diaries; - } - - public DiaryDTO entityToDiaryDTO(Diary diary){ - return new DiaryDTO(diary, 0); - } - - public DiaryDTO projectionToDiaryDTO(DiaryWithRatingsProjection projection) { - DiaryDTO diary = new DiaryDTO(); - diary.setDiary(projection.getDiary()); - diary.setRating(projection.getRating() != null ? projection.getRating() : 0 ); - - return diary; - } -} - 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..bcaccb0 --- /dev/null +++ b/src/main/java/com/petproject/boardgamefun/service/DiaryService.kt @@ -0,0 +1,26 @@ +package com.petproject.boardgamefun.service + +import com.petproject.boardgamefun.dto.projection.DiaryWithRatingsProjection +import com.petproject.boardgamefun.dto.DiaryDTO +import com.petproject.boardgamefun.model.Diary +import org.springframework.stereotype.Service +import java.util.ArrayList + +@Service +class DiaryService { + fun projectionsToDiaryDTO(projections: List): List { + val diaries: MutableList = ArrayList() + for (projection in projections) { + diaries.add(DiaryDTO(projection.diary, projection.rating)) + } + return diaries + } + + fun entityToDiaryDTO(diary: Diary): DiaryDTO { + return DiaryDTO(diary, 0.0) + } + + fun projectionToDiaryDTO(projection: DiaryWithRatingsProjection): DiaryDTO { + return DiaryDTO(projection.diary, projection.rating) + } +} \ No newline at end of file From 6e97fc3c3755ec3653a0bc1753bf4c075c39cf5a Mon Sep 17 00:00:00 2001 From: "i.i.artamonov" Date: Fri, 18 Feb 2022 13:19:27 +0400 Subject: [PATCH 066/141] Add new field to DiaryCommentDTO Added User field to DTO. Update DiaryCommentService --- .../java/com/petproject/boardgamefun/dto/DiaryCommentDTO.java | 2 ++ .../petproject/boardgamefun/service/DiaryCommentService.java | 4 ++-- 2 files changed, 4 insertions(+), 2 deletions(-) diff --git a/src/main/java/com/petproject/boardgamefun/dto/DiaryCommentDTO.java b/src/main/java/com/petproject/boardgamefun/dto/DiaryCommentDTO.java index 55d23f2..4450219 100644 --- a/src/main/java/com/petproject/boardgamefun/dto/DiaryCommentDTO.java +++ b/src/main/java/com/petproject/boardgamefun/dto/DiaryCommentDTO.java @@ -1,5 +1,6 @@ package com.petproject.boardgamefun.dto; +import com.petproject.boardgamefun.model.User; import lombok.AllArgsConstructor; import lombok.Data; @@ -11,4 +12,5 @@ public class DiaryCommentDTO { private Integer id; private String comment; private OffsetDateTime time; + private User user; } diff --git a/src/main/java/com/petproject/boardgamefun/service/DiaryCommentService.java b/src/main/java/com/petproject/boardgamefun/service/DiaryCommentService.java index 94b4354..b29febb 100644 --- a/src/main/java/com/petproject/boardgamefun/service/DiaryCommentService.java +++ b/src/main/java/com/petproject/boardgamefun/service/DiaryCommentService.java @@ -11,14 +11,14 @@ public class DiaryCommentService { public DiaryCommentDTO entityToDiaryCommentDTO(DiaryComment diaryComment) { - return new DiaryCommentDTO(diaryComment.getId(), diaryComment.getComment(), diaryComment.getCommentTime()); + return new DiaryCommentDTO(diaryComment.getId(), diaryComment.getComment(), diaryComment.getCommentTime(), 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())); + diaryCommentsDTO.add(new DiaryCommentDTO(diaryComment.getId(), diaryComment.getComment(), diaryComment.getCommentTime(), diaryComment.getUser())); } return diaryCommentsDTO; } From df6df093a81efc869ddcec9e206ecc60aa8f15f9 Mon Sep 17 00:00:00 2001 From: "i.i.artamonov" Date: Fri, 18 Feb 2022 14:10:44 +0400 Subject: [PATCH 067/141] Added changes in addDiary method in UserController Now game id we get from path variable not request body --- .../boardgamefun/controller/UserController.java | 13 +++++-------- 1 file changed, 5 insertions(+), 8 deletions(-) diff --git a/src/main/java/com/petproject/boardgamefun/controller/UserController.java b/src/main/java/com/petproject/boardgamefun/controller/UserController.java index cc68d2b..586f05a 100644 --- a/src/main/java/com/petproject/boardgamefun/controller/UserController.java +++ b/src/main/java/com/petproject/boardgamefun/controller/UserController.java @@ -336,18 +336,15 @@ public ResponseEntity updateSellGame(@RequestBody GameSell gameSell){ } @Transactional - @PostMapping("{userId}/add-diary") - public ResponseEntity addDiary(@PathVariable Integer userId, @RequestBody Diary diary){ + @PostMapping("{userId}/add-diary/{gameId}") + public ResponseEntity addDiary(@PathVariable Integer userId, @PathVariable Integer gameId, @RequestBody Diary diary){ var user = userRepository.findUserById(userId); + var game = gameRepository.findGameById(gameId); + diary.setUser(user); + diary.setGame(game); diary.setPublicationTime(OffsetDateTime.now()); - // todo: в будущем переделать без поиска в репозитории, а сразу получать весь объект, пока нет фронта - заглушка - if (diary.getGame() != null){ - var game = gameRepository.findGameById(diary.getGame().getId()); - diary.setGame(game); - } - diaryRepository.save(diary); var diaryDTO = diaryService.entityToDiaryDTO(diary); From 990b4c8ae15703783850fd73a6f25ffcc806b466 Mon Sep 17 00:00:00 2001 From: "i.i.artamonov" Date: Mon, 21 Feb 2022 13:05:20 +0400 Subject: [PATCH 068/141] Add PATCH such as allowed method Added PATCH method to cors politics --- .../com/petproject/boardgamefun/security/WebSecurityConfig.java | 1 + 1 file changed, 1 insertion(+) diff --git a/src/main/java/com/petproject/boardgamefun/security/WebSecurityConfig.java b/src/main/java/com/petproject/boardgamefun/security/WebSecurityConfig.java index df941a7..8b9f18b 100644 --- a/src/main/java/com/petproject/boardgamefun/security/WebSecurityConfig.java +++ b/src/main/java/com/petproject/boardgamefun/security/WebSecurityConfig.java @@ -73,6 +73,7 @@ public CorsFilter corsFilter() { config.addAllowedOrigin("*"); config.addAllowedHeader("*"); config.addAllowedMethod("OPTIONS"); + config.addAllowedMethod("PATCH"); config.addAllowedMethod("GET"); config.addAllowedMethod("POST"); config.addAllowedMethod("PUT"); From 0cc044463c39f42784b3b69a2fa5b377cad21d14 Mon Sep 17 00:00:00 2001 From: "i.i.artamonov" Date: Mon, 21 Feb 2022 13:33:45 +0400 Subject: [PATCH 069/141] Added roles to methods in controller Added roles to methods which can change data in data base. --- .../controller/DesignerController.java | 4 ++++ .../boardgamefun/controller/DiaryController.java | 7 +++++++ .../boardgamefun/controller/ForumController.java | 9 +++++++++ .../boardgamefun/controller/GameController.java | 11 +++++++++++ .../boardgamefun/controller/UserController.java | 15 +++++++++++++++ 5 files changed, 46 insertions(+) diff --git a/src/main/java/com/petproject/boardgamefun/controller/DesignerController.java b/src/main/java/com/petproject/boardgamefun/controller/DesignerController.java index 8ad26bd..02699aa 100644 --- a/src/main/java/com/petproject/boardgamefun/controller/DesignerController.java +++ b/src/main/java/com/petproject/boardgamefun/controller/DesignerController.java @@ -7,6 +7,7 @@ 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; @@ -42,6 +43,7 @@ public ResponseEntity getDesignerByName(@PathVariable String name){ @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()); @@ -54,6 +56,7 @@ public ResponseEntity> addDesigner(@RequestBody DesignerReques @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); @@ -67,6 +70,7 @@ public ResponseEntity> updateDesigner(@PathVariable Integer id @Transactional @DeleteMapping("/delete/{id}") + @PreAuthorize("hasRole('USER') or hasRole('MODERATOR') or hasRole('ADMIN')") public ResponseEntity> deleteDesigner(@PathVariable Integer id){ var designer = designerRepository.findDesignerById(id); diff --git a/src/main/java/com/petproject/boardgamefun/controller/DiaryController.java b/src/main/java/com/petproject/boardgamefun/controller/DiaryController.java index 7089ce9..d6a4863 100644 --- a/src/main/java/com/petproject/boardgamefun/controller/DiaryController.java +++ b/src/main/java/com/petproject/boardgamefun/controller/DiaryController.java @@ -16,6 +16,7 @@ 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; @@ -79,6 +80,7 @@ public ResponseEntity> getDiaryComments(@PathVariable Inte @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); @@ -98,6 +100,7 @@ public ResponseEntity> addComment(@PathVariable Integer di @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())) { @@ -112,6 +115,7 @@ public ResponseEntity> updateComment(@PathVariable Integer @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); @@ -123,6 +127,7 @@ public ResponseEntity> deleteComment(@PathVariable Integer @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); @@ -140,6 +145,7 @@ public ResponseEntity setDiaryRating(@PathVariable Integer diary @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); @@ -155,6 +161,7 @@ public ResponseEntity updateDiaryRating(@PathVariable Integer ra @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); diff --git a/src/main/java/com/petproject/boardgamefun/controller/ForumController.java b/src/main/java/com/petproject/boardgamefun/controller/ForumController.java index c3a6ecb..b441e5c 100644 --- a/src/main/java/com/petproject/boardgamefun/controller/ForumController.java +++ b/src/main/java/com/petproject/boardgamefun/controller/ForumController.java @@ -13,6 +13,7 @@ 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; @@ -67,6 +68,7 @@ public ResponseEntity getForum(@PathVariable Integer forumId) { @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); @@ -88,6 +90,7 @@ public ResponseEntity addForum(@PathVariable Integer gameId, @PathVari @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); @@ -106,6 +109,7 @@ public ResponseEntity updateForum(@PathVariable Integer forumId, @Requ @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); @@ -131,6 +135,7 @@ else if (userId != null) @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); @@ -152,6 +157,7 @@ public ResponseEntity> addMessage(@PathVariable Integer fo @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); @@ -167,6 +173,7 @@ public ResponseEntity> updateMessage(@PathVariable Integer @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); @@ -178,6 +185,7 @@ public ResponseEntity> deleteMessage(@PathVariable Integer @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); @@ -198,6 +206,7 @@ public ResponseEntity setForumRating(@PathVariable Integer forumId, @P @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); diff --git a/src/main/java/com/petproject/boardgamefun/controller/GameController.java b/src/main/java/com/petproject/boardgamefun/controller/GameController.java index be4eb27..8cff09d 100644 --- a/src/main/java/com/petproject/boardgamefun/controller/GameController.java +++ b/src/main/java/com/petproject/boardgamefun/controller/GameController.java @@ -11,6 +11,7 @@ import com.petproject.boardgamefun.service.GameService; import org.springframework.http.HttpStatus; import org.springframework.http.ResponseEntity; +import org.springframework.security.access.prepost.PreAuthorize; import org.springframework.transaction.annotation.Transactional; import org.springframework.web.bind.annotation.*; import org.springframework.web.multipart.MultipartFile; @@ -66,6 +67,7 @@ public ResponseEntity> getGamesByTitle(@PathVariable String @Transactional @PostMapping("/add") + @PreAuthorize("hasRole('MODERATOR') or hasRole('ADMIN')") public ResponseEntity addGame(@RequestBody Game newGame) { gameRepository.save(newGame); var game = gameService.entityToGameDTO(newGame); @@ -75,6 +77,7 @@ public ResponseEntity addGame(@RequestBody Game newGame) { @Transactional @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 game = gameRepository.findGameById(gameId); game.setPicture(file.getBytes()); @@ -85,6 +88,7 @@ public ResponseEntity uploadImage(@PathVariable Integer gameId, @Reques @Transactional @PutMapping("/update") + @PreAuthorize("hasRole('MODERATOR') or hasRole('ADMIN')") public ResponseEntity updateGame(@RequestBody Game updatedGame) { gameRepository.save(updatedGame); var game = gameService.entityToGameDTO(updatedGame); @@ -93,6 +97,7 @@ public ResponseEntity updateGame(@RequestBody Game updatedGame) { @Transactional @DeleteMapping("/remove") + @PreAuthorize("hasRole('MODERATOR') or hasRole('ADMIN')") public ResponseEntity removeGameFromSite(@RequestBody Game deleteGame) { gameRepository.delete(deleteGame); @@ -109,6 +114,7 @@ public ResponseEntity> getExpansions(@PathVariable Integer gameId) @Transactional @PostMapping("/add-expansion/{parentGameId}/{daughterGameId}") + @PreAuthorize("hasRole('USER') or hasRole('MODERATOR') or hasRole('ADMIN')") public ResponseEntity> addExpansion(@PathVariable Integer parentGameId, @PathVariable Integer daughterGameId) { var parentGame = gameRepository.findGameById(parentGameId); var daughterGame = gameRepository.findGameById(daughterGameId); @@ -125,6 +131,7 @@ public ResponseEntity> addExpansion(@PathVariable Integer parentGa @Transactional @DeleteMapping("/delete-expansion/{parentGameId}/{daughterGameId}") + @PreAuthorize("hasRole('USER') or hasRole('MODERATOR') or hasRole('ADMIN')") public ResponseEntity> deleteExpansion(@PathVariable Integer daughterGameId, @PathVariable Integer parentGameId) { var expansion = expansionRepository.findExpansion_ByDaughterGameIdAndParentGameId(daughterGameId, parentGameId); expansionRepository.delete(expansion); @@ -144,6 +151,7 @@ public ResponseEntity> getSimilarGames(@PathVariable Integer gameI @Transactional @PostMapping("/add-similar/{referenceGameId}/{sourceGameId}") + @PreAuthorize("hasRole('USER') or hasRole('MODERATOR') or hasRole('ADMIN')") public ResponseEntity> addSimilarGame(@PathVariable Integer referenceGameId, @PathVariable Integer sourceGameId) { var referenceGame = gameRepository.findGameById(referenceGameId); var sourceGame = gameRepository.findGameById(sourceGameId); @@ -160,6 +168,7 @@ public ResponseEntity> addSimilarGame(@PathVariable Integer refere @Transactional @DeleteMapping("/delete-similar/{referenceGameId}/{sourceGameId}") + @PreAuthorize("hasRole('USER') or hasRole('MODERATOR') or hasRole('ADMIN')") public ResponseEntity> deleteSameGame(@PathVariable Integer referenceGameId, @PathVariable Integer sourceGameId) { var sameGame = sameGameRepository.findSameGame_ByReferenceGameIdAndSourceGameId(referenceGameId, sourceGameId); sameGameRepository.delete(sameGame); @@ -182,6 +191,7 @@ public ResponseEntity> getUsersRating(@PathVariable Int @Transactional @PostMapping("/{gameId}/set-designer/{designerId}") + @PreAuthorize("hasRole('USER') or hasRole('MODERATOR') or hasRole('ADMIN')") public ResponseEntity addDesignerToGame(@PathVariable Integer gameId, @PathVariable Integer designerId) { var game = gameRepository.findGameById(gameId); var designer = designerRepository.findDesignerById(designerId); @@ -200,6 +210,7 @@ public ResponseEntity addDesignerToGame(@PathVariable Integer gameId, @ @Transactional @DeleteMapping("{gameId}/remove-designer/{gameByDesignerId}") + @PreAuthorize("hasRole('USER') or hasRole('MODERATOR') or hasRole('ADMIN')") public ResponseEntity deleteDesignerFromGame(@PathVariable Integer gameId, @PathVariable Integer gameByDesignerId) { gameByDesignerRepository.deleteById(gameByDesignerId); diff --git a/src/main/java/com/petproject/boardgamefun/controller/UserController.java b/src/main/java/com/petproject/boardgamefun/controller/UserController.java index 586f05a..a44b3e1 100644 --- a/src/main/java/com/petproject/boardgamefun/controller/UserController.java +++ b/src/main/java/com/petproject/boardgamefun/controller/UserController.java @@ -19,6 +19,7 @@ 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; @@ -127,6 +128,7 @@ public ResponseEntity uploadAvatar(@PathVariable String userName, @Reque @Transactional @PatchMapping("/edit/{userId}") + @PreAuthorize("hasRole('USER') or hasRole('MODERATOR') or hasRole('ADMIN')") public ResponseEntity editUser(@PathVariable Integer userId, @RequestBody UserEditRequest userEditRequest){ var user = userRepository.findUserById(userId); if (userEditRequest.getName() != null && !userRepository.existsByName(userEditRequest.getName())) { @@ -146,6 +148,7 @@ public ResponseEntity editUser(@PathVariable Integer userId, @RequestBody Use @Transactional @PatchMapping("/change-password/{userId}") + @PreAuthorize("hasRole('USER') or hasRole('MODERATOR') or hasRole('ADMIN')") public ResponseEntity changePassword(@PathVariable Integer userId, @RequestBody PasswordChangeRequest passwordRequest){ var user = userRepository.findUserById(userId); if (passwordRequest.getPassword() != null && passwordEncoder.matches(passwordRequest.getPassword(), user.getPassword())){ @@ -177,6 +180,7 @@ public ResponseEntity> getUserCollection(@PathVariable Integer id) @Transactional @PostMapping("{userId}/add-game/{gameId}") + @PreAuthorize("hasRole('USER') or hasRole('MODERATOR') or hasRole('ADMIN')") public ResponseEntity addGameToUser(@PathVariable Integer userId, @PathVariable Integer gameId) { var user = userRepository.findUserById(userId); @@ -193,6 +197,7 @@ public ResponseEntity addGameToUser(@PathVariable Integer userId, @PathVariab @Transactional @DeleteMapping("{userId}/delete-game/{gameId}") + @PreAuthorize("hasRole('USER') or hasRole('MODERATOR') or hasRole('ADMIN')") public ResponseEntity deleteGameFromUserCollection(@PathVariable Integer userId, @PathVariable Integer gameId) { var userOwnGame = userOwnGameRepository.findUserOwnGame_ByGameIdAndUserId(gameId, userId); @@ -212,6 +217,7 @@ public ResponseEntity> getUserRatingList(@PathVariable Integer use @Transactional @DeleteMapping("/{userId}/delete-game-rating/{gameId}") + @PreAuthorize("hasRole('USER') or hasRole('MODERATOR') or hasRole('ADMIN')") public ResponseEntity deleteGameRating(@PathVariable Integer userId, @PathVariable Integer gameId) { var ratingGameByUser = ratingGameByUserRepository.findRatingGame_ByGameIdAndUserId(gameId, userId); @@ -223,6 +229,7 @@ public ResponseEntity deleteGameRating(@PathVariable Integer userId, @Pa @Transactional @PostMapping("/{userId}/set-game-rating/{gameId}/{rating}") + @PreAuthorize("hasRole('USER') or hasRole('MODERATOR') or hasRole('ADMIN')") public ResponseEntity setGameRating(@PathVariable Integer userId, @PathVariable Integer gameId, @PathVariable Integer rating) { var ratingGameByUser = ratingGameByUserRepository.findRatingGame_ByGameIdAndUserId(gameId, userId); @@ -252,6 +259,7 @@ public ResponseEntity> getUserWishlist(@PathVariable Integer id) { @Transactional @PostMapping("{userId}/add-game-to-wishlist/{gameId}") + @PreAuthorize("hasRole('USER') or hasRole('MODERATOR') or hasRole('ADMIN')") public ResponseEntity addGameToUserWishlist(@PathVariable Integer userId, @PathVariable Integer gameId) { var user = userRepository.findUserById(userId); @@ -268,6 +276,7 @@ public ResponseEntity addGameToUserWishlist(@PathVariable Integer userId, @Pa @Transactional @DeleteMapping("{userId}/delete-game-from-wishlist/{gameId}") + @PreAuthorize("hasRole('USER') or hasRole('MODERATOR') or hasRole('ADMIN')") public ResponseEntity deleteGameFromUserWishlist(@PathVariable Integer userId, @PathVariable Integer gameId) { var user = userRepository.findUserById(userId); @@ -282,6 +291,7 @@ public ResponseEntity deleteGameFromUserWishlist(@PathVariable Integer userId @Transactional @PostMapping("{userId}/add-game-to-sell/{gameId}") + @PreAuthorize("hasRole('USER') or hasRole('MODERATOR') or hasRole('ADMIN')") public ResponseEntity> addGameToSellList(@PathVariable Integer userId, @PathVariable Integer gameId, @RequestBody GameSell gameSell){ var user = userRepository.findUserById(userId); @@ -308,6 +318,7 @@ public ResponseEntity> getGameSellList(@PathVariable Integer u @Transactional @DeleteMapping("{userId}/remove-game-from-sell/{gameId}") + @PreAuthorize("hasRole('USER') or hasRole('MODERATOR') or hasRole('ADMIN')") public ResponseEntity removeGameFromSell(@PathVariable Integer userId, @PathVariable Integer gameId){ var gameSell = gameSellRepository.findGameSell_ByGameIdAndUserId(gameId, userId); @@ -318,6 +329,7 @@ public ResponseEntity removeGameFromSell(@PathVariable Integer userId, @Transactional @PutMapping("/update-game-to-sell") + @PreAuthorize("hasRole('USER') or hasRole('MODERATOR') or hasRole('ADMIN')") public ResponseEntity updateSellGame(@RequestBody GameSell gameSell){ if (gameSell.getComment() != null){ @@ -337,6 +349,7 @@ public ResponseEntity updateSellGame(@RequestBody GameSell gameSell){ @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){ var user = userRepository.findUserById(userId); @@ -354,6 +367,7 @@ public ResponseEntity addDiary(@PathVariable Integer userId, @PathVari @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); @@ -365,6 +379,7 @@ public ResponseEntity deleteDiary(@PathVariable Integer userId, @PathVar @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){ var diary = diaryRepository.findDiary_ByUserIdAndId(userId, diaryId); From 3c4202499b66d27ecbce12a218dd7d2e27b86674 Mon Sep 17 00:00:00 2001 From: "i.i.artamonov" Date: Tue, 22 Feb 2022 11:11:17 +0400 Subject: [PATCH 070/141] Add refresh token Add refreshToken method to UserController. Add TokenControllerAdvice for catching unauthorized errors. Add custom exception for unauthorized http status. Add ErrorMessage model. Add refreshToken field to JwtResponse. Add RefreshTokenRequest and RefresgTokenResponse. Add RefreshTokenService for generating token and verify it. Edit todos --- pom.xml | 2 - .../controller/UserController.java | 61 ++++++++++++------- .../controller/TokenControllerAdvice.java | 24 ++++++++ .../exception/RefreshTokenException.java | 12 ++++ .../boardgamefun/security/jwt/JwtUtils.java | 8 +++ .../security/model/ErrorMessage.java | 15 +++++ .../security/model/JwtResponse.java | 4 +- .../security/model/RefreshTokenRequest.java | 9 +++ .../security/model/RefreshTokenResponse.java | 15 +++++ 9 files changed, 124 insertions(+), 26 deletions(-) create mode 100644 src/main/java/com/petproject/boardgamefun/security/controller/TokenControllerAdvice.java create mode 100644 src/main/java/com/petproject/boardgamefun/security/exception/RefreshTokenException.java create mode 100644 src/main/java/com/petproject/boardgamefun/security/model/ErrorMessage.java create mode 100644 src/main/java/com/petproject/boardgamefun/security/model/RefreshTokenRequest.java create mode 100644 src/main/java/com/petproject/boardgamefun/security/model/RefreshTokenResponse.java diff --git a/pom.xml b/pom.xml index 8234ca0..8a916c0 100644 --- a/pom.xml +++ b/pom.xml @@ -17,8 +17,6 @@ 17 1.6.20-M1 - - diff --git a/src/main/java/com/petproject/boardgamefun/controller/UserController.java b/src/main/java/com/petproject/boardgamefun/controller/UserController.java index a44b3e1..de045f6 100644 --- a/src/main/java/com/petproject/boardgamefun/controller/UserController.java +++ b/src/main/java/com/petproject/boardgamefun/controller/UserController.java @@ -12,6 +12,9 @@ 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.DiaryService; import com.petproject.boardgamefun.service.GameSellService; @@ -50,9 +53,11 @@ public class UserController { final GameService gameService; final UserService userService; + final PasswordEncoder passwordEncoder; final JwtUtils jwtUtils; final AuthenticationManager authenticationManager; + final RefreshTokenService refreshTokenService; public UserController(GameRepository gameRepository, UserRepository userRepository, @@ -61,7 +66,7 @@ public UserController(GameRepository gameRepository, UserWishRepository userWishRepository, GameSellRepository gameSellRepository, DiaryRepository diaryRepository, DiaryService diaryService, GameSellService gameSellService, GameService gameService, UserService userService, PasswordEncoder passwordEncoder, JwtUtils jwtUtils, - AuthenticationManager authenticationManager) { + AuthenticationManager authenticationManager, RefreshTokenService refreshTokenService) { this.gameRepository = gameRepository; this.userRepository = userRepository; this.userOwnGameRepository = userOwnGameRepository; @@ -76,6 +81,7 @@ public UserController(GameRepository gameRepository, this.passwordEncoder = passwordEncoder; this.jwtUtils = jwtUtils; this.authenticationManager = authenticationManager; + this.refreshTokenService = refreshTokenService; } @GetMapping() @@ -95,7 +101,8 @@ public ResponseEntity authenticateUser(@RequestBody LoginRequest loginRequest String jwt = jwtUtils.generateJwtToken(authentication); UserDetailsImpl userDetails = (UserDetailsImpl) authentication.getPrincipal(); - return new ResponseEntity<>(new JwtResponse(jwt, userDetails.getId(), userDetails.getUsername(), userDetails.getEmail()), HttpStatus.OK); + var refreshToken = refreshTokenService.createRefreshToken(loginRequest.getName()); + return new ResponseEntity<>(new JwtResponse(jwt, userDetails.getId(), userDetails.getUsername(), userDetails.getEmail(), refreshToken), HttpStatus.OK); } @PostMapping("/sign-up") @@ -116,6 +123,16 @@ public ResponseEntity registerUser(@RequestBody User 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); + } + @Transactional @PostMapping("/upload-avatar/{userName}") public ResponseEntity uploadAvatar(@PathVariable String userName, @RequestParam("avatar") MultipartFile file) throws IOException { @@ -124,20 +141,19 @@ public ResponseEntity uploadAvatar(@PathVariable String userName, @Reque userRepository.save(user); return new ResponseEntity<>(HttpStatus.OK); } - + @Transactional @PatchMapping("/edit/{userId}") @PreAuthorize("hasRole('USER') or hasRole('MODERATOR') or hasRole('ADMIN')") - public ResponseEntity editUser(@PathVariable Integer userId, @RequestBody UserEditRequest userEditRequest){ + public ResponseEntity editUser(@PathVariable Integer userId, @RequestBody UserEditRequest userEditRequest) { var user = userRepository.findUserById(userId); if (userEditRequest.getName() != null && !userRepository.existsByName(userEditRequest.getName())) { user.setName(userEditRequest.getName()); - } - else{ + } else { return new ResponseEntity<>("Пользователь с таким никнеймом уже существует", HttpStatus.BAD_REQUEST); } - if (userEditRequest.getRole() != null && !Objects.equals(userEditRequest.getRole(), user.getRole())){ + if (userEditRequest.getRole() != null && !Objects.equals(userEditRequest.getRole(), user.getRole())) { user.setRole(userEditRequest.getRole()); } @@ -149,12 +165,11 @@ public ResponseEntity editUser(@PathVariable Integer userId, @RequestBody Use @Transactional @PatchMapping("/change-password/{userId}") @PreAuthorize("hasRole('USER') or hasRole('MODERATOR') or hasRole('ADMIN')") - public ResponseEntity changePassword(@PathVariable Integer userId, @RequestBody PasswordChangeRequest passwordRequest){ + public ResponseEntity changePassword(@PathVariable Integer userId, @RequestBody PasswordChangeRequest passwordRequest) { var user = userRepository.findUserById(userId); - if (passwordRequest.getPassword() != null && passwordEncoder.matches(passwordRequest.getPassword(), user.getPassword())){ + if (passwordRequest.getPassword() != null && passwordEncoder.matches(passwordRequest.getPassword(), user.getPassword())) { user.setPassword(passwordEncoder.encode(passwordRequest.getPassword())); - } - else { + } else { return new ResponseEntity<>("Вы ввели точно такой же пароль", HttpStatus.BAD_REQUEST); } userRepository.save(user); @@ -292,7 +307,7 @@ public ResponseEntity deleteGameFromUserWishlist(@PathVariable Integer userId @Transactional @PostMapping("{userId}/add-game-to-sell/{gameId}") @PreAuthorize("hasRole('USER') or hasRole('MODERATOR') or hasRole('ADMIN')") - public ResponseEntity> addGameToSellList(@PathVariable Integer userId, @PathVariable Integer gameId, @RequestBody GameSell gameSell){ + public ResponseEntity> addGameToSellList(@PathVariable Integer userId, @PathVariable Integer gameId, @RequestBody GameSell gameSell) { var user = userRepository.findUserById(userId); var game = gameRepository.findGameById(gameId); @@ -308,18 +323,18 @@ public ResponseEntity> addGameToSellList(@PathVariable Integer @Transactional @GetMapping("{userId}/games-to-sell") - public ResponseEntity> getGameSellList(@PathVariable Integer userId){ + public ResponseEntity> getGameSellList(@PathVariable Integer userId) { var gameSellList = gameSellService.projectionsToGameSellDTO(gameRepository.getGameSellList(userId)); - return new ResponseEntity<>(gameSellList,HttpStatus.OK); + return new ResponseEntity<>(gameSellList, HttpStatus.OK); } @Transactional @DeleteMapping("{userId}/remove-game-from-sell/{gameId}") @PreAuthorize("hasRole('USER') or hasRole('MODERATOR') or hasRole('ADMIN')") - public ResponseEntity removeGameFromSell(@PathVariable Integer userId, @PathVariable Integer gameId){ + public ResponseEntity removeGameFromSell(@PathVariable Integer userId, @PathVariable Integer gameId) { var gameSell = gameSellRepository.findGameSell_ByGameIdAndUserId(gameId, userId); gameSellRepository.delete(gameSell); @@ -330,15 +345,15 @@ public ResponseEntity removeGameFromSell(@PathVariable Integer userId, @Transactional @PutMapping("/update-game-to-sell") @PreAuthorize("hasRole('USER') or hasRole('MODERATOR') or hasRole('ADMIN')") - public ResponseEntity updateSellGame(@RequestBody GameSell gameSell){ + public ResponseEntity updateSellGame(@RequestBody GameSell gameSell) { - if (gameSell.getComment() != null){ + if (gameSell.getComment() != null) { gameSell.setComment(gameSell.getComment()); } - if (gameSell.getPrice() != null){ + if (gameSell.getPrice() != null) { gameSell.setPrice(gameSell.getPrice()); } - if (gameSell.getCondition() != null){ + if (gameSell.getCondition() != null) { gameSell.setCondition(gameSell.getCondition()); } @@ -350,7 +365,7 @@ public ResponseEntity updateSellGame(@RequestBody GameSell gameSell){ @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){ + public ResponseEntity addDiary(@PathVariable Integer userId, @PathVariable Integer gameId, @RequestBody Diary diary) { var user = userRepository.findUserById(userId); var game = gameRepository.findGameById(gameId); @@ -368,7 +383,7 @@ public ResponseEntity addDiary(@PathVariable Integer userId, @PathVari @Transactional @DeleteMapping("{userId}/remove-diary/{diaryId}") @PreAuthorize("hasRole('USER') or hasRole('MODERATOR') or hasRole('ADMIN')") - public ResponseEntity deleteDiary(@PathVariable Integer userId, @PathVariable Integer diaryId){ + public ResponseEntity deleteDiary(@PathVariable Integer userId, @PathVariable Integer diaryId) { var diary = diaryRepository.findDiary_ByUserIdAndId(userId, diaryId); @@ -380,10 +395,10 @@ public ResponseEntity deleteDiary(@PathVariable Integer userId, @PathVar @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){ + public ResponseEntity updateDiary(@PathVariable Integer diaryId, @PathVariable Integer userId, @RequestBody Diary diaryRequest) { var diary = diaryRepository.findDiary_ByUserIdAndId(userId, diaryId); - if (diaryRequest.getTitle() != null && !Objects.equals(diary.getTitle(), diaryRequest.getTitle())){ + if (diaryRequest.getTitle() != null && !Objects.equals(diary.getTitle(), diaryRequest.getTitle())) { diary.setTitle(diaryRequest.getTitle()); } if (diaryRequest.getText() != null && !Objects.equals(diary.getText(), diaryRequest.getText())) { 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/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/JwtUtils.java b/src/main/java/com/petproject/boardgamefun/security/jwt/JwtUtils.java index 3e85272..250a371 100644 --- a/src/main/java/com/petproject/boardgamefun/security/jwt/JwtUtils.java +++ b/src/main/java/com/petproject/boardgamefun/security/jwt/JwtUtils.java @@ -31,6 +31,14 @@ public String generateJwtToken(Authentication authentication) { .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(); 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 index b4fca3f..e80ddc7 100644 --- a/src/main/java/com/petproject/boardgamefun/security/model/JwtResponse.java +++ b/src/main/java/com/petproject/boardgamefun/security/model/JwtResponse.java @@ -9,11 +9,13 @@ public class JwtResponse { private Integer id; private String userName; private String email; + private String refreshToken; - public JwtResponse(String jwt, Integer id, String username, String email) { + 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/RefreshTokenRequest.java b/src/main/java/com/petproject/boardgamefun/security/model/RefreshTokenRequest.java new file mode 100644 index 0000000..00dd3ae --- /dev/null +++ b/src/main/java/com/petproject/boardgamefun/security/model/RefreshTokenRequest.java @@ -0,0 +1,9 @@ +package com.petproject.boardgamefun.security.model; + +import lombok.Data; + +@Data +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; + } +} From e267cf807cddc692ea532208d3938a1cecdf0e6b Mon Sep 17 00:00:00 2001 From: "i.i.artamonov" Date: Tue, 22 Feb 2022 11:11:56 +0400 Subject: [PATCH 071/141] Forgotten staged files form commit below --- .../services/RefreshTokenService.java | 38 +++++++++++++++++++ src/main/resources/application.properties | 4 +- 2 files changed, 41 insertions(+), 1 deletion(-) create mode 100644 src/main/java/com/petproject/boardgamefun/security/services/RefreshTokenService.java 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..37a508c --- /dev/null +++ b/src/main/java/com/petproject/boardgamefun/security/services/RefreshTokenService.java @@ -0,0 +1,38 @@ +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); + 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/resources/application.properties b/src/main/resources/application.properties index 757cfe9..1c724d3 100644 --- a/src/main/resources/application.properties +++ b/src/main/resources/application.properties @@ -6,4 +6,6 @@ spring.datasource.password=1 # App Properties boardgamefun.app.jwtSecret = PetProjectSecretKey -boardgamefun.app.jwtExpirationMs = 86400000 \ No newline at end of file +boardgamefun.app.jwtExpirationMs = 600000 +boardgamefun.app.jwtRefreshSecret = PetProjectRefreshKey +boardgamefun.app.refreshTokenExpirationMs = 86400000 From 16c4cd3d73edcc209b046bc9a974dee5d6f90764 Mon Sep 17 00:00:00 2001 From: "i.i.artamonov" Date: Tue, 1 Mar 2022 10:43:55 +0400 Subject: [PATCH 072/141] Added test for return status in getUser method --- pom.xml | 12 ++++++ .../controller/UserController.java | 8 ++-- .../SpringSecurityWebTestConfig.java | 30 +++++++++++++++ .../boardgamefun/UserControllerTests.java | 37 +++++++++++++++++++ 4 files changed, 84 insertions(+), 3 deletions(-) create mode 100644 src/test/java/com/petproject/boardgamefun/SpringSecurityWebTestConfig.java create mode 100644 src/test/java/com/petproject/boardgamefun/UserControllerTests.java diff --git a/pom.xml b/pom.xml index 8a916c0..5daa36f 100644 --- a/pom.xml +++ b/pom.xml @@ -17,6 +17,7 @@ 17 1.6.20-M1 + @@ -111,6 +112,17 @@ ${kotlin.version} test + + org.springframework.security + spring-security-test + 5.5.3 + test + + + junit + junit + test + diff --git a/src/main/java/com/petproject/boardgamefun/controller/UserController.java b/src/main/java/com/petproject/boardgamefun/controller/UserController.java index de045f6..e0c1643 100644 --- a/src/main/java/com/petproject/boardgamefun/controller/UserController.java +++ b/src/main/java/com/petproject/boardgamefun/controller/UserController.java @@ -181,8 +181,11 @@ public ResponseEntity changePassword(@PathVariable Integer userId, @RequestBo @Transactional @GetMapping("{id}") public ResponseEntity getUser(@PathVariable Integer id) { - var user = userService.entityToUserDTO(userRepository.findUserById(id)); - return new ResponseEntity<>(user, HttpStatus.OK); + var userDTO = userService.entityToUserDTO(userRepository.findUserById(id)); + if (userDTO.getUser() == null){ + return new ResponseEntity<>(null, HttpStatus.NOT_FOUND); + } + return new ResponseEntity<>(userDTO, HttpStatus.OK); } @Transactional @@ -414,7 +417,6 @@ public ResponseEntity updateDiary(@PathVariable Integer diaryId, @Path //todo: optimize response - not whole model, only needed fields //todo: add news - //todo: add rights //todo: unique repository??? } 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/UserControllerTests.java b/src/test/java/com/petproject/boardgamefun/UserControllerTests.java new file mode 100644 index 0000000..4b3759e --- /dev/null +++ b/src/test/java/com/petproject/boardgamefun/UserControllerTests.java @@ -0,0 +1,37 @@ +package com.petproject.boardgamefun; + +import static org.springframework.test.web.servlet.result.MockMvcResultHandlers.print; +import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status; +import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.content; + +import org.junit.Test; +import org.junit.runner.RunWith; +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.test.context.junit4.SpringRunner; +import org.springframework.test.web.servlet.MockMvc; +import org.springframework.test.web.servlet.request.MockMvcRequestBuilders; + + +@RunWith(SpringRunner.class) +@SpringBootTest( + webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT, + classes = SpringSecurityWebTestConfig.class +) +@AutoConfigureMockMvc +public class UserControllerTests { + + @Autowired + private MockMvc mockMvc; + + @Test + public void getUserShouldReturnStatusOkTest() throws Exception { + this.mockMvc.perform(MockMvcRequestBuilders.get("/users/1")).andDo(print()).andExpect(status().isOk()); + } + + @Test + public void getUserShouldReturnStatusNotFound() throws Exception{ + this.mockMvc.perform(MockMvcRequestBuilders.get("/users/-1")).andDo(print()).andExpect(status().isNotFound()); + } +} From fb9dac58fcf30bc2244c7788d9c42f470e47d199 Mon Sep 17 00:00:00 2001 From: "i.i.artamonov" Date: Tue, 1 Mar 2022 10:56:41 +0400 Subject: [PATCH 073/141] Added verifying path value in getUserMethod --- .../petproject/boardgamefun/UserControllerTests.java | 11 ++++++++++- 1 file changed, 10 insertions(+), 1 deletion(-) diff --git a/src/test/java/com/petproject/boardgamefun/UserControllerTests.java b/src/test/java/com/petproject/boardgamefun/UserControllerTests.java index 4b3759e..2ee5477 100644 --- a/src/test/java/com/petproject/boardgamefun/UserControllerTests.java +++ b/src/test/java/com/petproject/boardgamefun/UserControllerTests.java @@ -4,6 +4,7 @@ import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status; import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.content; +import com.fasterxml.jackson.databind.ObjectMapper; import org.junit.Test; import org.junit.runner.RunWith; import org.springframework.beans.factory.annotation.Autowired; @@ -25,13 +26,21 @@ public class UserControllerTests { @Autowired private MockMvc mockMvc; + @Autowired + private ObjectMapper objectMapper; + @Test public void getUserShouldReturnStatusOkTest() throws Exception { this.mockMvc.perform(MockMvcRequestBuilders.get("/users/1")).andDo(print()).andExpect(status().isOk()); } @Test - public void getUserShouldReturnStatusNotFound() throws Exception{ + public void getUserShouldReturnStatusNotFound() throws Exception { this.mockMvc.perform(MockMvcRequestBuilders.get("/users/-1")).andDo(print()).andExpect(status().isNotFound()); } + + @Test + public void whenBadPathValueReturn400() throws Exception { + mockMvc.perform(MockMvcRequestBuilders.get("/users/{userId}", "userId")).andExpect(status().isBadRequest()); + } } From 2c94fe09afe2c4bb0226f7d025fd1cca19e9cd1e Mon Sep 17 00:00:00 2001 From: "i.i.artamonov" Date: Thu, 3 Mar 2022 13:24:39 +0400 Subject: [PATCH 074/141] Added test for verifying output of getUserMethod Add dependency jackson-datatype-jsr310 for mapping DateTime fields. Add noargconstructor annotation to UserDTO. --- pom.xml | 4 +++ .../petproject/boardgamefun/dto/UserDTO.java | 2 ++ .../boardgamefun/UserControllerTests.java | 26 +++++++++++++++++-- 3 files changed, 30 insertions(+), 2 deletions(-) diff --git a/pom.xml b/pom.xml index 5daa36f..b028f14 100644 --- a/pom.xml +++ b/pom.xml @@ -64,6 +64,10 @@ org.springframework.boot spring-boot-starter-webflux + + com.fasterxml.jackson.datatype + jackson-datatype-jsr310 + org.springframework.boot diff --git a/src/main/java/com/petproject/boardgamefun/dto/UserDTO.java b/src/main/java/com/petproject/boardgamefun/dto/UserDTO.java index 1471958..fd01898 100644 --- a/src/main/java/com/petproject/boardgamefun/dto/UserDTO.java +++ b/src/main/java/com/petproject/boardgamefun/dto/UserDTO.java @@ -3,9 +3,11 @@ import com.petproject.boardgamefun.model.User; import lombok.AllArgsConstructor; import lombok.Data; +import lombok.NoArgsConstructor; @Data @AllArgsConstructor +@NoArgsConstructor public class UserDTO { private User user; } diff --git a/src/test/java/com/petproject/boardgamefun/UserControllerTests.java b/src/test/java/com/petproject/boardgamefun/UserControllerTests.java index 2ee5477..c7a486e 100644 --- a/src/test/java/com/petproject/boardgamefun/UserControllerTests.java +++ b/src/test/java/com/petproject/boardgamefun/UserControllerTests.java @@ -5,6 +5,8 @@ import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.content; import com.fasterxml.jackson.databind.ObjectMapper; +import com.petproject.boardgamefun.dto.UserDTO; +import com.petproject.boardgamefun.model.User; import org.junit.Test; import org.junit.runner.RunWith; import org.springframework.beans.factory.annotation.Autowired; @@ -12,8 +14,10 @@ import org.springframework.boot.test.context.SpringBootTest; import org.springframework.test.context.junit4.SpringRunner; import org.springframework.test.web.servlet.MockMvc; +import org.springframework.test.web.servlet.MvcResult; import org.springframework.test.web.servlet.request.MockMvcRequestBuilders; +import static org.junit.Assert.*; @RunWith(SpringRunner.class) @SpringBootTest( @@ -26,8 +30,6 @@ public class UserControllerTests { @Autowired private MockMvc mockMvc; - @Autowired - private ObjectMapper objectMapper; @Test public void getUserShouldReturnStatusOkTest() throws Exception { @@ -43,4 +45,24 @@ public void getUserShouldReturnStatusNotFound() throws Exception { public void whenBadPathValueReturn400() throws Exception { mockMvc.perform(MockMvcRequestBuilders.get("/users/{userId}", "userId")).andExpect(status().isBadRequest()); } + + @Test + public void whenValidInput_thenReturnUserResource() throws Exception { + + User admin = new User(); + admin.setName("Admin"); + admin.setRole("ROLE_ADMIN"); + admin.setMail("chupacabra@mail.ru"); + + MvcResult mvcResult = mockMvc.perform(MockMvcRequestBuilders.get("/users/{userId}", "1")).andExpect(status().isOk()).andReturn(); + + ObjectMapper mapper = new ObjectMapper(); + mapper.findAndRegisterModules(); + + UserDTO userResponse = mapper.readValue(mvcResult.getResponse().getContentAsByteArray(), UserDTO.class); + + assertEquals(userResponse.getUser().getName(), admin.getName()); + assertEquals(userResponse.getUser().getMail(), admin.getMail()); + assertEquals(userResponse.getUser().getRole(), admin.getRole()); + } } From 6c477e3ec5b218ccaca6f74328e89954a0e6b4e3 Mon Sep 17 00:00:00 2001 From: "i.i.artamonov" Date: Thu, 3 Mar 2022 14:48:52 +0400 Subject: [PATCH 075/141] Updated annotations to junit 5 --- .../boardgamefun/UserControllerTests.java | 35 +++++++++++-------- 1 file changed, 20 insertions(+), 15 deletions(-) diff --git a/src/test/java/com/petproject/boardgamefun/UserControllerTests.java b/src/test/java/com/petproject/boardgamefun/UserControllerTests.java index c7a486e..299486f 100644 --- a/src/test/java/com/petproject/boardgamefun/UserControllerTests.java +++ b/src/test/java/com/petproject/boardgamefun/UserControllerTests.java @@ -7,21 +7,23 @@ import com.fasterxml.jackson.databind.ObjectMapper; import com.petproject.boardgamefun.dto.UserDTO; import com.petproject.boardgamefun.model.User; -import org.junit.Test; -import org.junit.runner.RunWith; + +import org.junit.jupiter.api.Assertions; +import org.junit.jupiter.api.Test; +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.test.context.junit4.SpringRunner; import org.springframework.test.web.servlet.MockMvc; import org.springframework.test.web.servlet.MvcResult; import org.springframework.test.web.servlet.request.MockMvcRequestBuilders; -import static org.junit.Assert.*; -@RunWith(SpringRunner.class) + +@ExtendWith(MockitoExtension.class) @SpringBootTest( - webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT, + webEnvironment = SpringBootTest.WebEnvironment.MOCK, classes = SpringSecurityWebTestConfig.class ) @AutoConfigureMockMvc @@ -30,6 +32,12 @@ public class UserControllerTests { @Autowired private MockMvc mockMvc; + ObjectMapper objectMapper; + + public UserControllerTests(){ + objectMapper = new ObjectMapper(); + objectMapper.findAndRegisterModules(); + } @Test public void getUserShouldReturnStatusOkTest() throws Exception { @@ -42,12 +50,12 @@ public void getUserShouldReturnStatusNotFound() throws Exception { } @Test - public void whenBadPathValueReturn400() throws Exception { + public void getUserWhenBadPathValueReturn400() throws Exception { mockMvc.perform(MockMvcRequestBuilders.get("/users/{userId}", "userId")).andExpect(status().isBadRequest()); } @Test - public void whenValidInput_thenReturnUserResource() throws Exception { + public void getUserWhenValidInput_thenReturnUserResource() throws Exception { User admin = new User(); admin.setName("Admin"); @@ -56,13 +64,10 @@ public void whenValidInput_thenReturnUserResource() throws Exception { MvcResult mvcResult = mockMvc.perform(MockMvcRequestBuilders.get("/users/{userId}", "1")).andExpect(status().isOk()).andReturn(); - ObjectMapper mapper = new ObjectMapper(); - mapper.findAndRegisterModules(); - - UserDTO userResponse = mapper.readValue(mvcResult.getResponse().getContentAsByteArray(), UserDTO.class); + UserDTO userResponse = objectMapper.readValue(mvcResult.getResponse().getContentAsByteArray(), UserDTO.class); - assertEquals(userResponse.getUser().getName(), admin.getName()); - assertEquals(userResponse.getUser().getMail(), admin.getMail()); - assertEquals(userResponse.getUser().getRole(), admin.getRole()); + Assertions.assertEquals(userResponse.getUser().getName(), admin.getName()); + Assertions.assertEquals(userResponse.getUser().getMail(), admin.getMail()); + Assertions.assertEquals(userResponse.getUser().getRole(), admin.getRole()); } } From ef01cd5d32d16482fa4ecf7cdbbbac98e9924f8f Mon Sep 17 00:00:00 2001 From: "i.i.artamonov" Date: Wed, 9 Mar 2022 16:14:03 +0400 Subject: [PATCH 076/141] Added tests to addGameToUser and deleteGameFromUserCollection Added methods to check bad path, unknown ids, and good case for each of methods. Added changes due tests. --- .../controller/UserController.java | 6 + .../boardgamefun/UserControllerTests.java | 105 ++++++++++++++++-- 2 files changed, 103 insertions(+), 8 deletions(-) diff --git a/src/main/java/com/petproject/boardgamefun/controller/UserController.java b/src/main/java/com/petproject/boardgamefun/controller/UserController.java index e0c1643..27e5709 100644 --- a/src/main/java/com/petproject/boardgamefun/controller/UserController.java +++ b/src/main/java/com/petproject/boardgamefun/controller/UserController.java @@ -204,6 +204,9 @@ public ResponseEntity addGameToUser(@PathVariable Integer userId, @PathVariab var user = userRepository.findUserById(userId); var game = gameRepository.findGameById(gameId); + if (user == null || game == null) + return new ResponseEntity<>(null, HttpStatus.NOT_FOUND); + var userOwnGame = new UserOwnGame(); userOwnGame.setGame(game); userOwnGame.setUser(user); @@ -220,6 +223,9 @@ public ResponseEntity deleteGameFromUserCollection(@PathVariable Intege var userOwnGame = userOwnGameRepository.findUserOwnGame_ByGameIdAndUserId(gameId, userId); + if (userOwnGame == null) + return new ResponseEntity<>(null, HttpStatus.NOT_FOUND); + userOwnGameRepository.delete(userOwnGame); return new ResponseEntity<>(gameId, HttpStatus.OK); diff --git a/src/test/java/com/petproject/boardgamefun/UserControllerTests.java b/src/test/java/com/petproject/boardgamefun/UserControllerTests.java index 299486f..2f47247 100644 --- a/src/test/java/com/petproject/boardgamefun/UserControllerTests.java +++ b/src/test/java/com/petproject/boardgamefun/UserControllerTests.java @@ -8,50 +8,52 @@ import com.petproject.boardgamefun.dto.UserDTO; import com.petproject.boardgamefun.model.User; -import org.junit.jupiter.api.Assertions; -import org.junit.jupiter.api.Test; +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.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.MockMvcRequestBuilders; - @ExtendWith(MockitoExtension.class) @SpringBootTest( webEnvironment = SpringBootTest.WebEnvironment.MOCK, classes = SpringSecurityWebTestConfig.class ) @AutoConfigureMockMvc +@TestMethodOrder(MethodOrderer.OrderAnnotation.class) public class UserControllerTests { + private final String Gateway = "users"; + @Autowired private MockMvc mockMvc; ObjectMapper objectMapper; - public UserControllerTests(){ + public UserControllerTests() { objectMapper = new ObjectMapper(); objectMapper.findAndRegisterModules(); } @Test public void getUserShouldReturnStatusOkTest() throws Exception { - this.mockMvc.perform(MockMvcRequestBuilders.get("/users/1")).andDo(print()).andExpect(status().isOk()); + this.mockMvc.perform(MockMvcRequestBuilders.get("/" + Gateway + "/1")).andDo(print()).andExpect(status().isOk()); } @Test public void getUserShouldReturnStatusNotFound() throws Exception { - this.mockMvc.perform(MockMvcRequestBuilders.get("/users/-1")).andDo(print()).andExpect(status().isNotFound()); + this.mockMvc.perform(MockMvcRequestBuilders.get("/" + Gateway + "/-1")).andDo(print()).andExpect(status().isNotFound()); } @Test public void getUserWhenBadPathValueReturn400() throws Exception { - mockMvc.perform(MockMvcRequestBuilders.get("/users/{userId}", "userId")).andExpect(status().isBadRequest()); + mockMvc.perform(MockMvcRequestBuilders.get("/" + Gateway + "/{userId}", "userId")).andExpect(status().isBadRequest()); } @Test @@ -62,7 +64,7 @@ public void getUserWhenValidInput_thenReturnUserResource() throws Exception { admin.setRole("ROLE_ADMIN"); admin.setMail("chupacabra@mail.ru"); - MvcResult mvcResult = mockMvc.perform(MockMvcRequestBuilders.get("/users/{userId}", "1")).andExpect(status().isOk()).andReturn(); + MvcResult mvcResult = mockMvc.perform(MockMvcRequestBuilders.get("/" + Gateway + "/{userId}", "1")).andExpect(status().isOk()).andReturn(); UserDTO userResponse = objectMapper.readValue(mvcResult.getResponse().getContentAsByteArray(), UserDTO.class); @@ -70,4 +72,91 @@ public void getUserWhenValidInput_thenReturnUserResource() throws Exception { Assertions.assertEquals(userResponse.getUser().getMail(), admin.getMail()); Assertions.assertEquals(userResponse.getUser().getRole(), admin.getRole()); } + + @Test + @WithMockUser(roles = "USER") + @Order(1) + public void addGameToUserShouldReturnOk() throws Exception { + this.mockMvc.perform(MockMvcRequestBuilders.post("/" + Gateway + "/1/add-game/1")).andDo(print()).andExpect(status().isOk()); + } + + @Test + @WithMockUser(roles = "USER") + public void addGameToUserShouldReturnStatusNotFound_FirstParameter() throws Exception { + this.mockMvc.perform(MockMvcRequestBuilders.post("/" + Gateway + "/-11/add-game/1")).andDo(print()).andExpect(status().isNotFound()); + } + + @Test + @WithMockUser(roles = "USER") + public void addGameToUserShouldReturnStatusNotFound_SecondParameter() throws Exception { + this.mockMvc.perform(MockMvcRequestBuilders.post("/" + Gateway + "/1/add-game/-1")).andDo(print()).andExpect(status().isNotFound()); + } + + @Test + @WithMockUser(roles = "USER") + public void addGameToUserShouldReturnStatusNotFound_BothParameters() throws Exception { + this.mockMvc.perform(MockMvcRequestBuilders.post("/" + Gateway + "/-1/add-game/-1")).andDo(print()).andExpect(status().isNotFound()); + } + + @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 { + this.mockMvc.perform(MockMvcRequestBuilders.delete("/" + Gateway + "/-1/delete-game/1")).andDo(print()).andExpect(status().isNotFound()); + } + + @Test + @WithMockUser(roles = "USER") + public void deleteGameFromUserCollectionShouldReturnNotFound_SecondParameter() throws Exception { + this.mockMvc.perform(MockMvcRequestBuilders.delete("/" + Gateway + "/1/delete-game/-1")).andDo(print()).andExpect(status().isNotFound()); + } + + @Test + @WithMockUser(roles = "USER") + public void deleteGameFromUserCollectionShouldReturnNotFound_BothParameters() throws Exception { + this.mockMvc.perform(MockMvcRequestBuilders.delete("/" + Gateway + "/-11/delete-game/-11")).andDo(print()).andExpect(status().isNotFound()); + } + + @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") + @Order(2) + public void deleteGameFromUserCollectionShouldReturnOk() throws Exception { + this.mockMvc.perform(MockMvcRequestBuilders.delete("/" + Gateway + "/1/delete-game/1")).andDo(print()).andExpect(status().isOk()); + } + } From d23a48b8e45d54ced25bcdf534a6a495aa0785f2 Mon Sep 17 00:00:00 2001 From: "i.i.artamonov" Date: Thu, 10 Mar 2022 15:29:39 +0400 Subject: [PATCH 077/141] Added test for getUsers method --- .../petproject/boardgamefun/controller/UserController.java | 2 +- .../com/petproject/boardgamefun/UserControllerTests.java | 5 +++++ 2 files changed, 6 insertions(+), 1 deletion(-) diff --git a/src/main/java/com/petproject/boardgamefun/controller/UserController.java b/src/main/java/com/petproject/boardgamefun/controller/UserController.java index 27e5709..c58da94 100644 --- a/src/main/java/com/petproject/boardgamefun/controller/UserController.java +++ b/src/main/java/com/petproject/boardgamefun/controller/UserController.java @@ -93,7 +93,7 @@ public ResponseEntity> getUsers() { @PostMapping("sign-in") public ResponseEntity authenticateUser(@RequestBody LoginRequest loginRequest) { if (!userRepository.existsByName(loginRequest.getName())) { - return new ResponseEntity<>("Пользователя с таким никнеймом не существует", HttpStatus.BAD_REQUEST); + return new ResponseEntity<>("Пользователя с таким никнеймом не существует", HttpStatus.NOT_FOUND); } Authentication authentication = authenticationManager.authenticate(new UsernamePasswordAuthenticationToken(loginRequest.getName(), loginRequest.getPassword())); diff --git a/src/test/java/com/petproject/boardgamefun/UserControllerTests.java b/src/test/java/com/petproject/boardgamefun/UserControllerTests.java index 2f47247..417de5a 100644 --- a/src/test/java/com/petproject/boardgamefun/UserControllerTests.java +++ b/src/test/java/com/petproject/boardgamefun/UserControllerTests.java @@ -41,6 +41,11 @@ public UserControllerTests() { objectMapper.findAndRegisterModules(); } + @Test + public void getUsersShouldReturnOk() throws Exception { + this.mockMvc.perform(MockMvcRequestBuilders.get("/" + Gateway)).andDo(print()).andExpect(status().isOk()); + } + @Test public void getUserShouldReturnStatusOkTest() throws Exception { this.mockMvc.perform(MockMvcRequestBuilders.get("/" + Gateway + "/1")).andDo(print()).andExpect(status().isOk()); From 9e040ee102cd49c1a10854031422df8dbe8545fb Mon Sep 17 00:00:00 2001 From: "i.i.artamonov" Date: Thu, 10 Mar 2022 16:10:36 +0400 Subject: [PATCH 078/141] Added tests for authentication method Change LoginRequest due tests --- .../security/model/LoginRequest.java | 8 +-- .../boardgamefun/UserControllerTests.java | 58 +++++++++++++++++-- 2 files changed, 56 insertions(+), 10 deletions(-) diff --git a/src/main/java/com/petproject/boardgamefun/security/model/LoginRequest.java b/src/main/java/com/petproject/boardgamefun/security/model/LoginRequest.java index 18427ba..dd146b8 100644 --- a/src/main/java/com/petproject/boardgamefun/security/model/LoginRequest.java +++ b/src/main/java/com/petproject/boardgamefun/security/model/LoginRequest.java @@ -1,12 +1,10 @@ package com.petproject.boardgamefun.security.model; -import lombok.Data; -import lombok.Getter; -import lombok.Setter; +import lombok.*; @Data -@Getter -@Setter +@AllArgsConstructor +@NoArgsConstructor public class LoginRequest { private String name; diff --git a/src/test/java/com/petproject/boardgamefun/UserControllerTests.java b/src/test/java/com/petproject/boardgamefun/UserControllerTests.java index 417de5a..20f8318 100644 --- a/src/test/java/com/petproject/boardgamefun/UserControllerTests.java +++ b/src/test/java/com/petproject/boardgamefun/UserControllerTests.java @@ -8,12 +8,14 @@ import com.petproject.boardgamefun.dto.UserDTO; import com.petproject.boardgamefun.model.User; +import com.petproject.boardgamefun.security.model.LoginRequest; 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.http.MediaType; import org.springframework.security.test.context.support.WithMockUser; import org.springframework.test.web.servlet.MockMvc; import org.springframework.test.web.servlet.MvcResult; @@ -36,9 +38,15 @@ public class UserControllerTests { ObjectMapper objectMapper; + User admin; + public UserControllerTests() { objectMapper = new ObjectMapper(); objectMapper.findAndRegisterModules(); + admin = new User(); + admin.setName("Admin"); + admin.setRole("ROLE_ADMIN"); + admin.setMail("chupacabra@mail.ru"); } @Test @@ -46,6 +54,51 @@ public void getUsersShouldReturnOk() throws Exception { this.mockMvc.perform(MockMvcRequestBuilders.get("/" + Gateway)).andDo(print()).andExpect(status().isOk()); } + @Test + public void authenticateUserShouldReturnOk() throws Exception{ + LoginRequest loginRequest = new LoginRequest("Admin", "123qweAdmin"); + this.mockMvc.perform(MockMvcRequestBuilders.post("/" + Gateway + "/sign-in").contentType(MediaType.APPLICATION_JSON) + .accept(MediaType.APPLICATION_JSON) + .content(objectMapper.writeValueAsString(loginRequest))).andExpect(status().isOk()); + } + + @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"); + 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("Admin", "qweAdmin"); + 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 getUserShouldReturnStatusOkTest() throws Exception { this.mockMvc.perform(MockMvcRequestBuilders.get("/" + Gateway + "/1")).andDo(print()).andExpect(status().isOk()); @@ -64,11 +117,6 @@ public void getUserWhenBadPathValueReturn400() throws Exception { @Test public void getUserWhenValidInput_thenReturnUserResource() throws Exception { - User admin = new User(); - admin.setName("Admin"); - admin.setRole("ROLE_ADMIN"); - admin.setMail("chupacabra@mail.ru"); - MvcResult mvcResult = mockMvc.perform(MockMvcRequestBuilders.get("/" + Gateway + "/{userId}", "1")).andExpect(status().isOk()).andReturn(); UserDTO userResponse = objectMapper.readValue(mvcResult.getResponse().getContentAsByteArray(), UserDTO.class); From a8856cb0c1389a575117f8b2a3553c3ed6ee9416 Mon Sep 17 00:00:00 2001 From: "i.i.artamonov" Date: Mon, 14 Mar 2022 09:13:35 +0400 Subject: [PATCH 079/141] Added tetst for refreshToken method. Change RefrteshTokenRequest due to tests. Add check for contains dot in string. --- .../controller/UserController.java | 2 +- .../security/model/RefreshTokenRequest.java | 4 ++ .../services/RefreshTokenService.java | 2 + .../boardgamefun/UserControllerTests.java | 43 +++++++++++++++---- 4 files changed, 42 insertions(+), 9 deletions(-) diff --git a/src/main/java/com/petproject/boardgamefun/controller/UserController.java b/src/main/java/com/petproject/boardgamefun/controller/UserController.java index c58da94..b055c0f 100644 --- a/src/main/java/com/petproject/boardgamefun/controller/UserController.java +++ b/src/main/java/com/petproject/boardgamefun/controller/UserController.java @@ -182,7 +182,7 @@ public ResponseEntity changePassword(@PathVariable Integer userId, @RequestBo @GetMapping("{id}") public ResponseEntity getUser(@PathVariable Integer id) { var userDTO = userService.entityToUserDTO(userRepository.findUserById(id)); - if (userDTO.getUser() == null){ + if (userDTO.getUser() == null) { return new ResponseEntity<>(null, HttpStatus.NOT_FOUND); } return new ResponseEntity<>(userDTO, HttpStatus.OK); diff --git a/src/main/java/com/petproject/boardgamefun/security/model/RefreshTokenRequest.java b/src/main/java/com/petproject/boardgamefun/security/model/RefreshTokenRequest.java index 00dd3ae..3095031 100644 --- a/src/main/java/com/petproject/boardgamefun/security/model/RefreshTokenRequest.java +++ b/src/main/java/com/petproject/boardgamefun/security/model/RefreshTokenRequest.java @@ -1,8 +1,12 @@ 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/services/RefreshTokenService.java b/src/main/java/com/petproject/boardgamefun/security/services/RefreshTokenService.java index 37a508c..d73b665 100644 --- a/src/main/java/com/petproject/boardgamefun/security/services/RefreshTokenService.java +++ b/src/main/java/com/petproject/boardgamefun/security/services/RefreshTokenService.java @@ -26,6 +26,8 @@ public String createRefreshToken(String userName) { 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) { diff --git a/src/test/java/com/petproject/boardgamefun/UserControllerTests.java b/src/test/java/com/petproject/boardgamefun/UserControllerTests.java index 20f8318..0113365 100644 --- a/src/test/java/com/petproject/boardgamefun/UserControllerTests.java +++ b/src/test/java/com/petproject/boardgamefun/UserControllerTests.java @@ -2,13 +2,14 @@ import static org.springframework.test.web.servlet.result.MockMvcResultHandlers.print; import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status; -import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.content; import com.fasterxml.jackson.databind.ObjectMapper; import com.petproject.boardgamefun.dto.UserDTO; import com.petproject.boardgamefun.model.User; +import com.petproject.boardgamefun.security.model.JwtResponse; import com.petproject.boardgamefun.security.model.LoginRequest; +import com.petproject.boardgamefun.security.model.RefreshTokenRequest; import org.junit.jupiter.api.*; import org.junit.jupiter.api.extension.ExtendWith; import org.mockito.junit.jupiter.MockitoExtension; @@ -55,7 +56,7 @@ public void getUsersShouldReturnOk() throws Exception { } @Test - public void authenticateUserShouldReturnOk() throws Exception{ + public void authenticateUserShouldReturnOk() throws Exception { LoginRequest loginRequest = new LoginRequest("Admin", "123qweAdmin"); this.mockMvc.perform(MockMvcRequestBuilders.post("/" + Gateway + "/sign-in").contentType(MediaType.APPLICATION_JSON) .accept(MediaType.APPLICATION_JSON) @@ -63,7 +64,7 @@ public void authenticateUserShouldReturnOk() throws Exception{ } @Test - public void authenticateUserShouldReturn415() throws Exception{ + public void authenticateUserShouldReturn415() throws Exception { LoginRequest loginRequest = new LoginRequest("Admin", "123qweAdmin"); this.mockMvc.perform(MockMvcRequestBuilders.post("/" + Gateway + "/sign-in") .contentType(MediaType.APPLICATION_XML) @@ -72,7 +73,7 @@ public void authenticateUserShouldReturn415() throws Exception{ } @Test - public void authenticateUserShouldReturnNotFound() throws Exception{ + public void authenticateUserShouldReturnNotFound() throws Exception { LoginRequest loginRequest = new LoginRequest("-1Admin", "123qweAdmin"); this.mockMvc.perform(MockMvcRequestBuilders.post("/" + Gateway + "/sign-in") .contentType(MediaType.APPLICATION_JSON) @@ -81,7 +82,7 @@ public void authenticateUserShouldReturnNotFound() throws Exception{ } @Test - public void authenticateUserShouldReturnNotAuthorized() throws Exception{ + public void authenticateUserShouldReturnNotAuthorized() throws Exception { LoginRequest loginRequest = new LoginRequest("Admin", "qweAdmin"); this.mockMvc.perform(MockMvcRequestBuilders.post("/" + Gateway + "/sign-in") .contentType(MediaType.APPLICATION_JSON) @@ -90,14 +91,40 @@ public void authenticateUserShouldReturnNotAuthorized() throws Exception{ } @Test - public void authenticateUserShouldReturnBadRequest() throws Exception{ + public void authenticateUserShouldReturnBadRequest() throws Exception { this.mockMvc.perform(MockMvcRequestBuilders.post("/" + Gateway + "/sign-in") - .contentType(MediaType.APPLICATION_JSON) - .accept(MediaType.APPLICATION_JSON)) + .contentType(MediaType.APPLICATION_JSON) + .accept(MediaType.APPLICATION_JSON)) .andExpect(status().isBadRequest()); } + @Test + public void refreshTokenShouldReturnNotAuthorizedBadAccessToken() throws Exception { + RefreshTokenRequest refreshTokenRequest = new RefreshTokenRequest("Admin", "bla-bla"); + this.mockMvc.perform(MockMvcRequestBuilders.post("/" + Gateway + "/refresh-token") + .contentType(MediaType.APPLICATION_JSON) + .accept(MediaType.APPLICATION_JSON) + .content(objectMapper.writeValueAsString(refreshTokenRequest))) + .andExpect(status().isUnauthorized()); + } + + @Test + public void refreshTokenShouldReturnIsOk() throws Exception { + + LoginRequest loginRequest = new LoginRequest("Admin", "123qweAdmin"); + MvcResult mvcResult = this.mockMvc.perform(MockMvcRequestBuilders.post("/" + Gateway + "/sign-in").contentType(MediaType.APPLICATION_JSON) + .accept(MediaType.APPLICATION_JSON) + .content(objectMapper.writeValueAsString(loginRequest))).andExpect(status().isOk()).andReturn(); + JwtResponse jwtResponse = objectMapper.readValue(mvcResult.getResponse().getContentAsByteArray(), JwtResponse.class); + + RefreshTokenRequest refreshTokenRequest = new RefreshTokenRequest(jwtResponse.getUserName(), jwtResponse.getRefreshToken()); + this.mockMvc.perform(MockMvcRequestBuilders.post("/" + Gateway + "/refresh-token") + .contentType(MediaType.APPLICATION_JSON) + .accept(MediaType.APPLICATION_JSON) + .content(objectMapper.writeValueAsString(refreshTokenRequest))) + .andExpect(status().isOk()); + } @Test public void getUserShouldReturnStatusOkTest() throws Exception { From e721308418e7a8ae4fba158314a3c8e82f1ca18f Mon Sep 17 00:00:00 2001 From: "i.i.artamonov" Date: Mon, 14 Mar 2022 09:42:36 +0400 Subject: [PATCH 080/141] Added tests to getUserCollection --- .../boardgamefun/UserControllerTests.java | 17 ++++++++++++++++- 1 file changed, 16 insertions(+), 1 deletion(-) diff --git a/src/test/java/com/petproject/boardgamefun/UserControllerTests.java b/src/test/java/com/petproject/boardgamefun/UserControllerTests.java index 0113365..7366555 100644 --- a/src/test/java/com/petproject/boardgamefun/UserControllerTests.java +++ b/src/test/java/com/petproject/boardgamefun/UserControllerTests.java @@ -4,6 +4,7 @@ import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status; import com.fasterxml.jackson.databind.ObjectMapper; +import com.petproject.boardgamefun.dto.GameDTO; import com.petproject.boardgamefun.dto.UserDTO; import com.petproject.boardgamefun.model.User; @@ -112,7 +113,7 @@ public void refreshTokenShouldReturnNotAuthorizedBadAccessToken() throws Excepti public void refreshTokenShouldReturnIsOk() throws Exception { LoginRequest loginRequest = new LoginRequest("Admin", "123qweAdmin"); - MvcResult mvcResult = this.mockMvc.perform(MockMvcRequestBuilders.post("/" + Gateway + "/sign-in").contentType(MediaType.APPLICATION_JSON) + MvcResult mvcResult = this.mockMvc.perform(MockMvcRequestBuilders.post("/" + Gateway + "/sign-in").contentType(MediaType.APPLICATION_JSON) .accept(MediaType.APPLICATION_JSON) .content(objectMapper.writeValueAsString(loginRequest))).andExpect(status().isOk()).andReturn(); @@ -153,6 +154,20 @@ public void getUserWhenValidInput_thenReturnUserResource() throws Exception { Assertions.assertEquals(userResponse.getUser().getRole(), admin.getRole()); } + @Test + @WithMockUser(roles = "USER") + public void getUserCollectionShouldReturnIsOk() throws Exception { + this.mockMvc.perform(MockMvcRequestBuilders.get("/" + Gateway + "/1/games")).andExpect(status().isOk()); + } + + @Test + @WithMockUser(roles = "USER") + public void getUserCollectionShouldReturnBlankArray() throws Exception { + MvcResult mvcResult = this.mockMvc.perform(MockMvcRequestBuilders.get("/" + Gateway + "/-1/games")).andExpect(status().isOk()).andReturn(); + var gameDTOS = objectMapper.readValue(mvcResult.getResponse().getContentAsByteArray(), GameDTO[].class); + Assertions.assertEquals(0, gameDTOS.length); + } + @Test @WithMockUser(roles = "USER") @Order(1) From af20fccbc8c0e484c251c7b160bd4c9d0578092e Mon Sep 17 00:00:00 2001 From: "i.i.artamonov" Date: Mon, 14 Mar 2022 15:55:55 +0400 Subject: [PATCH 081/141] Added tests to getUserRatingList --- .../boardgamefun/UserControllerTests.java | 14 ++++++++++++++ 1 file changed, 14 insertions(+) diff --git a/src/test/java/com/petproject/boardgamefun/UserControllerTests.java b/src/test/java/com/petproject/boardgamefun/UserControllerTests.java index 7366555..d943980 100644 --- a/src/test/java/com/petproject/boardgamefun/UserControllerTests.java +++ b/src/test/java/com/petproject/boardgamefun/UserControllerTests.java @@ -168,6 +168,20 @@ public void getUserCollectionShouldReturnBlankArray() throws Exception { Assertions.assertEquals(0, gameDTOS.length); } + @Test + @WithMockUser(roles = "USER") + public void getUserRatingListShouldReturnIsOk() throws Exception { + this.mockMvc.perform(MockMvcRequestBuilders.get("/" + Gateway + "/1/games-rating")).andExpect(status().isOk()); + } + + @Test + @WithMockUser(roles = "USER") + public void getUserRatingListShouldReturnBlankArray() throws Exception { + MvcResult mvcResult = this.mockMvc.perform(MockMvcRequestBuilders.get("/" + Gateway + "/-1/games-rating")).andExpect(status().isOk()).andReturn(); + var gameDTOS = objectMapper.readValue(mvcResult.getResponse().getContentAsByteArray(), GameDTO[].class); + Assertions.assertEquals(0, gameDTOS.length); + } + @Test @WithMockUser(roles = "USER") @Order(1) From 50a1bf95634c87a3e9aa94ec826d38dd291869bb Mon Sep 17 00:00:00 2001 From: "i.i.artamonov" Date: Mon, 14 Mar 2022 16:14:28 +0400 Subject: [PATCH 082/141] Added tests for deleteGameRating Added changes due to tests. Added test for creating rating --- .../controller/UserController.java | 3 ++ .../boardgamefun/UserControllerTests.java | 32 +++++++++++++++++++ 2 files changed, 35 insertions(+) diff --git a/src/main/java/com/petproject/boardgamefun/controller/UserController.java b/src/main/java/com/petproject/boardgamefun/controller/UserController.java index b055c0f..034e3a8 100644 --- a/src/main/java/com/petproject/boardgamefun/controller/UserController.java +++ b/src/main/java/com/petproject/boardgamefun/controller/UserController.java @@ -246,6 +246,9 @@ public ResponseEntity deleteGameRating(@PathVariable Integer userId, @Pa var ratingGameByUser = ratingGameByUserRepository.findRatingGame_ByGameIdAndUserId(gameId, userId); + if (ratingGameByUser == null) + return new ResponseEntity<>(null, HttpStatus.NOT_FOUND); + ratingGameByUserRepository.delete(ratingGameByUser); return new ResponseEntity<>("Оценка с текущей игры удалена", HttpStatus.OK); diff --git a/src/test/java/com/petproject/boardgamefun/UserControllerTests.java b/src/test/java/com/petproject/boardgamefun/UserControllerTests.java index d943980..1eed73a 100644 --- a/src/test/java/com/petproject/boardgamefun/UserControllerTests.java +++ b/src/test/java/com/petproject/boardgamefun/UserControllerTests.java @@ -182,6 +182,38 @@ public void getUserRatingListShouldReturnBlankArray() throws Exception { Assertions.assertEquals(0, gameDTOS.length); } + @Test + @WithMockUser(roles = "USER") + public void deleteGameRatingShouldReturnNotFound_FirstParameter() throws Exception { + this.mockMvc.perform(MockMvcRequestBuilders.delete("/" + Gateway + "/-1/delete-game-rating/1")).andDo(print()).andExpect(status().isNotFound()); + } + + @Test + @WithMockUser(roles = "USER") + public void deleteGameRatingShouldReturnNotFound_SecondParameter() throws Exception { + this.mockMvc.perform(MockMvcRequestBuilders.delete("/" + Gateway + "/1/delete-game-rating/-1")).andDo(print()).andExpect(status().isNotFound()); + } + + @Test + @WithMockUser(roles = "USER") + public void deleteGameRatingShouldReturnNotFound_BothParameters() throws Exception { + this.mockMvc.perform(MockMvcRequestBuilders.delete("/" + Gateway + "/-1/delete-game-rating/-1")).andDo(print()).andExpect(status().isNotFound()); + } + + @Test + @WithMockUser(roles = "USER") + @Order(2) + public void deleteGameRatingShouldReturnOk() throws Exception { + this.mockMvc.perform(MockMvcRequestBuilders.delete("/" + Gateway + "/1/delete-game-rating/1")).andDo(print()).andExpect(status().isOk()); + } + + @Test + @WithMockUser(roles = "USER") + @Order(1) + public void setGameRatingShouldReturnOk() throws Exception { + this.mockMvc.perform(MockMvcRequestBuilders.post("/" + Gateway + "/1/set-game-rating/1/10")).andDo(print()).andExpect(status().isOk()); + } + @Test @WithMockUser(roles = "USER") @Order(1) From adfde08d82f8ac8edee850b827daa5c093ae7489 Mon Sep 17 00:00:00 2001 From: "i.i.artamonov" Date: Wed, 16 Mar 2022 09:03:59 +0400 Subject: [PATCH 083/141] Added tests for setGameRating. Split this method to POST and PTCH methods. Now PYCh method is updateGameRating --- .../controller/UserController.java | 50 ++++++++++++++----- .../boardgamefun/UserControllerTests.java | 31 ++++++++++++ 2 files changed, 68 insertions(+), 13 deletions(-) diff --git a/src/main/java/com/petproject/boardgamefun/controller/UserController.java b/src/main/java/com/petproject/boardgamefun/controller/UserController.java index 034e3a8..f95e995 100644 --- a/src/main/java/com/petproject/boardgamefun/controller/UserController.java +++ b/src/main/java/com/petproject/boardgamefun/controller/UserController.java @@ -259,21 +259,45 @@ public ResponseEntity deleteGameRating(@PathVariable Integer userId, @Pa @PreAuthorize("hasRole('USER') or hasRole('MODERATOR') or hasRole('ADMIN')") public ResponseEntity setGameRating(@PathVariable Integer userId, @PathVariable Integer gameId, @PathVariable Integer rating) { - var ratingGameByUser = ratingGameByUserRepository.findRatingGame_ByGameIdAndUserId(gameId, userId); + if (rating > 10 || rating < 1) { + return new ResponseEntity<>(null, HttpStatus.BAD_REQUEST); + } - if (ratingGameByUser != null) { - ratingGameByUser.setRating(rating); - ratingGameByUserRepository.save(ratingGameByUser); - } else { - var gameRating = new RatingGameByUser(); - var game = gameRepository.findGameById(gameId); - var user = userRepository.findUserById(userId); - gameRating.setGame(game); - gameRating.setUser(user); - gameRating.setRating(rating); - - ratingGameByUserRepository.save(gameRating); + var gameRating = new RatingGameByUser(); + var game = gameRepository.findGameById(gameId); + var user = userRepository.findUserById(userId); + + if (game == null || user == null) + return new ResponseEntity<>(null, HttpStatus.NOT_FOUND); + + gameRating.setGame(game); + gameRating.setUser(user); + gameRating.setRating(rating); + + ratingGameByUserRepository.save(gameRating); + + + return new ResponseEntity<>(rating, HttpStatus.OK); + } + + @Transactional + @PostMapping("/{userId}/update-game-rating/{gameId}/{rating}") + @PreAuthorize("hasRole('USER') or hasRole('MODERATOR') or hasRole('ADMIN')") + public ResponseEntity updateGameRating(@PathVariable Integer userId, @PathVariable Integer gameId, @PathVariable Integer rating) { + + if (rating > 10 || rating < 1) { + return new ResponseEntity<>(null, HttpStatus.BAD_REQUEST); } + var ratingGameByUser = ratingGameByUserRepository.findRatingGame_ByGameIdAndUserId(gameId, userId); + if (ratingGameByUser == null) { + return new ResponseEntity<>(null, HttpStatus.NOT_FOUND); + } + + ratingGameByUser.setRating(rating); + ratingGameByUserRepository.save(ratingGameByUser); + + + ratingGameByUserRepository.save(ratingGameByUser); return new ResponseEntity<>(rating, HttpStatus.OK); } diff --git a/src/test/java/com/petproject/boardgamefun/UserControllerTests.java b/src/test/java/com/petproject/boardgamefun/UserControllerTests.java index 1eed73a..3500972 100644 --- a/src/test/java/com/petproject/boardgamefun/UserControllerTests.java +++ b/src/test/java/com/petproject/boardgamefun/UserControllerTests.java @@ -214,6 +214,37 @@ public void setGameRatingShouldReturnOk() throws Exception { this.mockMvc.perform(MockMvcRequestBuilders.post("/" + Gateway + "/1/set-game-rating/1/10")).andDo(print()).andExpect(status().isOk()); } + @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 { + this.mockMvc.perform(MockMvcRequestBuilders.post("/" + Gateway + "/-1/set-game-rating/1/1")).andDo(print()).andExpect(status().isNotFound()); + } + + @Test + @WithMockUser(roles = "USER") + public void setGameRatingShouldReturnNotFound_SecondParameter() throws Exception { + this.mockMvc.perform(MockMvcRequestBuilders.post("/" + Gateway + "/1/set-game-rating/-1/1")).andDo(print()).andExpect(status().isNotFound()); + } + + @Test + @WithMockUser(roles = "USER") + public void setGameRatingShouldReturnNotFound_BothParameters() throws Exception { + this.mockMvc.perform(MockMvcRequestBuilders.post("/" + Gateway + "/-1/set-game-rating/-1/1")).andDo(print()).andExpect(status().isNotFound()); + } + + @Test @WithMockUser(roles = "USER") @Order(1) From e5b506286d9855527ef1f11ee0fa728d812d82ac Mon Sep 17 00:00:00 2001 From: "i.i.artamonov" Date: Wed, 16 Mar 2022 09:13:11 +0400 Subject: [PATCH 084/141] Added tests for updateGameRating --- .../boardgamefun/UserControllerTests.java | 46 +++++++++++++++++-- 1 file changed, 42 insertions(+), 4 deletions(-) diff --git a/src/test/java/com/petproject/boardgamefun/UserControllerTests.java b/src/test/java/com/petproject/boardgamefun/UserControllerTests.java index 3500972..b9cded1 100644 --- a/src/test/java/com/petproject/boardgamefun/UserControllerTests.java +++ b/src/test/java/com/petproject/boardgamefun/UserControllerTests.java @@ -37,6 +37,7 @@ public class UserControllerTests { @Autowired private MockMvc mockMvc; + private static final int insertDataOrder = 1, updateDataOrder = 2, deleteDataOrder = 3; ObjectMapper objectMapper; @@ -202,14 +203,14 @@ public void deleteGameRatingShouldReturnNotFound_BothParameters() throws Excepti @Test @WithMockUser(roles = "USER") - @Order(2) + @Order(deleteDataOrder) public void deleteGameRatingShouldReturnOk() throws Exception { this.mockMvc.perform(MockMvcRequestBuilders.delete("/" + Gateway + "/1/delete-game-rating/1")).andDo(print()).andExpect(status().isOk()); } @Test @WithMockUser(roles = "USER") - @Order(1) + @Order(insertDataOrder) public void setGameRatingShouldReturnOk() throws Exception { this.mockMvc.perform(MockMvcRequestBuilders.post("/" + Gateway + "/1/set-game-rating/1/10")).andDo(print()).andExpect(status().isOk()); } @@ -244,10 +245,47 @@ public void setGameRatingShouldReturnNotFound_BothParameters() throws Exception this.mockMvc.perform(MockMvcRequestBuilders.post("/" + Gateway + "/-1/set-game-rating/-1/1")).andDo(print()).andExpect(status().isNotFound()); } + @Test + @WithMockUser(roles = "USER") + @Order(updateDataOrder) + public void updateGameRatingShouldReturnOk() throws Exception { + this.mockMvc.perform(MockMvcRequestBuilders.post("/" + Gateway + "/1/update-game-rating/1/10")).andDo(print()).andExpect(status().isOk()); + } + + @Test + @WithMockUser(roles = "USER") + public void updateGameRatingShouldReturnBadRequestLessThanNormal() throws Exception { + this.mockMvc.perform(MockMvcRequestBuilders.post("/" + 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.post("/" + Gateway + "/1/update-game-rating/1/11")).andDo(print()).andExpect(status().isBadRequest()); + } + + @Test + @WithMockUser(roles = "USER") + public void updateGameRatingShouldReturnNotFound_FirstParameter() throws Exception { + this.mockMvc.perform(MockMvcRequestBuilders.post("/" + Gateway + "/-1/update-game-rating/1/1")).andDo(print()).andExpect(status().isNotFound()); + } + + @Test + @WithMockUser(roles = "USER") + public void updateGameRatingShouldReturnNotFound_SecondParameter() throws Exception { + this.mockMvc.perform(MockMvcRequestBuilders.post("/" + Gateway + "/1/update-game-rating/-1/1")).andDo(print()).andExpect(status().isNotFound()); + } + + @Test + @WithMockUser(roles = "USER") + public void updateGameRatingShouldReturnNotFound_BothParameters() throws Exception { + this.mockMvc.perform(MockMvcRequestBuilders.post("/" + Gateway + "/-1/update-game-rating/-1/1")).andDo(print()).andExpect(status().isNotFound()); + } + @Test @WithMockUser(roles = "USER") - @Order(1) + @Order(insertDataOrder) public void addGameToUserShouldReturnOk() throws Exception { this.mockMvc.perform(MockMvcRequestBuilders.post("/" + Gateway + "/1/add-game/1")).andDo(print()).andExpect(status().isOk()); } @@ -326,7 +364,7 @@ public void deleteGameFromUserCollectionShouldReturnBadRequest_BothParameters() @Test @WithMockUser(roles = "USER") - @Order(2) + @Order(deleteDataOrder) public void deleteGameFromUserCollectionShouldReturnOk() throws Exception { this.mockMvc.perform(MockMvcRequestBuilders.delete("/" + Gateway + "/1/delete-game/1")).andDo(print()).andExpect(status().isOk()); } From b21e0af50433e366cec0b45a8d92fb99376cc7e9 Mon Sep 17 00:00:00 2001 From: "i.i.artamonov" Date: Thu, 17 Mar 2022 15:22:34 +0400 Subject: [PATCH 085/141] Added tests for getUserWishlist --- .../boardgamefun/UserControllerTests.java | 23 ++++++++++++++++++- 1 file changed, 22 insertions(+), 1 deletion(-) diff --git a/src/test/java/com/petproject/boardgamefun/UserControllerTests.java b/src/test/java/com/petproject/boardgamefun/UserControllerTests.java index b9cded1..7fcbfdc 100644 --- a/src/test/java/com/petproject/boardgamefun/UserControllerTests.java +++ b/src/test/java/com/petproject/boardgamefun/UserControllerTests.java @@ -282,7 +282,6 @@ public void updateGameRatingShouldReturnNotFound_BothParameters() throws Excepti this.mockMvc.perform(MockMvcRequestBuilders.post("/" + Gateway + "/-1/update-game-rating/-1/1")).andDo(print()).andExpect(status().isNotFound()); } - @Test @WithMockUser(roles = "USER") @Order(insertDataOrder) @@ -369,4 +368,26 @@ public void deleteGameFromUserCollectionShouldReturnOk() throws Exception { this.mockMvc.perform(MockMvcRequestBuilders.delete("/" + Gateway + "/1/delete-game/1")).andDo(print()).andExpect(status().isOk()); } + @Test + @WithMockUser(roles = "USER") + public void getUserWishlistShouldReturnIsOk() throws Exception { + this.mockMvc.perform(MockMvcRequestBuilders.get("/" + Gateway + "/1/wishlist")).andExpect(status().isOk()); + } + + @Test + @WithMockUser(roles = "USER") + public void getUserWishlistShouldReturnBlankArray() throws Exception { + MvcResult mvcResult = this.mockMvc.perform(MockMvcRequestBuilders.get("/" + Gateway + "/-1/wishlist")).andExpect(status().isOk()).andReturn(); + var gameDTOS = objectMapper.readValue(mvcResult.getResponse().getContentAsByteArray(), GameDTO[].class); + Assertions.assertEquals(0, gameDTOS.length); + } + + @Test + @WithMockUser(roles = "USER") + public void getUserWishlistShouldReturnBadRequest() throws Exception { + this.mockMvc.perform(MockMvcRequestBuilders.get("/" + Gateway + "/bla/wishlist")).andExpect(status().isBadRequest()); + } + + + } From 864b23c73a4d55646b94b13e610b527fd8640f57 Mon Sep 17 00:00:00 2001 From: "i.i.artamonov" Date: Thu, 17 Mar 2022 15:32:14 +0400 Subject: [PATCH 086/141] Added tests to addGameToUserWishlist Added changes due to tests --- .../controller/UserController.java | 4 ++ .../boardgamefun/UserControllerTests.java | 47 +++++++++++++++++++ 2 files changed, 51 insertions(+) diff --git a/src/main/java/com/petproject/boardgamefun/controller/UserController.java b/src/main/java/com/petproject/boardgamefun/controller/UserController.java index f95e995..e589fda 100644 --- a/src/main/java/com/petproject/boardgamefun/controller/UserController.java +++ b/src/main/java/com/petproject/boardgamefun/controller/UserController.java @@ -316,6 +316,10 @@ public ResponseEntity addGameToUserWishlist(@PathVariable Integer userId, @Pa var user = userRepository.findUserById(userId); var game = gameRepository.findGameById(gameId); + if (user == null || game == null) { + return new ResponseEntity<>(null, HttpStatus.NOT_FOUND); + } + var userWish = new UserWish(); userWish.setGame(game); userWish.setUser(user); diff --git a/src/test/java/com/petproject/boardgamefun/UserControllerTests.java b/src/test/java/com/petproject/boardgamefun/UserControllerTests.java index 7fcbfdc..52c1035 100644 --- a/src/test/java/com/petproject/boardgamefun/UserControllerTests.java +++ b/src/test/java/com/petproject/boardgamefun/UserControllerTests.java @@ -388,6 +388,53 @@ public void getUserWishlistShouldReturnBadRequest() throws Exception { this.mockMvc.perform(MockMvcRequestBuilders.get("/" + Gateway + "/bla/wishlist")).andExpect(status().isBadRequest()); } + @Test + @WithMockUser(roles = "USER") + @Order(insertDataOrder) + public void addGameToUserWishlistShouldReturnOk() throws Exception { + this.mockMvc.perform(MockMvcRequestBuilders.post("/" + Gateway + "/1/add-game-to-wishlist/1")).andDo(print()).andExpect(status().isOk()); + } + + @Test + @WithMockUser(roles = "USER") + public void addGameToUserWishlistShouldReturnStatusNotFound_FirstParameter() throws Exception { + this.mockMvc.perform(MockMvcRequestBuilders.post("/" + Gateway + "/-11/add-game-to-wishlist/1")).andDo(print()).andExpect(status().isNotFound()); + } + @Test + @WithMockUser(roles = "USER") + public void addGameToUserWishlistShouldReturnStatusNotFound_SecondParameter() throws Exception { + this.mockMvc.perform(MockMvcRequestBuilders.post("/" + Gateway + "/1/add-game-to-wishlist/-1")).andDo(print()).andExpect(status().isNotFound()); + } + + @Test + @WithMockUser(roles = "USER") + public void addGameToUserWishlistShouldReturnStatusNotFound_BothParameters() throws Exception { + this.mockMvc.perform(MockMvcRequestBuilders.post("/" + Gateway + "/-1/add-game-to-wishlist/-1")).andDo(print()).andExpect(status().isNotFound()); + } + @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") + @Order(deleteDataOrder) + public void deleteGameFromUserWishlistShouldReturnOk() throws Exception { + this.mockMvc.perform(MockMvcRequestBuilders.delete("/" + Gateway + "/1/delete-game-from-wishlist/1")).andDo(print()).andExpect(status().isOk()); + } } From 8e2f22d029a0cb2d5d3b7c0587c5ff6570301e34 Mon Sep 17 00:00:00 2001 From: "i.i.artamonov" Date: Mon, 4 Apr 2022 09:08:50 +0400 Subject: [PATCH 087/141] Change the tests - mock the database Add additional checks to method - addGameToUserWishlist, setGameRating, addGameToUser. --- .../controller/UserController.java | 12 ++ .../boardgamefun/UserControllerTests.java | 144 ++++++++++++++++-- 2 files changed, 147 insertions(+), 9 deletions(-) diff --git a/src/main/java/com/petproject/boardgamefun/controller/UserController.java b/src/main/java/com/petproject/boardgamefun/controller/UserController.java index e589fda..05c60a9 100644 --- a/src/main/java/com/petproject/boardgamefun/controller/UserController.java +++ b/src/main/java/com/petproject/boardgamefun/controller/UserController.java @@ -207,6 +207,11 @@ public ResponseEntity addGameToUser(@PathVariable Integer userId, @PathVariab if (user == null || game == null) return new ResponseEntity<>(null, HttpStatus.NOT_FOUND); + var games = gameRepository.findUserGames(userId); + if (games.stream().anyMatch(g -> g.getId().equals(gameId))) { + return new ResponseEntity<>(null, HttpStatus.BAD_REQUEST); + } + var userOwnGame = new UserOwnGame(); userOwnGame.setGame(game); userOwnGame.setUser(user); @@ -262,6 +267,9 @@ public ResponseEntity setGameRating(@PathVariable Integer userId, @Path if (rating > 10 || rating < 1) { return new ResponseEntity<>(null, HttpStatus.BAD_REQUEST); } + if (ratingGameByUserRepository.findRatingGame_ByGameIdAndUserId(gameId, userId) != null) { + return new ResponseEntity<>(null, HttpStatus.BAD_REQUEST); + } var gameRating = new RatingGameByUser(); var game = gameRepository.findGameById(gameId); @@ -316,6 +324,10 @@ public ResponseEntity addGameToUserWishlist(@PathVariable Integer userId, @Pa var user = userRepository.findUserById(userId); var game = gameRepository.findGameById(gameId); + if (userWishRepository.findByGameAndUser(game, user) != null) { + return new ResponseEntity<>(null, HttpStatus.BAD_REQUEST); + } + if (user == null || game == null) { return new ResponseEntity<>(null, HttpStatus.NOT_FOUND); } diff --git a/src/test/java/com/petproject/boardgamefun/UserControllerTests.java b/src/test/java/com/petproject/boardgamefun/UserControllerTests.java index 52c1035..0fdf097 100644 --- a/src/test/java/com/petproject/boardgamefun/UserControllerTests.java +++ b/src/test/java/com/petproject/boardgamefun/UserControllerTests.java @@ -1,5 +1,6 @@ package com.petproject.boardgamefun; +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; @@ -8,21 +9,33 @@ import com.petproject.boardgamefun.dto.UserDTO; import com.petproject.boardgamefun.model.User; +import com.petproject.boardgamefun.repository.UserRepository; 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.service.UserService; 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.http.MediaType; 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.MockMvcRequestBuilders; +import java.time.OffsetDateTime; +import java.util.ArrayList; +import java.util.List; + @ExtendWith(MockitoExtension.class) @SpringBootTest( @@ -31,30 +44,106 @@ ) @AutoConfigureMockMvc @TestMethodOrder(MethodOrderer.OrderAnnotation.class) +@TestInstance(TestInstance.Lifecycle.PER_CLASS) public class UserControllerTests { private final String Gateway = "users"; + @MockBean + private UserRepository userRepository; + + @MockBean + private UserService userService; + + private List usersDTO; + private UserDTO userDTO; + private User userAdmin; + private User userModerator; + private User user; + private List users; + @Autowired private MockMvc mockMvc; - private static final int insertDataOrder = 1, updateDataOrder = 2, deleteDataOrder = 3; + private static final int insertDataOrder = 1, checkOnDuplicate = 2, updateDataOrder = 3, deleteDataOrder = 4; + + @Captor + ArgumentCaptor> userListArgumentCaptor; + + @Captor + ArgumentCaptor userArgumentCaptor; ObjectMapper objectMapper; User admin; - public UserControllerTests() { + @BeforeAll + public void setup() { objectMapper = new ObjectMapper(); objectMapper.findAndRegisterModules(); - admin = new User(); - admin.setName("Admin"); - admin.setRole("ROLE_ADMIN"); - admin.setMail("chupacabra@mail.ru"); + 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("pswdbobby"); + 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 = new UserDTO(user); + usersDTO = new ArrayList<>(); + usersDTO.add(new UserDTO(userAdmin)); + usersDTO.add(new UserDTO(userModerator)); + usersDTO.add(new UserDTO(user)); } @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 @@ -130,12 +219,21 @@ public void refreshTokenShouldReturnIsOk() throws Exception { @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.getUser().getName()); } @Test public void getUserShouldReturnStatusNotFound() throws Exception { + when(userRepository.findUserById(-1)).thenReturn(null); + when(userService.entityToUserDTO(null)).thenReturn(new UserDTO()); this.mockMvc.perform(MockMvcRequestBuilders.get("/" + Gateway + "/-1")).andDo(print()).andExpect(status().isNotFound()); + verify(userRepository, only()).findUserById(-1); + verify(userService, only()).entityToUserDTO(null); } @Test @@ -146,13 +244,20 @@ public void getUserWhenBadPathValueReturn400() throws Exception { @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); - Assertions.assertEquals(userResponse.getUser().getName(), admin.getName()); - Assertions.assertEquals(userResponse.getUser().getMail(), admin.getMail()); - Assertions.assertEquals(userResponse.getUser().getRole(), admin.getRole()); + verify(userRepository, only()).findUserById(1); + verify(userService, only()).entityToUserDTO(userArgumentCaptor.capture()); + + Assertions.assertEquals(userArgumentCaptor.getValue().getName(), userDTO.getUser().getName()); + + Assertions.assertEquals(userResponse.getUser().getName(), user.getName()); + Assertions.assertEquals(userResponse.getUser().getMail(), user.getMail()); + Assertions.assertEquals(userResponse.getUser().getRole(), user.getRole()); } @Test @@ -215,6 +320,13 @@ public void setGameRatingShouldReturnOk() throws Exception { this.mockMvc.perform(MockMvcRequestBuilders.post("/" + Gateway + "/1/set-game-rating/1/10")).andDo(print()).andExpect(status().isOk()); } + @Test + @WithMockUser(roles = "USER") + @Order(checkOnDuplicate) + public void setGameRatingShouldReturnBadRequest() throws Exception { + this.mockMvc.perform(MockMvcRequestBuilders.post("/" + Gateway + "/1/set-game-rating/1/10")).andDo(print()).andExpect(status().isBadRequest()); + } + @Test @WithMockUser(roles = "USER") public void setGameRatingShouldReturnBadRequestLessThanNormal() throws Exception { @@ -289,6 +401,13 @@ public void addGameToUserShouldReturnOk() throws Exception { this.mockMvc.perform(MockMvcRequestBuilders.post("/" + Gateway + "/1/add-game/1")).andDo(print()).andExpect(status().isOk()); } + @Test + @WithMockUser(roles = "USER") + @Order(checkOnDuplicate) + public void addGameToUserShouldReturnBadRequest() throws Exception { + this.mockMvc.perform(MockMvcRequestBuilders.post("/" + Gateway + "/1/add-game/1")).andDo(print()).andExpect(status().isBadRequest()); + } + @Test @WithMockUser(roles = "USER") public void addGameToUserShouldReturnStatusNotFound_FirstParameter() throws Exception { @@ -395,6 +514,13 @@ public void addGameToUserWishlistShouldReturnOk() throws Exception { this.mockMvc.perform(MockMvcRequestBuilders.post("/" + Gateway + "/1/add-game-to-wishlist/1")).andDo(print()).andExpect(status().isOk()); } + @Test + @WithMockUser(roles = "USER") + @Order(checkOnDuplicate) + public void addGameToUserWishlistShouldReturnBadRequest() throws Exception { + this.mockMvc.perform(MockMvcRequestBuilders.post("/" + Gateway + "/1/add-game-to-wishlist/1")).andDo(print()).andExpect(status().isBadRequest()); + } + @Test @WithMockUser(roles = "USER") public void addGameToUserWishlistShouldReturnStatusNotFound_FirstParameter() throws Exception { From ee8c1d9665e0da5f1ecd8f7cb0260e16c2bc133e Mon Sep 17 00:00:00 2001 From: "i.i.artamonov" Date: Tue, 5 Apr 2022 08:54:13 +0400 Subject: [PATCH 088/141] Changed getUserCollection Added mock objects --- .../boardgamefun/UserControllerTests.java | 97 ++++++++++++++++++- 1 file changed, 95 insertions(+), 2 deletions(-) diff --git a/src/test/java/com/petproject/boardgamefun/UserControllerTests.java b/src/test/java/com/petproject/boardgamefun/UserControllerTests.java index 0fdf097..c4da9b0 100644 --- a/src/test/java/com/petproject/boardgamefun/UserControllerTests.java +++ b/src/test/java/com/petproject/boardgamefun/UserControllerTests.java @@ -5,14 +5,19 @@ import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status; import com.fasterxml.jackson.databind.ObjectMapper; +import com.petproject.boardgamefun.dto.DesignerDTO; import com.petproject.boardgamefun.dto.GameDTO; import com.petproject.boardgamefun.dto.UserDTO; +import com.petproject.boardgamefun.model.Designer; +import com.petproject.boardgamefun.model.Game; import com.petproject.boardgamefun.model.User; +import com.petproject.boardgamefun.repository.GameRepository; import com.petproject.boardgamefun.repository.UserRepository; 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.service.GameService; import com.petproject.boardgamefun.service.UserService; import org.junit.jupiter.api.*; import org.junit.jupiter.api.extension.ExtendWith; @@ -55,12 +60,24 @@ public class UserControllerTests { @MockBean private UserService userService; + @MockBean + private GameService gameService; + + @MockBean + private GameRepository gameRepository; + private List usersDTO; private UserDTO userDTO; private User userAdmin; private User userModerator; private User user; private List users; + private List gamesDTO; + private GameDTO gameDTO; + private Game game; + private List games; + private Designer designer; + private DesignerDTO designerDTO; @Autowired private MockMvc mockMvc; @@ -72,6 +89,12 @@ public class UserControllerTests { @Captor ArgumentCaptor userArgumentCaptor; + @Captor + ArgumentCaptor> gameListArgumentCaptor; + + @Captor + ArgumentCaptor gameArgumentCaptor; + ObjectMapper objectMapper; User admin; @@ -118,6 +141,59 @@ public void setup() { usersDTO.add(new UserDTO(userAdmin)); usersDTO.add(new UserDTO(userModerator)); usersDTO.add(new UserDTO(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()); + + gameDTO = new GameDTO(game, 8.4, designers); + designers.remove(1); + GameDTO gameDTO1 = new GameDTO(game, 7.9, designers); + + gamesDTO = new ArrayList<>(); + gamesDTO.add(gameDTO); + gamesDTO.add(gameDTO1); + } @Test @@ -263,15 +339,32 @@ public void getUserWhenValidInput_thenReturnUserResource() throws Exception { @Test @WithMockUser(roles = "USER") public void getUserCollectionShouldReturnIsOk() throws Exception { - this.mockMvc.perform(MockMvcRequestBuilders.get("/" + Gateway + "/1/games")).andExpect(status().isOk()); + 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(), GameDTO[].class); + + verify(gameRepository, only()).findUserGames(1); + verify(gameService, only()).entitiesToGameDTO(gameListArgumentCaptor.capture()); + + Assertions.assertNotEquals(gameListArgumentCaptor.getValue().size(), 0); + Assertions.assertEquals(userCollection[0].getGame().getId(), gamesDTO.get(0).getGame().getId()); } @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(), GameDTO[].class); - Assertions.assertEquals(0, gameDTOS.length); + + verify(gameRepository, only()).findUserGames(-1); + verify(gameService, only()).entitiesToGameDTO(gameListArgumentCaptor.capture()); + + Assertions.assertNull(gameListArgumentCaptor.getValue()); + Assertions.assertEquals(gameDTOS.length, 0); } @Test From f6c16134eb346a2efb414f3a135fca0c0c27e79b Mon Sep 17 00:00:00 2001 From: "i.i.artamonov" Date: Tue, 5 Apr 2022 09:25:38 +0400 Subject: [PATCH 089/141] Changed getUserRatingList Added mock objects. Add pojo to imitate UserGameRatingProjection --- .../boardgamefun/UserControllerTests.java | 33 +++++++++++++++++-- .../model/UserGameRatingPOJO.java | 23 +++++++++++++ 2 files changed, 53 insertions(+), 3 deletions(-) create mode 100644 src/test/java/com/petproject/boardgamefun/model/UserGameRatingPOJO.java diff --git a/src/test/java/com/petproject/boardgamefun/UserControllerTests.java b/src/test/java/com/petproject/boardgamefun/UserControllerTests.java index c4da9b0..e0fc3bd 100644 --- a/src/test/java/com/petproject/boardgamefun/UserControllerTests.java +++ b/src/test/java/com/petproject/boardgamefun/UserControllerTests.java @@ -8,10 +8,12 @@ import com.petproject.boardgamefun.dto.DesignerDTO; import com.petproject.boardgamefun.dto.GameDTO; import com.petproject.boardgamefun.dto.UserDTO; +import com.petproject.boardgamefun.dto.projection.UserGameRatingProjection; import com.petproject.boardgamefun.model.Designer; import com.petproject.boardgamefun.model.Game; import com.petproject.boardgamefun.model.User; +import com.petproject.boardgamefun.model.UserGameRatingPOJO; import com.petproject.boardgamefun.repository.GameRepository; import com.petproject.boardgamefun.repository.UserRepository; import com.petproject.boardgamefun.security.model.JwtResponse; @@ -76,6 +78,7 @@ public class UserControllerTests { private GameDTO gameDTO; private Game game; private List games; + private List userGameRatingProjections; private Designer designer; private DesignerDTO designerDTO; @@ -92,13 +95,15 @@ public class UserControllerTests { @Captor ArgumentCaptor> gameListArgumentCaptor; + @Captor + ArgumentCaptor> userGameRatingProjectionCaptor; + @Captor ArgumentCaptor gameArgumentCaptor; ObjectMapper objectMapper; User admin; - @BeforeAll public void setup() { objectMapper = new ObjectMapper(); @@ -190,6 +195,10 @@ public void setup() { designers.remove(1); GameDTO gameDTO1 = new GameDTO(game, 7.9, designers); + userGameRatingProjections = new ArrayList<>(); + userGameRatingProjections.add(new UserGameRatingPOJO(game, 3)); + userGameRatingProjections.add(new UserGameRatingPOJO(game, 10)); + gamesDTO = new ArrayList<>(); gamesDTO.add(gameDTO); gamesDTO.add(gameDTO1); @@ -370,15 +379,33 @@ public void getUserCollectionShouldReturnBlankArray() throws Exception { @Test @WithMockUser(roles = "USER") public void getUserRatingListShouldReturnIsOk() throws Exception { - this.mockMvc.perform(MockMvcRequestBuilders.get("/" + Gateway + "/1/games-rating")).andExpect(status().isOk()); + when(gameRepository.findUserGameRatingList(1)).thenReturn(userGameRatingProjections); + when(gameService.userGameRatingToGameDTO(userGameRatingProjections)).thenReturn(gamesDTO); + + MvcResult mvcResult = this.mockMvc.perform(MockMvcRequestBuilders.get("/" + Gateway + "/1/games-rating")).andExpect(status().isOk()).andReturn(); + var userRatingList = objectMapper.readValue(mvcResult.getResponse().getContentAsByteArray(), GameDTO[].class); + + verify(gameRepository, only()).findUserGameRatingList(1); + verify(gameService, only()).userGameRatingToGameDTO(userGameRatingProjectionCaptor.capture()); + + Assertions.assertNotEquals(userGameRatingProjectionCaptor.getValue().size(), 0); + Assertions.assertEquals(userRatingList[0].getGame().getId(), gamesDTO.get(0).getGame().getId()); } @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(), GameDTO[].class); - Assertions.assertEquals(0, gameDTOS.length); + + verify(gameRepository, only()).findUserGameRatingList(-1); + verify(gameService, only()).userGameRatingToGameDTO(userGameRatingProjectionCaptor.capture()); + + Assertions.assertNull(userGameRatingProjectionCaptor.getValue()); + Assertions.assertEquals(gameDTOS.length, 0); } @Test 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; + } +} From 96513ca47874c1e07d3c36560198528a62c74d94 Mon Sep 17 00:00:00 2001 From: "i.i.artamonov" Date: Wed, 6 Apr 2022 10:20:19 +0400 Subject: [PATCH 090/141] Changed deleteGameRating tests Added mocks to tests. Change the signature and name of method of RatingGameByUserRepository for removing misunderstanding. Add changes to controller --- .../controller/UserController.java | 6 +-- .../RatingGameByUserRepository.java | 2 +- .../boardgamefun/UserControllerTests.java | 45 ++++++++++++++++--- 3 files changed, 43 insertions(+), 10 deletions(-) diff --git a/src/main/java/com/petproject/boardgamefun/controller/UserController.java b/src/main/java/com/petproject/boardgamefun/controller/UserController.java index 05c60a9..74be032 100644 --- a/src/main/java/com/petproject/boardgamefun/controller/UserController.java +++ b/src/main/java/com/petproject/boardgamefun/controller/UserController.java @@ -249,7 +249,7 @@ public ResponseEntity> getUserRatingList(@PathVariable Integer use @PreAuthorize("hasRole('USER') or hasRole('MODERATOR') or hasRole('ADMIN')") public ResponseEntity deleteGameRating(@PathVariable Integer userId, @PathVariable Integer gameId) { - var ratingGameByUser = ratingGameByUserRepository.findRatingGame_ByGameIdAndUserId(gameId, userId); + var ratingGameByUser = ratingGameByUserRepository.findRatingGame_ByUserIdAndGameId(userId, gameId); if (ratingGameByUser == null) return new ResponseEntity<>(null, HttpStatus.NOT_FOUND); @@ -267,7 +267,7 @@ public ResponseEntity setGameRating(@PathVariable Integer userId, @Path if (rating > 10 || rating < 1) { return new ResponseEntity<>(null, HttpStatus.BAD_REQUEST); } - if (ratingGameByUserRepository.findRatingGame_ByGameIdAndUserId(gameId, userId) != null) { + if (ratingGameByUserRepository.findRatingGame_ByUserIdAndGameId(userId, gameId) != null) { return new ResponseEntity<>(null, HttpStatus.BAD_REQUEST); } @@ -296,7 +296,7 @@ public ResponseEntity updateGameRating(@PathVariable Integer userId, @P if (rating > 10 || rating < 1) { return new ResponseEntity<>(null, HttpStatus.BAD_REQUEST); } - var ratingGameByUser = ratingGameByUserRepository.findRatingGame_ByGameIdAndUserId(gameId, userId); + var ratingGameByUser = ratingGameByUserRepository.findRatingGame_ByUserIdAndGameId(userId, gameId); if (ratingGameByUser == null) { return new ResponseEntity<>(null, HttpStatus.NOT_FOUND); } diff --git a/src/main/java/com/petproject/boardgamefun/repository/RatingGameByUserRepository.java b/src/main/java/com/petproject/boardgamefun/repository/RatingGameByUserRepository.java index 5b3ea03..af46bca 100644 --- a/src/main/java/com/petproject/boardgamefun/repository/RatingGameByUserRepository.java +++ b/src/main/java/com/petproject/boardgamefun/repository/RatingGameByUserRepository.java @@ -4,5 +4,5 @@ import org.springframework.data.jpa.repository.JpaRepository; public interface RatingGameByUserRepository extends JpaRepository { - RatingGameByUser findRatingGame_ByGameIdAndUserId(Integer gameId, Integer userId); + RatingGameByUser findRatingGame_ByUserIdAndGameId(Integer userId, Integer gameId ); } \ No newline at end of file diff --git a/src/test/java/com/petproject/boardgamefun/UserControllerTests.java b/src/test/java/com/petproject/boardgamefun/UserControllerTests.java index e0fc3bd..d1af384 100644 --- a/src/test/java/com/petproject/boardgamefun/UserControllerTests.java +++ b/src/test/java/com/petproject/boardgamefun/UserControllerTests.java @@ -9,12 +9,10 @@ import com.petproject.boardgamefun.dto.GameDTO; import com.petproject.boardgamefun.dto.UserDTO; import com.petproject.boardgamefun.dto.projection.UserGameRatingProjection; -import com.petproject.boardgamefun.model.Designer; -import com.petproject.boardgamefun.model.Game; -import com.petproject.boardgamefun.model.User; +import com.petproject.boardgamefun.model.*; -import com.petproject.boardgamefun.model.UserGameRatingPOJO; import com.petproject.boardgamefun.repository.GameRepository; +import com.petproject.boardgamefun.repository.RatingGameByUserRepository; import com.petproject.boardgamefun.repository.UserRepository; import com.petproject.boardgamefun.security.model.JwtResponse; import com.petproject.boardgamefun.security.model.LoginRequest; @@ -68,6 +66,9 @@ public class UserControllerTests { @MockBean private GameRepository gameRepository; + @MockBean + private RatingGameByUserRepository ratingGameByUserRepository; + private List usersDTO; private UserDTO userDTO; private User userAdmin; @@ -81,6 +82,7 @@ public class UserControllerTests { private List userGameRatingProjections; private Designer designer; private DesignerDTO designerDTO; + private RatingGameByUser ratingGameByUser; @Autowired private MockMvc mockMvc; @@ -101,9 +103,13 @@ public class UserControllerTests { @Captor ArgumentCaptor gameArgumentCaptor; + @Captor + ArgumentCaptor ratingGameByUserArgumentCaptor; + ObjectMapper objectMapper; User admin; + @BeforeAll public void setup() { objectMapper = new ObjectMapper(); @@ -203,6 +209,12 @@ public void setup() { gamesDTO.add(gameDTO); gamesDTO.add(gameDTO1); + ratingGameByUser = new RatingGameByUser(); + ratingGameByUser.setUser(user); + ratingGameByUser.setGame(game); + ratingGameByUser.setRating(8); + ratingGameByUser.setId(1); + } @Test @@ -411,26 +423,47 @@ public void getUserRatingListShouldReturnBlankArray() throws Exception { @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") - @Order(deleteDataOrder) public void deleteGameRatingShouldReturnOk() throws Exception { - this.mockMvc.perform(MockMvcRequestBuilders.delete("/" + Gateway + "/1/delete-game-rating/1")).andDo(print()).andExpect(status().isOk()); + 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 From fb358c1a9603a7e58329b864cd36c45f2b22ad47 Mon Sep 17 00:00:00 2001 From: "i.i.artamonov" Date: Thu, 7 Apr 2022 08:24:01 +0400 Subject: [PATCH 091/141] Added changes to pom for kotlin compiler Now kotlin compile the project good. Commented unused tests for compiling --- pom.xml | 91 ++++++++++--------- .../boardgamefun/UserControllerTests.java | 15 +-- 2 files changed, 58 insertions(+), 48 deletions(-) diff --git a/pom.xml b/pom.xml index b028f14..4946ea8 100644 --- a/pom.xml +++ b/pom.xml @@ -144,70 +144,79 @@ - 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 - - - - org.jetbrains.kotlin kotlin-maven-plugin + org.jetbrains.kotlin ${kotlin.version} compile - compile - - compile - + compile + + + ${project.basedir}/src/main/kotlin + ${project.basedir}/src/main/java + + test-compile - test-compile - - test-compile - + test-compile + + + ${project.basedir}/src/test/kotlin + ${project.basedir}/src/test/java + + - - 1.8 - - + org.apache.maven.plugins maven-compiler-plugin + - compile + default-compile + none + + + + default-testCompile + none + + + java-compile compile - - compile - + compile - testCompile + java-test-compile test-compile + testCompile + + + + + cz.habarta.typescript-generator + typescript-generator-maven-plugin + 2.34.976 + + + generate - testCompile + generate + process-classes + + jackson2 + + com.petproject.boardgamefun.dto.* + + target/rest.d.ts + module + diff --git a/src/test/java/com/petproject/boardgamefun/UserControllerTests.java b/src/test/java/com/petproject/boardgamefun/UserControllerTests.java index d1af384..c291245 100644 --- a/src/test/java/com/petproject/boardgamefun/UserControllerTests.java +++ b/src/test/java/com/petproject/boardgamefun/UserControllerTests.java @@ -243,7 +243,7 @@ public void getUsersShouldReturnOk_BlankList() throws Exception { Assertions.assertEquals(userResponse.length, 0); } - @Test + /*@Test public void authenticateUserShouldReturnOk() throws Exception { LoginRequest loginRequest = new LoginRequest("Admin", "123qweAdmin"); this.mockMvc.perform(MockMvcRequestBuilders.post("/" + Gateway + "/sign-in").contentType(MediaType.APPLICATION_JSON) @@ -294,9 +294,9 @@ public void refreshTokenShouldReturnNotAuthorizedBadAccessToken() throws Excepti .accept(MediaType.APPLICATION_JSON) .content(objectMapper.writeValueAsString(refreshTokenRequest))) .andExpect(status().isUnauthorized()); - } + }*/ - @Test + /* @Test public void refreshTokenShouldReturnIsOk() throws Exception { LoginRequest loginRequest = new LoginRequest("Admin", "123qweAdmin"); @@ -312,7 +312,7 @@ public void refreshTokenShouldReturnIsOk() throws Exception { .accept(MediaType.APPLICATION_JSON) .content(objectMapper.writeValueAsString(refreshTokenRequest))) .andExpect(status().isOk()); - } + }*/ @Test public void getUserShouldReturnStatusOkTest() throws Exception { @@ -394,7 +394,8 @@ 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")).andExpect(status().isOk()).andReturn(); + 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(), GameDTO[].class); verify(gameRepository, only()).findUserGameRatingList(1); @@ -466,7 +467,7 @@ public void deleteGameRatingShouldReturnOk() throws Exception { Assertions.assertEquals(mvcResult, "Оценка с текущей игры удалена"); } - @Test + /*@Test @WithMockUser(roles = "USER") @Order(insertDataOrder) public void setGameRatingShouldReturnOk() throws Exception { @@ -715,5 +716,5 @@ public void addGameToUserWishlistShouldReturnStatusBadRequest_BothParameters() t @Order(deleteDataOrder) public void deleteGameFromUserWishlistShouldReturnOk() throws Exception { this.mockMvc.perform(MockMvcRequestBuilders.delete("/" + Gateway + "/1/delete-game-from-wishlist/1")).andDo(print()).andExpect(status().isOk()); - } + }*/ } From 0f402d62ad4600c6b197c296262aa46df550ea7e Mon Sep 17 00:00:00 2001 From: "i.i.artamonov" Date: Fri, 8 Apr 2022 15:58:34 +0400 Subject: [PATCH 092/141] Changed authenticateUser tests Mock the objects --- .../boardgamefun/UserControllerTests.java | 67 ++++++++++++++++--- 1 file changed, 58 insertions(+), 9 deletions(-) diff --git a/src/test/java/com/petproject/boardgamefun/UserControllerTests.java b/src/test/java/com/petproject/boardgamefun/UserControllerTests.java index c291245..75517ac 100644 --- a/src/test/java/com/petproject/boardgamefun/UserControllerTests.java +++ b/src/test/java/com/petproject/boardgamefun/UserControllerTests.java @@ -14,9 +14,10 @@ import com.petproject.boardgamefun.repository.GameRepository; import com.petproject.boardgamefun.repository.RatingGameByUserRepository; import com.petproject.boardgamefun.repository.UserRepository; -import com.petproject.boardgamefun.security.model.JwtResponse; +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.services.RefreshTokenService; +import com.petproject.boardgamefun.security.services.UserDetailsImpl; import com.petproject.boardgamefun.service.GameService; import com.petproject.boardgamefun.service.UserService; import org.junit.jupiter.api.*; @@ -32,6 +33,10 @@ import org.springframework.boot.test.context.SpringBootTest; import org.springframework.boot.test.mock.mockito.MockBean; import org.springframework.http.MediaType; +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; @@ -69,6 +74,21 @@ public class UserControllerTests { @MockBean private RatingGameByUserRepository ratingGameByUserRepository; + @MockBean + private RefreshTokenService refreshTokenService; + + @MockBean + private AuthenticationManager authenticationManager; + + @MockBean + private Authentication authentication; + + @MockBean + private JwtUtils jwtUtils; + + @MockBean + private UserDetailsImpl userDetails; + private List usersDTO; private UserDTO userDTO; private User userAdmin; @@ -106,6 +126,9 @@ public class UserControllerTests { @Captor ArgumentCaptor ratingGameByUserArgumentCaptor; + @Captor + ArgumentCaptor stringArgumentCaptor; + ObjectMapper objectMapper; User admin; @@ -135,7 +158,7 @@ public void setup() { user = new User(); user.setId(34); user.setName("Bobby"); - user.setPassword("pswdbobby"); + user.setPassword("1234qwer"); user.setRole("USER"); user.setMail("bobby@ggogle.com"); user.setRating(1.0); @@ -243,12 +266,29 @@ public void getUsersShouldReturnOk_BlankList() throws Exception { Assertions.assertEquals(userResponse.length, 0); } - /*@Test + @Test + @WithMockUser(roles = "USER") public void authenticateUserShouldReturnOk() throws Exception { - LoginRequest loginRequest = new LoginRequest("Admin", "123qweAdmin"); + 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 @@ -263,6 +303,7 @@ public void authenticateUserShouldReturn415() throws Exception { @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) @@ -271,7 +312,16 @@ public void authenticateUserShouldReturnNotFound() throws Exception { @Test public void authenticateUserShouldReturnNotAuthorized() throws Exception { - LoginRequest loginRequest = new LoginRequest("Admin", "qweAdmin"); + 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) @@ -286,7 +336,7 @@ public void authenticateUserShouldReturnBadRequest() throws Exception { .andExpect(status().isBadRequest()); } - @Test + /* @Test public void refreshTokenShouldReturnNotAuthorizedBadAccessToken() throws Exception { RefreshTokenRequest refreshTokenRequest = new RefreshTokenRequest("Admin", "bla-bla"); this.mockMvc.perform(MockMvcRequestBuilders.post("/" + Gateway + "/refresh-token") @@ -294,9 +344,8 @@ public void refreshTokenShouldReturnNotAuthorizedBadAccessToken() throws Excepti .accept(MediaType.APPLICATION_JSON) .content(objectMapper.writeValueAsString(refreshTokenRequest))) .andExpect(status().isUnauthorized()); - }*/ - /* @Test + @Test public void refreshTokenShouldReturnIsOk() throws Exception { LoginRequest loginRequest = new LoginRequest("Admin", "123qweAdmin"); From 151a7c43709c680720331a898cf734c551d6c321 Mon Sep 17 00:00:00 2001 From: "i.i.artamonov" Date: Mon, 11 Apr 2022 09:18:40 +0400 Subject: [PATCH 093/141] Changed refreshToken tests Add mocks to tests --- .../boardgamefun/UserControllerTests.java | 30 ++++++++++++------- 1 file changed, 19 insertions(+), 11 deletions(-) diff --git a/src/test/java/com/petproject/boardgamefun/UserControllerTests.java b/src/test/java/com/petproject/boardgamefun/UserControllerTests.java index 75517ac..f7f5cb1 100644 --- a/src/test/java/com/petproject/boardgamefun/UserControllerTests.java +++ b/src/test/java/com/petproject/boardgamefun/UserControllerTests.java @@ -14,8 +14,11 @@ import com.petproject.boardgamefun.repository.GameRepository; import com.petproject.boardgamefun.repository.RatingGameByUserRepository; import com.petproject.boardgamefun.repository.UserRepository; +import com.petproject.boardgamefun.security.exception.RefreshTokenException; 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.GameService; @@ -336,32 +339,37 @@ public void authenticateUserShouldReturnBadRequest() throws Exception { .andExpect(status().isBadRequest()); } - /* @Test + @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"); - LoginRequest loginRequest = new LoginRequest("Admin", "123qweAdmin"); - MvcResult mvcResult = this.mockMvc.perform(MockMvcRequestBuilders.post("/" + Gateway + "/sign-in").contentType(MediaType.APPLICATION_JSON) - .accept(MediaType.APPLICATION_JSON) - .content(objectMapper.writeValueAsString(loginRequest))).andExpect(status().isOk()).andReturn(); - - JwtResponse jwtResponse = objectMapper.readValue(mvcResult.getResponse().getContentAsByteArray(), JwtResponse.class); + when(refreshTokenService.verifyExpiration(refreshTokenRequest.getRefreshToken())).thenReturn(true); + when(jwtUtils.generateJwtToken(refreshTokenRequest.getUserName())).thenReturn("new token"); - RefreshTokenRequest refreshTokenRequest = new RefreshTokenRequest(jwtResponse.getUserName(), jwtResponse.getRefreshToken()); - this.mockMvc.perform(MockMvcRequestBuilders.post("/" + Gateway + "/refresh-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()); - }*/ + .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 { From 628c165d063167a033986cea7c8fc98e84b8e7c4 Mon Sep 17 00:00:00 2001 From: "i.i.artamonov" Date: Tue, 12 Apr 2022 09:55:44 +0400 Subject: [PATCH 094/141] Changed setGameRating tests Added mocks to tests. Delete duplicate saving ratingGameByUserRepository entity --- .../controller/UserController.java | 3 - .../boardgamefun/UserControllerTests.java | 65 +++++++++++++++---- 2 files changed, 53 insertions(+), 15 deletions(-) diff --git a/src/main/java/com/petproject/boardgamefun/controller/UserController.java b/src/main/java/com/petproject/boardgamefun/controller/UserController.java index 74be032..6be9831 100644 --- a/src/main/java/com/petproject/boardgamefun/controller/UserController.java +++ b/src/main/java/com/petproject/boardgamefun/controller/UserController.java @@ -304,9 +304,6 @@ public ResponseEntity updateGameRating(@PathVariable Integer userId, @P ratingGameByUser.setRating(rating); ratingGameByUserRepository.save(ratingGameByUser); - - ratingGameByUserRepository.save(ratingGameByUser); - return new ResponseEntity<>(rating, HttpStatus.OK); } diff --git a/src/test/java/com/petproject/boardgamefun/UserControllerTests.java b/src/test/java/com/petproject/boardgamefun/UserControllerTests.java index f7f5cb1..c77eff7 100644 --- a/src/test/java/com/petproject/boardgamefun/UserControllerTests.java +++ b/src/test/java/com/petproject/boardgamefun/UserControllerTests.java @@ -238,9 +238,7 @@ public void setup() { ratingGameByUser = new RatingGameByUser(); ratingGameByUser.setUser(user); ratingGameByUser.setGame(game); - ratingGameByUser.setRating(8); - ratingGameByUser.setId(1); - + ratingGameByUser.setRating(10); } @Test @@ -368,7 +366,7 @@ public void refreshTokenShouldReturnIsOk() throws Exception { verify(refreshTokenService, only()).verifyExpiration(refreshTokenRequest.getRefreshToken()); verify(jwtUtils, only()).generateJwtToken(refreshTokenRequest.getUserName()); - Assertions.assertEquals(refreshTokenResponse.getAccessToken(),"new token"); + Assertions.assertEquals(refreshTokenResponse.getAccessToken(), "new token"); } @Test @@ -524,18 +522,35 @@ public void deleteGameRatingShouldReturnOk() throws Exception { Assertions.assertEquals(mvcResult, "Оценка с текущей игры удалена"); } - /*@Test + @Test @WithMockUser(roles = "USER") - @Order(insertDataOrder) public void setGameRatingShouldReturnOk() throws Exception { - this.mockMvc.perform(MockMvcRequestBuilders.post("/" + Gateway + "/1/set-game-rating/1/10")).andDo(print()).andExpect(status().isOk()); + 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(), Integer.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") - @Order(checkOnDuplicate) 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 @@ -553,22 +568,48 @@ public void setGameRatingShouldReturnBadRequestMoreThanNormal() throws Exception @Test @WithMockUser(roles = "USER") public void setGameRatingShouldReturnNotFound_FirstParameter() throws Exception { - this.mockMvc.perform(MockMvcRequestBuilders.post("/" + Gateway + "/-1/set-game-rating/1/1")).andDo(print()).andExpect(status().isNotFound()); + 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 { - this.mockMvc.perform(MockMvcRequestBuilders.post("/" + Gateway + "/1/set-game-rating/-1/1")).andDo(print()).andExpect(status().isNotFound()); + 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 { - this.mockMvc.perform(MockMvcRequestBuilders.post("/" + Gateway + "/-1/set-game-rating/-1/1")).andDo(print()).andExpect(status().isNotFound()); + 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 + /*@Test @WithMockUser(roles = "USER") @Order(updateDataOrder) public void updateGameRatingShouldReturnOk() throws Exception { From 95aff1d1f13cf1e0916433263d8587c2b591d453 Mon Sep 17 00:00:00 2001 From: "i.i.artamonov" Date: Wed, 13 Apr 2022 08:47:08 +0400 Subject: [PATCH 095/141] Changed updateGameRating tests Added mocks --- .../boardgamefun/UserControllerTests.java | 39 +++++++++++++++---- 1 file changed, 32 insertions(+), 7 deletions(-) diff --git a/src/test/java/com/petproject/boardgamefun/UserControllerTests.java b/src/test/java/com/petproject/boardgamefun/UserControllerTests.java index c77eff7..16b4548 100644 --- a/src/test/java/com/petproject/boardgamefun/UserControllerTests.java +++ b/src/test/java/com/petproject/boardgamefun/UserControllerTests.java @@ -609,11 +609,21 @@ public void setGameRatingShouldReturnNotFound_BothParameters() throws Exception verify(gameRepository).findGameById(-1); } - /*@Test + @Test @WithMockUser(roles = "USER") - @Order(updateDataOrder) public void updateGameRatingShouldReturnOk() throws Exception { - this.mockMvc.perform(MockMvcRequestBuilders.post("/" + Gateway + "/1/update-game-rating/1/10")).andDo(print()).andExpect(status().isOk()); + + when(ratingGameByUserRepository.findRatingGame_ByUserIdAndGameId(1, 1)).thenReturn(ratingGameByUser); + when(ratingGameByUserRepository.save(ratingGameByUser)).thenReturn(null); + + var result = this.mockMvc.perform(MockMvcRequestBuilders.post("/" + Gateway + "/1/update-game-rating/1/10")) + .andDo(print()).andExpect(status().isOk()).andReturn(); + + var rating = objectMapper.readValue(result.getResponse().getContentAsByteArray(), Integer.class); + + verify(ratingGameByUserRepository).findRatingGame_ByUserIdAndGameId(1, 1); + verify(ratingGameByUserRepository).save(ratingGameByUser); + Assertions.assertEquals(ratingGameByUser.getRating(), rating); } @Test @@ -631,22 +641,37 @@ public void updateGameRatingShouldReturnBadRequestMoreThanNormal() throws Except @Test @WithMockUser(roles = "USER") public void updateGameRatingShouldReturnNotFound_FirstParameter() throws Exception { - this.mockMvc.perform(MockMvcRequestBuilders.post("/" + Gateway + "/-1/update-game-rating/1/1")).andDo(print()).andExpect(status().isNotFound()); + when(ratingGameByUserRepository.findRatingGame_ByUserIdAndGameId(-1, 1)).thenReturn(null); + + this.mockMvc.perform(MockMvcRequestBuilders.post("/" + 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 { - this.mockMvc.perform(MockMvcRequestBuilders.post("/" + Gateway + "/1/update-game-rating/-1/1")).andDo(print()).andExpect(status().isNotFound()); + when(ratingGameByUserRepository.findRatingGame_ByUserIdAndGameId(1, -1)).thenReturn(null); + + this.mockMvc.perform(MockMvcRequestBuilders.post("/" + 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 { - this.mockMvc.perform(MockMvcRequestBuilders.post("/" + Gateway + "/-1/update-game-rating/-1/1")).andDo(print()).andExpect(status().isNotFound()); + when(ratingGameByUserRepository.findRatingGame_ByUserIdAndGameId(-1, -1)).thenReturn(null); + + this.mockMvc.perform(MockMvcRequestBuilders.post("/" + Gateway + "/-1/update-game-rating/-1/1")) + .andDo(print()).andExpect(status().isNotFound()); + + verify(ratingGameByUserRepository).findRatingGame_ByUserIdAndGameId(-1, -1); } - @Test + /*@Test @WithMockUser(roles = "USER") @Order(insertDataOrder) public void addGameToUserShouldReturnOk() throws Exception { From f5034c1ba9e70955593a0ea75b6cd625df4a8688 Mon Sep 17 00:00:00 2001 From: "i.i.artamonov" Date: Thu, 14 Apr 2022 09:06:27 +0400 Subject: [PATCH 096/141] Changed addGameToUser tests Added mocks to tests. Added checks for empty list in addGameToUser method --- .../controller/UserController.java | 2 +- .../boardgamefun/UserControllerTests.java | 70 ++++++++++++++++--- 2 files changed, 61 insertions(+), 11 deletions(-) diff --git a/src/main/java/com/petproject/boardgamefun/controller/UserController.java b/src/main/java/com/petproject/boardgamefun/controller/UserController.java index 6be9831..3544a34 100644 --- a/src/main/java/com/petproject/boardgamefun/controller/UserController.java +++ b/src/main/java/com/petproject/boardgamefun/controller/UserController.java @@ -208,7 +208,7 @@ public ResponseEntity addGameToUser(@PathVariable Integer userId, @PathVariab return new ResponseEntity<>(null, HttpStatus.NOT_FOUND); var games = gameRepository.findUserGames(userId); - if (games.stream().anyMatch(g -> g.getId().equals(gameId))) { + if (games.size() != 0 && games.stream().anyMatch(g -> g.getId().equals(gameId))) { return new ResponseEntity<>(null, HttpStatus.BAD_REQUEST); } diff --git a/src/test/java/com/petproject/boardgamefun/UserControllerTests.java b/src/test/java/com/petproject/boardgamefun/UserControllerTests.java index 16b4548..8863ef0 100644 --- a/src/test/java/com/petproject/boardgamefun/UserControllerTests.java +++ b/src/test/java/com/petproject/boardgamefun/UserControllerTests.java @@ -13,8 +13,8 @@ import com.petproject.boardgamefun.repository.GameRepository; import com.petproject.boardgamefun.repository.RatingGameByUserRepository; +import com.petproject.boardgamefun.repository.UserOwnGameRepository; import com.petproject.boardgamefun.repository.UserRepository; -import com.petproject.boardgamefun.security.exception.RefreshTokenException; import com.petproject.boardgamefun.security.jwt.JwtUtils; import com.petproject.boardgamefun.security.model.LoginRequest; import com.petproject.boardgamefun.security.model.RefreshTokenRequest; @@ -92,6 +92,9 @@ public class UserControllerTests { @MockBean private UserDetailsImpl userDetails; + @MockBean + private UserOwnGameRepository userOwnGameRepository; + private List usersDTO; private UserDTO userDTO; private User userAdmin; @@ -106,6 +109,7 @@ public class UserControllerTests { private Designer designer; private DesignerDTO designerDTO; private RatingGameByUser ratingGameByUser; + private UserOwnGame userOwnGame; @Autowired private MockMvc mockMvc; @@ -239,6 +243,10 @@ public void setup() { ratingGameByUser.setUser(user); ratingGameByUser.setGame(game); ratingGameByUser.setRating(10); + + userOwnGame = new UserOwnGame(); + userOwnGame.setUser(user); + userOwnGame.setGame(game); } @Test @@ -671,36 +679,78 @@ public void updateGameRatingShouldReturnNotFound_BothParameters() throws Excepti verify(ratingGameByUserRepository).findRatingGame_ByUserIdAndGameId(-1, -1); } - /*@Test + @Test @WithMockUser(roles = "USER") - @Order(insertDataOrder) public void addGameToUserShouldReturnOk() throws Exception { - this.mockMvc.perform(MockMvcRequestBuilders.post("/" + Gateway + "/1/add-game/1")).andDo(print()).andExpect(status().isOk()); + + 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") - @Order(checkOnDuplicate) public void addGameToUserShouldReturnBadRequest() throws Exception { - this.mockMvc.perform(MockMvcRequestBuilders.post("/" + Gateway + "/1/add-game/1")).andDo(print()).andExpect(status().isBadRequest()); + 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 { - this.mockMvc.perform(MockMvcRequestBuilders.post("/" + Gateway + "/-11/add-game/1")).andDo(print()).andExpect(status().isNotFound()); + 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 { - this.mockMvc.perform(MockMvcRequestBuilders.post("/" + Gateway + "/1/add-game/-1")).andDo(print()).andExpect(status().isNotFound()); + 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 { - this.mockMvc.perform(MockMvcRequestBuilders.post("/" + Gateway + "/-1/add-game/-1")).andDo(print()).andExpect(status().isNotFound()); + 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 @@ -721,7 +771,7 @@ public void addGameToUserShouldReturnStatusBadRequest_BothParameters() throws Ex this.mockMvc.perform(MockMvcRequestBuilders.post("/" + Gateway + "/bla/add-game/bla")).andDo(print()).andExpect(status().isBadRequest()); } - @Test + /*@Test @WithMockUser(roles = "USER") public void deleteGameFromUserCollectionShouldReturnNotFound_FirstParameter() throws Exception { this.mockMvc.perform(MockMvcRequestBuilders.delete("/" + Gateway + "/-1/delete-game/1")).andDo(print()).andExpect(status().isNotFound()); From 1b0fa6c370206e167817613932c3c363f66c5c27 Mon Sep 17 00:00:00 2001 From: "i.i.artamonov" Date: Fri, 15 Apr 2022 08:47:36 +0400 Subject: [PATCH 097/141] Changed deleteGameFromUserCollection Added mocks to method. Change name and signature of findUserOwnGame_ByUserIdAndGameId method in UserOwnGameRepository. Added this changes to controller --- .../controller/UserController.java | 2 +- .../repository/UserOwnGameRepository.java | 2 +- .../boardgamefun/UserControllerTests.java | 35 +++++++++++++++---- 3 files changed, 30 insertions(+), 9 deletions(-) diff --git a/src/main/java/com/petproject/boardgamefun/controller/UserController.java b/src/main/java/com/petproject/boardgamefun/controller/UserController.java index 3544a34..1527403 100644 --- a/src/main/java/com/petproject/boardgamefun/controller/UserController.java +++ b/src/main/java/com/petproject/boardgamefun/controller/UserController.java @@ -226,7 +226,7 @@ public ResponseEntity addGameToUser(@PathVariable Integer userId, @PathVariab @PreAuthorize("hasRole('USER') or hasRole('MODERATOR') or hasRole('ADMIN')") public ResponseEntity deleteGameFromUserCollection(@PathVariable Integer userId, @PathVariable Integer gameId) { - var userOwnGame = userOwnGameRepository.findUserOwnGame_ByGameIdAndUserId(gameId, userId); + var userOwnGame = userOwnGameRepository.findUserOwnGame_ByUserIdAndGameId(userId, gameId); if (userOwnGame == null) return new ResponseEntity<>(null, HttpStatus.NOT_FOUND); diff --git a/src/main/java/com/petproject/boardgamefun/repository/UserOwnGameRepository.java b/src/main/java/com/petproject/boardgamefun/repository/UserOwnGameRepository.java index 9a6824b..3124ce0 100644 --- a/src/main/java/com/petproject/boardgamefun/repository/UserOwnGameRepository.java +++ b/src/main/java/com/petproject/boardgamefun/repository/UserOwnGameRepository.java @@ -4,5 +4,5 @@ import org.springframework.data.jpa.repository.JpaRepository; public interface UserOwnGameRepository extends JpaRepository { - UserOwnGame findUserOwnGame_ByGameIdAndUserId(Integer gameId, Integer userId); + UserOwnGame findUserOwnGame_ByUserIdAndGameId(Integer userId, Integer gameId); } diff --git a/src/test/java/com/petproject/boardgamefun/UserControllerTests.java b/src/test/java/com/petproject/boardgamefun/UserControllerTests.java index 8863ef0..f618e88 100644 --- a/src/test/java/com/petproject/boardgamefun/UserControllerTests.java +++ b/src/test/java/com/petproject/boardgamefun/UserControllerTests.java @@ -771,22 +771,37 @@ public void addGameToUserShouldReturnStatusBadRequest_BothParameters() throws Ex this.mockMvc.perform(MockMvcRequestBuilders.post("/" + Gateway + "/bla/add-game/bla")).andDo(print()).andExpect(status().isBadRequest()); } - /*@Test + @Test @WithMockUser(roles = "USER") public void deleteGameFromUserCollectionShouldReturnNotFound_FirstParameter() throws Exception { - this.mockMvc.perform(MockMvcRequestBuilders.delete("/" + Gateway + "/-1/delete-game/1")).andDo(print()).andExpect(status().isNotFound()); + 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 { - this.mockMvc.perform(MockMvcRequestBuilders.delete("/" + Gateway + "/1/delete-game/-1")).andDo(print()).andExpect(status().isNotFound()); + 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 { - this.mockMvc.perform(MockMvcRequestBuilders.delete("/" + Gateway + "/-11/delete-game/-11")).andDo(print()).andExpect(status().isNotFound()); + 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 @@ -809,12 +824,18 @@ public void deleteGameFromUserCollectionShouldReturnBadRequest_BothParameters() @Test @WithMockUser(roles = "USER") - @Order(deleteDataOrder) public void deleteGameFromUserCollectionShouldReturnOk() throws Exception { - this.mockMvc.perform(MockMvcRequestBuilders.delete("/" + Gateway + "/1/delete-game/1")).andDo(print()).andExpect(status().isOk()); + 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 + /*@Test @WithMockUser(roles = "USER") public void getUserWishlistShouldReturnIsOk() throws Exception { this.mockMvc.perform(MockMvcRequestBuilders.get("/" + Gateway + "/1/wishlist")).andExpect(status().isOk()); From b0e8a52ed11b387d093862366ce68e13063a49c5 Mon Sep 17 00:00:00 2001 From: "i.i.artamonov" Date: Mon, 18 Apr 2022 09:08:55 +0400 Subject: [PATCH 098/141] Changed getUserWishlist tests Added mocks to tests --- .../boardgamefun/UserControllerTests.java | 29 +++++++++++++++---- 1 file changed, 23 insertions(+), 6 deletions(-) diff --git a/src/test/java/com/petproject/boardgamefun/UserControllerTests.java b/src/test/java/com/petproject/boardgamefun/UserControllerTests.java index f618e88..6a6e9b1 100644 --- a/src/test/java/com/petproject/boardgamefun/UserControllerTests.java +++ b/src/test/java/com/petproject/boardgamefun/UserControllerTests.java @@ -835,18 +835,35 @@ public void deleteGameFromUserCollectionShouldReturnOk() throws Exception { verify(userOwnGameRepository).delete(userOwnGame); } - /*@Test + @Test @WithMockUser(roles = "USER") public void getUserWishlistShouldReturnIsOk() throws Exception { - this.mockMvc.perform(MockMvcRequestBuilders.get("/" + Gateway + "/1/wishlist")).andExpect(status().isOk()); + 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(), GameDTO[].class); + + verify(gameRepository).findUserWishlist(1); + verify(gameService).entitiesToGameDTO(gameListArgumentCaptor.capture()); + + Assertions.assertEquals(response.length, gamesDTO.size()); + Assertions.assertEquals(response[0].getGame().getId(), gamesDTO.get(0).getGame().getId()); + 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 { - MvcResult mvcResult = this.mockMvc.perform(MockMvcRequestBuilders.get("/" + Gateway + "/-1/wishlist")).andExpect(status().isOk()).andReturn(); - var gameDTOS = objectMapper.readValue(mvcResult.getResponse().getContentAsByteArray(), GameDTO[].class); - Assertions.assertEquals(0, gameDTOS.length); + 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(), GameDTO[].class); + Assertions.assertEquals(0, response.length); } @Test @@ -855,7 +872,7 @@ public void getUserWishlistShouldReturnBadRequest() throws Exception { this.mockMvc.perform(MockMvcRequestBuilders.get("/" + Gateway + "/bla/wishlist")).andExpect(status().isBadRequest()); } - @Test + /*@Test @WithMockUser(roles = "USER") @Order(insertDataOrder) public void addGameToUserWishlistShouldReturnOk() throws Exception { From 440bc42111fa785d00dad099f667cd48072730af Mon Sep 17 00:00:00 2001 From: "i.i.artamonov" Date: Mon, 18 Apr 2022 09:52:23 +0400 Subject: [PATCH 099/141] Changed addGameToUserWishlist Added mocks to tests. Change signature of findByUserAndGame method in UserWishRepository. Change all appearance of this method in controllers. --- .../controller/UserController.java | 4 +- .../repository/UserWishRepository.java | 2 +- .../boardgamefun/UserControllerTests.java | 76 +++++++++++++++---- 3 files changed, 65 insertions(+), 17 deletions(-) diff --git a/src/main/java/com/petproject/boardgamefun/controller/UserController.java b/src/main/java/com/petproject/boardgamefun/controller/UserController.java index 1527403..7f25491 100644 --- a/src/main/java/com/petproject/boardgamefun/controller/UserController.java +++ b/src/main/java/com/petproject/boardgamefun/controller/UserController.java @@ -321,7 +321,7 @@ public ResponseEntity addGameToUserWishlist(@PathVariable Integer userId, @Pa var user = userRepository.findUserById(userId); var game = gameRepository.findGameById(gameId); - if (userWishRepository.findByGameAndUser(game, user) != null) { + if (userWishRepository.findByUserAndGame(user, game) != null) { return new ResponseEntity<>(null, HttpStatus.BAD_REQUEST); } @@ -346,7 +346,7 @@ public ResponseEntity deleteGameFromUserWishlist(@PathVariable Integer userId var user = userRepository.findUserById(userId); var game = gameRepository.findGameById(gameId); - var userWish = userWishRepository.findByGameAndUser(game, user); + var userWish = userWishRepository.findByUserAndGame(user, game); userWishRepository.delete(userWish); diff --git a/src/main/java/com/petproject/boardgamefun/repository/UserWishRepository.java b/src/main/java/com/petproject/boardgamefun/repository/UserWishRepository.java index 931c4dd..6fa358f 100644 --- a/src/main/java/com/petproject/boardgamefun/repository/UserWishRepository.java +++ b/src/main/java/com/petproject/boardgamefun/repository/UserWishRepository.java @@ -6,5 +6,5 @@ import org.springframework.data.jpa.repository.JpaRepository; public interface UserWishRepository extends JpaRepository { - UserWish findByGameAndUser(Game game, User user); + UserWish findByUserAndGame(User user, Game game); } \ No newline at end of file diff --git a/src/test/java/com/petproject/boardgamefun/UserControllerTests.java b/src/test/java/com/petproject/boardgamefun/UserControllerTests.java index 6a6e9b1..c873960 100644 --- a/src/test/java/com/petproject/boardgamefun/UserControllerTests.java +++ b/src/test/java/com/petproject/boardgamefun/UserControllerTests.java @@ -11,10 +11,7 @@ import com.petproject.boardgamefun.dto.projection.UserGameRatingProjection; import com.petproject.boardgamefun.model.*; -import com.petproject.boardgamefun.repository.GameRepository; -import com.petproject.boardgamefun.repository.RatingGameByUserRepository; -import com.petproject.boardgamefun.repository.UserOwnGameRepository; -import com.petproject.boardgamefun.repository.UserRepository; +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; @@ -95,6 +92,9 @@ public class UserControllerTests { @MockBean private UserOwnGameRepository userOwnGameRepository; + @MockBean + private UserWishRepository userWishRepository; + private List usersDTO; private UserDTO userDTO; private User userAdmin; @@ -110,6 +110,7 @@ public class UserControllerTests { private DesignerDTO designerDTO; private RatingGameByUser ratingGameByUser; private UserOwnGame userOwnGame; + private UserWish userWish; @Autowired private MockMvc mockMvc; @@ -247,6 +248,11 @@ public void setup() { userOwnGame = new UserOwnGame(); userOwnGame.setUser(user); userOwnGame.setGame(game); + + userWish = new UserWish(); + userWish.setUser(user); + userWish.setGame(game); + userWish.setId(1); } @Test @@ -872,36 +878,78 @@ public void getUserWishlistShouldReturnBadRequest() throws Exception { this.mockMvc.perform(MockMvcRequestBuilders.get("/" + Gateway + "/bla/wishlist")).andExpect(status().isBadRequest()); } - /*@Test + @Test @WithMockUser(roles = "USER") - @Order(insertDataOrder) public void addGameToUserWishlistShouldReturnOk() throws Exception { - this.mockMvc.perform(MockMvcRequestBuilders.post("/" + Gateway + "/1/add-game-to-wishlist/1")).andDo(print()).andExpect(status().isOk()); + 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") - @Order(checkOnDuplicate) - public void addGameToUserWishlistShouldReturnBadRequest() throws Exception { - this.mockMvc.perform(MockMvcRequestBuilders.post("/" + Gateway + "/1/add-game-to-wishlist/1")).andDo(print()).andExpect(status().isBadRequest()); + 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 { - this.mockMvc.perform(MockMvcRequestBuilders.post("/" + Gateway + "/-11/add-game-to-wishlist/1")).andDo(print()).andExpect(status().isNotFound()); + 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 { - 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); + + 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 { - this.mockMvc.perform(MockMvcRequestBuilders.post("/" + Gateway + "/-1/add-game-to-wishlist/-1")).andDo(print()).andExpect(status().isNotFound()); + 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 @@ -921,7 +969,7 @@ public void addGameToUserWishlistShouldReturnStatusBadRequest_SecondParameter() 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") @Order(deleteDataOrder) From c39b6fa049c7c3eeee042eef0e4419faf38e80f4 Mon Sep 17 00:00:00 2001 From: "i.i.artamonov" Date: Tue, 19 Apr 2022 09:28:19 +0400 Subject: [PATCH 100/141] Added tests to deleteGameFromUserWishlist Change this method to parameters only wish id, not user and game --- .../controller/UserController.java | 16 +++---- .../boardgamefun/UserControllerTests.java | 45 +++++++++++++++++-- 2 files changed, 49 insertions(+), 12 deletions(-) diff --git a/src/main/java/com/petproject/boardgamefun/controller/UserController.java b/src/main/java/com/petproject/boardgamefun/controller/UserController.java index 7f25491..5b6a133 100644 --- a/src/main/java/com/petproject/boardgamefun/controller/UserController.java +++ b/src/main/java/com/petproject/boardgamefun/controller/UserController.java @@ -339,18 +339,18 @@ public ResponseEntity addGameToUserWishlist(@PathVariable Integer userId, @Pa } @Transactional - @DeleteMapping("{userId}/delete-game-from-wishlist/{gameId}") + @DeleteMapping("delete-game-from-wishlist/{userWishId}") @PreAuthorize("hasRole('USER') or hasRole('MODERATOR') or hasRole('ADMIN')") - public ResponseEntity deleteGameFromUserWishlist(@PathVariable Integer userId, @PathVariable Integer gameId) { + public ResponseEntity deleteGameFromUserWishlist(@PathVariable Integer userWishId) { - var user = userRepository.findUserById(userId); - var game = gameRepository.findGameById(gameId); + var userWish = userWishRepository.findById(userWishId); - var userWish = userWishRepository.findByUserAndGame(user, game); - - userWishRepository.delete(userWish); + if (userWish.isEmpty()) { + return new ResponseEntity<>(false, HttpStatus.NOT_FOUND); + } + userWishRepository.delete(userWish.get()); - return new ResponseEntity<>(game.getTitle() + " удалена из вашего списка желаемого", HttpStatus.OK); + return new ResponseEntity<>(true, HttpStatus.OK); } @Transactional diff --git a/src/test/java/com/petproject/boardgamefun/UserControllerTests.java b/src/test/java/com/petproject/boardgamefun/UserControllerTests.java index c873960..acd8f2e 100644 --- a/src/test/java/com/petproject/boardgamefun/UserControllerTests.java +++ b/src/test/java/com/petproject/boardgamefun/UserControllerTests.java @@ -20,6 +20,7 @@ import com.petproject.boardgamefun.security.services.UserDetailsImpl; import com.petproject.boardgamefun.service.GameService; import com.petproject.boardgamefun.service.UserService; +import net.bytebuddy.dynamic.DynamicType; import org.junit.jupiter.api.*; import org.junit.jupiter.api.extension.ExtendWith; @@ -45,6 +46,7 @@ import java.time.OffsetDateTime; import java.util.ArrayList; import java.util.List; +import java.util.Optional; @ExtendWith(MockitoExtension.class) @@ -969,11 +971,46 @@ public void addGameToUserWishlistShouldReturnStatusBadRequest_SecondParameter() 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") - @Order(deleteDataOrder) public void deleteGameFromUserWishlistShouldReturnOk() throws Exception { - this.mockMvc.perform(MockMvcRequestBuilders.delete("/" + Gateway + "/1/delete-game-from-wishlist/1")).andDo(print()).andExpect(status().isOk()); - }*/ + 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()); + + } } From 07fd66fe0526e36e0aa4d00f87d264c0e541b2b0 Mon Sep 17 00:00:00 2001 From: "i.i.artamonov" Date: Wed, 20 Apr 2022 10:27:52 +0400 Subject: [PATCH 101/141] Added tests to addGameToSellList Added additional checks in this method for null safety and duplicates. Added GameSellPOJO for mocking object --- .../controller/UserController.java | 8 ++ .../boardgamefun/UserControllerTests.java | 100 +++++++++++++++++- .../boardgamefun/model/GameSellPOJO.java | 33 ++++++ 3 files changed, 140 insertions(+), 1 deletion(-) create mode 100644 src/test/java/com/petproject/boardgamefun/model/GameSellPOJO.java diff --git a/src/main/java/com/petproject/boardgamefun/controller/UserController.java b/src/main/java/com/petproject/boardgamefun/controller/UserController.java index 5b6a133..5a9ae7a 100644 --- a/src/main/java/com/petproject/boardgamefun/controller/UserController.java +++ b/src/main/java/com/petproject/boardgamefun/controller/UserController.java @@ -358,9 +358,17 @@ public ResponseEntity deleteGameFromUserWishlist(@PathVariable Integer userWi @PreAuthorize("hasRole('USER') or hasRole('MODERATOR') or hasRole('ADMIN')") public ResponseEntity> addGameToSellList(@PathVariable Integer userId, @PathVariable Integer gameId, @RequestBody GameSell gameSell) { + if (gameSell.getId() != 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); + } + gameSell.setGame(game); gameSell.setUser(user); diff --git a/src/test/java/com/petproject/boardgamefun/UserControllerTests.java b/src/test/java/com/petproject/boardgamefun/UserControllerTests.java index acd8f2e..ad869a9 100644 --- a/src/test/java/com/petproject/boardgamefun/UserControllerTests.java +++ b/src/test/java/com/petproject/boardgamefun/UserControllerTests.java @@ -7,7 +7,9 @@ import com.fasterxml.jackson.databind.ObjectMapper; import com.petproject.boardgamefun.dto.DesignerDTO; import com.petproject.boardgamefun.dto.GameDTO; +import com.petproject.boardgamefun.dto.GameSellDTO; import com.petproject.boardgamefun.dto.UserDTO; +import com.petproject.boardgamefun.dto.projection.GameSellProjection; import com.petproject.boardgamefun.dto.projection.UserGameRatingProjection; import com.petproject.boardgamefun.model.*; @@ -18,9 +20,9 @@ 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.GameSellService; import com.petproject.boardgamefun.service.GameService; import com.petproject.boardgamefun.service.UserService; -import net.bytebuddy.dynamic.DynamicType; import org.junit.jupiter.api.*; import org.junit.jupiter.api.extension.ExtendWith; @@ -97,6 +99,12 @@ public class UserControllerTests { @MockBean private UserWishRepository userWishRepository; + @MockBean + private GameSellRepository gameSellRepository; + + @MockBean + private GameSellService gameSellService; + private List usersDTO; private UserDTO userDTO; private User userAdmin; @@ -113,6 +121,10 @@ public class UserControllerTests { private RatingGameByUser ratingGameByUser; private UserOwnGame userOwnGame; private UserWish userWish; + private List gameSellProjectionList; + private List gameSellDTOList; + private GameSellDTO gameSellDTO; + private GameSell gameSell; @Autowired private MockMvc mockMvc; @@ -255,6 +267,28 @@ public void setup() { 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(game); + gameSellDTO.setCondition("good"); + gameSellDTO.setComment("so good"); + gameSellDTO.setPrice(100); + + gameSellDTOList = new ArrayList<>(); + gameSellDTOList.add(gameSellDTO); + gameSellDTOList.add(new GameSellDTO(game1, "excellent", "not open", 300)); + } @Test @@ -1013,4 +1047,68 @@ public void deleteGameFromUserWishlistShouldReturnBadRequest() throws Exception .andDo(print()).andExpect(status().isBadRequest()); } + + @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); + } } 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; + } +} From 3d888e33c6b3afb42ee723bb1d87e3004703a5d7 Mon Sep 17 00:00:00 2001 From: "i.i.artamonov" Date: Thu, 21 Apr 2022 09:05:22 +0400 Subject: [PATCH 102/141] Added tests to getGameSellList method Added lost method for addGameToSellListShouldReturnOk() --- .../boardgamefun/UserControllerTests.java | 66 +++++++++++++++++++ 1 file changed, 66 insertions(+) diff --git a/src/test/java/com/petproject/boardgamefun/UserControllerTests.java b/src/test/java/com/petproject/boardgamefun/UserControllerTests.java index ad869a9..0346e0e 100644 --- a/src/test/java/com/petproject/boardgamefun/UserControllerTests.java +++ b/src/test/java/com/petproject/boardgamefun/UserControllerTests.java @@ -1048,6 +1048,34 @@ public void deleteGameFromUserWishlistShouldReturnBadRequest() throws Exception } + @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().getId(), gameSellDTOList.get(0).getGame().getId()); + } + @Test @WithMockUser(roles = "USER") public void addGameToSellListShouldReturnBadRequest_Duplicates() throws Exception { @@ -1111,4 +1139,42 @@ public void addGameToSellListShouldReturnNotFound_BothParameters() throws Except 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().getId(), gameSellDTOList.get(0).getGame().getId()); + + } + + @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); + } + + } From b3b023e8ef1457a541f4740639a9ca6faacc7ff3 Mon Sep 17 00:00:00 2001 From: "i.i.artamonov" Date: Thu, 21 Apr 2022 09:11:06 +0400 Subject: [PATCH 103/141] Changed gateway For comfort refactor change the string path in methods --- .../boardgamefun/UserControllerTests.java | 142 +++++++++--------- 1 file changed, 71 insertions(+), 71 deletions(-) diff --git a/src/test/java/com/petproject/boardgamefun/UserControllerTests.java b/src/test/java/com/petproject/boardgamefun/UserControllerTests.java index 0346e0e..7b60245 100644 --- a/src/test/java/com/petproject/boardgamefun/UserControllerTests.java +++ b/src/test/java/com/petproject/boardgamefun/UserControllerTests.java @@ -61,7 +61,7 @@ @TestInstance(TestInstance.Lifecycle.PER_CLASS) public class UserControllerTests { - private final String Gateway = "users"; + private final String Gateway = "/users"; @MockBean private UserRepository userRepository; @@ -296,7 +296,7 @@ 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()); + this.mockMvc.perform(MockMvcRequestBuilders.get(Gateway)).andDo(print()).andExpect(status().isOk()); verify(userRepository, only()).findAll(); @@ -309,7 +309,7 @@ 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(); + 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()); @@ -333,7 +333,7 @@ public void authenticateUserShouldReturnOk() throws Exception { when(userDetails.getUsername()).thenReturn(user.getName()); when(userDetails.getEmail()).thenReturn(user.getMail()); - this.mockMvc.perform(MockMvcRequestBuilders.post("/" + Gateway + "/sign-in").contentType(MediaType.APPLICATION_JSON) + this.mockMvc.perform(MockMvcRequestBuilders.post(Gateway + "/sign-in").contentType(MediaType.APPLICATION_JSON) .accept(MediaType.APPLICATION_JSON) .content(objectMapper.writeValueAsString(loginRequest))).andExpect(status().isOk()); @@ -345,7 +345,7 @@ public void authenticateUserShouldReturnOk() throws Exception { @Test public void authenticateUserShouldReturn415() throws Exception { LoginRequest loginRequest = new LoginRequest("Admin", "123qweAdmin"); - this.mockMvc.perform(MockMvcRequestBuilders.post("/" + Gateway + "/sign-in") + this.mockMvc.perform(MockMvcRequestBuilders.post(Gateway + "/sign-in") .contentType(MediaType.APPLICATION_XML) .accept(MediaType.APPLICATION_XML) .content(objectMapper.writeValueAsString(loginRequest))).andExpect(status().isUnsupportedMediaType()); @@ -355,7 +355,7 @@ public void authenticateUserShouldReturn415() throws Exception { 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") + this.mockMvc.perform(MockMvcRequestBuilders.post(Gateway + "/sign-in") .contentType(MediaType.APPLICATION_JSON) .accept(MediaType.APPLICATION_JSON) .content(objectMapper.writeValueAsString(loginRequest))).andExpect(status().isNotFound()); @@ -373,7 +373,7 @@ public String getMessage() { } }); - this.mockMvc.perform(MockMvcRequestBuilders.post("/" + Gateway + "/sign-in") + this.mockMvc.perform(MockMvcRequestBuilders.post(Gateway + "/sign-in") .contentType(MediaType.APPLICATION_JSON) .accept(MediaType.APPLICATION_JSON) .content(objectMapper.writeValueAsString(loginRequest))).andExpect(status().isUnauthorized()); @@ -381,7 +381,7 @@ public String getMessage() { @Test public void authenticateUserShouldReturnBadRequest() throws Exception { - this.mockMvc.perform(MockMvcRequestBuilders.post("/" + Gateway + "/sign-in") + this.mockMvc.perform(MockMvcRequestBuilders.post(Gateway + "/sign-in") .contentType(MediaType.APPLICATION_JSON) .accept(MediaType.APPLICATION_JSON)) .andExpect(status().isBadRequest()); @@ -391,7 +391,7 @@ public void authenticateUserShouldReturnBadRequest() throws Exception { 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") + this.mockMvc.perform(MockMvcRequestBuilders.post(Gateway + "/refresh-token") .contentType(MediaType.APPLICATION_JSON) .accept(MediaType.APPLICATION_JSON) .content(objectMapper.writeValueAsString(refreshTokenRequest))) @@ -406,7 +406,7 @@ public void refreshTokenShouldReturnIsOk() throws Exception { 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") + var response = this.mockMvc.perform(MockMvcRequestBuilders.post(Gateway + "/refresh-token") .contentType(MediaType.APPLICATION_JSON) .accept(MediaType.APPLICATION_JSON) .content(objectMapper.writeValueAsString(refreshTokenRequest))) @@ -423,7 +423,7 @@ public void refreshTokenShouldReturnIsOk() throws Exception { 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()); + 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.getUser().getName()); @@ -433,14 +433,14 @@ public void getUserShouldReturnStatusOkTest() throws Exception { public void getUserShouldReturnStatusNotFound() throws Exception { when(userRepository.findUserById(-1)).thenReturn(null); when(userService.entityToUserDTO(null)).thenReturn(new UserDTO()); - this.mockMvc.perform(MockMvcRequestBuilders.get("/" + Gateway + "/-1")).andDo(print()).andExpect(status().isNotFound()); + 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()); + mockMvc.perform(MockMvcRequestBuilders.get(Gateway + "/{userId}", "userId")).andExpect(status().isBadRequest()); } @Test @@ -448,7 +448,7 @@ 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(); + MvcResult mvcResult = mockMvc.perform(MockMvcRequestBuilders.get(Gateway + "/{userId}", "1")).andExpect(status().isOk()).andReturn(); UserDTO userResponse = objectMapper.readValue(mvcResult.getResponse().getContentAsByteArray(), UserDTO.class); @@ -468,7 +468,7 @@ 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(); + MvcResult mvcResult = this.mockMvc.perform(MockMvcRequestBuilders.get(Gateway + "/1/games")).andExpect(status().isOk()).andReturn(); var userCollection = objectMapper.readValue(mvcResult.getResponse().getContentAsByteArray(), GameDTO[].class); verify(gameRepository, only()).findUserGames(1); @@ -483,7 +483,7 @@ public void getUserCollectionShouldReturnIsOk() throws Exception { 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(); + MvcResult mvcResult = this.mockMvc.perform(MockMvcRequestBuilders.get(Gateway + "/-1/games")).andExpect(status().isOk()).andReturn(); var gameDTOS = objectMapper.readValue(mvcResult.getResponse().getContentAsByteArray(), GameDTO[].class); verify(gameRepository, only()).findUserGames(-1); @@ -499,7 +499,7 @@ 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")) + 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(), GameDTO[].class); @@ -516,7 +516,7 @@ 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(); + MvcResult mvcResult = this.mockMvc.perform(MockMvcRequestBuilders.get(Gateway + "/-1/games-rating")).andExpect(status().isOk()).andReturn(); var gameDTOS = objectMapper.readValue(mvcResult.getResponse().getContentAsByteArray(), GameDTO[].class); verify(gameRepository, only()).findUserGameRatingList(-1); @@ -531,7 +531,7 @@ public void getUserRatingListShouldReturnBlankArray() throws Exception { 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()); + this.mockMvc.perform(MockMvcRequestBuilders.delete(Gateway + "/-1/delete-game-rating/1")).andDo(print()).andExpect(status().isNotFound()); verify(ratingGameByUserRepository, only()).findRatingGame_ByUserIdAndGameId(-1, 1); } @@ -541,7 +541,7 @@ public void deleteGameRatingShouldReturnNotFound_FirstParameter() throws Excepti 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()); + this.mockMvc.perform(MockMvcRequestBuilders.delete(Gateway + "/1/delete-game-rating/-1")).andDo(print()).andExpect(status().isNotFound()); verify(ratingGameByUserRepository, only()).findRatingGame_ByUserIdAndGameId(1, -1); } @@ -551,7 +551,7 @@ public void deleteGameRatingShouldReturnNotFound_SecondParameter() throws Except 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()); + this.mockMvc.perform(MockMvcRequestBuilders.delete(Gateway + "/-1/delete-game-rating/-1")).andDo(print()).andExpect(status().isNotFound()); verify(ratingGameByUserRepository, only()).findRatingGame_ByUserIdAndGameId(-1, -1); } @@ -562,7 +562,7 @@ 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") + 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); @@ -580,7 +580,7 @@ public void setGameRatingShouldReturnOk() throws Exception { 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")) + 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(), Integer.class); @@ -597,7 +597,7 @@ public void setGameRatingShouldReturnOk() throws Exception { 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()); + this.mockMvc.perform(MockMvcRequestBuilders.post(Gateway + "/1/set-game-rating/1/10")).andDo(print()).andExpect(status().isBadRequest()); verify(ratingGameByUserRepository).findRatingGame_ByUserIdAndGameId(1, 1); @@ -606,13 +606,13 @@ public void setGameRatingShouldReturnBadRequest() throws Exception { @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()); + 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()); + this.mockMvc.perform(MockMvcRequestBuilders.post(Gateway + "/1/set-game-rating/1/11")).andDo(print()).andExpect(status().isBadRequest()); } @Test @@ -622,7 +622,7 @@ public void setGameRatingShouldReturnNotFound_FirstParameter() throws Exception 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()); + 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); @@ -636,7 +636,7 @@ public void setGameRatingShouldReturnNotFound_SecondParameter() throws Exception when(userRepository.findUserById(1)).thenReturn(user); when(gameRepository.findGameById(-1)).thenReturn(null); - this.mockMvc.perform(MockMvcRequestBuilders.post("/" + Gateway + "/1/set-game-rating/-1/1")) + this.mockMvc.perform(MockMvcRequestBuilders.post(Gateway + "/1/set-game-rating/-1/1")) .andDo(print()).andExpect(status().isNotFound()); verify(ratingGameByUserRepository).findRatingGame_ByUserIdAndGameId(1, -1); @@ -651,7 +651,7 @@ public void setGameRatingShouldReturnNotFound_BothParameters() throws Exception when(userRepository.findUserById(-1)).thenReturn(null); when(gameRepository.findGameById(-1)).thenReturn(null); - this.mockMvc.perform(MockMvcRequestBuilders.post("/" + Gateway + "/-1/set-game-rating/-1/1")) + this.mockMvc.perform(MockMvcRequestBuilders.post(Gateway + "/-1/set-game-rating/-1/1")) .andDo(print()).andExpect(status().isNotFound()); verify(ratingGameByUserRepository).findRatingGame_ByUserIdAndGameId(-1, -1); @@ -666,7 +666,7 @@ 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.post("/" + Gateway + "/1/update-game-rating/1/10")) + var result = this.mockMvc.perform(MockMvcRequestBuilders.post(Gateway + "/1/update-game-rating/1/10")) .andDo(print()).andExpect(status().isOk()).andReturn(); var rating = objectMapper.readValue(result.getResponse().getContentAsByteArray(), Integer.class); @@ -679,13 +679,13 @@ public void updateGameRatingShouldReturnOk() throws Exception { @Test @WithMockUser(roles = "USER") public void updateGameRatingShouldReturnBadRequestLessThanNormal() throws Exception { - this.mockMvc.perform(MockMvcRequestBuilders.post("/" + Gateway + "/1/update-game-rating/1/0")).andDo(print()).andExpect(status().isBadRequest()); + this.mockMvc.perform(MockMvcRequestBuilders.post(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.post("/" + Gateway + "/1/update-game-rating/1/11")).andDo(print()).andExpect(status().isBadRequest()); + this.mockMvc.perform(MockMvcRequestBuilders.post(Gateway + "/1/update-game-rating/1/11")).andDo(print()).andExpect(status().isBadRequest()); } @Test @@ -693,7 +693,7 @@ public void updateGameRatingShouldReturnBadRequestMoreThanNormal() throws Except public void updateGameRatingShouldReturnNotFound_FirstParameter() throws Exception { when(ratingGameByUserRepository.findRatingGame_ByUserIdAndGameId(-1, 1)).thenReturn(null); - this.mockMvc.perform(MockMvcRequestBuilders.post("/" + Gateway + "/-1/update-game-rating/1/1")) + this.mockMvc.perform(MockMvcRequestBuilders.post(Gateway + "/-1/update-game-rating/1/1")) .andDo(print()).andExpect(status().isNotFound()); verify(ratingGameByUserRepository).findRatingGame_ByUserIdAndGameId(-1, 1); @@ -704,7 +704,7 @@ public void updateGameRatingShouldReturnNotFound_FirstParameter() throws Excepti public void updateGameRatingShouldReturnNotFound_SecondParameter() throws Exception { when(ratingGameByUserRepository.findRatingGame_ByUserIdAndGameId(1, -1)).thenReturn(null); - this.mockMvc.perform(MockMvcRequestBuilders.post("/" + Gateway + "/1/update-game-rating/-1/1")) + this.mockMvc.perform(MockMvcRequestBuilders.post(Gateway + "/1/update-game-rating/-1/1")) .andDo(print()).andExpect(status().isNotFound()); verify(ratingGameByUserRepository).findRatingGame_ByUserIdAndGameId(1, -1); @@ -715,7 +715,7 @@ public void updateGameRatingShouldReturnNotFound_SecondParameter() throws Except public void updateGameRatingShouldReturnNotFound_BothParameters() throws Exception { when(ratingGameByUserRepository.findRatingGame_ByUserIdAndGameId(-1, -1)).thenReturn(null); - this.mockMvc.perform(MockMvcRequestBuilders.post("/" + Gateway + "/-1/update-game-rating/-1/1")) + this.mockMvc.perform(MockMvcRequestBuilders.post(Gateway + "/-1/update-game-rating/-1/1")) .andDo(print()).andExpect(status().isNotFound()); verify(ratingGameByUserRepository).findRatingGame_ByUserIdAndGameId(-1, -1); @@ -730,7 +730,7 @@ public void addGameToUserShouldReturnOk() throws Exception { 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")) + var result = this.mockMvc.perform(MockMvcRequestBuilders.post(Gateway + "/1/add-game/1")) .andDo(print()).andExpect(status().isOk()).andReturn().getResponse().getContentAsString(); verify(userRepository).findUserById(1); @@ -748,7 +748,7 @@ public void addGameToUserShouldReturnBadRequest() throws Exception { when(gameRepository.findGameById(1)).thenReturn(game); when(gameRepository.findUserGames(1)).thenReturn(games); - this.mockMvc.perform(MockMvcRequestBuilders.post("/" + Gateway + "/1/add-game/1")) + this.mockMvc.perform(MockMvcRequestBuilders.post(Gateway + "/1/add-game/1")) .andDo(print()).andExpect(status().isBadRequest()); verify(userRepository).findUserById(1); @@ -762,7 +762,7 @@ public void addGameToUserShouldReturnStatusNotFound_FirstParameter() throws Exce when(userRepository.findUserById(-1)).thenReturn(null); when(gameRepository.findGameById(1)).thenReturn(game); - this.mockMvc.perform(MockMvcRequestBuilders.post("/" + Gateway + "/-1/add-game/1")) + this.mockMvc.perform(MockMvcRequestBuilders.post(Gateway + "/-1/add-game/1")) .andDo(print()).andExpect(status().isNotFound()); verify(userRepository).findUserById(-1); @@ -775,7 +775,7 @@ public void addGameToUserShouldReturnStatusNotFound_SecondParameter() throws Exc when(userRepository.findUserById(1)).thenReturn(user); when(gameRepository.findGameById(-1)).thenReturn(null); - this.mockMvc.perform(MockMvcRequestBuilders.post("/" + Gateway + "/1/add-game/-1")) + this.mockMvc.perform(MockMvcRequestBuilders.post(Gateway + "/1/add-game/-1")) .andDo(print()).andExpect(status().isNotFound()); verify(userRepository).findUserById(1); @@ -788,7 +788,7 @@ public void addGameToUserShouldReturnStatusNotFound_BothParameters() throws Exce when(userRepository.findUserById(-1)).thenReturn(null); when(gameRepository.findGameById(-1)).thenReturn(null); - this.mockMvc.perform(MockMvcRequestBuilders.post("/" + Gateway + "/-1/add-game/-1")) + this.mockMvc.perform(MockMvcRequestBuilders.post(Gateway + "/-1/add-game/-1")) .andDo(print()).andExpect(status().isNotFound()); verify(userRepository).findUserById(-1); @@ -798,19 +798,19 @@ public void addGameToUserShouldReturnStatusNotFound_BothParameters() throws Exce @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()); + 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()); + 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()); + this.mockMvc.perform(MockMvcRequestBuilders.post(Gateway + "/bla/add-game/bla")).andDo(print()).andExpect(status().isBadRequest()); } @Test @@ -818,7 +818,7 @@ public void addGameToUserShouldReturnStatusBadRequest_BothParameters() throws Ex public void deleteGameFromUserCollectionShouldReturnNotFound_FirstParameter() throws Exception { when(userOwnGameRepository.findUserOwnGame_ByUserIdAndGameId(-1, 1)).thenReturn(null); - this.mockMvc.perform(MockMvcRequestBuilders.delete("/" + Gateway + "/-1/delete-game/1")) + this.mockMvc.perform(MockMvcRequestBuilders.delete(Gateway + "/-1/delete-game/1")) .andDo(print()).andExpect(status().isNotFound()); verify(userOwnGameRepository).findUserOwnGame_ByUserIdAndGameId(-1, 1); @@ -829,7 +829,7 @@ public void deleteGameFromUserCollectionShouldReturnNotFound_FirstParameter() th public void deleteGameFromUserCollectionShouldReturnNotFound_SecondParameter() throws Exception { when(userOwnGameRepository.findUserOwnGame_ByUserIdAndGameId(1, -1)).thenReturn(null); - this.mockMvc.perform(MockMvcRequestBuilders.delete("/" + Gateway + "/1/delete-game/-1")) + this.mockMvc.perform(MockMvcRequestBuilders.delete(Gateway + "/1/delete-game/-1")) .andDo(print()).andExpect(status().isNotFound()); verify(userOwnGameRepository).findUserOwnGame_ByUserIdAndGameId(1, -1); @@ -840,7 +840,7 @@ public void deleteGameFromUserCollectionShouldReturnNotFound_SecondParameter() t public void deleteGameFromUserCollectionShouldReturnNotFound_BothParameters() throws Exception { when(userOwnGameRepository.findUserOwnGame_ByUserIdAndGameId(-1, -1)).thenReturn(null); - this.mockMvc.perform(MockMvcRequestBuilders.delete("/" + Gateway + "/-1/delete-game/-1")) + this.mockMvc.perform(MockMvcRequestBuilders.delete(Gateway + "/-1/delete-game/-1")) .andDo(print()).andExpect(status().isNotFound()); verify(userOwnGameRepository).findUserOwnGame_ByUserIdAndGameId(-1, -1); @@ -849,19 +849,19 @@ public void deleteGameFromUserCollectionShouldReturnNotFound_BothParameters() th @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()); + 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()); + 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()); + this.mockMvc.perform(MockMvcRequestBuilders.delete(Gateway + "/bla/delete-game/bla")).andDo(print()).andExpect(status().isBadRequest()); } @Test @@ -870,7 +870,7 @@ 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")) + this.mockMvc.perform(MockMvcRequestBuilders.delete(Gateway + "/1/delete-game/1")) .andDo(print()).andExpect(status().isOk()); verify(userOwnGameRepository).findUserOwnGame_ByUserIdAndGameId(1, 1); @@ -883,7 +883,7 @@ 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")) + var mvcResult = this.mockMvc.perform(MockMvcRequestBuilders.get(Gateway + "/1/wishlist")) .andExpect(status().isOk()).andReturn(); var response = objectMapper.readValue(mvcResult.getResponse().getContentAsByteArray(), GameDTO[].class); @@ -903,7 +903,7 @@ public void getUserWishlistShouldReturnIsOk() throws Exception { 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 mvcResult = this.mockMvc.perform(MockMvcRequestBuilders.get(Gateway + "/-1/wishlist")).andExpect(status().isOk()).andReturn(); var response = objectMapper.readValue(mvcResult.getResponse().getContentAsByteArray(), GameDTO[].class); Assertions.assertEquals(0, response.length); } @@ -911,7 +911,7 @@ public void getUserWishlistShouldReturnBlankArray() throws Exception { @Test @WithMockUser(roles = "USER") public void getUserWishlistShouldReturnBadRequest() throws Exception { - this.mockMvc.perform(MockMvcRequestBuilders.get("/" + Gateway + "/bla/wishlist")).andExpect(status().isBadRequest()); + this.mockMvc.perform(MockMvcRequestBuilders.get(Gateway + "/bla/wishlist")).andExpect(status().isBadRequest()); } @Test @@ -922,7 +922,7 @@ public void addGameToUserWishlistShouldReturnOk() throws Exception { 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")) + 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); @@ -941,7 +941,7 @@ public void addGameToUserWishlistShouldReturnBadRequest_CheckOnDuplicates() thro 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")) + this.mockMvc.perform(MockMvcRequestBuilders.post(Gateway + "/1/add-game-to-wishlist/1")) .andDo(print()).andExpect(status().isBadRequest()); verify(userRepository).findUserById(1); @@ -955,7 +955,7 @@ public void addGameToUserWishlistShouldReturnStatusNotFound_FirstParameter() thr when(userRepository.findUserById(-1)).thenReturn(null); when(gameRepository.findGameById(1)).thenReturn(game); - this.mockMvc.perform(MockMvcRequestBuilders.post("/" + Gateway + "/-1/add-game-to-wishlist/1")) + this.mockMvc.perform(MockMvcRequestBuilders.post(Gateway + "/-1/add-game-to-wishlist/1")) .andDo(print()).andExpect(status().isNotFound()); verify(userRepository).findUserById(-1); @@ -968,7 +968,7 @@ public void addGameToUserWishlistShouldReturnStatusNotFound_SecondParameter() th when(userRepository.findUserById(1)).thenReturn(user); when(gameRepository.findGameById(-1)).thenReturn(null); - this.mockMvc.perform(MockMvcRequestBuilders.post("/" + Gateway + "/1/add-game-to-wishlist/-1")) + this.mockMvc.perform(MockMvcRequestBuilders.post(Gateway + "/1/add-game-to-wishlist/-1")) .andDo(print()).andExpect(status().isNotFound()); when(userRepository.findUserById(1)).thenReturn(user); @@ -981,7 +981,7 @@ public void addGameToUserWishlistShouldReturnStatusNotFound_BothParameters() thr when(userRepository.findUserById(-1)).thenReturn(null); when(gameRepository.findGameById(-1)).thenReturn(null); - this.mockMvc.perform(MockMvcRequestBuilders.post("/" + Gateway + "/-1/add-game-to-wishlist/-1")) + this.mockMvc.perform(MockMvcRequestBuilders.post(Gateway + "/-1/add-game-to-wishlist/-1")) .andDo(print()).andExpect(status().isNotFound()); when(userRepository.findUserById(-1)).thenReturn(user); @@ -991,19 +991,19 @@ public void addGameToUserWishlistShouldReturnStatusNotFound_BothParameters() thr @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()); + 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()); + 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()); + this.mockMvc.perform(MockMvcRequestBuilders.post(Gateway + "/bla/add-game-to-wishlist/bla")).andDo(print()).andExpect(status().isBadRequest()); } @Test @@ -1012,7 +1012,7 @@ 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")) + 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); @@ -1029,7 +1029,7 @@ public void deleteGameFromUserWishlistShouldReturnOk() throws Exception { 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")) + 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); @@ -1043,7 +1043,7 @@ public void deleteGameFromUserWishlistShouldReturnNotFound() throws Exception { @Test @WithMockUser(roles = "USER") public void deleteGameFromUserWishlistShouldReturnBadRequest() throws Exception { - this.mockMvc.perform(MockMvcRequestBuilders.delete("/" + Gateway + "/delete-game-from-wishlist/bla-bla")) + this.mockMvc.perform(MockMvcRequestBuilders.delete(Gateway + "/delete-game-from-wishlist/bla-bla")) .andDo(print()).andExpect(status().isBadRequest()); } @@ -1058,7 +1058,7 @@ public void addGameToSellListShouldReturnOk() throws Exception { 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") + 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))) @@ -1081,7 +1081,7 @@ public void addGameToSellListShouldReturnOk() throws Exception { public void addGameToSellListShouldReturnBadRequest_Duplicates() throws Exception { gameSell.setId(1); - this.mockMvc.perform(MockMvcRequestBuilders.post("/" + Gateway + "/1/add-game-to-sell/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))) @@ -1096,7 +1096,7 @@ public void addGameToSellListShouldReturnNotFound_FirstParameter() throws Except when(userRepository.findUserById(-1)).thenReturn(null); when(gameRepository.findGameById(1)).thenReturn(game); - this.mockMvc.perform(MockMvcRequestBuilders.post("/" + Gateway + "/-1/add-game-to-sell/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))) @@ -1113,7 +1113,7 @@ public void addGameToSellListShouldReturnNotFound_SecondParameter() throws Excep when(userRepository.findUserById(1)).thenReturn(user); when(gameRepository.findGameById(-1)).thenReturn(null); - this.mockMvc.perform(MockMvcRequestBuilders.post("/" + Gateway + "/1/add-game-to-sell/-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))) @@ -1130,7 +1130,7 @@ public void addGameToSellListShouldReturnNotFound_BothParameters() throws Except when(userRepository.findUserById(-1)).thenReturn(null); when(gameRepository.findGameById(-1)).thenReturn(null); - this.mockMvc.perform(MockMvcRequestBuilders.post("/" + Gateway + "/-1/add-game-to-sell/-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))) @@ -1146,7 +1146,7 @@ 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")) + 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); @@ -1165,7 +1165,7 @@ 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")) + 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); From 5847f4105379c17050d49fb1d0ec44498549c258 Mon Sep 17 00:00:00 2001 From: "i.i.artamonov" Date: Thu, 21 Apr 2022 10:02:51 +0400 Subject: [PATCH 104/141] Added tests to removeGameFromSellList Added checks for null. Change signature of findGameSell_ByUserIdAndGameId for more understanding. --- .../controller/UserController.java | 5 ++- .../repository/GameSellRepository.java | 2 +- .../boardgamefun/UserControllerTests.java | 45 +++++++++++++++++++ 3 files changed, 50 insertions(+), 2 deletions(-) diff --git a/src/main/java/com/petproject/boardgamefun/controller/UserController.java b/src/main/java/com/petproject/boardgamefun/controller/UserController.java index 5a9ae7a..fea1bae 100644 --- a/src/main/java/com/petproject/boardgamefun/controller/UserController.java +++ b/src/main/java/com/petproject/boardgamefun/controller/UserController.java @@ -393,7 +393,10 @@ public ResponseEntity> getGameSellList(@PathVariable Integer u @PreAuthorize("hasRole('USER') or hasRole('MODERATOR') or hasRole('ADMIN')") public ResponseEntity removeGameFromSell(@PathVariable Integer userId, @PathVariable Integer gameId) { - var gameSell = gameSellRepository.findGameSell_ByGameIdAndUserId(gameId, userId); + var gameSell = gameSellRepository.findGameSell_ByUserIdAndGameId(userId, gameId); + if (gameSell == null){ + return new ResponseEntity<>(null, HttpStatus.NOT_FOUND); + } gameSellRepository.delete(gameSell); return new ResponseEntity<>(gameId, HttpStatus.OK); diff --git a/src/main/java/com/petproject/boardgamefun/repository/GameSellRepository.java b/src/main/java/com/petproject/boardgamefun/repository/GameSellRepository.java index f1c33b0..4fd3e0e 100644 --- a/src/main/java/com/petproject/boardgamefun/repository/GameSellRepository.java +++ b/src/main/java/com/petproject/boardgamefun/repository/GameSellRepository.java @@ -4,5 +4,5 @@ import org.springframework.data.jpa.repository.JpaRepository; public interface GameSellRepository extends JpaRepository { - GameSell findGameSell_ByGameIdAndUserId(Integer gameId, Integer userId); + GameSell findGameSell_ByUserIdAndGameId( Integer userId, Integer gameId); } \ No newline at end of file diff --git a/src/test/java/com/petproject/boardgamefun/UserControllerTests.java b/src/test/java/com/petproject/boardgamefun/UserControllerTests.java index 7b60245..cae50db 100644 --- a/src/test/java/com/petproject/boardgamefun/UserControllerTests.java +++ b/src/test/java/com/petproject/boardgamefun/UserControllerTests.java @@ -1176,5 +1176,50 @@ public void getGameSellListShouldReturnBlankArray() throws Exception { 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); + } } From c309180aa9851b002952e8ae3ebbeef7902c65ed Mon Sep 17 00:00:00 2001 From: "i.i.artamonov" Date: Fri, 22 Apr 2022 08:46:52 +0400 Subject: [PATCH 105/141] Added tests to updateSellGame Added null checking for method --- .../controller/UserController.java | 6 +- .../boardgamefun/UserControllerTests.java | 64 +++++++++++++++++++ 2 files changed, 69 insertions(+), 1 deletion(-) diff --git a/src/main/java/com/petproject/boardgamefun/controller/UserController.java b/src/main/java/com/petproject/boardgamefun/controller/UserController.java index fea1bae..ca5ac25 100644 --- a/src/main/java/com/petproject/boardgamefun/controller/UserController.java +++ b/src/main/java/com/petproject/boardgamefun/controller/UserController.java @@ -394,7 +394,7 @@ public ResponseEntity> getGameSellList(@PathVariable Integer u public ResponseEntity removeGameFromSell(@PathVariable Integer userId, @PathVariable Integer gameId) { var gameSell = gameSellRepository.findGameSell_ByUserIdAndGameId(userId, gameId); - if (gameSell == null){ + if (gameSell == null) { return new ResponseEntity<>(null, HttpStatus.NOT_FOUND); } gameSellRepository.delete(gameSell); @@ -407,6 +407,10 @@ public ResponseEntity removeGameFromSell(@PathVariable Integer userId, @PreAuthorize("hasRole('USER') or hasRole('MODERATOR') or hasRole('ADMIN')") public ResponseEntity updateSellGame(@RequestBody GameSell gameSell) { + if (gameSell.getId() == null || gameSell.getGame() == null || gameSell.getUser() == null) { + return new ResponseEntity<>(null, HttpStatus.BAD_REQUEST); + } + if (gameSell.getComment() != null) { gameSell.setComment(gameSell.getComment()); } diff --git a/src/test/java/com/petproject/boardgamefun/UserControllerTests.java b/src/test/java/com/petproject/boardgamefun/UserControllerTests.java index cae50db..987f106 100644 --- a/src/test/java/com/petproject/boardgamefun/UserControllerTests.java +++ b/src/test/java/com/petproject/boardgamefun/UserControllerTests.java @@ -1222,4 +1222,68 @@ public void removeGameFromSellShouldReturnNotFound_BothParameters() throws Excep 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); + + } + } From e0fbc2b2e57b16308c8710ab58b2db8fccd1319c Mon Sep 17 00:00:00 2001 From: "i.i.artamonov" Date: Mon, 25 Apr 2022 15:16:33 +0400 Subject: [PATCH 106/141] Added tests to addDiary Added null and valid checks to method --- .../controller/UserController.java | 8 ++ .../boardgamefun/service/DiaryService.kt | 8 +- .../boardgamefun/UserControllerTests.java | 111 +++++++++++++++++- 3 files changed, 119 insertions(+), 8 deletions(-) diff --git a/src/main/java/com/petproject/boardgamefun/controller/UserController.java b/src/main/java/com/petproject/boardgamefun/controller/UserController.java index ca5ac25..3ff8666 100644 --- a/src/main/java/com/petproject/boardgamefun/controller/UserController.java +++ b/src/main/java/com/petproject/boardgamefun/controller/UserController.java @@ -431,9 +431,17 @@ public ResponseEntity updateSellGame(@RequestBody GameSell gameSell) { @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()); diff --git a/src/main/java/com/petproject/boardgamefun/service/DiaryService.kt b/src/main/java/com/petproject/boardgamefun/service/DiaryService.kt index bcaccb0..0d1eaa0 100644 --- a/src/main/java/com/petproject/boardgamefun/service/DiaryService.kt +++ b/src/main/java/com/petproject/boardgamefun/service/DiaryService.kt @@ -7,8 +7,8 @@ import org.springframework.stereotype.Service import java.util.ArrayList @Service -class DiaryService { - fun projectionsToDiaryDTO(projections: List): List { +open class DiaryService { + open fun projectionsToDiaryDTO(projections: List): List { val diaries: MutableList = ArrayList() for (projection in projections) { diaries.add(DiaryDTO(projection.diary, projection.rating)) @@ -16,11 +16,11 @@ class DiaryService { return diaries } - fun entityToDiaryDTO(diary: Diary): DiaryDTO { + open fun entityToDiaryDTO(diary: Diary): DiaryDTO { return DiaryDTO(diary, 0.0) } - fun projectionToDiaryDTO(projection: DiaryWithRatingsProjection): DiaryDTO { + open fun projectionToDiaryDTO(projection: DiaryWithRatingsProjection): DiaryDTO { return DiaryDTO(projection.diary, projection.rating) } } \ No newline at end of file diff --git a/src/test/java/com/petproject/boardgamefun/UserControllerTests.java b/src/test/java/com/petproject/boardgamefun/UserControllerTests.java index 987f106..416c45c 100644 --- a/src/test/java/com/petproject/boardgamefun/UserControllerTests.java +++ b/src/test/java/com/petproject/boardgamefun/UserControllerTests.java @@ -5,10 +5,7 @@ import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status; import com.fasterxml.jackson.databind.ObjectMapper; -import com.petproject.boardgamefun.dto.DesignerDTO; -import com.petproject.boardgamefun.dto.GameDTO; -import com.petproject.boardgamefun.dto.GameSellDTO; -import com.petproject.boardgamefun.dto.UserDTO; +import com.petproject.boardgamefun.dto.*; import com.petproject.boardgamefun.dto.projection.GameSellProjection; import com.petproject.boardgamefun.dto.projection.UserGameRatingProjection; import com.petproject.boardgamefun.model.*; @@ -20,6 +17,7 @@ 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; @@ -105,6 +103,12 @@ public class UserControllerTests { @MockBean private GameSellService gameSellService; + @MockBean + private DiaryRepository diaryRepository; + + @MockBean + private DiaryService diaryService; + private List usersDTO; private UserDTO userDTO; private User userAdmin; @@ -125,6 +129,8 @@ public class UserControllerTests { private List gameSellDTOList; private GameSellDTO gameSellDTO; private GameSell gameSell; + private Diary diary; + private DiaryDTO diaryDTO; @Autowired private MockMvc mockMvc; @@ -289,6 +295,14 @@ public void setup() { gameSellDTOList.add(gameSellDTO); gameSellDTOList.add(new GameSellDTO(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 DiaryDTO(diary, 8.0); } @Test @@ -1286,4 +1300,93 @@ public void updateSellGameShouldReturnBadRequest_UserIsNull() throws Exception { } + @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(), DiaryDTO.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().getId(), response.getDiary().getId()); + + } + + @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()); + + } + } From 9a0b6fc240d908fcb8ce1f02de0f0461a40f59c2 Mon Sep 17 00:00:00 2001 From: "i.i.artamonov" Date: Tue, 26 Apr 2022 08:46:58 +0400 Subject: [PATCH 107/141] Added file to resolve final kotlin classes Now we can mock the final classes of kotlin --- pom.xml | 1 + .../com/petproject/boardgamefun/service/DiaryService.kt | 8 ++++---- .../mockito-extensions/org.mockito.plugins.MockMaker | 1 + 3 files changed, 6 insertions(+), 4 deletions(-) create mode 100644 src/test/resources/mockito-extensions/org.mockito.plugins.MockMaker diff --git a/pom.xml b/pom.xml index 4946ea8..e8d5acc 100644 --- a/pom.xml +++ b/pom.xml @@ -69,6 +69,7 @@ jackson-datatype-jsr310 + org.springframework.boot spring-boot-devtools diff --git a/src/main/java/com/petproject/boardgamefun/service/DiaryService.kt b/src/main/java/com/petproject/boardgamefun/service/DiaryService.kt index 0d1eaa0..bcaccb0 100644 --- a/src/main/java/com/petproject/boardgamefun/service/DiaryService.kt +++ b/src/main/java/com/petproject/boardgamefun/service/DiaryService.kt @@ -7,8 +7,8 @@ import org.springframework.stereotype.Service import java.util.ArrayList @Service -open class DiaryService { - open fun projectionsToDiaryDTO(projections: List): List { +class DiaryService { + fun projectionsToDiaryDTO(projections: List): List { val diaries: MutableList = ArrayList() for (projection in projections) { diaries.add(DiaryDTO(projection.diary, projection.rating)) @@ -16,11 +16,11 @@ open class DiaryService { return diaries } - open fun entityToDiaryDTO(diary: Diary): DiaryDTO { + fun entityToDiaryDTO(diary: Diary): DiaryDTO { return DiaryDTO(diary, 0.0) } - open fun projectionToDiaryDTO(projection: DiaryWithRatingsProjection): DiaryDTO { + fun projectionToDiaryDTO(projection: DiaryWithRatingsProjection): DiaryDTO { return DiaryDTO(projection.diary, projection.rating) } } \ No newline at end of file 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 From 31d27e4eed0729f9e7d32e0f66673aebb50fa481 Mon Sep 17 00:00:00 2001 From: "i.i.artamonov" Date: Tue, 26 Apr 2022 09:05:46 +0400 Subject: [PATCH 108/141] Added tests to deleteDiary Added null safety checks --- .../controller/UserController.java | 3 ++ .../boardgamefun/UserControllerTests.java | 51 +++++++++++++++++++ 2 files changed, 54 insertions(+) diff --git a/src/main/java/com/petproject/boardgamefun/controller/UserController.java b/src/main/java/com/petproject/boardgamefun/controller/UserController.java index 3ff8666..df257db 100644 --- a/src/main/java/com/petproject/boardgamefun/controller/UserController.java +++ b/src/main/java/com/petproject/boardgamefun/controller/UserController.java @@ -458,6 +458,9 @@ public ResponseEntity addDiary(@PathVariable Integer userId, @PathVari 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); diff --git a/src/test/java/com/petproject/boardgamefun/UserControllerTests.java b/src/test/java/com/petproject/boardgamefun/UserControllerTests.java index 416c45c..d9b0b4d 100644 --- a/src/test/java/com/petproject/boardgamefun/UserControllerTests.java +++ b/src/test/java/com/petproject/boardgamefun/UserControllerTests.java @@ -1389,4 +1389,55 @@ public void addDiaryShouldReturnBadRequest_InvalidInput() throws Exception { } + @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); + } + } From a6c7f25cc91d4da434ed1c1dfca52c7d7479be5a Mon Sep 17 00:00:00 2001 From: "i.i.artamonov" Date: Wed, 27 Apr 2022 14:47:16 +0400 Subject: [PATCH 109/141] Added tests to updateDiary Added null checks to controller method --- .../controller/UserController.java | 8 ++ .../boardgamefun/UserControllerTests.java | 92 +++++++++++++++++++ 2 files changed, 100 insertions(+) diff --git a/src/main/java/com/petproject/boardgamefun/controller/UserController.java b/src/main/java/com/petproject/boardgamefun/controller/UserController.java index df257db..57d09a8 100644 --- a/src/main/java/com/petproject/boardgamefun/controller/UserController.java +++ b/src/main/java/com/petproject/boardgamefun/controller/UserController.java @@ -472,7 +472,15 @@ public ResponseEntity deleteDiary(@PathVariable Integer userId, @PathVar @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()); } diff --git a/src/test/java/com/petproject/boardgamefun/UserControllerTests.java b/src/test/java/com/petproject/boardgamefun/UserControllerTests.java index d9b0b4d..15d71d6 100644 --- a/src/test/java/com/petproject/boardgamefun/UserControllerTests.java +++ b/src/test/java/com/petproject/boardgamefun/UserControllerTests.java @@ -1440,4 +1440,96 @@ public void deleteDiaryShouldReturnNotFound_BothParameters() throws Exception { 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(), DiaryDTO.class); + + verify(diaryRepository).findDiary_ByUserIdAndId(1, 1); + verify(diaryRepository).save(any(Diary.class)); + verify(diaryService).entityToDiaryDTO(any(Diary.class)); + + Assertions.assertEquals(diaryDTO.getDiary().getId(), response.getDiary().getId()); + + 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); + } + } From ab5a635c23c10220b288a097f9d8d8d47904ad86 Mon Sep 17 00:00:00 2001 From: "i.i.artamonov" Date: Thu, 5 May 2022 14:18:08 +0400 Subject: [PATCH 110/141] Changes UserDTO. Added mapper for UserDTO Added mapstruct library for generating mappers for dto. Intellij idea give some strange errors about generated classes in target folder. Add kapt execution to kotlin for generate source code. --- pom.xml | 41 ++++++++++++++++--- .../controller/UserController.java | 2 +- .../petproject/boardgamefun/dto/UserDTO.java | 14 +++---- .../boardgamefun/service/UserService.java | 15 +++++-- .../service/mappers/UserMapper.java | 15 +++++++ .../boardgamefun/UserControllerTests.java | 24 ++++++----- 6 files changed, 82 insertions(+), 29 deletions(-) create mode 100644 src/main/java/com/petproject/boardgamefun/service/mappers/UserMapper.java diff --git a/pom.xml b/pom.xml index e8d5acc..7b283d0 100644 --- a/pom.xml +++ b/pom.xml @@ -16,6 +16,7 @@ 17 1.6.20-M1 + 1.4.2.Final @@ -128,6 +129,11 @@ junit test + + org.mapstruct + mapstruct + ${org.mapstruct.version} + @@ -151,7 +157,9 @@ compile - compile + + compile + ${project.basedir}/src/main/kotlin @@ -159,9 +167,26 @@ + + kapt + + kapt + + + + + org.mapstruct + mapstruct-processor + ${org.mapstruct.version} + + + + test-compile - test-compile + + test-compile + ${project.basedir}/src/test/kotlin @@ -171,7 +196,7 @@ - + org.apache.maven.plugins maven-compiler-plugin @@ -179,6 +204,8 @@ default-compile none + + @@ -188,12 +215,16 @@ java-compile compile - compile + + compile + java-test-compile test-compile - testCompile + + testCompile + diff --git a/src/main/java/com/petproject/boardgamefun/controller/UserController.java b/src/main/java/com/petproject/boardgamefun/controller/UserController.java index 57d09a8..42a3323 100644 --- a/src/main/java/com/petproject/boardgamefun/controller/UserController.java +++ b/src/main/java/com/petproject/boardgamefun/controller/UserController.java @@ -182,7 +182,7 @@ public ResponseEntity changePassword(@PathVariable Integer userId, @RequestBo @GetMapping("{id}") public ResponseEntity getUser(@PathVariable Integer id) { var userDTO = userService.entityToUserDTO(userRepository.findUserById(id)); - if (userDTO.getUser() == null) { + if (userDTO == null) { return new ResponseEntity<>(null, HttpStatus.NOT_FOUND); } return new ResponseEntity<>(userDTO, HttpStatus.OK); diff --git a/src/main/java/com/petproject/boardgamefun/dto/UserDTO.java b/src/main/java/com/petproject/boardgamefun/dto/UserDTO.java index fd01898..62f849a 100644 --- a/src/main/java/com/petproject/boardgamefun/dto/UserDTO.java +++ b/src/main/java/com/petproject/boardgamefun/dto/UserDTO.java @@ -1,13 +1,9 @@ package com.petproject.boardgamefun.dto; -import com.petproject.boardgamefun.model.User; -import lombok.AllArgsConstructor; -import lombok.Data; -import lombok.NoArgsConstructor; +import java.io.Serializable; +import java.time.OffsetDateTime; -@Data -@AllArgsConstructor -@NoArgsConstructor -public class UserDTO { - private User user; + +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/service/UserService.java b/src/main/java/com/petproject/boardgamefun/service/UserService.java index 30e978b..00d96d4 100644 --- a/src/main/java/com/petproject/boardgamefun/service/UserService.java +++ b/src/main/java/com/petproject/boardgamefun/service/UserService.java @@ -2,6 +2,7 @@ import com.petproject.boardgamefun.dto.UserDTO; import com.petproject.boardgamefun.model.User; +import com.petproject.boardgamefun.service.mappers.UserMapper; import org.springframework.stereotype.Service; import java.util.ArrayList; @@ -9,16 +10,22 @@ @Service public class UserService { - public List entitiesToUserDTO(List users){ + final UserMapper userMapper; + + public UserService(UserMapper userMapper) { + this.userMapper = userMapper; + } + + public List entitiesToUserDTO(List users) { List usersDTO = new ArrayList<>(); for (var user : users) { - usersDTO.add(new UserDTO(user)); + usersDTO.add(userMapper.userToUserDTO(user)); } return usersDTO; } - public UserDTO entityToUserDTO(User user){ - return new UserDTO(user); + public UserDTO entityToUserDTO(User user) { + return userMapper.userToUserDTO(user); } } 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/test/java/com/petproject/boardgamefun/UserControllerTests.java b/src/test/java/com/petproject/boardgamefun/UserControllerTests.java index 15d71d6..f36d44d 100644 --- a/src/test/java/com/petproject/boardgamefun/UserControllerTests.java +++ b/src/test/java/com/petproject/boardgamefun/UserControllerTests.java @@ -21,6 +21,7 @@ import com.petproject.boardgamefun.service.GameSellService; import com.petproject.boardgamefun.service.GameService; import com.petproject.boardgamefun.service.UserService; +import com.petproject.boardgamefun.service.mappers.UserMapper; import org.junit.jupiter.api.*; import org.junit.jupiter.api.extension.ExtendWith; @@ -61,6 +62,9 @@ public class UserControllerTests { private final String Gateway = "/users"; + @Autowired + UserMapper userMapper; + @MockBean private UserRepository userRepository; @@ -198,11 +202,11 @@ public void setup() { users.add(user); - userDTO = new UserDTO(user); + userDTO = userMapper.userToUserDTO(user); usersDTO = new ArrayList<>(); - usersDTO.add(new UserDTO(userAdmin)); - usersDTO.add(new UserDTO(userModerator)); - usersDTO.add(new UserDTO(user)); + usersDTO.add(userMapper.userToUserDTO(userAdmin)); + usersDTO.add(userMapper.userToUserDTO(userModerator)); + usersDTO.add(userMapper.userToUserDTO(user)); game = new Game(); @@ -440,13 +444,13 @@ public void getUserShouldReturnStatusOkTest() throws Exception { 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.getUser().getName()); + Assertions.assertEquals(userArgumentCaptor.getValue().getName(), userDTO.name()); } @Test public void getUserShouldReturnStatusNotFound() throws Exception { when(userRepository.findUserById(-1)).thenReturn(null); - when(userService.entityToUserDTO(null)).thenReturn(new UserDTO()); + 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); @@ -469,11 +473,11 @@ public void getUserWhenValidInput_thenReturnUserResource() throws Exception { verify(userRepository, only()).findUserById(1); verify(userService, only()).entityToUserDTO(userArgumentCaptor.capture()); - Assertions.assertEquals(userArgumentCaptor.getValue().getName(), userDTO.getUser().getName()); + Assertions.assertEquals(userArgumentCaptor.getValue().getName(), userDTO.name()); - Assertions.assertEquals(userResponse.getUser().getName(), user.getName()); - Assertions.assertEquals(userResponse.getUser().getMail(), user.getMail()); - Assertions.assertEquals(userResponse.getUser().getRole(), user.getRole()); + Assertions.assertEquals(userResponse.name(), user.getName()); + Assertions.assertEquals(userResponse.mail(), user.getMail()); + Assertions.assertEquals(userResponse.role(), user.getRole()); } @Test From 79a1177cdaea7370e730369f1f793b4cd74fe18c Mon Sep 17 00:00:00 2001 From: "i.i.artamonov" Date: Thu, 5 May 2022 15:36:56 +0400 Subject: [PATCH 111/141] Added GameDTO. Added GameMapper previous gameDTO change to GameDataDTO --- .../controller/GameController.java | 28 ++++++------ .../controller/UserController.java | 8 ++-- .../petproject/boardgamefun/dto/GameDTO.java | 16 +++---- .../boardgamefun/dto/GameDataDTO.java | 14 ++++++ .../boardgamefun/service/GameService.java | 43 +++++++++++-------- .../service/mappers/GameMapper.java | 15 +++++++ .../boardgamefun/UserControllerTests.java | 34 ++++++++------- 7 files changed, 97 insertions(+), 61 deletions(-) create mode 100644 src/main/java/com/petproject/boardgamefun/dto/GameDataDTO.java create mode 100644 src/main/java/com/petproject/boardgamefun/service/mappers/GameMapper.java diff --git a/src/main/java/com/petproject/boardgamefun/controller/GameController.java b/src/main/java/com/petproject/boardgamefun/controller/GameController.java index 8cff09d..8181dbf 100644 --- a/src/main/java/com/petproject/boardgamefun/controller/GameController.java +++ b/src/main/java/com/petproject/boardgamefun/controller/GameController.java @@ -1,7 +1,7 @@ package com.petproject.boardgamefun.controller; import com.petproject.boardgamefun.dto.FilterGamesDTO; -import com.petproject.boardgamefun.dto.GameDTO; +import com.petproject.boardgamefun.dto.GameDataDTO; import com.petproject.boardgamefun.dto.UsersGameRatingDTO; import com.petproject.boardgamefun.model.Expansion; import com.petproject.boardgamefun.model.Game; @@ -43,7 +43,7 @@ public GameController(GameRepository gameRepository, UserRepository userReposito @Transactional @GetMapping() - ResponseEntity> getGames() { + ResponseEntity> getGames() { var games = gameService.projectionsToGameDTO(gameRepository.findGames()); @@ -52,7 +52,7 @@ ResponseEntity> getGames() { @Transactional @GetMapping("/get-game/{id}") - public ResponseEntity getGameByCriteria(@PathVariable Integer id) { + public ResponseEntity getGameByCriteria(@PathVariable Integer id) { var gameDTO = gameService.projectionsToGameDTO(gameRepository.findGame(id), designerRepository.findDesignersUsingGame(id)); return new ResponseEntity<>(gameDTO, HttpStatus.OK); } @@ -68,7 +68,7 @@ public ResponseEntity> getGamesByTitle(@PathVariable String @Transactional @PostMapping("/add") @PreAuthorize("hasRole('MODERATOR') or hasRole('ADMIN')") - public ResponseEntity addGame(@RequestBody Game newGame) { + public ResponseEntity addGame(@RequestBody Game newGame) { gameRepository.save(newGame); var game = gameService.entityToGameDTO(newGame); @@ -78,7 +78,7 @@ public ResponseEntity addGame(@RequestBody Game newGame) { @Transactional @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 { + public ResponseEntity uploadImage(@PathVariable Integer gameId, @RequestParam("picture") MultipartFile file) throws IOException { var game = gameRepository.findGameById(gameId); game.setPicture(file.getBytes()); gameRepository.save(game); @@ -89,7 +89,7 @@ public ResponseEntity uploadImage(@PathVariable Integer gameId, @Reques @Transactional @PutMapping("/update") @PreAuthorize("hasRole('MODERATOR') or hasRole('ADMIN')") - public ResponseEntity updateGame(@RequestBody Game updatedGame) { + public ResponseEntity updateGame(@RequestBody Game updatedGame) { gameRepository.save(updatedGame); var game = gameService.entityToGameDTO(updatedGame); return new ResponseEntity<>(game, HttpStatus.OK); @@ -106,7 +106,7 @@ public ResponseEntity removeGameFromSite(@RequestBody Game deleteGame) { @Transactional @GetMapping("/expansions/{gameId}") - public ResponseEntity> getExpansions(@PathVariable Integer gameId) { + public ResponseEntity> getExpansions(@PathVariable Integer gameId) { var gamesExpansions = gameService.entitiesToGameDTO(gameRepository.getExpansions(gameId)); return new ResponseEntity<>(gamesExpansions, HttpStatus.OK); @@ -115,7 +115,7 @@ public ResponseEntity> getExpansions(@PathVariable Integer gameId) @Transactional @PostMapping("/add-expansion/{parentGameId}/{daughterGameId}") @PreAuthorize("hasRole('USER') or hasRole('MODERATOR') or hasRole('ADMIN')") - public ResponseEntity> addExpansion(@PathVariable Integer parentGameId, @PathVariable Integer daughterGameId) { + public ResponseEntity> addExpansion(@PathVariable Integer parentGameId, @PathVariable Integer daughterGameId) { var parentGame = gameRepository.findGameById(parentGameId); var daughterGame = gameRepository.findGameById(daughterGameId); @@ -132,7 +132,7 @@ public ResponseEntity> addExpansion(@PathVariable Integer parentGa @Transactional @DeleteMapping("/delete-expansion/{parentGameId}/{daughterGameId}") @PreAuthorize("hasRole('USER') or hasRole('MODERATOR') or hasRole('ADMIN')") - public ResponseEntity> deleteExpansion(@PathVariable Integer daughterGameId, @PathVariable Integer parentGameId) { + public ResponseEntity> deleteExpansion(@PathVariable Integer daughterGameId, @PathVariable Integer parentGameId) { var expansion = expansionRepository.findExpansion_ByDaughterGameIdAndParentGameId(daughterGameId, parentGameId); expansionRepository.delete(expansion); @@ -143,7 +143,7 @@ public ResponseEntity> deleteExpansion(@PathVariable Integer daugh @Transactional @GetMapping("/similar/{gameId}") - public ResponseEntity> getSimilarGames(@PathVariable Integer gameId) { + public ResponseEntity> getSimilarGames(@PathVariable Integer gameId) { var similarGames = gameService.entitiesToGameDTO(gameRepository.getSimilarGames(gameId)); return new ResponseEntity<>(similarGames, HttpStatus.OK); @@ -152,7 +152,7 @@ public ResponseEntity> getSimilarGames(@PathVariable Integer gameI @Transactional @PostMapping("/add-similar/{referenceGameId}/{sourceGameId}") @PreAuthorize("hasRole('USER') or hasRole('MODERATOR') or hasRole('ADMIN')") - public ResponseEntity> addSimilarGame(@PathVariable Integer referenceGameId, @PathVariable Integer sourceGameId) { + public ResponseEntity> addSimilarGame(@PathVariable Integer referenceGameId, @PathVariable Integer sourceGameId) { var referenceGame = gameRepository.findGameById(referenceGameId); var sourceGame = gameRepository.findGameById(sourceGameId); @@ -169,7 +169,7 @@ public ResponseEntity> addSimilarGame(@PathVariable Integer refere @Transactional @DeleteMapping("/delete-similar/{referenceGameId}/{sourceGameId}") @PreAuthorize("hasRole('USER') or hasRole('MODERATOR') or hasRole('ADMIN')") - public ResponseEntity> deleteSameGame(@PathVariable Integer referenceGameId, @PathVariable Integer sourceGameId) { + public ResponseEntity> deleteSameGame(@PathVariable Integer referenceGameId, @PathVariable Integer sourceGameId) { var sameGame = sameGameRepository.findSameGame_ByReferenceGameIdAndSourceGameId(referenceGameId, sourceGameId); sameGameRepository.delete(sameGame); @@ -192,7 +192,7 @@ public ResponseEntity> getUsersRating(@PathVariable Int @Transactional @PostMapping("/{gameId}/set-designer/{designerId}") @PreAuthorize("hasRole('USER') or hasRole('MODERATOR') or hasRole('ADMIN')") - public ResponseEntity addDesignerToGame(@PathVariable Integer gameId, @PathVariable Integer designerId) { + public ResponseEntity addDesignerToGame(@PathVariable Integer gameId, @PathVariable Integer designerId) { var game = gameRepository.findGameById(gameId); var designer = designerRepository.findDesignerById(designerId); @@ -211,7 +211,7 @@ public ResponseEntity addDesignerToGame(@PathVariable Integer gameId, @ @Transactional @DeleteMapping("{gameId}/remove-designer/{gameByDesignerId}") @PreAuthorize("hasRole('USER') or hasRole('MODERATOR') or hasRole('ADMIN')") - public ResponseEntity deleteDesignerFromGame(@PathVariable Integer gameId, @PathVariable Integer gameByDesignerId) { + public ResponseEntity deleteDesignerFromGame(@PathVariable Integer gameId, @PathVariable Integer gameByDesignerId) { gameByDesignerRepository.deleteById(gameByDesignerId); diff --git a/src/main/java/com/petproject/boardgamefun/controller/UserController.java b/src/main/java/com/petproject/boardgamefun/controller/UserController.java index 42a3323..6fbdde3 100644 --- a/src/main/java/com/petproject/boardgamefun/controller/UserController.java +++ b/src/main/java/com/petproject/boardgamefun/controller/UserController.java @@ -1,7 +1,7 @@ package com.petproject.boardgamefun.controller; import com.petproject.boardgamefun.dto.DiaryDTO; -import com.petproject.boardgamefun.dto.GameDTO; +import com.petproject.boardgamefun.dto.GameDataDTO; import com.petproject.boardgamefun.dto.GameSellDTO; import com.petproject.boardgamefun.dto.UserDTO; import com.petproject.boardgamefun.dto.request.PasswordChangeRequest; @@ -190,7 +190,7 @@ public ResponseEntity getUser(@PathVariable Integer id) { @Transactional @GetMapping("/{id}/games") - public ResponseEntity> getUserCollection(@PathVariable Integer id) { + public ResponseEntity> getUserCollection(@PathVariable Integer id) { var games = gameService.entitiesToGameDTO(gameRepository.findUserGames(id)); return new ResponseEntity<>(games, HttpStatus.OK); @@ -237,7 +237,7 @@ public ResponseEntity deleteGameFromUserCollection(@PathVariable Intege } @GetMapping("/{userId}/games-rating") - public ResponseEntity> getUserRatingList(@PathVariable Integer userId) { + public ResponseEntity> getUserRatingList(@PathVariable Integer userId) { var ratingGamesByUser = gameService.userGameRatingToGameDTO(gameRepository.findUserGameRatingList(userId)); @@ -308,7 +308,7 @@ public ResponseEntity updateGameRating(@PathVariable Integer userId, @P } @GetMapping("/{id}/wishlist") - public ResponseEntity> getUserWishlist(@PathVariable Integer id) { + public ResponseEntity> getUserWishlist(@PathVariable Integer id) { var games = gameService.entitiesToGameDTO(gameRepository.findUserWishlist(id)); return new ResponseEntity<>(games, HttpStatus.OK); } diff --git a/src/main/java/com/petproject/boardgamefun/dto/GameDTO.java b/src/main/java/com/petproject/boardgamefun/dto/GameDTO.java index c07e8b6..94871bb 100644 --- a/src/main/java/com/petproject/boardgamefun/dto/GameDTO.java +++ b/src/main/java/com/petproject/boardgamefun/dto/GameDTO.java @@ -1,15 +1,9 @@ package com.petproject.boardgamefun.dto; -import com.petproject.boardgamefun.model.Game; -import lombok.AllArgsConstructor; -import lombok.Data; +import java.io.Serializable; +import java.time.OffsetDateTime; -import java.util.List; - -@Data -@AllArgsConstructor -public class GameDTO { - private Game game; - private Double rating; - private List designers; +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/service/GameService.java b/src/main/java/com/petproject/boardgamefun/service/GameService.java index 0cabf3e..3ac53dd 100644 --- a/src/main/java/com/petproject/boardgamefun/service/GameService.java +++ b/src/main/java/com/petproject/boardgamefun/service/GameService.java @@ -3,8 +3,9 @@ import com.petproject.boardgamefun.dto.FilterGamesDTO; import com.petproject.boardgamefun.dto.UsersGameRatingDTO; import com.petproject.boardgamefun.dto.projection.*; -import com.petproject.boardgamefun.dto.GameDTO; +import com.petproject.boardgamefun.dto.GameDataDTO; import com.petproject.boardgamefun.model.Game; +import com.petproject.boardgamefun.service.mappers.GameMapper; import org.springframework.stereotype.Service; import java.util.ArrayList; @@ -13,52 +14,60 @@ @Service public class GameService { - public GameDTO projectionsToGameDTO(GameProjection gameProjection, List designersProjection) { - return new GameDTO(gameProjection.getGame(), + + final + GameMapper gameMapper; + + public GameService(GameMapper gameMapper) { + this.gameMapper = gameMapper; + } + + public GameDataDTO projectionsToGameDTO(GameProjection gameProjection, List designersProjection) { + return new GameDataDTO(gameMapper.gameToGameDTO(gameProjection.getGame()), gameProjection.getRating(), designersProjection.stream().map(DesignersProjection::getDesigner).collect(Collectors.toList())); } - public GameDTO projectionToGameDTO(GameProjection gameProjection) { - return new GameDTO(gameProjection.getGame(), null, null); + public GameDataDTO projectionToGameDTO(GameProjection gameProjection) { + return new GameDataDTO(gameMapper.gameToGameDTO(gameProjection.getGame()), null, null); } - public List projectionsToGameDTO(List gameProjections) { - List games = new ArrayList<>(); + public List projectionsToGameDTO(List gameProjections) { + List games = new ArrayList<>(); for (var game : gameProjections) { - games.add(new GameDTO(game.getGame(), game.getRating(), null)); + games.add(new GameDataDTO(gameMapper.gameToGameDTO(game.getGame()), game.getRating(), null)); } return games; } - public List entitiesToGameDTO(List games) { - ArrayList gamesDTO = new ArrayList<>(); + public List entitiesToGameDTO(List games) { + ArrayList gamesDTO = new ArrayList<>(); for (var game : games) { - gamesDTO.add(new GameDTO(game, null, null)); + gamesDTO.add(new GameDataDTO(gameMapper.gameToGameDTO(game), null, null)); } return gamesDTO; } - public GameDTO entityToGameDTO(Game game){ - return new GameDTO(game, null, null); + 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){ + for (var projection : projections) { games.add(new FilterGamesDTO(projection.getId(), projection.getTitle())); } return games; } - public List userGameRatingToGameDTO(List projections) { - ArrayList games = new ArrayList<>(); + public List userGameRatingToGameDTO(List projections) { + ArrayList games = new ArrayList<>(); for (var projection : projections) { - games.add(new GameDTO(projection.getGame(), (double) projection.getRating(), null)); + games.add(new GameDataDTO(gameMapper.gameToGameDTO(projection.getGame()), (double) projection.getRating(), null)); } return games; } 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/test/java/com/petproject/boardgamefun/UserControllerTests.java b/src/test/java/com/petproject/boardgamefun/UserControllerTests.java index f36d44d..086cfa9 100644 --- a/src/test/java/com/petproject/boardgamefun/UserControllerTests.java +++ b/src/test/java/com/petproject/boardgamefun/UserControllerTests.java @@ -21,6 +21,7 @@ import com.petproject.boardgamefun.service.GameSellService; import com.petproject.boardgamefun.service.GameService; import com.petproject.boardgamefun.service.UserService; +import com.petproject.boardgamefun.service.mappers.GameMapper; import com.petproject.boardgamefun.service.mappers.UserMapper; import org.junit.jupiter.api.*; import org.junit.jupiter.api.extension.ExtendWith; @@ -65,6 +66,9 @@ public class UserControllerTests { @Autowired UserMapper userMapper; + @Autowired + GameMapper gameMapper; + @MockBean private UserRepository userRepository; @@ -119,8 +123,8 @@ public class UserControllerTests { private User userModerator; private User user; private List users; - private List gamesDTO; - private GameDTO gameDTO; + private List gamesDTO; + private GameDataDTO gameDataDTO; private Game game; private List games; private List userGameRatingProjections; @@ -252,17 +256,17 @@ public void setup() { designers.add(designer.getName()); designers.add(designer2.getName()); - gameDTO = new GameDTO(game, 8.4, designers); + gameDataDTO = new GameDataDTO(gameMapper.gameToGameDTO(game), 8.4, designers); designers.remove(1); - GameDTO gameDTO1 = new GameDTO(game, 7.9, designers); + 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(gameDTO); - gamesDTO.add(gameDTO1); + gamesDTO.add(gameDataDTO); + gamesDTO.add(gameDataDTO1); ratingGameByUser = new RatingGameByUser(); ratingGameByUser.setUser(user); @@ -487,13 +491,13 @@ public void getUserCollectionShouldReturnIsOk() throws Exception { 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(), GameDTO[].class); + 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().getId(), gamesDTO.get(0).getGame().getId()); + Assertions.assertEquals(userCollection[0].getGame().id(), gamesDTO.get(0).getGame().id()); } @Test @@ -502,7 +506,7 @@ 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(), GameDTO[].class); + var gameDTOS = objectMapper.readValue(mvcResult.getResponse().getContentAsByteArray(), GameDataDTO[].class); verify(gameRepository, only()).findUserGames(-1); verify(gameService, only()).entitiesToGameDTO(gameListArgumentCaptor.capture()); @@ -519,13 +523,13 @@ public void getUserRatingListShouldReturnIsOk() throws Exception { 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(), GameDTO[].class); + 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().getId(), gamesDTO.get(0).getGame().getId()); + Assertions.assertEquals(userRatingList[0].getGame().id(), gamesDTO.get(0).getGame().id()); } @Test @@ -535,7 +539,7 @@ public void getUserRatingListShouldReturnBlankArray() throws Exception { 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(), GameDTO[].class); + var gameDTOS = objectMapper.readValue(mvcResult.getResponse().getContentAsByteArray(), GameDataDTO[].class); verify(gameRepository, only()).findUserGameRatingList(-1); verify(gameService, only()).userGameRatingToGameDTO(userGameRatingProjectionCaptor.capture()); @@ -904,13 +908,13 @@ public void getUserWishlistShouldReturnIsOk() throws Exception { var mvcResult = this.mockMvc.perform(MockMvcRequestBuilders.get(Gateway + "/1/wishlist")) .andExpect(status().isOk()).andReturn(); - var response = objectMapper.readValue(mvcResult.getResponse().getContentAsByteArray(), GameDTO[].class); + 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().getId(), gamesDTO.get(0).getGame().getId()); + 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()); @@ -922,7 +926,7 @@ 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(), GameDTO[].class); + var response = objectMapper.readValue(mvcResult.getResponse().getContentAsByteArray(), GameDataDTO[].class); Assertions.assertEquals(0, response.length); } From f20540ba406c9bd62e2bb4987482474e31334a67 Mon Sep 17 00:00:00 2001 From: "i.i.artamonov" Date: Fri, 6 May 2022 11:04:41 +0400 Subject: [PATCH 112/141] Added DiaryDTO. Added DiaryMapper --- .../controller/DiaryController.java | 8 ++++---- .../controller/UserController.java | 6 +++--- .../petproject/boardgamefun/dto/DiaryDTO.java | 8 ++++++++ .../petproject/boardgamefun/dto/DiaryDTO.kt | 5 ----- .../boardgamefun/dto/DiaryDataDTO.kt | 3 +++ .../boardgamefun/service/DiaryService.kt | 20 ++++++++++--------- .../service/mappers/DiaryMapper.java | 15 ++++++++++++++ .../boardgamefun/UserControllerTests.java | 16 +++++++++------ 8 files changed, 54 insertions(+), 27 deletions(-) create mode 100644 src/main/java/com/petproject/boardgamefun/dto/DiaryDTO.java delete mode 100644 src/main/java/com/petproject/boardgamefun/dto/DiaryDTO.kt create mode 100644 src/main/java/com/petproject/boardgamefun/dto/DiaryDataDTO.kt create mode 100644 src/main/java/com/petproject/boardgamefun/service/mappers/DiaryMapper.java diff --git a/src/main/java/com/petproject/boardgamefun/controller/DiaryController.java b/src/main/java/com/petproject/boardgamefun/controller/DiaryController.java index d6a4863..370e6f5 100644 --- a/src/main/java/com/petproject/boardgamefun/controller/DiaryController.java +++ b/src/main/java/com/petproject/boardgamefun/controller/DiaryController.java @@ -1,7 +1,7 @@ package com.petproject.boardgamefun.controller; import com.petproject.boardgamefun.dto.DiaryCommentDTO; -import com.petproject.boardgamefun.dto.DiaryDTO; +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; @@ -48,9 +48,9 @@ public DiaryController(DiaryCommentRepository diaryCommentRepository, UserReposi @Transactional @GetMapping("") - public ResponseEntity> getDiaries(@RequestParam(required = false) Integer userId, @RequestParam(required = false) Integer gameId) { + public ResponseEntity> getDiaries(@RequestParam(required = false) Integer userId, @RequestParam(required = false) Integer gameId) { - List diaries; + List diaries; if (userId != null) diaries = diaryService.projectionsToDiaryDTO(diaryRepository.findUserDiaries(userId)); @@ -64,7 +64,7 @@ else if(gameId != null) @Transactional @GetMapping("/{diaryId}") - public ResponseEntity getDiary(@PathVariable Integer diaryId) { + public ResponseEntity getDiary(@PathVariable Integer diaryId) { var diaryProjection = diaryService.projectionToDiaryDTO(diaryRepository.findDiaryUsingId(diaryId)); return new ResponseEntity<>(diaryProjection, HttpStatus.OK); diff --git a/src/main/java/com/petproject/boardgamefun/controller/UserController.java b/src/main/java/com/petproject/boardgamefun/controller/UserController.java index 6fbdde3..b2d77e4 100644 --- a/src/main/java/com/petproject/boardgamefun/controller/UserController.java +++ b/src/main/java/com/petproject/boardgamefun/controller/UserController.java @@ -1,6 +1,6 @@ package com.petproject.boardgamefun.controller; -import com.petproject.boardgamefun.dto.DiaryDTO; +import com.petproject.boardgamefun.dto.DiaryDataDTO; import com.petproject.boardgamefun.dto.GameDataDTO; import com.petproject.boardgamefun.dto.GameSellDTO; import com.petproject.boardgamefun.dto.UserDTO; @@ -429,7 +429,7 @@ public ResponseEntity updateSellGame(@RequestBody GameSell gameSell) { @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) { + 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); @@ -470,7 +470,7 @@ public ResponseEntity deleteDiary(@PathVariable Integer userId, @PathVar @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) { + public ResponseEntity updateDiary(@PathVariable Integer diaryId, @PathVariable Integer userId, @RequestBody Diary diaryRequest) { if (diaryRequest.getId() == null) { return new ResponseEntity<>(null, HttpStatus.BAD_REQUEST); 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/DiaryDTO.kt b/src/main/java/com/petproject/boardgamefun/dto/DiaryDTO.kt deleted file mode 100644 index a053d47..0000000 --- a/src/main/java/com/petproject/boardgamefun/dto/DiaryDTO.kt +++ /dev/null @@ -1,5 +0,0 @@ -package com.petproject.boardgamefun.dto - -import com.petproject.boardgamefun.model.Diary - -data class DiaryDTO(val diary: Diary, val rating: Double?) \ No newline at end of file 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/service/DiaryService.kt b/src/main/java/com/petproject/boardgamefun/service/DiaryService.kt index bcaccb0..ee1842f 100644 --- a/src/main/java/com/petproject/boardgamefun/service/DiaryService.kt +++ b/src/main/java/com/petproject/boardgamefun/service/DiaryService.kt @@ -1,26 +1,28 @@ package com.petproject.boardgamefun.service import com.petproject.boardgamefun.dto.projection.DiaryWithRatingsProjection -import com.petproject.boardgamefun.dto.DiaryDTO +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 { - fun projectionsToDiaryDTO(projections: List): List { - val diaries: MutableList = ArrayList() +class DiaryService (private val diaryMapper: DiaryMapper) { + + fun projectionsToDiaryDTO(projections: List): List { + val diaries: MutableList = ArrayList() for (projection in projections) { - diaries.add(DiaryDTO(projection.diary, projection.rating)) + diaries.add(DiaryDataDTO(diaryMapper.diaryToDiaryDTO(projection.diary), projection.rating)) } return diaries } - fun entityToDiaryDTO(diary: Diary): DiaryDTO { - return DiaryDTO(diary, 0.0) + fun entityToDiaryDTO(diary: Diary): DiaryDataDTO { + return DiaryDataDTO(diaryMapper.diaryToDiaryDTO(diary), 0.0) } - fun projectionToDiaryDTO(projection: DiaryWithRatingsProjection): DiaryDTO { - return DiaryDTO(projection.diary, projection.rating) + 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/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/test/java/com/petproject/boardgamefun/UserControllerTests.java b/src/test/java/com/petproject/boardgamefun/UserControllerTests.java index 086cfa9..a731b86 100644 --- a/src/test/java/com/petproject/boardgamefun/UserControllerTests.java +++ b/src/test/java/com/petproject/boardgamefun/UserControllerTests.java @@ -21,6 +21,7 @@ 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.junit.jupiter.api.*; @@ -69,6 +70,9 @@ public class UserControllerTests { @Autowired GameMapper gameMapper; + @Autowired + DiaryMapper diaryMapper; + @MockBean private UserRepository userRepository; @@ -138,7 +142,7 @@ public class UserControllerTests { private GameSellDTO gameSellDTO; private GameSell gameSell; private Diary diary; - private DiaryDTO diaryDTO; + private DiaryDataDTO diaryDTO; @Autowired private MockMvc mockMvc; @@ -310,7 +314,7 @@ public void setup() { diary.setText("Not so good, but good"); diary.setPublicationTime(OffsetDateTime.now()); - diaryDTO = new DiaryDTO(diary, 8.0); + diaryDTO = new DiaryDataDTO(diaryMapper.diaryToDiaryDTO(diary), 8.0); } @Test @@ -1323,14 +1327,14 @@ public void addDiaryShouldReturnIsOk() throws Exception { .content(objectMapper.writeValueAsString(diary))) .andDo(print()).andExpect(status().isOk()).andReturn(); - var response = objectMapper.readValue(mvcRes.getResponse().getContentAsByteArray(), DiaryDTO.class); + 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().getId(), response.getDiary().getId()); + Assertions.assertEquals(diaryDTO.getDiary().id(), response.getDiary().id()); } @@ -1462,13 +1466,13 @@ public void updateDiaryShouldReturnIsOk() throws Exception { .content(objectMapper.writeValueAsString(diary))) .andDo(print()).andExpect(status().isOk()).andReturn(); - var response = objectMapper.readValue(mvcRes.getResponse().getContentAsByteArray(), DiaryDTO.class); + 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().getId(), response.getDiary().getId()); + Assertions.assertEquals(diaryDTO.getDiary().id(), response.getDiary().id()); diary.setId(null); } From c5dea6f88afe988d7c1bc0e0e570fbcd3ac77868 Mon Sep 17 00:00:00 2001 From: "i.i.artamonov" Date: Fri, 6 May 2022 11:15:15 +0400 Subject: [PATCH 113/141] Changed diaryRatingDTO. Added DiaryRatingMapper not tested! --- .../boardgamefun/dto/DiaryRatingDTO.java | 9 ++------- .../service/mappers/DiaryRatingMapper.java | 15 +++++++++++++++ 2 files changed, 17 insertions(+), 7 deletions(-) create mode 100644 src/main/java/com/petproject/boardgamefun/service/mappers/DiaryRatingMapper.java diff --git a/src/main/java/com/petproject/boardgamefun/dto/DiaryRatingDTO.java b/src/main/java/com/petproject/boardgamefun/dto/DiaryRatingDTO.java index 88ec4bc..00d0509 100644 --- a/src/main/java/com/petproject/boardgamefun/dto/DiaryRatingDTO.java +++ b/src/main/java/com/petproject/boardgamefun/dto/DiaryRatingDTO.java @@ -1,11 +1,6 @@ package com.petproject.boardgamefun.dto; -import lombok.AllArgsConstructor; -import lombok.Data; +import java.io.Serializable; -@Data -@AllArgsConstructor -public class DiaryRatingDTO { - private Integer id; - private Double rating; +public record DiaryRatingDTO(Integer id, Double rating) implements Serializable { } 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); +} From 46ad8815f1bfc01cdc40e84ce8d51949725b5b48 Mon Sep 17 00:00:00 2001 From: "i.i.artamonov" Date: Fri, 6 May 2022 12:52:29 +0400 Subject: [PATCH 114/141] Added RatingGameByUserDTO. Added RatingGameByUserMapper changed rating data type??? --- .../controller/GameController.java | 4 ++-- .../controller/UserController.java | 14 ++++++------ .../boardgamefun/dto/RatingGameByUserDTO.java | 6 +++++ .../boardgamefun/dto/UsersGameRatingDTO.java | 14 ------------ .../boardgamefun/model/RatingGameByUser.java | 6 ++--- .../boardgamefun/service/GameService.java | 8 +++---- .../mappers/RatingGameByUserMapper.java | 22 +++++++++++++++++++ .../boardgamefun/UserControllerTests.java | 20 ++++++++--------- 8 files changed, 54 insertions(+), 40 deletions(-) create mode 100644 src/main/java/com/petproject/boardgamefun/dto/RatingGameByUserDTO.java delete mode 100644 src/main/java/com/petproject/boardgamefun/dto/UsersGameRatingDTO.java create mode 100644 src/main/java/com/petproject/boardgamefun/service/mappers/RatingGameByUserMapper.java diff --git a/src/main/java/com/petproject/boardgamefun/controller/GameController.java b/src/main/java/com/petproject/boardgamefun/controller/GameController.java index 8181dbf..cdab51c 100644 --- a/src/main/java/com/petproject/boardgamefun/controller/GameController.java +++ b/src/main/java/com/petproject/boardgamefun/controller/GameController.java @@ -2,7 +2,7 @@ import com.petproject.boardgamefun.dto.FilterGamesDTO; import com.petproject.boardgamefun.dto.GameDataDTO; -import com.petproject.boardgamefun.dto.UsersGameRatingDTO; +import com.petproject.boardgamefun.dto.RatingGameByUserDTO; import com.petproject.boardgamefun.model.Expansion; import com.petproject.boardgamefun.model.Game; import com.petproject.boardgamefun.model.GameByDesigner; @@ -180,7 +180,7 @@ public ResponseEntity> deleteSameGame(@PathVariable Integer re @Transactional @GetMapping("/{gameId}/users-rating") - public ResponseEntity> getUsersRating(@PathVariable Integer gameId) { + public ResponseEntity> getUsersRating(@PathVariable Integer gameId) { var ratings = gameService.usersGameRatingToDTO(userRepository.findGameRatings(gameId)); diff --git a/src/main/java/com/petproject/boardgamefun/controller/UserController.java b/src/main/java/com/petproject/boardgamefun/controller/UserController.java index b2d77e4..e30f666 100644 --- a/src/main/java/com/petproject/boardgamefun/controller/UserController.java +++ b/src/main/java/com/petproject/boardgamefun/controller/UserController.java @@ -262,7 +262,7 @@ public ResponseEntity deleteGameRating(@PathVariable Integer userId, @Pa @Transactional @PostMapping("/{userId}/set-game-rating/{gameId}/{rating}") @PreAuthorize("hasRole('USER') or hasRole('MODERATOR') or hasRole('ADMIN')") - public ResponseEntity setGameRating(@PathVariable Integer userId, @PathVariable Integer gameId, @PathVariable Integer rating) { + public ResponseEntity setGameRating(@PathVariable Integer userId, @PathVariable Integer gameId, @PathVariable Integer rating) { if (rating > 10 || rating < 1) { return new ResponseEntity<>(null, HttpStatus.BAD_REQUEST); @@ -280,18 +280,18 @@ public ResponseEntity setGameRating(@PathVariable Integer userId, @Path gameRating.setGame(game); gameRating.setUser(user); - gameRating.setRating(rating); + gameRating.setRating(rating.doubleValue()); ratingGameByUserRepository.save(gameRating); - return new ResponseEntity<>(rating, HttpStatus.OK); + return new ResponseEntity<>(rating.doubleValue(), HttpStatus.OK); } @Transactional - @PostMapping("/{userId}/update-game-rating/{gameId}/{rating}") + @PatchMapping("/{userId}/update-game-rating/{gameId}/{rating}") @PreAuthorize("hasRole('USER') or hasRole('MODERATOR') or hasRole('ADMIN')") - public ResponseEntity updateGameRating(@PathVariable Integer userId, @PathVariable Integer gameId, @PathVariable Integer rating) { + public ResponseEntity updateGameRating(@PathVariable Integer userId, @PathVariable Integer gameId, @PathVariable Integer rating) { if (rating > 10 || rating < 1) { return new ResponseEntity<>(null, HttpStatus.BAD_REQUEST); @@ -301,10 +301,10 @@ public ResponseEntity updateGameRating(@PathVariable Integer userId, @P return new ResponseEntity<>(null, HttpStatus.NOT_FOUND); } - ratingGameByUser.setRating(rating); + ratingGameByUser.setRating(rating.doubleValue()); ratingGameByUserRepository.save(ratingGameByUser); - return new ResponseEntity<>(rating, HttpStatus.OK); + return new ResponseEntity<>(rating.doubleValue(), HttpStatus.OK); } @GetMapping("/{id}/wishlist") 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/UsersGameRatingDTO.java b/src/main/java/com/petproject/boardgamefun/dto/UsersGameRatingDTO.java deleted file mode 100644 index f4cce84..0000000 --- a/src/main/java/com/petproject/boardgamefun/dto/UsersGameRatingDTO.java +++ /dev/null @@ -1,14 +0,0 @@ -package com.petproject.boardgamefun.dto; - -import com.petproject.boardgamefun.model.User; -import lombok.AllArgsConstructor; -import lombok.Data; -import lombok.NoArgsConstructor; - -@Data -@AllArgsConstructor -@NoArgsConstructor -public class UsersGameRatingDTO { - private User user; - private Double rating; -} diff --git a/src/main/java/com/petproject/boardgamefun/model/RatingGameByUser.java b/src/main/java/com/petproject/boardgamefun/model/RatingGameByUser.java index 20ec37b..dfe4679 100644 --- a/src/main/java/com/petproject/boardgamefun/model/RatingGameByUser.java +++ b/src/main/java/com/petproject/boardgamefun/model/RatingGameByUser.java @@ -11,7 +11,7 @@ public class RatingGameByUser { private Integer id; @Column(name = "rating", nullable = false) - private Integer rating; + private Double rating; @ManyToOne(optional = false) @JoinColumn(name = "\"user\"", nullable = false) @@ -37,11 +37,11 @@ public void setUser(User user) { this.user = user; } - public Integer getRating() { + public Double getRating() { return rating; } - public void setRating(Integer rating) { + public void setRating(Double rating) { this.rating = rating; } diff --git a/src/main/java/com/petproject/boardgamefun/service/GameService.java b/src/main/java/com/petproject/boardgamefun/service/GameService.java index 3ac53dd..d24339d 100644 --- a/src/main/java/com/petproject/boardgamefun/service/GameService.java +++ b/src/main/java/com/petproject/boardgamefun/service/GameService.java @@ -1,7 +1,7 @@ package com.petproject.boardgamefun.service; import com.petproject.boardgamefun.dto.FilterGamesDTO; -import com.petproject.boardgamefun.dto.UsersGameRatingDTO; +import com.petproject.boardgamefun.dto.RatingGameByUserDTO; import com.petproject.boardgamefun.dto.projection.*; import com.petproject.boardgamefun.dto.GameDataDTO; import com.petproject.boardgamefun.model.Game; @@ -72,11 +72,11 @@ public List userGameRatingToGameDTO(List return games; } - public List usersGameRatingToDTO(List projections) { - ArrayList users = new ArrayList<>(); + public List usersGameRatingToDTO(List projections) { + ArrayList users = new ArrayList<>(); for (var projection : projections) { - users.add(new UsersGameRatingDTO(projection.getUser(), projection.getRating())); + users.add(new RatingGameByUserDTO(projection.getUser().getId(), projection.getRating())); } return users; } 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/test/java/com/petproject/boardgamefun/UserControllerTests.java b/src/test/java/com/petproject/boardgamefun/UserControllerTests.java index a731b86..835d1cb 100644 --- a/src/test/java/com/petproject/boardgamefun/UserControllerTests.java +++ b/src/test/java/com/petproject/boardgamefun/UserControllerTests.java @@ -275,7 +275,7 @@ public void setup() { ratingGameByUser = new RatingGameByUser(); ratingGameByUser.setUser(user); ratingGameByUser.setGame(game); - ratingGameByUser.setRating(10); + ratingGameByUser.setRating(10.0); userOwnGame = new UserOwnGame(); userOwnGame.setUser(user); @@ -609,7 +609,7 @@ public void setGameRatingShouldReturnOk() throws Exception { 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(), Integer.class); + var rating = objectMapper.readValue(mvcResult.getResponse().getContentAsByteArray(), Double.class); verify(ratingGameByUserRepository).findRatingGame_ByUserIdAndGameId(1, 1); verify(userRepository).findUserById(1); @@ -692,26 +692,26 @@ 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.post(Gateway + "/1/update-game-rating/1/10")) + 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(), Integer.class); + var rating = objectMapper.readValue(result.getResponse().getContentAsByteArray(), Double.class); verify(ratingGameByUserRepository).findRatingGame_ByUserIdAndGameId(1, 1); verify(ratingGameByUserRepository).save(ratingGameByUser); - Assertions.assertEquals(ratingGameByUser.getRating(), rating); + Assertions.assertEquals(ratingGameByUser.getRating(), rating.doubleValue()); } @Test @WithMockUser(roles = "USER") public void updateGameRatingShouldReturnBadRequestLessThanNormal() throws Exception { - this.mockMvc.perform(MockMvcRequestBuilders.post(Gateway + "/1/update-game-rating/1/0")).andDo(print()).andExpect(status().isBadRequest()); + 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.post(Gateway + "/1/update-game-rating/1/11")).andDo(print()).andExpect(status().isBadRequest()); + this.mockMvc.perform(MockMvcRequestBuilders.patch(Gateway + "/1/update-game-rating/1/11")).andDo(print()).andExpect(status().isBadRequest()); } @Test @@ -719,7 +719,7 @@ public void updateGameRatingShouldReturnBadRequestMoreThanNormal() throws Except public void updateGameRatingShouldReturnNotFound_FirstParameter() throws Exception { when(ratingGameByUserRepository.findRatingGame_ByUserIdAndGameId(-1, 1)).thenReturn(null); - this.mockMvc.perform(MockMvcRequestBuilders.post(Gateway + "/-1/update-game-rating/1/1")) + this.mockMvc.perform(MockMvcRequestBuilders.patch(Gateway + "/-1/update-game-rating/1/1")) .andDo(print()).andExpect(status().isNotFound()); verify(ratingGameByUserRepository).findRatingGame_ByUserIdAndGameId(-1, 1); @@ -730,7 +730,7 @@ public void updateGameRatingShouldReturnNotFound_FirstParameter() throws Excepti public void updateGameRatingShouldReturnNotFound_SecondParameter() throws Exception { when(ratingGameByUserRepository.findRatingGame_ByUserIdAndGameId(1, -1)).thenReturn(null); - this.mockMvc.perform(MockMvcRequestBuilders.post(Gateway + "/1/update-game-rating/-1/1")) + this.mockMvc.perform(MockMvcRequestBuilders.patch(Gateway + "/1/update-game-rating/-1/1")) .andDo(print()).andExpect(status().isNotFound()); verify(ratingGameByUserRepository).findRatingGame_ByUserIdAndGameId(1, -1); @@ -741,7 +741,7 @@ public void updateGameRatingShouldReturnNotFound_SecondParameter() throws Except public void updateGameRatingShouldReturnNotFound_BothParameters() throws Exception { when(ratingGameByUserRepository.findRatingGame_ByUserIdAndGameId(-1, -1)).thenReturn(null); - this.mockMvc.perform(MockMvcRequestBuilders.post(Gateway + "/-1/update-game-rating/-1/1")) + this.mockMvc.perform(MockMvcRequestBuilders.patch(Gateway + "/-1/update-game-rating/-1/1")) .andDo(print()).andExpect(status().isNotFound()); verify(ratingGameByUserRepository).findRatingGame_ByUserIdAndGameId(-1, -1); From cce41526d2823df9b84510a93e10cc5ba503a4b3 Mon Sep 17 00:00:00 2001 From: "i.i.artamonov" Date: Wed, 11 May 2022 15:16:03 +0400 Subject: [PATCH 115/141] Changed GameSellDTO Change field from Game entity to DTO --- .../petproject/boardgamefun/dto/GameSellDTO.java | 3 +-- .../boardgamefun/service/GameSellService.java | 15 +++++++++++---- .../boardgamefun/UserControllerTests.java | 8 ++++---- 3 files changed, 16 insertions(+), 10 deletions(-) diff --git a/src/main/java/com/petproject/boardgamefun/dto/GameSellDTO.java b/src/main/java/com/petproject/boardgamefun/dto/GameSellDTO.java index c5f0f14..39b92b6 100644 --- a/src/main/java/com/petproject/boardgamefun/dto/GameSellDTO.java +++ b/src/main/java/com/petproject/boardgamefun/dto/GameSellDTO.java @@ -1,6 +1,5 @@ package com.petproject.boardgamefun.dto; -import com.petproject.boardgamefun.model.Game; import lombok.AllArgsConstructor; import lombok.Data; import lombok.NoArgsConstructor; @@ -9,7 +8,7 @@ @AllArgsConstructor @NoArgsConstructor public class GameSellDTO { - private Game game; + private GameDTO game; private String condition; private String comment; private Integer price; diff --git a/src/main/java/com/petproject/boardgamefun/service/GameSellService.java b/src/main/java/com/petproject/boardgamefun/service/GameSellService.java index 30febbc..63f1bf6 100644 --- a/src/main/java/com/petproject/boardgamefun/service/GameSellService.java +++ b/src/main/java/com/petproject/boardgamefun/service/GameSellService.java @@ -3,6 +3,7 @@ import com.petproject.boardgamefun.dto.GameSellDTO; import com.petproject.boardgamefun.dto.projection.GameSellProjection; import com.petproject.boardgamefun.model.Game; +import com.petproject.boardgamefun.service.mappers.GameMapper; import org.springframework.stereotype.Service; import java.util.ArrayList; @@ -11,15 +12,21 @@ @Service public class GameSellService { - public GameSellDTO entityToGameSellDTO(Game game){ - return new GameSellDTO(game, null, null, null); + final GameMapper gameMapper; + + public GameSellService(GameMapper gameMapper) { + this.gameMapper = gameMapper; + } + + public GameSellDTO entityToGameSellDTO(Game game) { + return new GameSellDTO(gameMapper.gameToGameDTO(game), null, null, null); } - public List projectionsToGameSellDTO(List projections){ + public List projectionsToGameSellDTO(List projections) { ArrayList gamesForSell = new ArrayList<>(); for (var projection : projections) { - gamesForSell.add(new GameSellDTO(projection.getGame(), + gamesForSell.add(new GameSellDTO(gameMapper.gameToGameDTO(projection.getGame()), projection.getCondition(), projection.getComment(), projection.getPrice() diff --git a/src/test/java/com/petproject/boardgamefun/UserControllerTests.java b/src/test/java/com/petproject/boardgamefun/UserControllerTests.java index 835d1cb..eea320b 100644 --- a/src/test/java/com/petproject/boardgamefun/UserControllerTests.java +++ b/src/test/java/com/petproject/boardgamefun/UserControllerTests.java @@ -298,14 +298,14 @@ public void setup() { gameSellProjectionList.add(new GameSellPOJO(game1, "excellent", "not open", 300)); gameSellDTO = new GameSellDTO(); - gameSellDTO.setGame(game); + 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(game1, "excellent", "not open", 300)); + gameSellDTOList.add(new GameSellDTO(gameMapper.gameToGameDTO(game1), "excellent", "not open", 300)); diary = new Diary(); diary.setGame(game); @@ -1099,7 +1099,7 @@ public void addGameToSellListShouldReturnOk() throws Exception { verify(gameSellService).projectionsToGameSellDTO(gameSellProjectionList); Assertions.assertEquals(response.length, gameSellDTOList.size()); - Assertions.assertEquals(response[0].getGame().getId(), gameSellDTOList.get(0).getGame().getId()); + Assertions.assertEquals(response[0].getGame().id(), gameSellDTOList.get(0).getGame().id()); } @Test @@ -1181,7 +1181,7 @@ public void getGameSellListShouldReturnOk() throws Exception { verify(gameSellService).projectionsToGameSellDTO(gameSellProjectionList); Assertions.assertEquals(response.length, gameSellDTOList.size()); - Assertions.assertEquals(response[0].getGame().getId(), gameSellDTOList.get(0).getGame().getId()); + Assertions.assertEquals(response[0].getGame().id(), gameSellDTOList.get(0).getGame().id()); } From 59370333819cc4029b12aac210fc0e8a0841cc65 Mon Sep 17 00:00:00 2001 From: "i.i.artamonov" Date: Wed, 11 May 2022 15:49:29 +0400 Subject: [PATCH 116/141] Add ForumDTO and ForunDataDTO --- .../controller/ForumController.java | 16 ++++----- .../petproject/boardgamefun/dto/ForumDTO.java | 14 +++----- .../boardgamefun/dto/ForumDataDTO.java | 13 +++++++ .../boardgamefun/service/ForumService.java | 36 +++++++++++-------- .../service/mappers/ForumMapper.java | 15 ++++++++ 5 files changed, 62 insertions(+), 32 deletions(-) create mode 100644 src/main/java/com/petproject/boardgamefun/dto/ForumDataDTO.java create mode 100644 src/main/java/com/petproject/boardgamefun/service/mappers/ForumMapper.java diff --git a/src/main/java/com/petproject/boardgamefun/controller/ForumController.java b/src/main/java/com/petproject/boardgamefun/controller/ForumController.java index b441e5c..3e99b1c 100644 --- a/src/main/java/com/petproject/boardgamefun/controller/ForumController.java +++ b/src/main/java/com/petproject/boardgamefun/controller/ForumController.java @@ -1,6 +1,6 @@ package com.petproject.boardgamefun.controller; -import com.petproject.boardgamefun.dto.ForumDTO; +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; @@ -45,8 +45,8 @@ public ForumController(ForumRepository forumRepository, GameRepository gameRepos @Transactional @GetMapping("") - public ResponseEntity> getForums(@RequestParam(required = false) Integer gameId, @RequestParam(required = false) Integer userId) { - List forums; + 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) { @@ -60,7 +60,7 @@ public ResponseEntity> getForums(@RequestParam(required = false) @Transactional @GetMapping("/{forumId}") - public ResponseEntity getForum(@PathVariable Integer forumId) { + public ResponseEntity getForum(@PathVariable Integer forumId) { var forum = forumService.projectionToForumDTO(forumRepository.findForumWithRatingUsingId(forumId)); return new ResponseEntity<>(forum, HttpStatus.OK); @@ -69,7 +69,7 @@ public ResponseEntity getForum(@PathVariable Integer forumId) { @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) { + public ResponseEntity addForum(@PathVariable Integer gameId, @PathVariable Integer userId, @RequestBody ForumRequest forumRequest) { var user = userRepository.findUserById(userId); var game = gameRepository.findGameById(gameId); @@ -91,7 +91,7 @@ public ResponseEntity addForum(@PathVariable Integer gameId, @PathVari @Transactional @PatchMapping("/update-forum/{forumId}") @PreAuthorize("hasRole('USER') or hasRole('MODERATOR') or hasRole('ADMIN')") - public ResponseEntity updateForum(@PathVariable Integer forumId, @RequestBody ForumRequest forumRequest) { + public ResponseEntity updateForum(@PathVariable Integer forumId, @RequestBody ForumRequest forumRequest) { var forum = forumRepository.findForumById(forumId); if (forumRequest.getTitle() != null && !Objects.equals(forumRequest.getTitle(), forum.getTitle())) @@ -186,7 +186,7 @@ public ResponseEntity> deleteMessage(@PathVariable Integer @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) { + public ResponseEntity setForumRating(@PathVariable Integer forumId, @PathVariable Integer userId, @RequestBody ForumRatingRequest forumRatingRequest) { var forumRating = forumRatingRepository.findForumRating_ByForumIdAndUserId(forumId, userId); if (forumRating == null) { @@ -207,7 +207,7 @@ public ResponseEntity setForumRating(@PathVariable Integer forumId, @P @Transactional @DeleteMapping("/{forumId}/remove-rating/{ratingId}") @PreAuthorize("hasRole('USER') or hasRole('MODERATOR') or hasRole('ADMIN')") - public ResponseEntity removeRatingFromForum(@PathVariable Integer forumId, @PathVariable Integer ratingId) { + public ResponseEntity removeRatingFromForum(@PathVariable Integer forumId, @PathVariable Integer ratingId) { var forumRating = forumRatingRepository.findForumRatingById(ratingId); forumRatingRepository.delete(forumRating); diff --git a/src/main/java/com/petproject/boardgamefun/dto/ForumDTO.java b/src/main/java/com/petproject/boardgamefun/dto/ForumDTO.java index 8819ff7..7a4257c 100644 --- a/src/main/java/com/petproject/boardgamefun/dto/ForumDTO.java +++ b/src/main/java/com/petproject/boardgamefun/dto/ForumDTO.java @@ -1,14 +1,8 @@ package com.petproject.boardgamefun.dto; -import com.petproject.boardgamefun.model.Forum; -import lombok.AllArgsConstructor; -import lombok.Data; -import lombok.NoArgsConstructor; +import java.io.Serializable; +import java.time.OffsetDateTime; -@Data -@AllArgsConstructor -@NoArgsConstructor -public class ForumDTO { - private Forum forum; - private Double rating; +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/service/ForumService.java b/src/main/java/com/petproject/boardgamefun/service/ForumService.java index 11f9fa2..d5d38f3 100644 --- a/src/main/java/com/petproject/boardgamefun/service/ForumService.java +++ b/src/main/java/com/petproject/boardgamefun/service/ForumService.java @@ -1,8 +1,9 @@ package com.petproject.boardgamefun.service; -import com.petproject.boardgamefun.dto.ForumDTO; +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; @@ -10,31 +11,38 @@ @Service public class ForumService { - public List projectionsToForumDTO(List projections) { - ArrayList forums = new ArrayList<>(); + + 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 ForumDTO(projection.getForum(), projection.getRating())); + forums.add(new ForumDataDTO(forumMapper.forumToForumDTO(projection.getForum()), projection.getRating())); } return forums; } - public ForumDTO projectionToForumDTO(ForumProjection projection) { - ForumDTO forum = new ForumDTO(); - forum.setForum(projection.getForum()); + 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<>(); + + public List entitiesToForumDTO(List forums) { + ArrayList forumsDTO = new ArrayList<>(); for (var forum : forums) { - forumsDTO.add(new ForumDTO(forum, null)); + forumsDTO.add(new ForumDataDTO(forumMapper.forumToForumDTO(forum), null)); } return forumsDTO; } - - public ForumDTO entityToForumDTO(Forum forum){ - return new ForumDTO(forum, null); + + public ForumDataDTO entityToForumDTO(Forum forum) { + return new ForumDataDTO(forumMapper.forumToForumDTO(forum), null); } } 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); +} From 7dba0ae4f33685098784427c8ea563e2d1e0c373 Mon Sep 17 00:00:00 2001 From: "i.i.artamonov" Date: Wed, 11 May 2022 15:59:56 +0400 Subject: [PATCH 117/141] Change User entity to User DTO --- .../petproject/boardgamefun/dto/ForumMessageDTO.java | 3 +-- .../boardgamefun/service/ForumMessageService.java | 12 ++++++++++-- 2 files changed, 11 insertions(+), 4 deletions(-) diff --git a/src/main/java/com/petproject/boardgamefun/dto/ForumMessageDTO.java b/src/main/java/com/petproject/boardgamefun/dto/ForumMessageDTO.java index 1e63d69..bdc40dc 100644 --- a/src/main/java/com/petproject/boardgamefun/dto/ForumMessageDTO.java +++ b/src/main/java/com/petproject/boardgamefun/dto/ForumMessageDTO.java @@ -1,6 +1,5 @@ package com.petproject.boardgamefun.dto; -import com.petproject.boardgamefun.model.User; import lombok.AllArgsConstructor; import lombok.Data; @@ -12,5 +11,5 @@ public class ForumMessageDTO { private Integer id; private String message; private OffsetDateTime messageTime; - private User user; + private UserDTO user; } diff --git a/src/main/java/com/petproject/boardgamefun/service/ForumMessageService.java b/src/main/java/com/petproject/boardgamefun/service/ForumMessageService.java index 815b671..5faed75 100644 --- a/src/main/java/com/petproject/boardgamefun/service/ForumMessageService.java +++ b/src/main/java/com/petproject/boardgamefun/service/ForumMessageService.java @@ -2,6 +2,7 @@ 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; @@ -9,15 +10,22 @@ @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(), forumMessage.getUser()); + 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(), forumMessage.getUser())); + forumMessagesDTO.add(new ForumMessageDTO(forumMessage.getId(), forumMessage.getComment(), forumMessage.getTime(), userMapper.userToUserDTO(forumMessage.getUser()))); } return forumMessagesDTO; } From 9a6e225f9e88390f9fa1c4e5118c6237933d9e6d Mon Sep 17 00:00:00 2001 From: "i.i.artamonov" Date: Wed, 11 May 2022 16:07:40 +0400 Subject: [PATCH 118/141] Change DiaryCommentDTO Change User entity to DTO. --- .../petproject/boardgamefun/dto/DiaryCommentDTO.java | 3 +-- .../boardgamefun/service/DiaryCommentService.java | 11 +++++++++-- 2 files changed, 10 insertions(+), 4 deletions(-) diff --git a/src/main/java/com/petproject/boardgamefun/dto/DiaryCommentDTO.java b/src/main/java/com/petproject/boardgamefun/dto/DiaryCommentDTO.java index 4450219..fce3963 100644 --- a/src/main/java/com/petproject/boardgamefun/dto/DiaryCommentDTO.java +++ b/src/main/java/com/petproject/boardgamefun/dto/DiaryCommentDTO.java @@ -1,6 +1,5 @@ package com.petproject.boardgamefun.dto; -import com.petproject.boardgamefun.model.User; import lombok.AllArgsConstructor; import lombok.Data; @@ -12,5 +11,5 @@ public class DiaryCommentDTO { private Integer id; private String comment; private OffsetDateTime time; - private User user; + private UserDTO user; } diff --git a/src/main/java/com/petproject/boardgamefun/service/DiaryCommentService.java b/src/main/java/com/petproject/boardgamefun/service/DiaryCommentService.java index b29febb..360adcb 100644 --- a/src/main/java/com/petproject/boardgamefun/service/DiaryCommentService.java +++ b/src/main/java/com/petproject/boardgamefun/service/DiaryCommentService.java @@ -2,6 +2,7 @@ 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; @@ -10,15 +11,21 @@ @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(), diaryComment.getUser()); + 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(), diaryComment.getUser())); + diaryCommentsDTO.add(new DiaryCommentDTO(diaryComment.getId(), diaryComment.getComment(), diaryComment.getCommentTime(), userMapper.userToUserDTO(diaryComment.getUser()))); } return diaryCommentsDTO; } From b9b64bb2d2f2fc9fb1b3d383d54f08903d41b8b3 Mon Sep 17 00:00:00 2001 From: "i.i.artamonov" Date: Thu, 12 May 2022 14:55:53 +0400 Subject: [PATCH 119/141] Added GameControllerTests class. Added test for getGames Add GamePOJO for GameProjection. --- .../boardgamefun/GameControllerTests.java | 169 ++++++++++++++++++ .../boardgamefun/model/GamePOJO.java | 22 +++ 2 files changed, 191 insertions(+) create mode 100644 src/test/java/com/petproject/boardgamefun/GameControllerTests.java create mode 100644 src/test/java/com/petproject/boardgamefun/model/GamePOJO.java diff --git a/src/test/java/com/petproject/boardgamefun/GameControllerTests.java b/src/test/java/com/petproject/boardgamefun/GameControllerTests.java new file mode 100644 index 0000000..4248059 --- /dev/null +++ b/src/test/java/com/petproject/boardgamefun/GameControllerTests.java @@ -0,0 +1,169 @@ +package com.petproject.boardgamefun; + +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.dto.DesignerDTO; +import com.petproject.boardgamefun.dto.GameDataDTO; +import com.petproject.boardgamefun.dto.projection.GameProjection; +import com.petproject.boardgamefun.model.Designer; +import com.petproject.boardgamefun.model.Game; +import com.petproject.boardgamefun.model.GamePOJO; +import com.petproject.boardgamefun.repository.GameRepository; +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.test.web.servlet.MockMvc; +import org.springframework.test.web.servlet.request.MockMvcRequestBuilders; + +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; + + private final String Gateway = "/games"; + + ObjectMapper objectMapper; + + @Autowired + GameMapper gameMapper; + + @MockBean + private GameService gameService; + + @MockBean + private GameRepository gameRepository; + + + private Game game; + private List games; + private GameProjection gamePOJO; + private List gamePOJOList; + private GameDataDTO gameDataDTO; + private List gamesDataDTO; + private Designer designer; + private DesignerDTO designerDTO; + + + @BeforeAll + public void setup() { + + objectMapper = new ObjectMapper(); + objectMapper.findAndRegisterModules(); + + 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); + + gamePOJO = new GamePOJO(game, 8.0); + gamePOJOList = new ArrayList<>(); + gamePOJOList.add(gamePOJO); + + 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); + + + } + + @Test + public void getGamesShouldReturnOk() throws Exception { + + when(gameRepository.findGames()).thenReturn(gamePOJOList); + when(gameService.projectionsToGameDTO(gamePOJOList)).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(gamePOJOList); + + 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); + + } + +} 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; + } +} From 5a47e9432bcb135a7f3cd6cbe4328db2a21cc72e Mon Sep 17 00:00:00 2001 From: "i.i.artamonov" Date: Thu, 12 May 2022 15:55:44 +0400 Subject: [PATCH 120/141] Added tests to getGameByCriteria Add DesignerPOJO for projection. Add null checks for Game service and method. --- .../controller/GameController.java | 7 +- .../boardgamefun/service/GameService.java | 2 + .../boardgamefun/GameControllerTests.java | 64 +++++++++++++++---- .../boardgamefun/model/DesignerPOJO.java | 15 +++++ 4 files changed, 74 insertions(+), 14 deletions(-) create mode 100644 src/test/java/com/petproject/boardgamefun/model/DesignerPOJO.java diff --git a/src/main/java/com/petproject/boardgamefun/controller/GameController.java b/src/main/java/com/petproject/boardgamefun/controller/GameController.java index cdab51c..9782a5d 100644 --- a/src/main/java/com/petproject/boardgamefun/controller/GameController.java +++ b/src/main/java/com/petproject/boardgamefun/controller/GameController.java @@ -53,8 +53,11 @@ ResponseEntity> getGames() { @Transactional @GetMapping("/get-game/{id}") public ResponseEntity getGameByCriteria(@PathVariable Integer id) { - var gameDTO = gameService.projectionsToGameDTO(gameRepository.findGame(id), designerRepository.findDesignersUsingGame(id)); - return new ResponseEntity<>(gameDTO, HttpStatus.OK); + var gameDataDTO = gameService.projectionsToGameDTO(gameRepository.findGame(id), designerRepository.findDesignersUsingGame(id)); + if (gameDataDTO == null) { + return new ResponseEntity<>(null, HttpStatus.NOT_FOUND); + } + return new ResponseEntity<>(gameDataDTO, HttpStatus.OK); } @Transactional diff --git a/src/main/java/com/petproject/boardgamefun/service/GameService.java b/src/main/java/com/petproject/boardgamefun/service/GameService.java index d24339d..a0abceb 100644 --- a/src/main/java/com/petproject/boardgamefun/service/GameService.java +++ b/src/main/java/com/petproject/boardgamefun/service/GameService.java @@ -23,6 +23,8 @@ public GameService(GameMapper gameMapper) { } 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())); diff --git a/src/test/java/com/petproject/boardgamefun/GameControllerTests.java b/src/test/java/com/petproject/boardgamefun/GameControllerTests.java index 4248059..2c20c10 100644 --- a/src/test/java/com/petproject/boardgamefun/GameControllerTests.java +++ b/src/test/java/com/petproject/boardgamefun/GameControllerTests.java @@ -7,10 +7,13 @@ import com.fasterxml.jackson.databind.ObjectMapper; import com.petproject.boardgamefun.dto.DesignerDTO; import com.petproject.boardgamefun.dto.GameDataDTO; +import com.petproject.boardgamefun.dto.projection.DesignersProjection; import com.petproject.boardgamefun.dto.projection.GameProjection; import com.petproject.boardgamefun.model.Designer; +import com.petproject.boardgamefun.model.DesignerPOJO; import com.petproject.boardgamefun.model.Game; import com.petproject.boardgamefun.model.GamePOJO; +import com.petproject.boardgamefun.repository.DesignerRepository; import com.petproject.boardgamefun.repository.GameRepository; import com.petproject.boardgamefun.service.GameService; import com.petproject.boardgamefun.service.mappers.GameMapper; @@ -32,10 +35,7 @@ @ExtendWith(MockitoExtension.class) -@SpringBootTest( - webEnvironment = SpringBootTest.WebEnvironment.MOCK, - classes = SpringSecurityWebTestConfig.class -) +@SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.MOCK, classes = SpringSecurityWebTestConfig.class) @AutoConfigureMockMvc @TestMethodOrder(MethodOrderer.OrderAnnotation.class) @TestInstance(TestInstance.Lifecycle.PER_CLASS) @@ -57,14 +57,20 @@ public class GameControllerTests { @MockBean private GameRepository gameRepository; + @MockBean + private DesignerRepository designerRepository; + private Game game; private List games; - private GameProjection gamePOJO; - private List gamePOJOList; + private GameProjection gameProjection; + private List gameProjectionList; private GameDataDTO gameDataDTO; private List gamesDataDTO; private Designer designer; + private List designersProjectionList; + private DesignersProjection designersProjection; + private DesignerDTO designerDTO; @@ -105,9 +111,9 @@ public void setup() { games.add(game); games.add(game1); - gamePOJO = new GamePOJO(game, 8.0); - gamePOJOList = new ArrayList<>(); - gamePOJOList.add(gamePOJO); + gameProjection = new GamePOJO(game, 8.0); + gameProjectionList = new ArrayList<>(); + gameProjectionList.add(gameProjection); designer = new Designer(); designer.setId(1); @@ -121,6 +127,10 @@ public void setup() { 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); @@ -135,15 +145,15 @@ public void setup() { @Test public void getGamesShouldReturnOk() throws Exception { - when(gameRepository.findGames()).thenReturn(gamePOJOList); - when(gameService.projectionsToGameDTO(gamePOJOList)).thenReturn(gamesDataDTO); + 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(gamePOJOList); + verify(gameService).projectionsToGameDTO(gameProjectionList); Assertions.assertEquals(res.length, 2); @@ -166,4 +176,34 @@ public void getGamesShouldReturnOk_BlankList() throws Exception { } + @Test + public void getGameByCriteriaShouldReturnOk() throws Exception { + when(gameRepository.findGame(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).findGame(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.findGame(-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).findGame(-1); + verify(designerRepository).findDesignersUsingGame(-1); + verify(gameService).projectionsToGameDTO(null, 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; + } +} From 674bbbbbd8966829d7e1da1dc9891fc95ad45874 Mon Sep 17 00:00:00 2001 From: "i.i.artamonov" Date: Fri, 13 May 2022 09:09:17 +0400 Subject: [PATCH 121/141] Added tests to getGamesByTitle method Added GameTitlePOJO for GamesFilterByTitleProjection. --- .../boardgamefun/GameControllerTests.java | 45 ++++++++++++++++--- .../boardgamefun/model/GameTitlePOJO.java | 21 +++++++++ 2 files changed, 61 insertions(+), 5 deletions(-) create mode 100644 src/test/java/com/petproject/boardgamefun/model/GameTitlePOJO.java diff --git a/src/test/java/com/petproject/boardgamefun/GameControllerTests.java b/src/test/java/com/petproject/boardgamefun/GameControllerTests.java index 2c20c10..f63d04d 100644 --- a/src/test/java/com/petproject/boardgamefun/GameControllerTests.java +++ b/src/test/java/com/petproject/boardgamefun/GameControllerTests.java @@ -6,13 +6,12 @@ import com.fasterxml.jackson.databind.ObjectMapper; import com.petproject.boardgamefun.dto.DesignerDTO; +import com.petproject.boardgamefun.dto.FilterGamesDTO; import com.petproject.boardgamefun.dto.GameDataDTO; import com.petproject.boardgamefun.dto.projection.DesignersProjection; import com.petproject.boardgamefun.dto.projection.GameProjection; -import com.petproject.boardgamefun.model.Designer; -import com.petproject.boardgamefun.model.DesignerPOJO; -import com.petproject.boardgamefun.model.Game; -import com.petproject.boardgamefun.model.GamePOJO; +import com.petproject.boardgamefun.dto.projection.GamesFilterByTitleProjection; +import com.petproject.boardgamefun.model.*; import com.petproject.boardgamefun.repository.DesignerRepository; import com.petproject.boardgamefun.repository.GameRepository; import com.petproject.boardgamefun.service.GameService; @@ -70,8 +69,9 @@ public class GameControllerTests { private Designer designer; private List designersProjectionList; private DesignersProjection designersProjection; - private DesignerDTO designerDTO; + private List gamesFilterByTitleProjectionList; + List filterGamesDTOList; @BeforeAll @@ -139,6 +139,13 @@ public void setup() { 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")); } @@ -206,4 +213,32 @@ public void getGameByCriteriaShouldReturnNotFound() throws Exception { 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); + } + } 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; + } +} From c1ad8e697522ad4abbb56dca47c08c185071949c Mon Sep 17 00:00:00 2001 From: "i.i.artamonov" Date: Fri, 13 May 2022 10:37:38 +0400 Subject: [PATCH 122/141] Added tests to addGame method Added null checks for model fields in addGame method --- .../controller/GameController.java | 6 ++ .../boardgamefun/GameControllerTests.java | 57 ++++++++++++++++++- 2 files changed, 61 insertions(+), 2 deletions(-) diff --git a/src/main/java/com/petproject/boardgamefun/controller/GameController.java b/src/main/java/com/petproject/boardgamefun/controller/GameController.java index 9782a5d..cece6d7 100644 --- a/src/main/java/com/petproject/boardgamefun/controller/GameController.java +++ b/src/main/java/com/petproject/boardgamefun/controller/GameController.java @@ -72,6 +72,12 @@ public ResponseEntity> getGamesByTitle(@PathVariable String @PostMapping("/add") @PreAuthorize("hasRole('MODERATOR') or hasRole('ADMIN')") public ResponseEntity addGame(@RequestBody Game newGame) { + if (newGame.getId() != null) { + return new ResponseEntity<>(null, HttpStatus.BAD_REQUEST); + } + if (newGame.getTitle() == null || newGame.getAnnotation() == null || newGame.getDescription() == null || newGame.getTimeToPlayMax() == null || newGame.getTimeToPlayMin() == null || newGame.getYearOfRelease() == null || newGame.getPlayersMin() == null || newGame.getPlayersMax() == null) { + return new ResponseEntity<>(null, HttpStatus.BAD_REQUEST); + } gameRepository.save(newGame); var game = gameService.entityToGameDTO(newGame); diff --git a/src/test/java/com/petproject/boardgamefun/GameControllerTests.java b/src/test/java/com/petproject/boardgamefun/GameControllerTests.java index f63d04d..5200991 100644 --- a/src/test/java/com/petproject/boardgamefun/GameControllerTests.java +++ b/src/test/java/com/petproject/boardgamefun/GameControllerTests.java @@ -4,6 +4,7 @@ import static org.springframework.test.web.servlet.result.MockMvcResultHandlers.print; import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status; +import com.fasterxml.jackson.core.JsonProcessingException; import com.fasterxml.jackson.databind.ObjectMapper; import com.petproject.boardgamefun.dto.DesignerDTO; import com.petproject.boardgamefun.dto.FilterGamesDTO; @@ -23,6 +24,8 @@ 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; @@ -79,6 +82,7 @@ public void setup() { objectMapper = new ObjectMapper(); objectMapper.findAndRegisterModules(); + String instantExpected = "2014-12-22T10:15:30Z"; game = new Game(); game.setId(1); @@ -91,7 +95,7 @@ public void setup() { game.setPlayersMax(5); game.setTimeToPlayMin(120); game.setTimeToPlayMax(360); - game.setYearOfRelease(OffsetDateTime.now()); + game.setYearOfRelease(OffsetDateTime.parse(instantExpected)); Game game1 = new Game(); @@ -105,7 +109,7 @@ public void setup() { game1.setPlayersMax(4); game1.setTimeToPlayMin(30); game1.setTimeToPlayMax(120); - game1.setYearOfRelease(OffsetDateTime.now()); + game1.setYearOfRelease(OffsetDateTime.parse(instantExpected)); games = new ArrayList<>(); games.add(game); @@ -241,4 +245,53 @@ public void getGamesByTitleShouldReturnOk_BlankArray() throws Exception { 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()); + } + } From a2d297ae2d050e43d58e3e54cc5579575eaf0c49 Mon Sep 17 00:00:00 2001 From: "i.i.artamonov" Date: Fri, 13 May 2022 14:49:53 +0400 Subject: [PATCH 123/141] Added executable jar into packaging --- pom.xml | 8 ++------ 1 file changed, 2 insertions(+), 6 deletions(-) diff --git a/pom.xml b/pom.xml index 7b283d0..dee269a 100644 --- a/pom.xml +++ b/pom.xml @@ -10,6 +10,7 @@ com.petproject Boardgamefun + jar 0.0.1-SNAPSHOT Boardgamefun Boardgamefun @@ -142,12 +143,7 @@ org.springframework.boot spring-boot-maven-plugin - - - org.projectlombok - lombok - - + true From 2f907569a34393341d734bf44d50ea8b8ba90bab Mon Sep 17 00:00:00 2001 From: "i.i.artamonov" Date: Mon, 16 May 2022 09:15:22 +0400 Subject: [PATCH 124/141] Added tests to uploadImage Added null checks. Change name of method in repositoru for more understanding --- .../controller/GameController.java | 10 +- .../repository/GameRepository.java | 2 +- .../boardgamefun/GameControllerTests.java | 91 +++++++++++++++++-- 3 files changed, 91 insertions(+), 12 deletions(-) diff --git a/src/main/java/com/petproject/boardgamefun/controller/GameController.java b/src/main/java/com/petproject/boardgamefun/controller/GameController.java index cece6d7..47c889c 100644 --- a/src/main/java/com/petproject/boardgamefun/controller/GameController.java +++ b/src/main/java/com/petproject/boardgamefun/controller/GameController.java @@ -53,7 +53,7 @@ ResponseEntity> getGames() { @Transactional @GetMapping("/get-game/{id}") public ResponseEntity getGameByCriteria(@PathVariable Integer id) { - var gameDataDTO = gameService.projectionsToGameDTO(gameRepository.findGame(id), designerRepository.findDesignersUsingGame(id)); + var gameDataDTO = gameService.projectionsToGameDTO(gameRepository.findGameWithRating(id), designerRepository.findDesignersUsingGame(id)); if (gameDataDTO == null) { return new ResponseEntity<>(null, HttpStatus.NOT_FOUND); } @@ -89,9 +89,11 @@ public ResponseEntity addGame(@RequestBody Game newGame) { @PreAuthorize("hasRole('USER') or hasRole('MODERATOR') or hasRole('ADMIN')") public ResponseEntity uploadImage(@PathVariable Integer gameId, @RequestParam("picture") MultipartFile file) throws IOException { var game = gameRepository.findGameById(gameId); + if (game == null) + return new ResponseEntity<>(null, HttpStatus.NOT_FOUND); game.setPicture(file.getBytes()); gameRepository.save(game); - var gameDTO = gameService.projectionsToGameDTO(gameRepository.findGame(gameId), designerRepository.findDesignersUsingGame(gameId)); + var gameDTO = gameService.projectionsToGameDTO(gameRepository.findGameWithRating(gameId), designerRepository.findDesignersUsingGame(gameId)); return new ResponseEntity<>(gameDTO, HttpStatus.OK); } @@ -211,7 +213,7 @@ public ResponseEntity addDesignerToGame(@PathVariable Integer gameI gameByDesignerRepository.save(gameByDesigner); - var gameDTO = gameService.projectionsToGameDTO(gameRepository.findGame(gameId), + var gameDTO = gameService.projectionsToGameDTO(gameRepository.findGameWithRating(gameId), designerRepository.findDesignersUsingGame(gameId)); return new ResponseEntity<>(gameDTO, HttpStatus.OK); @@ -224,7 +226,7 @@ public ResponseEntity deleteDesignerFromGame(@PathVariable Integer gameByDesignerRepository.deleteById(gameByDesignerId); - var gameDTO = gameService.projectionsToGameDTO(gameRepository.findGame(gameId), + var gameDTO = gameService.projectionsToGameDTO(gameRepository.findGameWithRating(gameId), designerRepository.findDesignersUsingGame(gameId)); return new ResponseEntity<>(gameDTO, HttpStatus.OK); diff --git a/src/main/java/com/petproject/boardgamefun/repository/GameRepository.java b/src/main/java/com/petproject/boardgamefun/repository/GameRepository.java index c7bb9e0..68133f9 100644 --- a/src/main/java/com/petproject/boardgamefun/repository/GameRepository.java +++ b/src/main/java/com/petproject/boardgamefun/repository/GameRepository.java @@ -17,7 +17,7 @@ public interface GameRepository extends JpaRepository { "left join RatingGameByUser rgbu on rgbu.game.id = g.id " + "where g.id = :id " + "group by g") - GameProjection findGame(Integer id); + GameProjection findGameWithRating(Integer id); @Query("select g.title as title, g.id as id from Game g " + "where lower(g.title) like :title%") diff --git a/src/test/java/com/petproject/boardgamefun/GameControllerTests.java b/src/test/java/com/petproject/boardgamefun/GameControllerTests.java index 5200991..cd68218 100644 --- a/src/test/java/com/petproject/boardgamefun/GameControllerTests.java +++ b/src/test/java/com/petproject/boardgamefun/GameControllerTests.java @@ -4,7 +4,6 @@ import static org.springframework.test.web.servlet.result.MockMvcResultHandlers.print; import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status; -import com.fasterxml.jackson.core.JsonProcessingException; import com.fasterxml.jackson.databind.ObjectMapper; import com.petproject.boardgamefun.dto.DesignerDTO; import com.petproject.boardgamefun.dto.FilterGamesDTO; @@ -25,9 +24,13 @@ 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.*; @@ -46,6 +49,9 @@ public class GameControllerTests { @Autowired private MockMvc mockMvc; + @Autowired + private WebApplicationContext webApplicationContext; + private final String Gateway = "/games"; ObjectMapper objectMapper; @@ -74,14 +80,21 @@ public class GameControllerTests { private DesignersProjection designersProjection; private DesignerDTO designerDTO; private List gamesFilterByTitleProjectionList; - List filterGamesDTOList; - + private List filterGamesDTOList; + private MockMultipartFile multipartFile; @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(); @@ -189,7 +202,7 @@ public void getGamesShouldReturnOk_BlankList() throws Exception { @Test public void getGameByCriteriaShouldReturnOk() throws Exception { - when(gameRepository.findGame(1)).thenReturn(gameProjection); + when(gameRepository.findGameWithRating(1)).thenReturn(gameProjection); when(designerRepository.findDesignersUsingGame(1)).thenReturn(designersProjectionList); when(gameService.projectionsToGameDTO(gameProjection, designersProjectionList)).thenReturn(gameDataDTO); @@ -197,7 +210,7 @@ public void getGameByCriteriaShouldReturnOk() throws Exception { var res = objectMapper.readValue(mvcRes.getResponse().getContentAsByteArray(), GameDataDTO.class); - verify(gameRepository).findGame(1); + verify(gameRepository).findGameWithRating(1); verify(designerRepository).findDesignersUsingGame(1); verify(gameService).projectionsToGameDTO(gameProjection, designersProjectionList); @@ -206,13 +219,13 @@ public void getGameByCriteriaShouldReturnOk() throws Exception { @Test public void getGameByCriteriaShouldReturnNotFound() throws Exception { - when(gameRepository.findGame(-1)).thenReturn(null); + 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).findGame(-1); + verify(gameRepository).findGameWithRating(-1); verify(designerRepository).findDesignersUsingGame(-1); verify(gameService).projectionsToGameDTO(null, null); } @@ -294,4 +307,68 @@ public void addGameShouldReturnUnauthorized() throws Exception { .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()); + } + } From 5b0e0503c50170490691e3f9ec425c4916805b33 Mon Sep 17 00:00:00 2001 From: "i.i.artamonov" Date: Mon, 16 May 2022 09:44:13 +0400 Subject: [PATCH 125/141] Added tests to updateGame Extract code to method in controller to avoid duplicates. --- .../controller/GameController.java | 17 ++++--- .../boardgamefun/GameControllerTests.java | 46 +++++++++++++++++++ 2 files changed, 56 insertions(+), 7 deletions(-) diff --git a/src/main/java/com/petproject/boardgamefun/controller/GameController.java b/src/main/java/com/petproject/boardgamefun/controller/GameController.java index 47c889c..9636c45 100644 --- a/src/main/java/com/petproject/boardgamefun/controller/GameController.java +++ b/src/main/java/com/petproject/boardgamefun/controller/GameController.java @@ -9,6 +9,7 @@ import com.petproject.boardgamefun.model.SameGame; import com.petproject.boardgamefun.repository.*; 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; @@ -75,13 +76,7 @@ public ResponseEntity addGame(@RequestBody Game newGame) { if (newGame.getId() != null) { return new ResponseEntity<>(null, HttpStatus.BAD_REQUEST); } - if (newGame.getTitle() == null || newGame.getAnnotation() == null || newGame.getDescription() == null || newGame.getTimeToPlayMax() == null || newGame.getTimeToPlayMin() == null || newGame.getYearOfRelease() == null || newGame.getPlayersMin() == null || newGame.getPlayersMax() == null) { - return new ResponseEntity<>(null, HttpStatus.BAD_REQUEST); - } - gameRepository.save(newGame); - var game = gameService.entityToGameDTO(newGame); - - return new ResponseEntity<>(game, HttpStatus.OK); + return getGameDataDTOResponseEntity(newGame); } @Transactional @@ -101,6 +96,14 @@ public ResponseEntity uploadImage(@PathVariable Integer gameId, @Re @PutMapping("/update") @PreAuthorize("hasRole('MODERATOR') or hasRole('ADMIN')") public ResponseEntity updateGame(@RequestBody Game updatedGame) { + return getGameDataDTOResponseEntity(updatedGame); + } + + @NotNull + private ResponseEntity getGameDataDTOResponseEntity(@RequestBody 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) { + return new ResponseEntity<>(null, HttpStatus.BAD_REQUEST); + } gameRepository.save(updatedGame); var game = gameService.entityToGameDTO(updatedGame); return new ResponseEntity<>(game, HttpStatus.OK); diff --git a/src/test/java/com/petproject/boardgamefun/GameControllerTests.java b/src/test/java/com/petproject/boardgamefun/GameControllerTests.java index cd68218..ffcd2b9 100644 --- a/src/test/java/com/petproject/boardgamefun/GameControllerTests.java +++ b/src/test/java/com/petproject/boardgamefun/GameControllerTests.java @@ -4,6 +4,7 @@ import static org.springframework.test.web.servlet.result.MockMvcResultHandlers.print; import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status; +import com.fasterxml.jackson.core.JsonProcessingException; import com.fasterxml.jackson.databind.ObjectMapper; import com.petproject.boardgamefun.dto.DesignerDTO; import com.petproject.boardgamefun.dto.FilterGamesDTO; @@ -371,4 +372,49 @@ public void uploadImageShouldReturnUnauthorized() throws Exception { .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()); + + } + } From c2709f89477eef7055dece3af0227e86da9c8a1f Mon Sep 17 00:00:00 2001 From: "i.i.artamonov" Date: Mon, 16 May 2022 15:35:43 +0400 Subject: [PATCH 126/141] Added tests to removeGameFromSite method Added null checks to controller method --- .../controller/GameController.java | 2 + .../boardgamefun/GameControllerTests.java | 39 +++++++++++++++++++ 2 files changed, 41 insertions(+) diff --git a/src/main/java/com/petproject/boardgamefun/controller/GameController.java b/src/main/java/com/petproject/boardgamefun/controller/GameController.java index 9636c45..0b2df6e 100644 --- a/src/main/java/com/petproject/boardgamefun/controller/GameController.java +++ b/src/main/java/com/petproject/boardgamefun/controller/GameController.java @@ -113,6 +113,8 @@ private ResponseEntity getGameDataDTOResponseEntity(@RequestBody Ga @DeleteMapping("/remove") @PreAuthorize("hasRole('MODERATOR') or hasRole('ADMIN')") public ResponseEntity removeGameFromSite(@RequestBody Game deleteGame) { + if (deleteGame.getId() == null) + return new ResponseEntity<>(null, HttpStatus.NOT_FOUND); gameRepository.delete(deleteGame); return new ResponseEntity<>(deleteGame.getTitle() + " удалена из базы данных", HttpStatus.OK); diff --git a/src/test/java/com/petproject/boardgamefun/GameControllerTests.java b/src/test/java/com/petproject/boardgamefun/GameControllerTests.java index ffcd2b9..477752f 100644 --- a/src/test/java/com/petproject/boardgamefun/GameControllerTests.java +++ b/src/test/java/com/petproject/boardgamefun/GameControllerTests.java @@ -417,4 +417,43 @@ public void updateGameShouldReturnIsUnauthorized() throws Exception { } + @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()); + } + } From 731f505060fed7145f9581110388b144af49d051 Mon Sep 17 00:00:00 2001 From: "i.i.artamonov" Date: Tue, 17 May 2022 10:09:40 +0400 Subject: [PATCH 127/141] Added tests to getExpansion method Added null checks to method in controller --- .../controller/GameController.java | 2 ++ .../boardgamefun/GameControllerTests.java | 34 ++++++++++++++++++- 2 files changed, 35 insertions(+), 1 deletion(-) diff --git a/src/main/java/com/petproject/boardgamefun/controller/GameController.java b/src/main/java/com/petproject/boardgamefun/controller/GameController.java index 0b2df6e..22572dc 100644 --- a/src/main/java/com/petproject/boardgamefun/controller/GameController.java +++ b/src/main/java/com/petproject/boardgamefun/controller/GameController.java @@ -123,6 +123,8 @@ public ResponseEntity removeGameFromSite(@RequestBody Game deleteGame) { @Transactional @GetMapping("/expansions/{gameId}") public ResponseEntity> getExpansions(@PathVariable Integer gameId) { + if (gameId == null) + return new ResponseEntity<>(null, HttpStatus.NOT_FOUND); var gamesExpansions = gameService.entitiesToGameDTO(gameRepository.getExpansions(gameId)); return new ResponseEntity<>(gamesExpansions, HttpStatus.OK); diff --git a/src/test/java/com/petproject/boardgamefun/GameControllerTests.java b/src/test/java/com/petproject/boardgamefun/GameControllerTests.java index 477752f..f24e43f 100644 --- a/src/test/java/com/petproject/boardgamefun/GameControllerTests.java +++ b/src/test/java/com/petproject/boardgamefun/GameControllerTests.java @@ -4,7 +4,6 @@ import static org.springframework.test.web.servlet.result.MockMvcResultHandlers.print; import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status; -import com.fasterxml.jackson.core.JsonProcessingException; import com.fasterxml.jackson.databind.ObjectMapper; import com.petproject.boardgamefun.dto.DesignerDTO; import com.petproject.boardgamefun.dto.FilterGamesDTO; @@ -456,4 +455,37 @@ public void removeGameFromSiteShouldReturnIsUnauthorized() throws Exception { .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()); + } + } From 29aefe20c9d987ef1cf7687584cd15ae16b5e65f Mon Sep 17 00:00:00 2001 From: "i.i.artamonov" Date: Tue, 17 May 2022 10:57:35 +0400 Subject: [PATCH 128/141] Added tests to addExpansion method Added null checks to method --- .../controller/GameController.java | 4 + .../boardgamefun/GameControllerTests.java | 98 ++++++++++++++++--- 2 files changed, 89 insertions(+), 13 deletions(-) diff --git a/src/main/java/com/petproject/boardgamefun/controller/GameController.java b/src/main/java/com/petproject/boardgamefun/controller/GameController.java index 22572dc..27b14ae 100644 --- a/src/main/java/com/petproject/boardgamefun/controller/GameController.java +++ b/src/main/java/com/petproject/boardgamefun/controller/GameController.java @@ -137,6 +137,10 @@ public ResponseEntity> addExpansion(@PathVariable Integer pare var parentGame = gameRepository.findGameById(parentGameId); var daughterGame = gameRepository.findGameById(daughterGameId); + if (parentGame == null || daughterGame == null) { + return new ResponseEntity<>(null, HttpStatus.BAD_REQUEST); + } + var expansion = new Expansion(); expansion.setParentGame(parentGame); expansion.setDaughterGame(daughterGame); diff --git a/src/test/java/com/petproject/boardgamefun/GameControllerTests.java b/src/test/java/com/petproject/boardgamefun/GameControllerTests.java index f24e43f..ada92be 100644 --- a/src/test/java/com/petproject/boardgamefun/GameControllerTests.java +++ b/src/test/java/com/petproject/boardgamefun/GameControllerTests.java @@ -13,6 +13,7 @@ import com.petproject.boardgamefun.dto.projection.GamesFilterByTitleProjection; import com.petproject.boardgamefun.model.*; import com.petproject.boardgamefun.repository.DesignerRepository; +import com.petproject.boardgamefun.repository.ExpansionRepository; import com.petproject.boardgamefun.repository.GameRepository; import com.petproject.boardgamefun.service.GameService; import com.petproject.boardgamefun.service.mappers.GameMapper; @@ -68,8 +69,11 @@ public class GameControllerTests { @MockBean private DesignerRepository designerRepository; + @MockBean + private ExpansionRepository expansionRepository; private Game game; + private Game game2; private List games; private GameProjection gameProjection; private List gameProjectionList; @@ -82,6 +86,7 @@ public class GameControllerTests { private List gamesFilterByTitleProjectionList; private List filterGamesDTOList; private MockMultipartFile multipartFile; + private Expansion expansion; @BeforeAll public void setup() { @@ -111,22 +116,27 @@ public void setup() { game.setYearOfRelease(OffsetDateTime.parse(instantExpected)); - 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.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(game1); + games.add(game2); + + expansion = new Expansion(); + expansion.setId(1); + expansion.setParentGame(game); + expansion.setDaughterGame(game2); gameProjection = new GamePOJO(game, 8.0); gameProjectionList = new ArrayList<>(); @@ -488,4 +498,66 @@ 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(); + } + } From 0f22bf59b1f0f1cef4b28c8504ba4b92fd5e33e6 Mon Sep 17 00:00:00 2001 From: "i.i.artamonov" Date: Wed, 18 May 2022 10:38:04 +0400 Subject: [PATCH 129/141] Added tests to deleteExpansion method Added null checks. Change signature of findExpansion_ByParentGameIdAndDaughterGameId in repository for more understanding --- .../controller/GameController.java | 7 ++-- .../repository/ExpansionRepository.java | 2 +- .../boardgamefun/GameControllerTests.java | 34 +++++++++++++++++++ 3 files changed, 40 insertions(+), 3 deletions(-) diff --git a/src/main/java/com/petproject/boardgamefun/controller/GameController.java b/src/main/java/com/petproject/boardgamefun/controller/GameController.java index 27b14ae..955fac5 100644 --- a/src/main/java/com/petproject/boardgamefun/controller/GameController.java +++ b/src/main/java/com/petproject/boardgamefun/controller/GameController.java @@ -154,8 +154,11 @@ public ResponseEntity> addExpansion(@PathVariable Integer pare @Transactional @DeleteMapping("/delete-expansion/{parentGameId}/{daughterGameId}") @PreAuthorize("hasRole('USER') or hasRole('MODERATOR') or hasRole('ADMIN')") - public ResponseEntity> deleteExpansion(@PathVariable Integer daughterGameId, @PathVariable Integer parentGameId) { - var expansion = expansionRepository.findExpansion_ByDaughterGameIdAndParentGameId(daughterGameId, parentGameId); + public ResponseEntity> deleteExpansion(@PathVariable Integer parentGameId, @PathVariable Integer daughterGameId) { + var expansion = expansionRepository.findExpansion_ByParentGameIdAndDaughterGameId(parentGameId, daughterGameId); + if (expansion == null) { + return new ResponseEntity<>(null, HttpStatus.NOT_FOUND); + } expansionRepository.delete(expansion); var gamesExpansions = gameService.entitiesToGameDTO(gameRepository.getExpansions(parentGameId)); diff --git a/src/main/java/com/petproject/boardgamefun/repository/ExpansionRepository.java b/src/main/java/com/petproject/boardgamefun/repository/ExpansionRepository.java index faed42d..dcf09de 100644 --- a/src/main/java/com/petproject/boardgamefun/repository/ExpansionRepository.java +++ b/src/main/java/com/petproject/boardgamefun/repository/ExpansionRepository.java @@ -4,5 +4,5 @@ import org.springframework.data.jpa.repository.JpaRepository; public interface ExpansionRepository extends JpaRepository { - Expansion findExpansion_ByDaughterGameIdAndParentGameId(Integer daughterId, Integer parentGameId); + Expansion findExpansion_ByParentGameIdAndDaughterGameId(Integer parentGameId, Integer daughterId); } \ No newline at end of file diff --git a/src/test/java/com/petproject/boardgamefun/GameControllerTests.java b/src/test/java/com/petproject/boardgamefun/GameControllerTests.java index ada92be..fbe1109 100644 --- a/src/test/java/com/petproject/boardgamefun/GameControllerTests.java +++ b/src/test/java/com/petproject/boardgamefun/GameControllerTests.java @@ -560,4 +560,38 @@ 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()); + } + } From ca8f79898646b1e31d792c56bba46191938ec95a Mon Sep 17 00:00:00 2001 From: "i.i.artamonov" Date: Wed, 18 May 2022 10:55:05 +0400 Subject: [PATCH 130/141] Added tests to getSimilarGames method Added null checks --- .../controller/GameController.java | 2 ++ .../boardgamefun/GameControllerTests.java | 34 +++++++++++++++++++ 2 files changed, 36 insertions(+) diff --git a/src/main/java/com/petproject/boardgamefun/controller/GameController.java b/src/main/java/com/petproject/boardgamefun/controller/GameController.java index 955fac5..55c2b5d 100644 --- a/src/main/java/com/petproject/boardgamefun/controller/GameController.java +++ b/src/main/java/com/petproject/boardgamefun/controller/GameController.java @@ -169,6 +169,8 @@ public ResponseEntity> deleteExpansion(@PathVariable Integer p @Transactional @GetMapping("/similar/{gameId}") public ResponseEntity> getSimilarGames(@PathVariable Integer gameId) { + if (gameId == null) + return new ResponseEntity<>(null, HttpStatus.NOT_FOUND); var similarGames = gameService.entitiesToGameDTO(gameRepository.getSimilarGames(gameId)); return new ResponseEntity<>(similarGames, HttpStatus.OK); diff --git a/src/test/java/com/petproject/boardgamefun/GameControllerTests.java b/src/test/java/com/petproject/boardgamefun/GameControllerTests.java index fbe1109..694846b 100644 --- a/src/test/java/com/petproject/boardgamefun/GameControllerTests.java +++ b/src/test/java/com/petproject/boardgamefun/GameControllerTests.java @@ -594,4 +594,38 @@ 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(); + } + } From fd4518f2e7a1b15fe41d28d759082e566912df27 Mon Sep 17 00:00:00 2001 From: "i.i.artamonov" Date: Wed, 18 May 2022 11:11:39 +0400 Subject: [PATCH 131/141] Added tests to addSimilarGame method Added null checks --- .../controller/GameController.java | 3 + .../boardgamefun/GameControllerTests.java | 73 +++++++++++++++++++ 2 files changed, 76 insertions(+) diff --git a/src/main/java/com/petproject/boardgamefun/controller/GameController.java b/src/main/java/com/petproject/boardgamefun/controller/GameController.java index 55c2b5d..6036c39 100644 --- a/src/main/java/com/petproject/boardgamefun/controller/GameController.java +++ b/src/main/java/com/petproject/boardgamefun/controller/GameController.java @@ -183,6 +183,9 @@ public ResponseEntity> addSimilarGame(@PathVariable Integer re var referenceGame = gameRepository.findGameById(referenceGameId); var sourceGame = gameRepository.findGameById(sourceGameId); + if (referenceGame == null || sourceGame == null) + return new ResponseEntity<>(null, HttpStatus.BAD_REQUEST); + var sameGame = new SameGame(); sameGame.setReferenceGame(referenceGame); sameGame.setSourceGame(sourceGame); diff --git a/src/test/java/com/petproject/boardgamefun/GameControllerTests.java b/src/test/java/com/petproject/boardgamefun/GameControllerTests.java index 694846b..b9ff460 100644 --- a/src/test/java/com/petproject/boardgamefun/GameControllerTests.java +++ b/src/test/java/com/petproject/boardgamefun/GameControllerTests.java @@ -15,6 +15,7 @@ import com.petproject.boardgamefun.repository.DesignerRepository; import com.petproject.boardgamefun.repository.ExpansionRepository; import com.petproject.boardgamefun.repository.GameRepository; +import com.petproject.boardgamefun.repository.SameGameRepository; import com.petproject.boardgamefun.service.GameService; import com.petproject.boardgamefun.service.mappers.GameMapper; import org.junit.jupiter.api.*; @@ -72,6 +73,9 @@ public class GameControllerTests { @MockBean private ExpansionRepository expansionRepository; + @MockBean + private SameGameRepository sameGameRepository; + private Game game; private Game game2; private List games; @@ -88,6 +92,8 @@ public class GameControllerTests { private MockMultipartFile multipartFile; private Expansion expansion; + private SameGame sameGame; + @BeforeAll public void setup() { @@ -138,6 +144,11 @@ public void setup() { 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); @@ -628,4 +639,66 @@ 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()).andReturn(); + } } From adb89ebe9f8ab647a3afaaa6e12d7b77dff237ee Mon Sep 17 00:00:00 2001 From: "i.i.artamonov" Date: Thu, 19 May 2022 10:23:11 +0400 Subject: [PATCH 132/141] Added tests to deleteSameGame method Added null checks --- .../controller/GameController.java | 3 + .../boardgamefun/GameControllerTests.java | 59 ++++++++++++++++++- 2 files changed, 61 insertions(+), 1 deletion(-) diff --git a/src/main/java/com/petproject/boardgamefun/controller/GameController.java b/src/main/java/com/petproject/boardgamefun/controller/GameController.java index 6036c39..0c7149d 100644 --- a/src/main/java/com/petproject/boardgamefun/controller/GameController.java +++ b/src/main/java/com/petproject/boardgamefun/controller/GameController.java @@ -201,6 +201,9 @@ public ResponseEntity> addSimilarGame(@PathVariable Integer re @PreAuthorize("hasRole('USER') or hasRole('MODERATOR') or hasRole('ADMIN')") public ResponseEntity> deleteSameGame(@PathVariable Integer referenceGameId, @PathVariable Integer sourceGameId) { var sameGame = sameGameRepository.findSameGame_ByReferenceGameIdAndSourceGameId(referenceGameId, sourceGameId); + if (sameGame == null) { + return new ResponseEntity<>(null, HttpStatus.NOT_FOUND); + } sameGameRepository.delete(sameGame); var sameGames = gameService.entitiesToGameDTO(gameRepository.getSimilarGames(referenceGameId)); diff --git a/src/test/java/com/petproject/boardgamefun/GameControllerTests.java b/src/test/java/com/petproject/boardgamefun/GameControllerTests.java index b9ff460..0e27869 100644 --- a/src/test/java/com/petproject/boardgamefun/GameControllerTests.java +++ b/src/test/java/com/petproject/boardgamefun/GameControllerTests.java @@ -699,6 +699,63 @@ public void addSimilarGameShouldReturnIsBadRequest_BothGame() throws Exception { @Test public void addSimilarGameShouldReturnIsUnauthorized() throws Exception { - this.mockMvc.perform(MockMvcRequestBuilders.post(Gateway + "/add-similar/1/2")).andExpect(status().isUnauthorized()).andReturn(); + 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()); } } From 235b800a6b5f8042266238826c954a76a57aae3b Mon Sep 17 00:00:00 2001 From: "i.i.artamonov" Date: Thu, 19 May 2022 10:47:23 +0400 Subject: [PATCH 133/141] Added tests to getUsersRating method Add pojo object for projection --- .../boardgamefun/GameControllerTests.java | 83 ++++++++++++++++++- .../model/UsersGameRatingProjectionPOJO.java | 20 +++++ 2 files changed, 99 insertions(+), 4 deletions(-) create mode 100644 src/test/java/com/petproject/boardgamefun/model/UsersGameRatingProjectionPOJO.java diff --git a/src/test/java/com/petproject/boardgamefun/GameControllerTests.java b/src/test/java/com/petproject/boardgamefun/GameControllerTests.java index 0e27869..4d14f13 100644 --- a/src/test/java/com/petproject/boardgamefun/GameControllerTests.java +++ b/src/test/java/com/petproject/boardgamefun/GameControllerTests.java @@ -8,14 +8,13 @@ import com.petproject.boardgamefun.dto.DesignerDTO; import com.petproject.boardgamefun.dto.FilterGamesDTO; import com.petproject.boardgamefun.dto.GameDataDTO; +import com.petproject.boardgamefun.dto.RatingGameByUserDTO; import com.petproject.boardgamefun.dto.projection.DesignersProjection; import com.petproject.boardgamefun.dto.projection.GameProjection; import com.petproject.boardgamefun.dto.projection.GamesFilterByTitleProjection; +import com.petproject.boardgamefun.dto.projection.UsersGameRatingProjection; import com.petproject.boardgamefun.model.*; -import com.petproject.boardgamefun.repository.DesignerRepository; -import com.petproject.boardgamefun.repository.ExpansionRepository; -import com.petproject.boardgamefun.repository.GameRepository; -import com.petproject.boardgamefun.repository.SameGameRepository; +import com.petproject.boardgamefun.repository.*; import com.petproject.boardgamefun.service.GameService; import com.petproject.boardgamefun.service.mappers.GameMapper; import org.junit.jupiter.api.*; @@ -76,6 +75,9 @@ public class GameControllerTests { @MockBean private SameGameRepository sameGameRepository; + @MockBean + private UserRepository userRepository; + private Game game; private Game game2; private List games; @@ -91,6 +93,11 @@ public class GameControllerTests { 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; @@ -185,6 +192,43 @@ public void setup() { 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)); } @Test @@ -758,4 +802,35 @@ public void deleteSameGameShouldReturnIsNotFound_BothGame() throws Exception { 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); + } + + + //todo: union beforeAll method? } 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; + } +} From 060f42604bd92b0a5be8bbbc534249c732a476aa Mon Sep 17 00:00:00 2001 From: "i.i.artamonov" Date: Thu, 19 May 2022 11:15:09 +0400 Subject: [PATCH 134/141] Added tests to addDesignerToGame method Added null checks --- .../controller/GameController.java | 4 + .../boardgamefun/GameControllerTests.java | 77 +++++++++++++++++++ 2 files changed, 81 insertions(+) diff --git a/src/main/java/com/petproject/boardgamefun/controller/GameController.java b/src/main/java/com/petproject/boardgamefun/controller/GameController.java index 0c7149d..33cde0a 100644 --- a/src/main/java/com/petproject/boardgamefun/controller/GameController.java +++ b/src/main/java/com/petproject/boardgamefun/controller/GameController.java @@ -229,6 +229,10 @@ public ResponseEntity addDesignerToGame(@PathVariable Integer gameI var game = gameRepository.findGameById(gameId); var designer = designerRepository.findDesignerById(designerId); + if (game == null || designer == null){ + return new ResponseEntity<>(null, HttpStatus.NOT_FOUND); + } + var gameByDesigner = new GameByDesigner(); gameByDesigner.setDesigner(designer); gameByDesigner.setGame(game); diff --git a/src/test/java/com/petproject/boardgamefun/GameControllerTests.java b/src/test/java/com/petproject/boardgamefun/GameControllerTests.java index 4d14f13..31d621e 100644 --- a/src/test/java/com/petproject/boardgamefun/GameControllerTests.java +++ b/src/test/java/com/petproject/boardgamefun/GameControllerTests.java @@ -78,6 +78,9 @@ public class GameControllerTests { @MockBean private UserRepository userRepository; + @MockBean + private GameByDesignerRepository gameByDesignerRepository; + private Game game; private Game game2; private List games; @@ -100,6 +103,7 @@ public class GameControllerTests { private List ratingGameByUserDTOList; private SameGame sameGame; + private GameByDesigner gameByDesigner; @BeforeAll public void setup() { @@ -229,6 +233,11 @@ public void setup() { 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 @@ -831,6 +840,74 @@ public void getUsersRatingShouldReturnIsOk_BlankArray() throws Exception { 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()); + } + //todo: union beforeAll method? } From 4c7cd544817fd03366bd22df70a8558ff9416765 Mon Sep 17 00:00:00 2001 From: "i.i.artamonov" Date: Thu, 19 May 2022 12:01:40 +0400 Subject: [PATCH 135/141] Added tests to deleteDesignerFromGame method --- .../boardgamefun/GameControllerTests.java | 24 +++++++++++++++++++ 1 file changed, 24 insertions(+) diff --git a/src/test/java/com/petproject/boardgamefun/GameControllerTests.java b/src/test/java/com/petproject/boardgamefun/GameControllerTests.java index 31d621e..786465c 100644 --- a/src/test/java/com/petproject/boardgamefun/GameControllerTests.java +++ b/src/test/java/com/petproject/boardgamefun/GameControllerTests.java @@ -908,6 +908,30 @@ 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? } From bee7f4923c4cabd83cb00a5cea1de74177d5eae5 Mon Sep 17 00:00:00 2001 From: "i.i.artamonov" Date: Thu, 8 Sep 2022 16:24:59 +0400 Subject: [PATCH 136/141] Added liquibase Added dependencies to pom.xml. Added init changelog of database --- pom.xml | 18 + src/main/resources/application.properties | 3 + src/main/resources/liquibase.properties | 3 + .../2022-09/v1-08-09-2022-changelog.xml | 691 ++++++++++++++++++ .../resources/liquibase/changelog-master.xml | 6 + 5 files changed, 721 insertions(+) create mode 100644 src/main/resources/liquibase.properties create mode 100644 src/main/resources/liquibase/2022-09/v1-08-09-2022-changelog.xml create mode 100644 src/main/resources/liquibase/changelog-master.xml diff --git a/pom.xml b/pom.xml index dee269a..14a7fad 100644 --- a/pom.xml +++ b/pom.xml @@ -113,6 +113,10 @@ kotlin-stdlib-jdk8 ${kotlin.version} + + org.liquibase + liquibase-core + org.jetbrains.kotlin kotlin-test @@ -135,10 +139,24 @@ 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 diff --git a/src/main/resources/application.properties b/src/main/resources/application.properties index 1c724d3..9345de0 100644 --- a/src/main/resources/application.properties +++ b/src/main/resources/application.properties @@ -9,3 +9,6 @@ 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 From 1d90d470c07947624748805c0bbf874a2ae9a103 Mon Sep 17 00:00:00 2001 From: "i.i.artamonov" Date: Tue, 13 Sep 2022 15:56:06 +0400 Subject: [PATCH 137/141] Refactored architecture of MVC pattern UserController Isolated business logic in UserService. Isolate not relative logic into another controllers and services. Add custom exception and exception hanlders. Change the tests for usercontroller --- pom.xml | 2 +- .../controller/DiaryController.java | 70 +++ .../controller/GameController.java | 31 ++ .../controller/GameSellController.java | 42 ++ .../RatingGameByUserController.java | 39 ++ .../controller/UserController.java | 411 +----------------- .../controller/UserOwnGameController.java | 32 ++ .../controller/UserWishController.java | 32 ++ .../dto/request/UserEditRequest.java | 6 +- .../exception/BadRequestException.java | 9 + .../DBChangeEntityOperationException.java | 7 + .../boardgamefun/exception/ErrorResponse.java | 13 + .../exception/GlobalExceptionHandler.java | 71 +++ .../exception/NoRecordFoundException.java | 9 + .../boardgamefun/service/GameSellService.java | 66 ++- .../service/RatingGameByUserService.java | 76 ++++ .../service/UserOwnGameService.java | 56 +++ .../boardgamefun/service/UserService.java | 94 +++- .../boardgamefun/service/UserWishService.java | 58 +++ .../{ => controller}/GameControllerTests.java | 5 +- .../{ => controller}/UserControllerTests.java | 391 ++++++++++++++++- 21 files changed, 1109 insertions(+), 411 deletions(-) create mode 100644 src/main/java/com/petproject/boardgamefun/controller/GameSellController.java create mode 100644 src/main/java/com/petproject/boardgamefun/controller/RatingGameByUserController.java create mode 100644 src/main/java/com/petproject/boardgamefun/controller/UserOwnGameController.java create mode 100644 src/main/java/com/petproject/boardgamefun/controller/UserWishController.java create mode 100644 src/main/java/com/petproject/boardgamefun/exception/BadRequestException.java create mode 100644 src/main/java/com/petproject/boardgamefun/exception/DBChangeEntityOperationException.java create mode 100644 src/main/java/com/petproject/boardgamefun/exception/ErrorResponse.java create mode 100644 src/main/java/com/petproject/boardgamefun/exception/GlobalExceptionHandler.java create mode 100644 src/main/java/com/petproject/boardgamefun/exception/NoRecordFoundException.java create mode 100644 src/main/java/com/petproject/boardgamefun/service/RatingGameByUserService.java create mode 100644 src/main/java/com/petproject/boardgamefun/service/UserOwnGameService.java create mode 100644 src/main/java/com/petproject/boardgamefun/service/UserWishService.java rename src/test/java/com/petproject/boardgamefun/{ => controller}/GameControllerTests.java (99%) rename src/test/java/com/petproject/boardgamefun/{ => controller}/UserControllerTests.java (79%) diff --git a/pom.xml b/pom.xml index 14a7fad..94ab4e8 100644 --- a/pom.xml +++ b/pom.xml @@ -21,13 +21,13 @@ - + diff --git a/src/main/java/com/petproject/boardgamefun/controller/DiaryController.java b/src/main/java/com/petproject/boardgamefun/controller/DiaryController.java index 370e6f5..92ba21f 100644 --- a/src/main/java/com/petproject/boardgamefun/controller/DiaryController.java +++ b/src/main/java/com/petproject/boardgamefun/controller/DiaryController.java @@ -5,6 +5,7 @@ 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; @@ -168,6 +169,75 @@ public ResponseEntity deleteDiaryRating(@PathVariable Integer ratingId) 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/GameController.java b/src/main/java/com/petproject/boardgamefun/controller/GameController.java index 33cde0a..94a1f98 100644 --- a/src/main/java/com/petproject/boardgamefun/controller/GameController.java +++ b/src/main/java/com/petproject/boardgamefun/controller/GameController.java @@ -2,6 +2,7 @@ import com.petproject.boardgamefun.dto.FilterGamesDTO; import com.petproject.boardgamefun.dto.GameDataDTO; +import com.petproject.boardgamefun.dto.GameSellDTO; import com.petproject.boardgamefun.dto.RatingGameByUserDTO; import com.petproject.boardgamefun.model.Expansion; import com.petproject.boardgamefun.model.Game; @@ -258,6 +259,36 @@ public ResponseEntity deleteDesignerFromGame(@PathVariable Integer return new ResponseEntity<>(gameDTO, HttpStatus.OK); } + @Transactional + @GetMapping("/{userId}/games") + public ResponseEntity> getUserCollection(@PathVariable Integer userId) { + + var games = gameService.entitiesToGameDTO(gameRepository.findUserGames(userId)); + return new ResponseEntity<>(games, HttpStatus.OK); + } + + @GetMapping("/{userId}/games-rating") + public ResponseEntity> getUserRatingList(@PathVariable Integer userId) { + + var ratingGamesByUser = gameService.userGameRatingToGameDTO(gameRepository.findUserGameRatingList(userId)); + + return new ResponseEntity<>(ratingGamesByUser, HttpStatus.OK); + } + + @GetMapping("/{id}/wishlist") + public ResponseEntity> getUserWishlist(@PathVariable Integer id) { + var games = gameService.entitiesToGameDTO(gameRepository.findUserWishlist(id)); + return new ResponseEntity<>(games, HttpStatus.OK); + } + + /* @GetMapping("{userId}/games-to-sell") + public ResponseEntity> getGameSellList(@PathVariable Integer userId) { + + var gameSellList = gameSellService.projectionsToGameSellDTO(gameRepository.getGameSellList(userId)); + + return new ResponseEntity<>(gameSellList, 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..d540e46 --- /dev/null +++ b/src/main/java/com/petproject/boardgamefun/controller/GameSellController.java @@ -0,0 +1,42 @@ +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); + } +} 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..724539b --- /dev/null +++ b/src/main/java/com/petproject/boardgamefun/controller/RatingGameByUserController.java @@ -0,0 +1,39 @@ +package com.petproject.boardgamefun.controller; + +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.*; + +@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); + } + +} diff --git a/src/main/java/com/petproject/boardgamefun/controller/UserController.java b/src/main/java/com/petproject/boardgamefun/controller/UserController.java index e30f666..dbf3542 100644 --- a/src/main/java/com/petproject/boardgamefun/controller/UserController.java +++ b/src/main/java/com/petproject/boardgamefun/controller/UserController.java @@ -1,14 +1,9 @@ package com.petproject.boardgamefun.controller; -import com.petproject.boardgamefun.dto.DiaryDataDTO; -import com.petproject.boardgamefun.dto.GameDataDTO; -import com.petproject.boardgamefun.dto.GameSellDTO; 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.repository.*; -import com.petproject.boardgamefun.security.enums.Role; import com.petproject.boardgamefun.security.jwt.JwtUtils; import com.petproject.boardgamefun.security.model.JwtResponse; import com.petproject.boardgamefun.security.model.LoginRequest; @@ -16,9 +11,6 @@ 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 org.springframework.http.HttpStatus; import org.springframework.http.ResponseEntity; @@ -27,58 +19,23 @@ import org.springframework.security.authentication.UsernamePasswordAuthenticationToken; import org.springframework.security.core.Authentication; import org.springframework.security.core.context.SecurityContextHolder; -import org.springframework.security.crypto.password.PasswordEncoder; import org.springframework.web.bind.annotation.*; import org.springframework.web.multipart.MultipartFile; -import javax.transaction.Transactional; import java.io.IOException; -import java.time.OffsetDateTime; import java.util.List; -import java.util.Objects; + @RestController @RequestMapping("/users") public class UserController { - - final GameRepository gameRepository; - final UserRepository userRepository; - final UserOwnGameRepository userOwnGameRepository; - final RatingGameByUserRepository ratingGameByUserRepository; - final UserWishRepository userWishRepository; - final GameSellRepository gameSellRepository; - final DiaryRepository diaryRepository; - final DiaryService diaryService; - final GameSellService gameSellService; - final GameService gameService; final UserService userService; - - - final PasswordEncoder passwordEncoder; final JwtUtils jwtUtils; final AuthenticationManager authenticationManager; final RefreshTokenService refreshTokenService; - public UserController(GameRepository gameRepository, - UserRepository userRepository, - UserOwnGameRepository userOwnGameRepository, - RatingGameByUserRepository ratingGameByUserRepository, - UserWishRepository userWishRepository, - GameSellRepository gameSellRepository, DiaryRepository diaryRepository, DiaryService diaryService, GameSellService gameSellService, GameService gameService, UserService userService, PasswordEncoder passwordEncoder, - JwtUtils jwtUtils, - AuthenticationManager authenticationManager, RefreshTokenService refreshTokenService) { - this.gameRepository = gameRepository; - this.userRepository = userRepository; - this.userOwnGameRepository = userOwnGameRepository; - this.ratingGameByUserRepository = ratingGameByUserRepository; - this.userWishRepository = userWishRepository; - this.gameSellRepository = gameSellRepository; - this.diaryRepository = diaryRepository; - this.diaryService = diaryService; - this.gameSellService = gameSellService; - this.gameService = gameService; + public UserController(UserService userService,JwtUtils jwtUtils,AuthenticationManager authenticationManager, RefreshTokenService refreshTokenService) { this.userService = userService; - this.passwordEncoder = passwordEncoder; this.jwtUtils = jwtUtils; this.authenticationManager = authenticationManager; this.refreshTokenService = refreshTokenService; @@ -86,13 +43,13 @@ public UserController(GameRepository gameRepository, @GetMapping() public ResponseEntity> getUsers() { - var users = userService.entitiesToUserDTO(userRepository.findAll()); + var users = userService.getUsers(); return new ResponseEntity<>(users, HttpStatus.OK); } @PostMapping("sign-in") public ResponseEntity authenticateUser(@RequestBody LoginRequest loginRequest) { - if (!userRepository.existsByName(loginRequest.getName())) { + if (!userService.existsByName(loginRequest.getName())) { return new ResponseEntity<>("Пользователя с таким никнеймом не существует", HttpStatus.NOT_FOUND); } Authentication authentication = authenticationManager.authenticate(new UsernamePasswordAuthenticationToken(loginRequest.getName(), loginRequest.getPassword())); @@ -107,19 +64,7 @@ public ResponseEntity authenticateUser(@RequestBody LoginRequest loginRequest @PostMapping("/sign-up") public ResponseEntity registerUser(@RequestBody User user) { - - if (userRepository.existsByName(user.getName())) { - return new ResponseEntity<>("Пользователь с таким никнеймом уже существует", HttpStatus.BAD_REQUEST); - } - - if (userRepository.existsByMail(user.getMail())) { - return new ResponseEntity<>("Пользователь с такой почтой уже существует", HttpStatus.BAD_REQUEST); - } - - user.setRole(Role.ROLE_USER.name()); - user.setPassword(passwordEncoder.encode(user.getPassword())); - user.setRegistrationDate(OffsetDateTime.now()); - userRepository.save(user); + userService.registerUser(user); return new ResponseEntity<>(user, HttpStatus.OK); } @@ -133,368 +78,32 @@ public ResponseEntity refreshToken(@RequestBody RefreshTokenRequest refreshTo return new ResponseEntity<>(HttpStatus.UNAUTHORIZED); } - @Transactional @PostMapping("/upload-avatar/{userName}") public ResponseEntity uploadAvatar(@PathVariable String userName, @RequestParam("avatar") MultipartFile file) throws IOException { - var user = userRepository.findUserByName(userName); - user.setAvatar(file.getBytes()); - userRepository.save(user); + this.userService.uploadAvatar(userName, file); return new ResponseEntity<>(HttpStatus.OK); } - - @Transactional - @PatchMapping("/edit/{userId}") + @PatchMapping("/{userId}") @PreAuthorize("hasRole('USER') or hasRole('MODERATOR') or hasRole('ADMIN')") public ResponseEntity editUser(@PathVariable Integer userId, @RequestBody UserEditRequest userEditRequest) { - var user = userRepository.findUserById(userId); - if (userEditRequest.getName() != null && !userRepository.existsByName(userEditRequest.getName())) { - user.setName(userEditRequest.getName()); - } else { - return new ResponseEntity<>("Пользователь с таким никнеймом уже существует", HttpStatus.BAD_REQUEST); - } - if (userEditRequest.getRole() != null && !Objects.equals(userEditRequest.getRole(), user.getRole())) { - user.setRole(userEditRequest.getRole()); - } - - userRepository.save(user); - + UserDTO user = userService.editUser(userId, userEditRequest); return new ResponseEntity<>(user, HttpStatus.OK); } - @Transactional @PatchMapping("/change-password/{userId}") @PreAuthorize("hasRole('USER') or hasRole('MODERATOR') or hasRole('ADMIN')") public ResponseEntity changePassword(@PathVariable Integer userId, @RequestBody PasswordChangeRequest passwordRequest) { - var user = userRepository.findUserById(userId); - if (passwordRequest.getPassword() != null && passwordEncoder.matches(passwordRequest.getPassword(), user.getPassword())) { - user.setPassword(passwordEncoder.encode(passwordRequest.getPassword())); - } else { - return new ResponseEntity<>("Вы ввели точно такой же пароль", HttpStatus.BAD_REQUEST); - } - userRepository.save(user); - + UserDTO user = userService.changePassword(userId, passwordRequest); return new ResponseEntity<>(user, HttpStatus.OK); } - - @Transactional @GetMapping("{id}") public ResponseEntity getUser(@PathVariable Integer id) { - var userDTO = userService.entityToUserDTO(userRepository.findUserById(id)); - if (userDTO == null) { - return new ResponseEntity<>(null, HttpStatus.NOT_FOUND); - } + var userDTO = userService.getUser(id); return new ResponseEntity<>(userDTO, HttpStatus.OK); } - @Transactional - @GetMapping("/{id}/games") - public ResponseEntity> getUserCollection(@PathVariable Integer id) { - - var games = gameService.entitiesToGameDTO(gameRepository.findUserGames(id)); - return new ResponseEntity<>(games, HttpStatus.OK); - } - - @Transactional - @PostMapping("{userId}/add-game/{gameId}") - @PreAuthorize("hasRole('USER') or hasRole('MODERATOR') or hasRole('ADMIN')") - public ResponseEntity addGameToUser(@PathVariable Integer userId, @PathVariable Integer gameId) { - - var user = userRepository.findUserById(userId); - var game = gameRepository.findGameById(gameId); - - if (user == null || game == null) - return new ResponseEntity<>(null, HttpStatus.NOT_FOUND); - - var games = gameRepository.findUserGames(userId); - if (games.size() != 0 && games.stream().anyMatch(g -> g.getId().equals(gameId))) { - return new ResponseEntity<>(null, HttpStatus.BAD_REQUEST); - } - - var userOwnGame = new UserOwnGame(); - userOwnGame.setGame(game); - userOwnGame.setUser(user); - - userOwnGameRepository.save(userOwnGame); - - return new ResponseEntity<>(game.getTitle() + " добавлена в вашу коллекцию", HttpStatus.OK); - } - - @Transactional - @DeleteMapping("{userId}/delete-game/{gameId}") - @PreAuthorize("hasRole('USER') or hasRole('MODERATOR') or hasRole('ADMIN')") - public ResponseEntity deleteGameFromUserCollection(@PathVariable Integer userId, @PathVariable Integer gameId) { - - var userOwnGame = userOwnGameRepository.findUserOwnGame_ByUserIdAndGameId(userId, gameId); - - if (userOwnGame == null) - return new ResponseEntity<>(null, HttpStatus.NOT_FOUND); - - userOwnGameRepository.delete(userOwnGame); - - return new ResponseEntity<>(gameId, HttpStatus.OK); - } - - @GetMapping("/{userId}/games-rating") - public ResponseEntity> getUserRatingList(@PathVariable Integer userId) { - - var ratingGamesByUser = gameService.userGameRatingToGameDTO(gameRepository.findUserGameRatingList(userId)); - - return new ResponseEntity<>(ratingGamesByUser, HttpStatus.OK); - } - - @Transactional - @DeleteMapping("/{userId}/delete-game-rating/{gameId}") - @PreAuthorize("hasRole('USER') or hasRole('MODERATOR') or hasRole('ADMIN')") - public ResponseEntity deleteGameRating(@PathVariable Integer userId, @PathVariable Integer gameId) { - - var ratingGameByUser = ratingGameByUserRepository.findRatingGame_ByUserIdAndGameId(userId, gameId); - - if (ratingGameByUser == null) - return new ResponseEntity<>(null, HttpStatus.NOT_FOUND); - - ratingGameByUserRepository.delete(ratingGameByUser); - - return new ResponseEntity<>("Оценка с текущей игры удалена", HttpStatus.OK); - } - - @Transactional - @PostMapping("/{userId}/set-game-rating/{gameId}/{rating}") - @PreAuthorize("hasRole('USER') or hasRole('MODERATOR') or hasRole('ADMIN')") - public ResponseEntity setGameRating(@PathVariable Integer userId, @PathVariable Integer gameId, @PathVariable Integer rating) { - - if (rating > 10 || rating < 1) { - return new ResponseEntity<>(null, HttpStatus.BAD_REQUEST); - } - if (ratingGameByUserRepository.findRatingGame_ByUserIdAndGameId(userId, gameId) != null) { - return new ResponseEntity<>(null, HttpStatus.BAD_REQUEST); - } - - var gameRating = new RatingGameByUser(); - var game = gameRepository.findGameById(gameId); - var user = userRepository.findUserById(userId); - - if (game == null || user == null) - return new ResponseEntity<>(null, HttpStatus.NOT_FOUND); - - gameRating.setGame(game); - gameRating.setUser(user); - gameRating.setRating(rating.doubleValue()); - - ratingGameByUserRepository.save(gameRating); - - - return new ResponseEntity<>(rating.doubleValue(), HttpStatus.OK); - } - - @Transactional - @PatchMapping("/{userId}/update-game-rating/{gameId}/{rating}") - @PreAuthorize("hasRole('USER') or hasRole('MODERATOR') or hasRole('ADMIN')") - public ResponseEntity updateGameRating(@PathVariable Integer userId, @PathVariable Integer gameId, @PathVariable Integer rating) { - - if (rating > 10 || rating < 1) { - return new ResponseEntity<>(null, HttpStatus.BAD_REQUEST); - } - var ratingGameByUser = ratingGameByUserRepository.findRatingGame_ByUserIdAndGameId(userId, gameId); - if (ratingGameByUser == null) { - return new ResponseEntity<>(null, HttpStatus.NOT_FOUND); - } - - ratingGameByUser.setRating(rating.doubleValue()); - ratingGameByUserRepository.save(ratingGameByUser); - - return new ResponseEntity<>(rating.doubleValue(), HttpStatus.OK); - } - - @GetMapping("/{id}/wishlist") - public ResponseEntity> getUserWishlist(@PathVariable Integer id) { - var games = gameService.entitiesToGameDTO(gameRepository.findUserWishlist(id)); - return new ResponseEntity<>(games, HttpStatus.OK); - } - - @Transactional - @PostMapping("{userId}/add-game-to-wishlist/{gameId}") - @PreAuthorize("hasRole('USER') or hasRole('MODERATOR') or hasRole('ADMIN')") - public ResponseEntity addGameToUserWishlist(@PathVariable Integer userId, @PathVariable Integer gameId) { - - var user = userRepository.findUserById(userId); - var game = gameRepository.findGameById(gameId); - - if (userWishRepository.findByUserAndGame(user, game) != null) { - return new ResponseEntity<>(null, HttpStatus.BAD_REQUEST); - } - - if (user == null || game == null) { - return new ResponseEntity<>(null, HttpStatus.NOT_FOUND); - } - - var userWish = new UserWish(); - userWish.setGame(game); - userWish.setUser(user); - - userWishRepository.save(userWish); - - return new ResponseEntity<>(game.getTitle() + " добавлена в ваши желания", HttpStatus.OK); - } - - @Transactional - @DeleteMapping("delete-game-from-wishlist/{userWishId}") - @PreAuthorize("hasRole('USER') or hasRole('MODERATOR') or hasRole('ADMIN')") - public ResponseEntity deleteGameFromUserWishlist(@PathVariable Integer userWishId) { - - var userWish = userWishRepository.findById(userWishId); - - if (userWish.isEmpty()) { - return new ResponseEntity<>(false, HttpStatus.NOT_FOUND); - } - userWishRepository.delete(userWish.get()); - - return new ResponseEntity<>(true, HttpStatus.OK); - } - - @Transactional - @PostMapping("{userId}/add-game-to-sell/{gameId}") - @PreAuthorize("hasRole('USER') or hasRole('MODERATOR') or hasRole('ADMIN')") - public ResponseEntity> addGameToSellList(@PathVariable Integer userId, @PathVariable Integer gameId, @RequestBody GameSell gameSell) { - - if (gameSell.getId() != 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); - } - - gameSell.setGame(game); - gameSell.setUser(user); - - gameSellRepository.save(gameSell); - var gameSellList = gameSellService.projectionsToGameSellDTO(gameRepository.getGameSellList(userId)); - - return new ResponseEntity<>(gameSellList, HttpStatus.OK); - } - - @Transactional - @GetMapping("{userId}/games-to-sell") - public ResponseEntity> getGameSellList(@PathVariable Integer userId) { - - var gameSellList = gameSellService.projectionsToGameSellDTO(gameRepository.getGameSellList(userId)); - - return new ResponseEntity<>(gameSellList, HttpStatus.OK); - } - - - @Transactional - @DeleteMapping("{userId}/remove-game-from-sell/{gameId}") - @PreAuthorize("hasRole('USER') or hasRole('MODERATOR') or hasRole('ADMIN')") - public ResponseEntity removeGameFromSell(@PathVariable Integer userId, @PathVariable Integer gameId) { - - var gameSell = gameSellRepository.findGameSell_ByUserIdAndGameId(userId, gameId); - if (gameSell == null) { - return new ResponseEntity<>(null, HttpStatus.NOT_FOUND); - } - gameSellRepository.delete(gameSell); - - return new ResponseEntity<>(gameId, HttpStatus.OK); - } - - @Transactional - @PutMapping("/update-game-to-sell") - @PreAuthorize("hasRole('USER') or hasRole('MODERATOR') or hasRole('ADMIN')") - public ResponseEntity updateSellGame(@RequestBody GameSell gameSell) { - - if (gameSell.getId() == null || gameSell.getGame() == null || gameSell.getUser() == null) { - return new ResponseEntity<>(null, HttpStatus.BAD_REQUEST); - } - - 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); - - return new ResponseEntity<>(gameSell.getGame().getTitle() + " обновлена", 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: 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..d6d34da --- /dev/null +++ b/src/main/java/com/petproject/boardgamefun/controller/UserWishController.java @@ -0,0 +1,32 @@ +package com.petproject.boardgamefun.controller; + +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.*; + +@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); + } +} diff --git a/src/main/java/com/petproject/boardgamefun/dto/request/UserEditRequest.java b/src/main/java/com/petproject/boardgamefun/dto/request/UserEditRequest.java index 2de0c99..508dfe4 100644 --- a/src/main/java/com/petproject/boardgamefun/dto/request/UserEditRequest.java +++ b/src/main/java/com/petproject/boardgamefun/dto/request/UserEditRequest.java @@ -4,7 +4,7 @@ @Data public class UserEditRequest { - private String name; - private String role; - private byte[] avatar; + 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/service/GameSellService.java b/src/main/java/com/petproject/boardgamefun/service/GameSellService.java index 63f1bf6..dcea9e9 100644 --- a/src/main/java/com/petproject/boardgamefun/service/GameSellService.java +++ b/src/main/java/com/petproject/boardgamefun/service/GameSellService.java @@ -2,10 +2,19 @@ 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.http.HttpStatus; +import org.springframework.http.ResponseEntity; import org.springframework.stereotype.Service; +import javax.transaction.Transactional; import java.util.ArrayList; import java.util.List; @@ -13,9 +22,63 @@ public class GameSellService { final GameMapper gameMapper; + final GameSellRepository gameSellRepository; + final UserRepository userRepository; + final GameRepository gameRepository; - public GameSellService(GameMapper gameMapper) { + 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); } public GameSellDTO entityToGameSellDTO(Game game) { @@ -34,6 +97,5 @@ public List projectionsToGameSellDTO(List proje } return gamesForSell; - } } 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..995891c --- /dev/null +++ b/src/main/java/com/petproject/boardgamefun/service/RatingGameByUserService.java @@ -0,0 +1,76 @@ +package com.petproject.boardgamefun.service; + +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; + +@Service +public class RatingGameByUserService { + + final RatingGameByUserRepository ratingGameByUserRepository; + final GameRepository gameRepository; + final UserRepository userRepository; + + public RatingGameByUserService(RatingGameByUserRepository ratingGameByUserRepository, GameRepository gameRepository, UserRepository userRepository) { + this.ratingGameByUserRepository = ratingGameByUserRepository; + this.gameRepository = gameRepository; + this.userRepository = userRepository; + } + + @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(); + } + +} 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 index 00d96d4..47fa757 100644 --- a/src/main/java/com/petproject/boardgamefun/service/UserService.java +++ b/src/main/java/com/petproject/boardgamefun/service/UserService.java @@ -1,21 +1,113 @@ 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) { + 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 : 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..9319d6e --- /dev/null +++ b/src/main/java/com/petproject/boardgamefun/service/UserWishService.java @@ -0,0 +1,58 @@ +package com.petproject.boardgamefun.service; + +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.http.HttpStatus; +import org.springframework.http.ResponseEntity; +import org.springframework.stereotype.Service; + +import javax.transaction.Transactional; + +@Service +public class UserWishService { + + final UserWishRepository userWishRepository; + final UserRepository userRepository; + final GameRepository gameRepository; + + public UserWishService(UserWishRepository userWishRepository, UserRepository userRepository, GameRepository gameRepository) { + this.userWishRepository = userWishRepository; + this.userRepository = userRepository; + this.gameRepository = gameRepository; + } + + @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()); + } +} diff --git a/src/test/java/com/petproject/boardgamefun/GameControllerTests.java b/src/test/java/com/petproject/boardgamefun/controller/GameControllerTests.java similarity index 99% rename from src/test/java/com/petproject/boardgamefun/GameControllerTests.java rename to src/test/java/com/petproject/boardgamefun/controller/GameControllerTests.java index 786465c..949c00f 100644 --- a/src/test/java/com/petproject/boardgamefun/GameControllerTests.java +++ b/src/test/java/com/petproject/boardgamefun/controller/GameControllerTests.java @@ -1,10 +1,12 @@ -package com.petproject.boardgamefun; +/* +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.DesignerDTO; import com.petproject.boardgamefun.dto.FilterGamesDTO; import com.petproject.boardgamefun.dto.GameDataDTO; @@ -935,3 +937,4 @@ public void deleteDesignerFromGameShouldReturnIsUnauthorized() throws Exception //todo: union beforeAll method? } +*/ diff --git a/src/test/java/com/petproject/boardgamefun/UserControllerTests.java b/src/test/java/com/petproject/boardgamefun/controller/UserControllerTests.java similarity index 79% rename from src/test/java/com/petproject/boardgamefun/UserControllerTests.java rename to src/test/java/com/petproject/boardgamefun/controller/UserControllerTests.java index eea320b..f59cd89 100644 --- a/src/test/java/com/petproject/boardgamefun/UserControllerTests.java +++ b/src/test/java/com/petproject/boardgamefun/controller/UserControllerTests.java @@ -1,13 +1,18 @@ -package com.petproject.boardgamefun; +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.*; @@ -24,6 +29,7 @@ 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; @@ -36,7 +42,9 @@ 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; @@ -44,10 +52,13 @@ 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; @@ -64,6 +75,382 @@ 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()); + } + + @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()); + } + + @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()); + + verify(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()); + + verify(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()); + verify(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()); + } + + @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; @@ -1544,4 +1931,4 @@ public void updateDiaryShouldReturnIsNotFound_BothParameters() throws Exception diary.setId(null); } -} +}*/ From 0f1a8239b7d33b8a58c98a29d14e7063d0db7908 Mon Sep 17 00:00:00 2001 From: "i.i.artamonov" Date: Fri, 16 Sep 2022 15:12:51 +0400 Subject: [PATCH 138/141] Refacrored architecture of MVC pattern GameController Isolated bisiness logic to game service. Isolate not relative logic into another controllers and services. Change the tests for GameController --- .../controller/DesignerController.java | 20 +- .../controller/ExpansionController.java | 44 ++ .../controller/GameController.java | 241 +---------- .../controller/GameSellController.java | 7 + .../RatingGameByUserController.java | 18 + .../controller/SimilarGameController.java | 45 ++ .../controller/UserWishController.java | 9 + .../boardgamefun/service/DesignerService.java | 43 ++ .../service/ExpansionService.java | 60 +++ .../boardgamefun/service/GameSellService.java | 7 +- .../boardgamefun/service/GameService.java | 73 +++- .../service/RatingGameByUserService.java | 16 +- .../service/SimilarGameService.java | 59 +++ .../boardgamefun/service/UserWishService.java | 13 +- .../controller/GameControllerTests.java | 395 +++++++++++++++++- .../controller/UserControllerTests.java | 1 + 16 files changed, 808 insertions(+), 243 deletions(-) create mode 100644 src/main/java/com/petproject/boardgamefun/controller/ExpansionController.java create mode 100644 src/main/java/com/petproject/boardgamefun/controller/SimilarGameController.java create mode 100644 src/main/java/com/petproject/boardgamefun/service/ExpansionService.java create mode 100644 src/main/java/com/petproject/boardgamefun/service/SimilarGameService.java diff --git a/src/main/java/com/petproject/boardgamefun/controller/DesignerController.java b/src/main/java/com/petproject/boardgamefun/controller/DesignerController.java index 02699aa..ddc5e95 100644 --- a/src/main/java/com/petproject/boardgamefun/controller/DesignerController.java +++ b/src/main/java/com/petproject/boardgamefun/controller/DesignerController.java @@ -1,6 +1,7 @@ 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; @@ -74,14 +75,27 @@ public ResponseEntity> updateDesigner(@PathVariable Integer id 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/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/GameController.java b/src/main/java/com/petproject/boardgamefun/controller/GameController.java index 94a1f98..f5a87c5 100644 --- a/src/main/java/com/petproject/boardgamefun/controller/GameController.java +++ b/src/main/java/com/petproject/boardgamefun/controller/GameController.java @@ -2,19 +2,12 @@ import com.petproject.boardgamefun.dto.FilterGamesDTO; import com.petproject.boardgamefun.dto.GameDataDTO; -import com.petproject.boardgamefun.dto.GameSellDTO; -import com.petproject.boardgamefun.dto.RatingGameByUserDTO; -import com.petproject.boardgamefun.model.Expansion; import com.petproject.boardgamefun.model.Game; -import com.petproject.boardgamefun.model.GameByDesigner; -import com.petproject.boardgamefun.model.SameGame; -import com.petproject.boardgamefun.repository.*; 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.transaction.annotation.Transactional; import org.springframework.web.bind.annotation.*; import org.springframework.web.multipart.MultipartFile; @@ -25,271 +18,69 @@ @RequestMapping("/games") public class GameController { - final GameRepository gameRepository; - final UserRepository userRepository; - final ExpansionRepository expansionRepository; - final SameGameRepository sameGameRepository; - final DesignerRepository designerRepository; - final GameByDesignerRepository gameByDesignerRepository; final GameService gameService; - public GameController(GameRepository gameRepository, UserRepository userRepository, ExpansionRepository expansionRepository, SameGameRepository sameGameRepository, DesignerRepository designerRepository, GameByDesignerRepository gameByDesignerRepository, GameService gameService) { - this.gameRepository = gameRepository; - this.userRepository = userRepository; - this.expansionRepository = expansionRepository; - this.sameGameRepository = sameGameRepository; - this.designerRepository = designerRepository; - this.gameByDesignerRepository = gameByDesignerRepository; - this.gameService = gameService; + public GameController(GameService gameService) { + this.gameService = gameService; } - @Transactional @GetMapping() ResponseEntity> getGames() { - - var games = gameService.projectionsToGameDTO(gameRepository.findGames()); - + var games = gameService.getGames(); return new ResponseEntity<>(games, HttpStatus.OK); } - @Transactional - @GetMapping("/get-game/{id}") - public ResponseEntity getGameByCriteria(@PathVariable Integer id) { - var gameDataDTO = gameService.projectionsToGameDTO(gameRepository.findGameWithRating(id), designerRepository.findDesignersUsingGame(id)); - if (gameDataDTO == null) { - return new ResponseEntity<>(null, HttpStatus.NOT_FOUND); - } + @GetMapping("/{id}") + public ResponseEntity getGameById(@PathVariable Integer id) { + var gameDataDTO = gameService.getGameById(id); return new ResponseEntity<>(gameDataDTO, HttpStatus.OK); } - @Transactional @GetMapping("/get-games-by-filter/{title}") public ResponseEntity> getGamesByTitle(@PathVariable String title) { - var games = gameService.getTitlesFromProjections(gameRepository.findGamesUsingTitle(title)); + var games = gameService.getGameByTitle(title); return new ResponseEntity<>(games, HttpStatus.OK); } - - @Transactional - @PostMapping("/add") + @PostMapping("/") @PreAuthorize("hasRole('MODERATOR') or hasRole('ADMIN')") public ResponseEntity addGame(@RequestBody Game newGame) { - if (newGame.getId() != null) { - return new ResponseEntity<>(null, HttpStatus.BAD_REQUEST); - } + gameService.checkExistence(newGame); return getGameDataDTOResponseEntity(newGame); } - @Transactional @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 game = gameRepository.findGameById(gameId); - if (game == null) - return new ResponseEntity<>(null, HttpStatus.NOT_FOUND); - game.setPicture(file.getBytes()); - gameRepository.save(game); - var gameDTO = gameService.projectionsToGameDTO(gameRepository.findGameWithRating(gameId), designerRepository.findDesignersUsingGame(gameId)); + var gameDTO = gameService.uploadImage(gameId, file); return new ResponseEntity<>(gameDTO, HttpStatus.OK); } - @Transactional - @PutMapping("/update") + @PutMapping("/") @PreAuthorize("hasRole('MODERATOR') or hasRole('ADMIN')") public ResponseEntity updateGame(@RequestBody Game updatedGame) { return getGameDataDTOResponseEntity(updatedGame); } @NotNull - private ResponseEntity getGameDataDTOResponseEntity(@RequestBody 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) { - return new ResponseEntity<>(null, HttpStatus.BAD_REQUEST); - } - gameRepository.save(updatedGame); - var game = gameService.entityToGameDTO(updatedGame); + private ResponseEntity getGameDataDTOResponseEntity(Game updatedGame) { + var game = gameService.save(updatedGame); return new ResponseEntity<>(game, HttpStatus.OK); } - @Transactional - @DeleteMapping("/remove") + @DeleteMapping("/") @PreAuthorize("hasRole('MODERATOR') or hasRole('ADMIN')") public ResponseEntity removeGameFromSite(@RequestBody Game deleteGame) { - if (deleteGame.getId() == null) - return new ResponseEntity<>(null, HttpStatus.NOT_FOUND); - gameRepository.delete(deleteGame); - + gameService.delete(deleteGame); return new ResponseEntity<>(deleteGame.getTitle() + " удалена из базы данных", HttpStatus.OK); } - - @Transactional - @GetMapping("/expansions/{gameId}") - public ResponseEntity> getExpansions(@PathVariable Integer gameId) { - if (gameId == null) - return new ResponseEntity<>(null, HttpStatus.NOT_FOUND); - var gamesExpansions = gameService.entitiesToGameDTO(gameRepository.getExpansions(gameId)); - - return new ResponseEntity<>(gamesExpansions, HttpStatus.OK); - } - - @Transactional - @PostMapping("/add-expansion/{parentGameId}/{daughterGameId}") - @PreAuthorize("hasRole('USER') or hasRole('MODERATOR') or hasRole('ADMIN')") - public ResponseEntity> addExpansion(@PathVariable Integer parentGameId, @PathVariable Integer daughterGameId) { - var parentGame = gameRepository.findGameById(parentGameId); - var daughterGame = gameRepository.findGameById(daughterGameId); - - if (parentGame == null || daughterGame == null) { - return new ResponseEntity<>(null, HttpStatus.BAD_REQUEST); - } - - var expansion = new Expansion(); - expansion.setParentGame(parentGame); - expansion.setDaughterGame(daughterGame); - expansionRepository.save(expansion); - - var gamesExpansions = gameService.entitiesToGameDTO(gameRepository.getExpansions(parentGameId)); - - return new ResponseEntity<>(gamesExpansions, HttpStatus.OK); - } - - @Transactional - @DeleteMapping("/delete-expansion/{parentGameId}/{daughterGameId}") - @PreAuthorize("hasRole('USER') or hasRole('MODERATOR') or hasRole('ADMIN')") - public ResponseEntity> deleteExpansion(@PathVariable Integer parentGameId, @PathVariable Integer daughterGameId) { - var expansion = expansionRepository.findExpansion_ByParentGameIdAndDaughterGameId(parentGameId, daughterGameId); - if (expansion == null) { - return new ResponseEntity<>(null, HttpStatus.NOT_FOUND); - } - expansionRepository.delete(expansion); - - var gamesExpansions = gameService.entitiesToGameDTO(gameRepository.getExpansions(parentGameId)); - - return new ResponseEntity<>(gamesExpansions, HttpStatus.OK); - } - - @Transactional - @GetMapping("/similar/{gameId}") - public ResponseEntity> getSimilarGames(@PathVariable Integer gameId) { - if (gameId == null) - return new ResponseEntity<>(null, HttpStatus.NOT_FOUND); - var similarGames = gameService.entitiesToGameDTO(gameRepository.getSimilarGames(gameId)); - - return new ResponseEntity<>(similarGames, HttpStatus.OK); - } - - @Transactional - @PostMapping("/add-similar/{referenceGameId}/{sourceGameId}") - @PreAuthorize("hasRole('USER') or hasRole('MODERATOR') or hasRole('ADMIN')") - public ResponseEntity> addSimilarGame(@PathVariable Integer referenceGameId, @PathVariable Integer sourceGameId) { - var referenceGame = gameRepository.findGameById(referenceGameId); - var sourceGame = gameRepository.findGameById(sourceGameId); - - if (referenceGame == null || sourceGame == null) - return new ResponseEntity<>(null, HttpStatus.BAD_REQUEST); - - var sameGame = new SameGame(); - sameGame.setReferenceGame(referenceGame); - sameGame.setSourceGame(sourceGame); - sameGameRepository.save(sameGame); - - var sameGames = gameService.entitiesToGameDTO(gameRepository.getSimilarGames(referenceGameId)); - - return new ResponseEntity<>(sameGames, HttpStatus.OK); - } - - @Transactional - @DeleteMapping("/delete-similar/{referenceGameId}/{sourceGameId}") - @PreAuthorize("hasRole('USER') or hasRole('MODERATOR') or hasRole('ADMIN')") - public ResponseEntity> deleteSameGame(@PathVariable Integer referenceGameId, @PathVariable Integer sourceGameId) { - var sameGame = sameGameRepository.findSameGame_ByReferenceGameIdAndSourceGameId(referenceGameId, sourceGameId); - if (sameGame == null) { - return new ResponseEntity<>(null, HttpStatus.NOT_FOUND); - } - sameGameRepository.delete(sameGame); - - var sameGames = gameService.entitiesToGameDTO(gameRepository.getSimilarGames(referenceGameId)); - - return new ResponseEntity<>(sameGames, HttpStatus.OK); - } - - @Transactional - @GetMapping("/{gameId}/users-rating") - public ResponseEntity> getUsersRating(@PathVariable Integer gameId) { - - var ratings = gameService.usersGameRatingToDTO(userRepository.findGameRatings(gameId)); - - return new ResponseEntity<>(ratings, HttpStatus.OK); - } - - //Поменять на тип текст либо убрать аннотацию - - @Transactional - @PostMapping("/{gameId}/set-designer/{designerId}") - @PreAuthorize("hasRole('USER') or hasRole('MODERATOR') or hasRole('ADMIN')") - public ResponseEntity addDesignerToGame(@PathVariable Integer gameId, @PathVariable Integer designerId) { - var game = gameRepository.findGameById(gameId); - var designer = designerRepository.findDesignerById(designerId); - - if (game == null || designer == null){ - return new ResponseEntity<>(null, HttpStatus.NOT_FOUND); - } - - var gameByDesigner = new GameByDesigner(); - gameByDesigner.setDesigner(designer); - gameByDesigner.setGame(game); - - gameByDesignerRepository.save(gameByDesigner); - - var gameDTO = gameService.projectionsToGameDTO(gameRepository.findGameWithRating(gameId), - designerRepository.findDesignersUsingGame(gameId)); - - return new ResponseEntity<>(gameDTO, HttpStatus.OK); - } - - @Transactional - @DeleteMapping("{gameId}/remove-designer/{gameByDesignerId}") - @PreAuthorize("hasRole('USER') or hasRole('MODERATOR') or hasRole('ADMIN')") - public ResponseEntity deleteDesignerFromGame(@PathVariable Integer gameId, @PathVariable Integer gameByDesignerId) { - - gameByDesignerRepository.deleteById(gameByDesignerId); - - var gameDTO = gameService.projectionsToGameDTO(gameRepository.findGameWithRating(gameId), - designerRepository.findDesignersUsingGame(gameId)); - - return new ResponseEntity<>(gameDTO, HttpStatus.OK); - } - - @Transactional @GetMapping("/{userId}/games") public ResponseEntity> getUserCollection(@PathVariable Integer userId) { - var games = gameService.entitiesToGameDTO(gameRepository.findUserGames(userId)); - return new ResponseEntity<>(games, HttpStatus.OK); - } - - @GetMapping("/{userId}/games-rating") - public ResponseEntity> getUserRatingList(@PathVariable Integer userId) { - - var ratingGamesByUser = gameService.userGameRatingToGameDTO(gameRepository.findUserGameRatingList(userId)); - - return new ResponseEntity<>(ratingGamesByUser, HttpStatus.OK); - } - - @GetMapping("/{id}/wishlist") - public ResponseEntity> getUserWishlist(@PathVariable Integer id) { - var games = gameService.entitiesToGameDTO(gameRepository.findUserWishlist(id)); + var games = gameService.getUserCollection(userId); return new ResponseEntity<>(games, HttpStatus.OK); } - /* @GetMapping("{userId}/games-to-sell") - public ResponseEntity> getGameSellList(@PathVariable Integer userId) { - - var gameSellList = gameSellService.projectionsToGameSellDTO(gameRepository.getGameSellList(userId)); - - return new ResponseEntity<>(gameSellList, 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 index d540e46..08c4047 100644 --- a/src/main/java/com/petproject/boardgamefun/controller/GameSellController.java +++ b/src/main/java/com/petproject/boardgamefun/controller/GameSellController.java @@ -39,4 +39,11 @@ 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/RatingGameByUserController.java b/src/main/java/com/petproject/boardgamefun/controller/RatingGameByUserController.java index 724539b..e1a1d38 100644 --- a/src/main/java/com/petproject/boardgamefun/controller/RatingGameByUserController.java +++ b/src/main/java/com/petproject/boardgamefun/controller/RatingGameByUserController.java @@ -1,11 +1,15 @@ 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 { @@ -36,4 +40,18 @@ public ResponseEntity updateGameRating(@PathVariable Integer userId, @Pa 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/UserWishController.java b/src/main/java/com/petproject/boardgamefun/controller/UserWishController.java index d6d34da..8d20197 100644 --- a/src/main/java/com/petproject/boardgamefun/controller/UserWishController.java +++ b/src/main/java/com/petproject/boardgamefun/controller/UserWishController.java @@ -1,11 +1,14 @@ 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 { @@ -29,4 +32,10 @@ public ResponseEntity deleteGameFromUserWishlist(@PathVariable Integer userWi 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/service/DesignerService.java b/src/main/java/com/petproject/boardgamefun/service/DesignerService.java index e14cf62..44b888c 100644 --- a/src/main/java/com/petproject/boardgamefun/service/DesignerService.java +++ b/src/main/java/com/petproject/boardgamefun/service/DesignerService.java @@ -1,15 +1,58 @@ 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<>(); 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/GameSellService.java b/src/main/java/com/petproject/boardgamefun/service/GameSellService.java index dcea9e9..949683b 100644 --- a/src/main/java/com/petproject/boardgamefun/service/GameSellService.java +++ b/src/main/java/com/petproject/boardgamefun/service/GameSellService.java @@ -10,8 +10,6 @@ import com.petproject.boardgamefun.repository.GameSellRepository; import com.petproject.boardgamefun.repository.UserRepository; import com.petproject.boardgamefun.service.mappers.GameMapper; -import org.springframework.http.HttpStatus; -import org.springframework.http.ResponseEntity; import org.springframework.stereotype.Service; import javax.transaction.Transactional; @@ -81,6 +79,11 @@ public void updateGameSell(GameSell gameSell) { gameSellRepository.save(gameSell); } + @Transactional + public List getGameSellList(Integer userId) { + return projectionsToGameSellDTO(gameRepository.getGameSellList(userId)); + } + public GameSellDTO entityToGameSellDTO(Game game) { return new GameSellDTO(gameMapper.gameToGameDTO(game), null, null, null); } diff --git a/src/main/java/com/petproject/boardgamefun/service/GameService.java b/src/main/java/com/petproject/boardgamefun/service/GameService.java index a0abceb..01a8e53 100644 --- a/src/main/java/com/petproject/boardgamefun/service/GameService.java +++ b/src/main/java/com/petproject/boardgamefun/service/GameService.java @@ -4,10 +4,16 @@ 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; @@ -15,11 +21,72 @@ @Service public class GameService { - final - GameMapper gameMapper; + final GameMapper gameMapper; + final GameRepository gameRepository; + final DesignerRepository designerRepository; - public GameService(GameMapper gameMapper) { + 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) { diff --git a/src/main/java/com/petproject/boardgamefun/service/RatingGameByUserService.java b/src/main/java/com/petproject/boardgamefun/service/RatingGameByUserService.java index 995891c..4217f47 100644 --- a/src/main/java/com/petproject/boardgamefun/service/RatingGameByUserService.java +++ b/src/main/java/com/petproject/boardgamefun/service/RatingGameByUserService.java @@ -1,5 +1,7 @@ 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; @@ -9,6 +11,7 @@ import org.springframework.stereotype.Service; import javax.transaction.Transactional; +import java.util.List; @Service public class RatingGameByUserService { @@ -16,11 +19,13 @@ public class RatingGameByUserService { final RatingGameByUserRepository ratingGameByUserRepository; final GameRepository gameRepository; final UserRepository userRepository; + final GameService gameService; - public RatingGameByUserService(RatingGameByUserRepository ratingGameByUserRepository, GameRepository gameRepository, UserRepository userRepository) { + public RatingGameByUserService(RatingGameByUserRepository ratingGameByUserRepository, GameRepository gameRepository, UserRepository userRepository, GameService gameService) { this.ratingGameByUserRepository = ratingGameByUserRepository; this.gameRepository = gameRepository; this.userRepository = userRepository; + this.gameService = gameService; } @Transactional @@ -73,4 +78,13 @@ public Double updateGameRating(Integer userId, Integer gameId, Integer rating) { 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/UserWishService.java b/src/main/java/com/petproject/boardgamefun/service/UserWishService.java index 9319d6e..7878376 100644 --- a/src/main/java/com/petproject/boardgamefun/service/UserWishService.java +++ b/src/main/java/com/petproject/boardgamefun/service/UserWishService.java @@ -1,16 +1,16 @@ 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.http.HttpStatus; -import org.springframework.http.ResponseEntity; import org.springframework.stereotype.Service; import javax.transaction.Transactional; +import java.util.List; @Service public class UserWishService { @@ -18,11 +18,13 @@ public class UserWishService { final UserWishRepository userWishRepository; final UserRepository userRepository; final GameRepository gameRepository; + final GameService gameService; - public UserWishService(UserWishRepository userWishRepository, UserRepository userRepository, GameRepository gameRepository) { + public UserWishService(UserWishRepository userWishRepository, UserRepository userRepository, GameRepository gameRepository, GameService gameUserService) { this.userWishRepository = userWishRepository; this.userRepository = userRepository; this.gameRepository = gameRepository; + this.gameService = gameUserService; } @Transactional @@ -55,4 +57,9 @@ public void deleteGameFromUserWishlist(Integer userWishId) { } userWishRepository.delete(userWish.get()); } + + @Transactional + public List getUserWishList(Integer id){ + return gameService.entitiesToGameDTO(gameRepository.findUserWishlist(id)); + } } diff --git a/src/test/java/com/petproject/boardgamefun/controller/GameControllerTests.java b/src/test/java/com/petproject/boardgamefun/controller/GameControllerTests.java index 949c00f..ed85307 100644 --- a/src/test/java/com/petproject/boardgamefun/controller/GameControllerTests.java +++ b/src/test/java/com/petproject/boardgamefun/controller/GameControllerTests.java @@ -1,4 +1,4 @@ -/* + package com.petproject.boardgamefun.controller; import static org.mockito.Mockito.when; @@ -7,20 +7,18 @@ import com.fasterxml.jackson.databind.ObjectMapper; import com.petproject.boardgamefun.SpringSecurityWebTestConfig; -import com.petproject.boardgamefun.dto.DesignerDTO; import com.petproject.boardgamefun.dto.FilterGamesDTO; import com.petproject.boardgamefun.dto.GameDataDTO; -import com.petproject.boardgamefun.dto.RatingGameByUserDTO; -import com.petproject.boardgamefun.dto.projection.DesignersProjection; import com.petproject.boardgamefun.dto.projection.GameProjection; import com.petproject.boardgamefun.dto.projection.GamesFilterByTitleProjection; -import com.petproject.boardgamefun.dto.projection.UsersGameRatingProjection; +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.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; @@ -41,7 +39,392 @@ import java.util.ArrayList; import java.util.List; +//todo: Assertions.assertDoesNotThrow(() -> gameService.save(game);); +@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()); + verify(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()); + verify(gameService).checkExistence(any(Game.class)); + } + + @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)); + verify(gameService).save(any(Game.class)); + } + + @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()); + + verify(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()); + + verify(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()); + verify(gameService).save(any(Game.class)); + 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()); + verify(gameService).save(any(Game.class)); + } + + @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()); + verify(gameService).delete(any(Game.class)); + } + + @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()); + verify(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 diff --git a/src/test/java/com/petproject/boardgamefun/controller/UserControllerTests.java b/src/test/java/com/petproject/boardgamefun/controller/UserControllerTests.java index f59cd89..5b41174 100644 --- a/src/test/java/com/petproject/boardgamefun/controller/UserControllerTests.java +++ b/src/test/java/com/petproject/boardgamefun/controller/UserControllerTests.java @@ -326,6 +326,7 @@ public void registerUserShouldReturnBadRequest() throws Exception { 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 From fe80dbce95d2cb66ebd0ee9ccb4ecf82cbd0a9c8 Mon Sep 17 00:00:00 2001 From: "i.i.artamonov" Date: Mon, 19 Sep 2022 11:28:01 +0400 Subject: [PATCH 139/141] Changed verifies to assertions for throw errors In UserControllerTests and GameControllerTests change verify to assertions, dont know if it really needed... --- .../controller/GameControllerTests.java | 19 +++++++++---------- .../controller/UserControllerTests.java | 12 +++++++----- 2 files changed, 16 insertions(+), 15 deletions(-) diff --git a/src/test/java/com/petproject/boardgamefun/controller/GameControllerTests.java b/src/test/java/com/petproject/boardgamefun/controller/GameControllerTests.java index ed85307..bc9b287 100644 --- a/src/test/java/com/petproject/boardgamefun/controller/GameControllerTests.java +++ b/src/test/java/com/petproject/boardgamefun/controller/GameControllerTests.java @@ -186,7 +186,7 @@ public void getGameByIdShouldReturnOk() throws Exception { public void getGameByIdShouldReturnNotFound() throws Exception { when(gameService.getGameById(-1)).thenThrow(new NoRecordFoundException()); this.mockMvc.perform(MockMvcRequestBuilders.get(Gateway + "/-1")).andDo(print()).andExpect(status().isNotFound()); - verify(gameService).getGameById(-1); + Assertions.assertThrows(NoRecordFoundException.class, () -> gameService.getGameById(-1)); } @Test @@ -229,7 +229,7 @@ public void addGameShouldReturnBadRequest() throws Exception { 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.checkExistence(game)); } @Test @@ -241,7 +241,7 @@ public void addGameShouldReturnBadRequest_BadModel() throws Exception { .accept(MediaType.APPLICATION_JSON) .content(objectMapper.writeValueAsString(game))).andExpect(status().isBadRequest()); verify(gameService).checkExistence(any(Game.class)); - verify(gameService).save(any(Game.class)); + Assertions.assertThrows(BadRequestException.class, () -> gameService.save(game)); } @Test @@ -279,8 +279,7 @@ public void uploadImageShouldReturnNotFound() throws Exception { MockMvcRequestBuilders.multipart(Gateway + "/upload-image/-1"); mockMvc.perform(multipartRequest.file(multipartFile)) .andExpect(status().isNotFound()); - - verify(gameService).uploadImage(-1, multipartFile); + Assertions.assertThrows(NoRecordFoundException.class, () -> gameService.uploadImage(-1, multipartFile)); } @Test @@ -299,7 +298,7 @@ public void uploadImageShouldReturnBadRequest() throws Exception { mockMvc.perform(multipartRequest.file(multipartFile1)) .andExpect(status().isBadRequest()); - verify(gameService).uploadImage(1, multipartFile1); + Assertions.assertThrows(BadRequestException.class, () -> gameService.uploadImage(1, multipartFile1)); } @Test @@ -329,7 +328,7 @@ public void updateGameShouldReturnBadRequest() throws Exception { this.mockMvc.perform(MockMvcRequestBuilders.put(Gateway + "/").contentType(MediaType.APPLICATION_JSON) .accept(MediaType.APPLICATION_JSON) .content(objectMapper.writeValueAsString(game))).andExpect(status().isBadRequest()); - verify(gameService).save(any(Game.class)); + Assertions.assertThrows(BadRequestException.class, () -> gameService.save(game)); game.setId(1); } @@ -340,7 +339,7 @@ public void updateGameShouldReturnBadRequest_BadModel() throws Exception { this.mockMvc.perform(MockMvcRequestBuilders.put(Gateway + "/").contentType(MediaType.APPLICATION_JSON) .accept(MediaType.APPLICATION_JSON) .content(objectMapper.writeValueAsString(game))).andExpect(status().isBadRequest()); - verify(gameService).save(any(Game.class)); + Assertions.assertThrows(BadRequestException.class, () -> gameService.save(game)); } @Test @@ -377,7 +376,7 @@ public void removeGameFromSiteShouldReturnNotFound() throws Exception { this.mockMvc.perform(MockMvcRequestBuilders.delete(Gateway + "/").contentType(MediaType.APPLICATION_JSON) .accept(MediaType.APPLICATION_JSON) .content(objectMapper.writeValueAsString(game))).andExpect(status().isNotFound()); - verify(gameService).delete(any(Game.class)); + Assertions.assertThrows(NoRecordFoundException.class, () -> gameService.delete(game)); } @Test @@ -409,7 +408,7 @@ public void getUserCollectionShouldReturnOk() throws Exception { 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()); - verify(gameService).getUserCollection(-1); + Assertions.assertThrows(NoRecordFoundException.class, () ->gameService.getUserCollection(-1)); } @Test diff --git a/src/test/java/com/petproject/boardgamefun/controller/UserControllerTests.java b/src/test/java/com/petproject/boardgamefun/controller/UserControllerTests.java index 5b41174..1e9208f 100644 --- a/src/test/java/com/petproject/boardgamefun/controller/UserControllerTests.java +++ b/src/test/java/com/petproject/boardgamefun/controller/UserControllerTests.java @@ -248,6 +248,8 @@ public String getMessage() { .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 @@ -360,8 +362,7 @@ public void uploadAvatarShouldReturnNotFound() throws Exception { MockMvcRequestBuilders.multipart(Gateway + "/upload-avatar/" + "user.getName()"); mockMvc.perform(multipartRequest.file(multipartFile)) .andExpect(status().isNotFound()); - - verify(userService).uploadAvatar("user.getName()", multipartFile); + Assertions.assertThrows(NoRecordFoundException.class, () -> userService.uploadAvatar("user.getName()", multipartFile)); } @Test @@ -378,7 +379,7 @@ public void uploadAvatarShouldReturnBadRequest() throws Exception { mockMvc.perform(multipartRequest.file(multipartFile)) .andExpect(status().isBadRequest()); - verify(userService).uploadAvatar(user.getName(), multipartFile); + Assertions.assertThrows(BadRequestException.class, () -> userService.uploadAvatar(user.getName(), multipartFile)); } @Test @@ -400,7 +401,7 @@ public void editUserShouldReturnBadReqQuest() throws Exception { mockMvc.perform(MockMvcRequestBuilders.patch(Gateway + "/1").contentType(MediaType.APPLICATION_JSON) .accept(MediaType.APPLICATION_JSON) .content(objectMapper.writeValueAsString(userEditRequest))).andExpect(status().isBadRequest()); - verify(userService).editUser(1, userEditRequest); + Assertions.assertThrows(BadRequestException.class, () -> userService.editUser(1, userEditRequest)); } @Test @@ -424,13 +425,14 @@ public void changePasswordShouldReturnBadRequest() throws Exception { 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) + 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); From 86733dbe7dc4a6452004cc087d288c4e783636c9 Mon Sep 17 00:00:00 2001 From: "i.i.artamonov" Date: Mon, 19 Sep 2022 13:23:56 +0400 Subject: [PATCH 140/141] Added tests to Expansion Controller --- .../controller/ExpansionControllerTests.java | 187 ++++++++++++++++++ .../controller/GameControllerTests.java | 1 - 2 files changed, 187 insertions(+), 1 deletion(-) create mode 100644 src/test/java/com/petproject/boardgamefun/controller/ExpansionControllerTests.java 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 index bc9b287..eccd5a9 100644 --- a/src/test/java/com/petproject/boardgamefun/controller/GameControllerTests.java +++ b/src/test/java/com/petproject/boardgamefun/controller/GameControllerTests.java @@ -39,7 +39,6 @@ import java.util.ArrayList; import java.util.List; -//todo: Assertions.assertDoesNotThrow(() -> gameService.save(game);); @ExtendWith(MockitoExtension.class) @SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.MOCK, classes = SpringSecurityWebTestConfig.class) @AutoConfigureMockMvc From 2eeec6fe0ee230a0deb6e4205b37d3fd948ede3a Mon Sep 17 00:00:00 2001 From: "i.i.artamonov" Date: Tue, 20 Sep 2022 09:02:29 +0400 Subject: [PATCH 141/141] Added tests to GameSellController Added GameSellMapper --- .../boardgamefun/service/GameSellService.java | 3 + .../service/mappers/GameSellMapper.java | 17 ++ .../controller/GameSellControllerTests.java | 243 ++++++++++++++++++ 3 files changed, 263 insertions(+) create mode 100644 src/main/java/com/petproject/boardgamefun/service/mappers/GameSellMapper.java create mode 100644 src/test/java/com/petproject/boardgamefun/controller/GameSellControllerTests.java diff --git a/src/main/java/com/petproject/boardgamefun/service/GameSellService.java b/src/main/java/com/petproject/boardgamefun/service/GameSellService.java index 949683b..58a3305 100644 --- a/src/main/java/com/petproject/boardgamefun/service/GameSellService.java +++ b/src/main/java/com/petproject/boardgamefun/service/GameSellService.java @@ -81,6 +81,9 @@ public void updateGameSell(GameSell gameSell) { @Transactional public List getGameSellList(Integer userId) { + if (userId < 0){ + throw new NoRecordFoundException("User with id " + userId + " not found"); + } return projectionsToGameSellDTO(gameRepository.getGameSellList(userId)); } 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/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)); + } +}