From 3133aac7cb4e0140504c413aa0df37f91c54eab6 Mon Sep 17 00:00:00 2001 From: eugenp Date: Wed, 4 Mar 2015 16:02:58 +0200 Subject: [PATCH] error handling cleanup --- .../org/baeldung/web/RedditController.java | 59 ++++++++++++------- .../baeldung/web/RestExceptionHandler.java | 30 ++++++++-- 2 files changed, 64 insertions(+), 25 deletions(-) diff --git a/spring-security-oauth/src/main/java/org/baeldung/web/RedditController.java b/spring-security-oauth/src/main/java/org/baeldung/web/RedditController.java index e6dd16764c..5fb746551b 100644 --- a/spring-security-oauth/src/main/java/org/baeldung/web/RedditController.java +++ b/spring-security-oauth/src/main/java/org/baeldung/web/RedditController.java @@ -43,7 +43,7 @@ public class RedditController { private PostRepository postReopsitory; @RequestMapping("/info") - public final String getInfo(Model model) { + public final String getInfo(final Model model) { final JsonNode node = redditRestTemplate.getForObject("https://oauth.reddit.com/api/v1/me", JsonNode.class); final String name = node.get("name").asText(); addUser(name, redditRestTemplate.getAccessToken()); @@ -52,28 +52,19 @@ public class RedditController { } @RequestMapping("/submit") - public final String submit(Model model, @RequestParam Map formParams) { - final MultiValueMap param = new LinkedMultiValueMap(); - param.add(RedditApiConstants.API_TYPE, "json"); - param.add(RedditApiConstants.KIND, "link"); - param.add(RedditApiConstants.RESUBMIT, "true"); - param.add(RedditApiConstants.SENDREPLIES, "false"); - param.add(RedditApiConstants.THEN, "comments"); + public final String submit(final Model model, @RequestParam final Map formParams) { + final MultiValueMap param1 = constructParams(formParams); - for (final Map.Entry entry : formParams.entrySet()) { - param.add(entry.getKey(), entry.getValue()); - } - - logger.info("User submitting Link with these parameters: " + formParams.entrySet()); - final JsonNode node = redditRestTemplate.postForObject("https://oauth.reddit.com/api/submit", param, JsonNode.class); - logger.info("Full Reddit Response: " + node.toString()); + logger.info("Submitting Link with these parameters: " + param1); + final JsonNode node = redditRestTemplate.postForObject("https://oauth.reddit.com/api/submit", param1, JsonNode.class); + logger.info("Submitted Link - Full Response from Reddit: " + node.toString()); final String responseMsg = parseResponse(node); model.addAttribute("msg", responseMsg); return "submissionResponse"; } @RequestMapping("/post") - public final String showSubmissionForm(Model model) { + public final String showSubmissionForm(final Model model) { final String needsCaptchaResult = needsCaptcha(); if (needsCaptchaResult.equalsIgnoreCase("true")) { final String iden = getNewCaptcha(); @@ -83,7 +74,7 @@ public class RedditController { } @RequestMapping("/postSchedule") - public final String showSchedulePostForm(Model model) { + public final String showSchedulePostForm(final Model model) { final String needsCaptchaResult = needsCaptcha(); if (needsCaptchaResult.equalsIgnoreCase("true")) { model.addAttribute("msg", "Sorry, You do not have enought karma"); @@ -93,7 +84,7 @@ public class RedditController { } @RequestMapping("/schedule") - public final String schedule(Model model, @RequestParam Map formParams) throws ParseException { + public final String schedule(final Model model, @RequestParam final Map formParams) throws ParseException { logger.info("User scheduling Post with these parameters: " + formParams.entrySet()); final User user = userReopsitory.findByAccessToken(redditRestTemplate.getAccessToken().getValue()); final Post post = new Post(); @@ -115,7 +106,7 @@ public class RedditController { } @RequestMapping("/posts") - public final String getScheduledPosts(Model model) { + public final String getScheduledPosts(final Model model) { final User user = userReopsitory.findByAccessToken(redditRestTemplate.getAccessToken().getValue()); final List posts = postReopsitory.findByUser(user); model.addAttribute("posts", posts); @@ -124,6 +115,32 @@ public class RedditController { // === private + private final MultiValueMap constructParams(final Map formParams) { + final MultiValueMap param = new LinkedMultiValueMap(); + param.add(RedditApiConstants.API_TYPE, "json"); + param.add(RedditApiConstants.KIND, "link"); + param.add(RedditApiConstants.RESUBMIT, "true"); + param.add(RedditApiConstants.SENDREPLIES, "false"); + param.add(RedditApiConstants.THEN, "comments"); + for (final Map.Entry entry : formParams.entrySet()) { + param.add(entry.getKey(), entry.getValue()); + } + return param; + } + + private final Map constructParams2(final Map formParams) { + final Map param = new HashMap(); + param.put(RedditApiConstants.API_TYPE, "json"); + param.put(RedditApiConstants.KIND, "link"); + param.put(RedditApiConstants.RESUBMIT, "true"); + param.put(RedditApiConstants.SENDREPLIES, "false"); + param.put(RedditApiConstants.THEN, "comments"); + for (final Map.Entry entry : formParams.entrySet()) { + param.put(entry.getKey(), entry.getValue()); + } + return param; + } + private final String needsCaptcha() { final String result = redditRestTemplate.getForObject("https://oauth.reddit.com/api/needs_captcha.json", String.class); return result; @@ -138,7 +155,7 @@ public class RedditController { return split[split.length - 2]; } - private final String parseResponse(JsonNode node) { + private final String parseResponse(final JsonNode node) { String result = ""; final JsonNode errorNode = node.get("json").get("errors").get(0); if (errorNode != null) { @@ -155,7 +172,7 @@ public class RedditController { } } - private final void addUser(String name, OAuth2AccessToken token) { + private final void addUser(final String name, final OAuth2AccessToken token) { User user = userReopsitory.findByUsername(name); if (user == null) { user = new User(); diff --git a/spring-security-oauth/src/main/java/org/baeldung/web/RestExceptionHandler.java b/spring-security-oauth/src/main/java/org/baeldung/web/RestExceptionHandler.java index cf835d87d3..c96b7020a2 100644 --- a/spring-security-oauth/src/main/java/org/baeldung/web/RestExceptionHandler.java +++ b/spring-security-oauth/src/main/java/org/baeldung/web/RestExceptionHandler.java @@ -2,13 +2,17 @@ package org.baeldung.web; import java.io.Serializable; +import javax.servlet.http.HttpServletResponse; + import org.springframework.http.HttpHeaders; import org.springframework.http.HttpStatus; import org.springframework.http.ResponseEntity; +import org.springframework.security.oauth2.client.resource.OAuth2AccessDeniedException; import org.springframework.security.oauth2.client.resource.UserApprovalRequiredException; import org.springframework.security.oauth2.client.resource.UserRedirectRequiredException; import org.springframework.web.bind.annotation.ControllerAdvice; import org.springframework.web.bind.annotation.ExceptionHandler; +import org.springframework.web.client.HttpClientErrorException; import org.springframework.web.context.request.WebRequest; import org.springframework.web.servlet.mvc.method.annotation.ResponseEntityExceptionHandler; @@ -23,7 +27,25 @@ public class RestExceptionHandler extends ResponseEntityExceptionHandler impleme // API + // 4xx + + @ExceptionHandler({ OAuth2AccessDeniedException.class }) + public ResponseEntity handleOAuth2AccessDeniedException(final OAuth2AccessDeniedException ex, final WebRequest request) { + logger.error("403 Status Code", ex); + final String response = "Error Occurred - Forbidden: " + ex.getMessage(); + return handleExceptionInternal(ex, response, new HttpHeaders(), HttpStatus.FORBIDDEN, request); + } + + @ExceptionHandler({ HttpClientErrorException.class }) + public ResponseEntity handleHttpClientErrorException(final HttpClientErrorException ex, final WebRequest request) { + logger.error("400 Status Code", ex); + final String response = "Error Occurred - To Many Requests: " + ex.getMessage(); + return handleExceptionInternal(ex, response, new HttpHeaders(), HttpStatus.TOO_MANY_REQUESTS, request); + } + + // HttpClientErrorException // 500 + @ExceptionHandler({ UserApprovalRequiredException.class, UserRedirectRequiredException.class }) public ResponseEntity handleRedirect(final RuntimeException ex, final WebRequest request) { logger.info(ex.getLocalizedMessage()); @@ -31,10 +53,10 @@ public class RestExceptionHandler extends ResponseEntityExceptionHandler impleme } @ExceptionHandler({ Exception.class }) - public ResponseEntity handleInternal(final RuntimeException ex, final WebRequest request) { - logger.info(request.getHeader("x-ratelimit-remaining")); + public ResponseEntity handleInternal(final RuntimeException ex, final WebRequest request, final HttpServletResponse response) { + logger.info(response.getHeader("x-ratelimit-remaining")); logger.error("500 Status Code", ex); - final String response = "Error Occurred : " + ex.getMessage(); - return handleExceptionInternal(ex, response, new HttpHeaders(), HttpStatus.INTERNAL_SERVER_ERROR, request); + final String message = "Error Occurred: " + ex.getMessage(); + return handleExceptionInternal(ex, message, new HttpHeaders(), HttpStatus.INTERNAL_SERVER_ERROR, request); } } \ No newline at end of file