From b73568fe17500765c33f6a062226e6b433412c49 Mon Sep 17 00:00:00 2001 From: Vitaly Takmazov Date: Wed, 24 Mar 2021 19:01:19 +0300 Subject: Cleanup HttpMediaTypeNotAcceptableException handler * move ExceptionHandler to ControllerAdvice * add test * reindent using VSCode --- src/main/java/com/juick/www/api/Index.java | 16 ++- src/main/java/com/juick/www/controllers/Site.java | 153 +++++++++------------- 2 files changed, 77 insertions(+), 92 deletions(-) (limited to 'src/main/java') diff --git a/src/main/java/com/juick/www/api/Index.java b/src/main/java/com/juick/www/api/Index.java index bafb6758..2d71683e 100644 --- a/src/main/java/com/juick/www/api/Index.java +++ b/src/main/java/com/juick/www/api/Index.java @@ -18,11 +18,18 @@ package com.juick.www.api; import io.swagger.v3.oas.annotations.Hidden; + +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; import org.springframework.http.HttpStatus; import org.springframework.http.ResponseEntity; +import org.springframework.web.HttpMediaTypeNotAcceptableException; +import org.springframework.web.bind.annotation.ControllerAdvice; +import org.springframework.web.bind.annotation.ExceptionHandler; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import org.springframework.web.bind.annotation.RestController; +import org.springframework.web.context.request.NativeWebRequest; import org.springframework.web.servlet.support.ServletUriComponentsBuilder; import java.net.URI; @@ -30,13 +37,20 @@ import java.net.URI; /** * Created by vitalyster on 25.07.2016. */ +@ControllerAdvice @RestController public class Index { - + private static final Logger logger = LoggerFactory.getLogger("API"); @Hidden @RequestMapping(value = { "/api/", "/ws/" }, method = RequestMethod.GET) public ResponseEntity description() { URI redirectUri = ServletUriComponentsBuilder.fromCurrentRequestUri().path("/swagger-ui.html").build().toUri(); return ResponseEntity.status(HttpStatus.MOVED_PERMANENTLY).location(redirectUri).build(); } + @ExceptionHandler(HttpMediaTypeNotAcceptableException.class) + public ResponseEntity invalidMediaType(final HttpMediaTypeNotAcceptableException exception, + final NativeWebRequest request) { + logger.info("Media type not resolved ({}) for url: {}", request.getHeaderValues("Accept"), ServletUriComponentsBuilder.fromCurrentRequestUri()); + return ResponseEntity.badRequest().body("Invalid media type"); + } } diff --git a/src/main/java/com/juick/www/controllers/Site.java b/src/main/java/com/juick/www/controllers/Site.java index ed8f951e..27e84001 100644 --- a/src/main/java/com/juick/www/controllers/Site.java +++ b/src/main/java/com/juick/www/controllers/Site.java @@ -30,21 +30,16 @@ import com.juick.util.MessageUtils; import org.apache.commons.lang3.StringUtils; import org.apache.commons.lang3.tuple.Pair; import org.apache.commons.text.StringEscapeUtils; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; import org.springframework.http.HttpStatus; import org.springframework.http.MediaType; import org.springframework.http.ResponseEntity; import org.springframework.stereotype.Controller; import org.springframework.ui.ModelMap; -import org.springframework.web.HttpMediaTypeNotAcceptableException; import org.springframework.web.bind.annotation.CookieValue; import org.springframework.web.bind.annotation.ExceptionHandler; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.PathVariable; import org.springframework.web.bind.annotation.RequestParam; -import org.springframework.web.context.request.NativeWebRequest; -import org.springframework.web.servlet.support.ServletUriComponentsBuilder; import javax.inject.Inject; import javax.servlet.http.HttpServletRequest; @@ -64,7 +59,6 @@ import java.util.stream.Collectors; */ @Controller public class Site { - private static final Logger logger = LoggerFactory.getLogger("Site"); @Inject private UserService userService; @Inject @@ -90,21 +84,19 @@ public class Site { model.addAttribute("statsMessages", userService.getStatsMessages(user.getUid())); model.addAttribute("statsReplies", userService.getStatsReplies(user.getUid())); model.addAttribute("iread", userService.getUserReadLeastPopular(user.getUid(), 8)); - model.addAttribute("tagStats", tagService.getUserTagStats(user.getUid()) - .stream().sorted((e1, e2) -> Integer.compare(e2.getUsageCount(), e1.getUsageCount())).limit(20).map(t -> t.getTag().getName()).collect(Collectors.toList())); + model.addAttribute("tagStats", + tagService.getUserTagStats(user.getUid()).stream() + .sorted((e1, e2) -> Integer.compare(e2.getUsageCount(), e1.getUsageCount())).limit(20) + .map(t -> t.getTag().getName()).collect(Collectors.toList())); } @GetMapping("/") - protected String doGet( - @Visitor User visitor, - Locale locale, - @RequestParam(required = false) String tag, + protected String doGet(@Visitor User visitor, Locale locale, @RequestParam(required = false) String tag, @RequestParam(name = "show", required = false) String paramShow, @RequestParam(name = "search", required = false) String paramSearch, @RequestParam(name = "before", required = false, defaultValue = "0") Integer paramBefore, @RequestParam(name = "to", required = false, defaultValue = "0") Long paramTo, - @RequestParam(name = "page", required = false, defaultValue = "0") Integer page, - ModelMap model) { + @RequestParam(name = "page", required = false, defaultValue = "0") Integer page, ModelMap model) { if (tag != null) { return "redirect:/tag/" + URLEncoder.encode(tag, StandardCharsets.UTF_8); } @@ -177,8 +169,8 @@ public class Site { model.addAttribute("headers", head); if (mids.size() >= 20) { String nextpage = paramSearch != null ? String.format("?page=%d", page + 1) - : (paramShow == null) ? "?to=" + msgs.get(msgs.size() - 1).getUpdated().toEpochMilli() - : "?before=" + mids.get(mids.size() - 1); + : (paramShow == null) ? "?to=" + msgs.get(msgs.size() - 1).getUpdated().toEpochMilli() + : "?before=" + mids.get(mids.size() - 1); if (paramShow != null) { nextpage += "&show=" + paramShow; } @@ -191,13 +183,10 @@ public class Site { } @GetMapping(path = "/{uname}/", headers = "Connection!=Upgrade") - protected String doGetBlog( - @Visitor User visitor, - @RequestParam(required = false, name = "show") String paramShow, + protected String doGetBlog(@Visitor User visitor, @RequestParam(required = false, name = "show") String paramShow, @RequestParam(required = false, name = "tag") String paramTagStr, @RequestParam(required = false, name = "search") String paramSearch, - @RequestParam(required = false, name = "page", defaultValue = "0") Integer page, - @PathVariable String uname, + @RequestParam(required = false, name = "page", defaultValue = "0") Integer page, @PathVariable String uname, @RequestParam(required = false, defaultValue = "0") Integer before, @CookieValue(name = "sape_cookie", required = false, defaultValue = StringUtils.EMPTY) String sapeCookie, ModelMap model) { @@ -241,7 +230,8 @@ public class Site { mids = messagesService.getUserTag(user.getUid(), paramTag.TID, privacy, before); } else if (paramSearch != null) { title = "Блог " + user.getName() + ": " + StringEscapeUtils.escapeHtml4(paramSearch); - mids = messagesService.getUserSearch(visitor, user.getUid(), WebUtils.encodeSphinx(paramSearch), privacy, page); + mids = messagesService.getUserSearch(visitor, user.getUid(), WebUtils.encodeSphinx(paramSearch), + privacy, page); } else { title = "Блог " + user.getName(); mids = messagesService.getUserBlog(user.getUid(), privacy, before); @@ -256,8 +246,8 @@ public class Site { throw new HttpNotFoundException(); } - String head = ""; + String head = ""; head += "\n"; if (paramTag != null && tagService.getTagNoIndex(paramTag.TID)) { head += ""; @@ -283,7 +273,8 @@ public class Site { model.addAttribute("msgs", msgs); model.addAttribute("headers", head); if (mids.size() >= 20) { - String nextpage = paramSearch != null ? String.format("?page=%d", page + 1) : "?before=" + mids.get(mids.size() - 1); + String nextpage = paramSearch != null ? String.format("?page=%d", page + 1) + : "?before=" + mids.get(mids.size() - 1); if (paramShow != null) { nextpage += "&show=" + paramShow; } @@ -299,9 +290,7 @@ public class Site { } @GetMapping("/{uname}/tags") - protected String doGetTags( - @Visitor User visitor, - @PathVariable String uname, ModelMap model) { + protected String doGetTags(@Visitor User visitor, @PathVariable String uname, ModelMap model) { User user = userService.getUserByName(uname); if (visitor.isBanned()) { throw new HttpNotFoundException(); @@ -312,16 +301,16 @@ public class Site { model.addAttribute("headers", ""); model.addAttribute("visitor", visitor); fillUserModel(model, user, visitor); - model.addAttribute("tags", tagService.getUserTagStats(user.getUid()).stream() - .sorted((e1, e2) -> Integer.compare(e2.getUsageCount(), e1.getUsageCount())).map(t -> t.getTag().getName()).collect(Collectors.toList())); + model.addAttribute("tags", + tagService.getUserTagStats(user.getUid()).stream() + .sorted((e1, e2) -> Integer.compare(e2.getUsageCount(), e1.getUsageCount())) + .map(t -> t.getTag().getName()).collect(Collectors.toList())); return "views/blog_tags"; } @GetMapping("/{uname}/friends") - protected String doGetFriends( - @Visitor User visitor, - @PathVariable String uname, ModelMap model) { + protected String doGetFriends(@Visitor User visitor, @PathVariable String uname, ModelMap model) { User user = userService.getUserByName(uname); if (visitor.isBanned()) { throw new HttpNotFoundException(); @@ -337,9 +326,7 @@ public class Site { } @GetMapping("/{uname}/readers") - protected String doGetReaders( - @Visitor User visitor, - @PathVariable String uname, ModelMap model) { + protected String doGetReaders(@Visitor User visitor, @PathVariable String uname, ModelMap model) { User user = userService.getUserByName(uname); visitor.setAvatar(webApp.getAvatarWebPath(visitor)); model.addAttribute("title", "Читатели " + user.getName()); @@ -352,9 +339,7 @@ public class Site { } @GetMapping("/{uname}/bl") - protected String doGetBL( - @Visitor User visitor, - @PathVariable String uname, ModelMap model) { + protected String doGetBL(@Visitor User visitor, @PathVariable String uname, ModelMap model) { User user = userService.getUserByName(uname); if (visitor.getUid() != user.getUid()) { throw new HttpForbiddenException(); @@ -368,13 +353,10 @@ public class Site { return "views/users"; } + @GetMapping("/tag/{tagName}") - protected String tagAction( - @Visitor User visitor, - HttpServletRequest request, - @PathVariable String tagName, - @RequestParam(required = false, defaultValue = "0") int before, - ModelMap model) { + protected String tagAction(@Visitor User visitor, HttpServletRequest request, @PathVariable String tagName, + @RequestParam(required = false, defaultValue = "0") int before, ModelMap model) { visitor.setAvatar(webApp.getAvatarWebPath(visitor)); String paramTagStr = StringEscapeUtils.unescapeHtml4(tagName); Tag paramTag = tagService.getTag(paramTagStr, false); @@ -382,13 +364,15 @@ public class Site { throw new HttpNotFoundException(); } else if (paramTag.SynonymID > 0 && paramTag.TID != paramTag.SynonymID) { Tag synTag = tagService.getTag(paramTag.SynonymID); - String url = "/tag/" + URLEncoder.encode(StringEscapeUtils.escapeHtml4(synTag.getName()), StandardCharsets.UTF_8); + String url = "/tag/" + + URLEncoder.encode(StringEscapeUtils.escapeHtml4(synTag.getName()), StandardCharsets.UTF_8); if (request.getQueryString() != null) { url += "?" + request.getQueryString(); } return "redirect:" + url; } else if (!paramTag.getName().equals(paramTagStr)) { - String url = "/tag/" + URLEncoder.encode(StringEscapeUtils.escapeHtml4(paramTag.getName()), StandardCharsets.UTF_8); + String url = "/tag/" + + URLEncoder.encode(StringEscapeUtils.escapeHtml4(paramTag.getName()), StandardCharsets.UTF_8); if (request.getQueryString() != null) { url += "?" + request.getQueryString(); } @@ -397,16 +381,15 @@ public class Site { String title = "*" + StringEscapeUtils.escapeHtml4(paramTag.getName()); model.addAttribute("title", title); - List mids = messagesService.getTag(paramTag.TID, visitor.getUid(), before, (visitor.isAnonymous()) ? 40 : 20); + List mids = messagesService.getTag(paramTag.TID, visitor.getUid(), before, + (visitor.isAnonymous()) ? 40 : 20); List msgs = messagesService.getMessages(visitor, mids); msgs.forEach(m -> m.getUser().setAvatar(webApp.getAvatarWebPath(m.getUser()))); if (!visitor.isAnonymous()) { List unread = messagesService.getUnread(visitor); visitor.setUnreadCount(unread.size()); - List blUIDs = userService.checkBL( - visitor.getUid(), - msgs.stream().map(m -> m.getUser().getUid()).collect(Collectors.toList()) - ); + List blUIDs = userService.checkBL(visitor.getUid(), + msgs.stream().map(m -> m.getUser().getUid()).collect(Collectors.toList())); msgs.forEach(m -> m.ReadOnly |= blUIDs.contains(m.getUser().getUid())); fillUserModel(model, visitor, visitor); } @@ -427,11 +410,13 @@ public class Site { model.addAttribute("isSubscribed", tagService.isSubscribed(visitor, paramTag)); model.addAttribute("isInBL", tagService.isInBL(visitor, paramTag)); if (mids.size() >= 20) { - String nextpage = "/tag/" + URLEncoder.encode(paramTag.getName(), StandardCharsets.UTF_8) + "?before=" + mids.get(mids.size() - 1); + String nextpage = "/tag/" + URLEncoder.encode(paramTag.getName(), StandardCharsets.UTF_8) + "?before=" + + mids.get(mids.size() - 1); model.addAttribute("nextpage", nextpage); } return "views/index"; } + @GetMapping("/pm/inbox") protected String doGetInbox(@Visitor User visitor, ModelMap model) { if (visitor.isAnonymous()) { @@ -450,10 +435,7 @@ public class Site { } @GetMapping("/pm/sent") - protected String doGetSent( - @Visitor User visitor, - @RequestParam(required = false) String uname, - ModelMap model) { + protected String doGetSent(@Visitor User visitor, @RequestParam(required = false) String uname, ModelMap model) { if (visitor.isAnonymous()) { return "redirect:/login"; } @@ -472,11 +454,9 @@ public class Site { model.addAttribute("uname", uname); return "views/pm_sent"; } + @GetMapping(value = "/{uname}/{mid}", produces = MediaType.TEXT_HTML_VALUE) - protected String threadAction( - @Visitor User visitor, - ModelMap model, - @PathVariable String uname, + protected String threadAction(@Visitor User visitor, ModelMap model, @PathVariable String uname, @PathVariable int mid, @CookieValue(name = "sape_cookie", required = false, defaultValue = StringUtils.EMPTY) String sapeCookie) { if (!messagesService.canViewThread(mid, visitor.getUid())) { @@ -513,13 +493,14 @@ public class Site { model.addAttribute("title", title); model.addAttribute("visitor", visitor); - String headers = ""; + String headers = ""; String pageUrl = "https://juick.com/" + msg.getUser().getName() + "/" + msg.getMid(); if (msg.Hidden) { headers += ""; } String cardType = StringUtils.isNotEmpty(msg.getAttachmentType()) ? "summary_large_image" : "summary"; - if (StringUtils.isNotEmpty(msg.getAttachmentType())) { + if (StringUtils.isNotEmpty(msg.getAttachmentType())) { // additional check in case of broken images if (msg.getAttachment() != null) { String msgImage = msg.getAttachment().getMedium().getUrl(); @@ -531,30 +512,27 @@ public class Site { } model.addAttribute("ogtype", "article"); String cardDescription = StringEscapeUtils.escapeHtml4(PlainTextFormatter.formatTwitterCard(msg)); - headers += "\n" + - "\n" + - "\n" + - "\n" + - "\n" + - "\n"; + headers += "\n" + + "\n" + "\n" + "\n" + "\n" + + "\n"; String twitterName = crosspostService.getTwitterName(msg.getUser().getUid()); if (StringUtils.isNotEmpty(twitterName)) { headers += "\n"; } if (msg.getTags().size() > 0) { - headers += "\n"; + headers += "\n"; } model.addAttribute("headers", headers); model.addAttribute("visitorSubscribed", messagesService.isSubscribed(visitor.getUid(), msg.getMid())); - model.addAttribute("visitorInBL", userService.isInBL(msg.getUser().getUid(), visitor.getUid())); - model.addAttribute("recomm", messagesService.getMessagesRecommendations( - Collections.singletonList(msg.getMid())).stream() - .map(Pair::getRight).collect(Collectors.toList())); + model.addAttribute("visitorInBL", userService.isInBL(msg.getUser().getUid(), visitor.getUid())); + model.addAttribute("recomm", messagesService.getMessagesRecommendations(Collections.singletonList(msg.getMid())) + .stream().map(Pair::getRight).collect(Collectors.toList())); List blUIDs = new ArrayList<>(); for (Message reply : replies) { - if (reply.getUser().getUid() != msg.getUser().getUid() - && !blUIDs.contains(reply.getUser().getUid())) { + if (reply.getUser().getUid() != msg.getUser().getUid() && !blUIDs.contains(reply.getUser().getUid())) { blUIDs.add(reply.getUser().getUid()); } reply.VisitorCanComment = !visitor.isAnonymous(); @@ -562,8 +540,8 @@ public class Site { if (!visitor.isAnonymous()) { boolean isMsgAuthor = visitor.getUid() == msg.getUser().getUid(); boolean isReplyAuthor = visitor.getUid() == reply.getUser().getUid(); - reply.VisitorCanComment = isMsgAuthor || (!msg.ReadOnly - && msg.VisitorCanComment && (isReplyAuthor || !userService.isInBL(visitor.getUid(), reply.getUser().getUid()))); + reply.VisitorCanComment = isMsgAuthor || (!msg.ReadOnly && msg.VisitorCanComment + && (isReplyAuthor || !userService.isInBL(visitor.getUid(), reply.getUser().getUid()))); } } model.addAttribute("replies", replies); @@ -571,9 +549,7 @@ public class Site { } @GetMapping("/post") - protected String postAction( - @Visitor User visitor, - @RequestParam(required = false) String body, ModelMap model) { + protected String postAction(@Visitor User visitor, @RequestParam(required = false) String body, ModelMap model) { fillUserModel(model, visitor, visitor); visitor.setAvatar(webApp.getAvatarWebPath(visitor)); model.addAttribute("title", "Написать"); @@ -590,8 +566,10 @@ public class Site { model.addAttribute("body", body); model.addAttribute("visitor", visitor); model.addAttribute("user", visitor); - model.addAttribute("tags", tagService.getUserTagStats(visitor.getUid()).stream() - .sorted((e1, e2) -> Integer.compare(e2.getUsageCount(), e1.getUsageCount())).map(t -> t.getTag().getName()).collect(Collectors.toList())); + model.addAttribute("tags", + tagService.getUserTagStats(visitor.getUid()).stream() + .sorted((e1, e2) -> Integer.compare(e2.getUsageCount(), e1.getUsageCount())) + .map(t -> t.getTag().getName()).collect(Collectors.toList())); return "views/post"; } @@ -600,11 +578,4 @@ public class Site { public ResponseEntity notFoundAction() { return new ResponseEntity<>(HttpStatus.NOT_FOUND); } - - @ExceptionHandler(HttpMediaTypeNotAcceptableException.class) - public ResponseEntity invalidMediaType(final HttpMediaTypeNotAcceptableException exception, - final NativeWebRequest request) { - logger.info("Invalid media type {}, url: {}", request.getHeaderValues("Content-Type"), ServletUriComponentsBuilder.fromCurrentRequestUri()); - return new ResponseEntity<>(HttpStatus.BAD_REQUEST); - } } -- cgit v1.2.3