1 package usecase.vote;
2
3 import model.entity.*;
4 import model.repository.GenericRepository;
5 import model.validation.CommentExists;
6 import model.validation.PostExists;
7 import usecase.auth.AuthenticationRequired;
8 import usecase.auth.CurrentUser;
9
10 import javax.enterprise.context.ApplicationScoped;
11 import javax.inject.Inject;
12 import javax.transaction.Transactional;
13
14
15
16
17 @ApplicationScoped
18 @Transactional
19 public class VoteService {
20 private GenericRepository genericRepository;
21 private CurrentUser currentUser;
22
23 protected VoteService(){}
24
25 @Inject
26 protected VoteService(GenericRepository genericRepository, CurrentUser currentUser){
27 this.genericRepository = genericRepository;
28 this.currentUser = currentUser;
29 }
30
31
32
33
34
35 @AuthenticationRequired
36 public void upvoteComment(@CommentExists int id){
37 voteComment(id, (short) +1);
38 }
39
40
41
42
43
44 @AuthenticationRequired
45 public void downvoteComment(@CommentExists int id){
46 voteComment(id, (short) -1);
47 }
48
49
50
51
52
53 @AuthenticationRequired
54 public void upvotePost(@PostExists int id){
55 votePost(id, (short) +1);
56 }
57
58
59
60
61
62 @AuthenticationRequired
63 public void downvotePost(@PostExists int id){
64 votePost(id, (short) -1);
65 }
66
67
68
69
70
71 @AuthenticationRequired
72 public void unvoteComment(@CommentExists int id){
73 Comment comment = genericRepository.findById(Comment.class, id);
74 User user = genericRepository.findById(User.class, currentUser.getId());
75 CommentVote commentVote = comment.getVote(user);
76 if(commentVote != null)
77 genericRepository.remove(commentVote);
78 }
79
80
81
82
83
84 @AuthenticationRequired
85 public void unvotePost(@PostExists int id){
86 Post post = genericRepository.findById(Post.class,id);
87 User user = genericRepository.findById(User.class, currentUser.getId());
88
89 PostVote vote = post.getVote(user);
90 if(vote != null)
91 genericRepository.remove(vote);
92 }
93
94
95
96
97
98
99 private void votePost(int id, short vote){
100 Post post = genericRepository.findById(Post.class,id);
101 User user = genericRepository.findById(User.class, currentUser.getId());
102
103 PostVote postVote = new PostVote(user,post,vote);
104 genericRepository.merge(postVote);
105 }
106
107
108
109
110
111
112 private void voteComment(int id, short vote) {
113 Comment comment = genericRepository.findById(Comment.class,id);
114 User user = genericRepository.findById(User.class, currentUser.getId());
115
116 CommentVote commentVote = new CommentVote(user,comment, vote);
117 genericRepository.merge(commentVote);
118 }
119 }