@RequestMapping(value = Constants.URI_API + Constants.URI_POSTS)
public class PostController {
private static final Logger log = LoggerFactory
.getLogger(PostController.class);
private BlogService blogService;
public PostController(BlogService blogService) {
this.blogService = blogService;
@RequestMapping(value = "", method = RequestMethod.GET)
public ResponseEntity<Page<PostDetails>> getAllPosts(
@RequestParam(value = "q", required = false) String keyword, //
@RequestParam(value = "status", required = false) Post.Status status, //
@PageableDefault(page = 0, size = 10, sort = "title", direction = Direction.DESC) Pageable page) {
Page<PostDetails> posts = blogService.searchPostsByCriteria(keyword, status, page);
log.debug("get posts size @" + posts.getTotalElements());
return new ResponseEntity<>(posts, HttpStatus.OK);
@RequestMapping(value = "/{id}", method = RequestMethod.GET)
public ResponseEntity<PostDetails> getPost(@PathVariable("id") Long id) {
log.debug("get postsinfo by id @" + id);
PostDetails post = blogService.findPostById(id);
log.debug("get post @" + post);
return new ResponseEntity<>(post, HttpStatus.OK);
@RequestMapping(value = "/{id}/comments", method = RequestMethod.GET)
public ResponseEntity<Page<CommentDetails>> getCommentsOfPost(
@PathVariable("id") Long id,
@PageableDefault(page = 0, size = 10, sort = "createdDate", direction = Direction.DESC) Pageable page) {
Page<CommentDetails> commentsOfPost = blogService.findCommentsByPostId(id, page);
log.debug("get post comment size @" + commentsOfPost.getTotalElements());
return new ResponseEntity<>(commentsOfPost, HttpStatus.OK);
@RequestMapping(value = "", method = RequestMethod.POST)
public ResponseEntity<ResponseMessage> createPost(@RequestBody @Valid PostForm post, BindingResult errResult) {
log.debug("create a new post");
if (errResult.hasErrors()) {
throw new InvalidRequestException(errResult);
PostDetails saved = blogService.savePost(post);
log.debug("saved post id is @" + saved.getId());
HttpHeaders headers = new HttpHeaders();
headers.setLocation(ServletUriComponentsBuilder.fromCurrentContextPath()
.path(Constants.URI_API + Constants.URI_POSTS + "/{id}")
.buildAndExpand(saved.getId())
return new ResponseEntity<>(ResponseMessage.success("post.created"), headers, HttpStatus.CREATED);
@RequestMapping(value = "/{id}", method = RequestMethod.DELETE)
public ResponseEntity<ResponseMessage> deletePostById(@PathVariable("id") Long id) {
log.debug("delete post by id @" + id);
blogService.deletePostById(id);
return new ResponseEntity<>(ResponseMessage.success("post.updated"), HttpStatus.NO_CONTENT);