View Javadoc
1   package usecase.post;
2   
3   import common.http.ParameterConverter;
4   import common.http.interceptor.InterceptableServlet;
5   import usecase.comment.CommentDTO;
6   import usecase.comment.CommentService;
7   
8   import javax.inject.Inject;
9   import javax.servlet.ServletException;
10  import javax.servlet.annotation.WebServlet;
11  import javax.servlet.http.HttpServletRequest;
12  import javax.servlet.http.HttpServletResponse;
13  import java.io.IOException;
14  import java.util.Collections;
15  import java.util.List;
16  import java.util.Map;
17  
18  /**
19   * Servlet per la visualizzazione di un post e i relativi commenti.
20   */
21  @WebServlet("/post")
22  class PostServlet extends InterceptableServlet {
23  
24      @Inject private PostService postService;
25      @Inject private CommentService service;
26  
27      @Override
28      public void init() throws ServletException {
29          getServletContext().setAttribute("maxCommentDepth", 3);
30      }
31  
32      @Override
33      protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
34          ParameterConverter converter = new ParameterConverter(req);
35          int postId = converter.getIntParameter("id").orElse(0); //viene ignorato se commentId != 0
36          int commentId = converter.getIntParameter("comment").orElse(0);
37  
38          PostPage post;
39          Map<Integer, List<CommentDTO>> comments;
40          int initialIndex;
41          if (commentId == 0) {
42              post = postService.getPost(postId);
43              comments = service.getPostComments(postId);
44              initialIndex = 0; //si parte dai root comments
45          } else{
46              comments = service.getReplies(commentId);
47              initialIndex = Collections.min(comments.keySet()); //il commento di partenza è quello all'indice più basso
48              postId = comments.get(initialIndex).get(0).getPostId(); //prendi un commento qualsiasi, ricava il postId
49              post = postService.getPost(postId);
50          }
51  
52          req.setAttribute("post", post);
53          req.setAttribute("comments", comments);
54          req.setAttribute("initialIndex", initialIndex);
55          req.getRequestDispatcher("/WEB-INF/views/section/post.jsp").forward(req, resp);
56      }
57  
58      @Override
59      protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
60          doGet(req, resp);
61      }
62  }