From c954e48b5f82aaf2d20030021e507bdd04ae2fa7 Mon Sep 17 00:00:00 2001
From: Radheshhathwar <radheshhathwar.bh@gmail.com>
Date: Mon, 4 Dec 2023 12:31:46 +0530
Subject: [PATCH] Made changes in RedisUtil for MismatchedInputException

---
 .../exceptions/UserInfoFetchException.java    | 12 +++
 .../examsAndAdmissions/util/RedisUtil.java    | 76 ++++++++++++++-----
 2 files changed, 67 insertions(+), 21 deletions(-)
 create mode 100644 src/main/java/com/tarento/upsmf/examsAndAdmissions/exceptions/UserInfoFetchException.java

diff --git a/src/main/java/com/tarento/upsmf/examsAndAdmissions/exceptions/UserInfoFetchException.java b/src/main/java/com/tarento/upsmf/examsAndAdmissions/exceptions/UserInfoFetchException.java
new file mode 100644
index 0000000..144bac0
--- /dev/null
+++ b/src/main/java/com/tarento/upsmf/examsAndAdmissions/exceptions/UserInfoFetchException.java
@@ -0,0 +1,12 @@
+package com.tarento.upsmf.examsAndAdmissions.exceptions;
+
+public class UserInfoFetchException extends RuntimeException {
+
+    public UserInfoFetchException(String message) {
+        super(message);
+    }
+
+    public UserInfoFetchException(String message, Throwable cause) {
+        super(message, cause);
+    }
+}
diff --git a/src/main/java/com/tarento/upsmf/examsAndAdmissions/util/RedisUtil.java b/src/main/java/com/tarento/upsmf/examsAndAdmissions/util/RedisUtil.java
index 46d6983..b8a5bfb 100644
--- a/src/main/java/com/tarento/upsmf/examsAndAdmissions/util/RedisUtil.java
+++ b/src/main/java/com/tarento/upsmf/examsAndAdmissions/util/RedisUtil.java
@@ -1,21 +1,27 @@
 package com.tarento.upsmf.examsAndAdmissions.util;
 
+import com.fasterxml.jackson.core.JsonProcessingException;
 import com.fasterxml.jackson.databind.JsonNode;
 import com.fasterxml.jackson.databind.ObjectMapper;
 import com.fasterxml.jackson.databind.node.ObjectNode;
+import com.tarento.upsmf.examsAndAdmissions.exception.InvalidRequestException;
+import com.tarento.upsmf.examsAndAdmissions.exceptions.UserInfoFetchException;
 import com.tarento.upsmf.examsAndAdmissions.model.User;
+import org.apache.kafka.common.requests.DeleteAclsResponse;
 import org.springframework.beans.factory.annotation.Autowired;
 import org.springframework.beans.factory.annotation.Value;
 import org.springframework.data.redis.core.HashOperations;
 import org.springframework.http.*;
-import org.springframework.http.converter.json.MappingJackson2HttpMessageConverter;
 import org.springframework.stereotype.Component;
 import org.springframework.web.client.RestTemplate;
 
 import javax.annotation.Resource;
+import java.io.IOException;
 import java.util.ArrayList;
 import java.util.List;
 
+import static org.apache.kafka.common.requests.DeleteAclsResponse.log;
+
 @Component
 public class RedisUtil {
 
@@ -42,40 +48,68 @@ public class RedisUtil {
      * @return
      */
     public User getUserById(String id) {
-        if(id == null || id.isBlank()) {
-            throw new RuntimeException("Invalid Request");
+        try {
+            validateId(id);
+
+            // Check in Redis
+            if (Boolean.TRUE.equals(hashOperations.getOperations().hasKey(id))) {
+                return hashOperations.get(userRedisHashKey, id);
+            }
+
+            // Fetch user information from the external service
+            ResponseEntity<String> response = fetchUserInfoFromExternalService(id);
+            return handleUserInfoResponse(response, id);
+
+        } catch (Exception e) {
+            // Log the exception and rethrow a custom exception
+            log.error("Error in getting user info for ID: {}", id, e);
+            throw new UserInfoFetchException("Error in getting user info.", e);
         }
-        // check in redis
-        boolean keyExists = Boolean.TRUE.equals(hashOperations.getOperations().hasKey(id));
-        if(keyExists) {
-            return hashOperations.get(userRedisHashKey, id);
+    }
+
+    private void validateId(String id) {
+        if (id == null || id.isBlank()) {
+            throw new InvalidRequestException("Invalid user ID");
         }
-        ObjectNode request = mapper.createObjectNode();
+    }
+
+    private ResponseEntity<String> fetchUserInfoFromExternalService(String id) {
+        ObjectNode request = createUserInfoRequest(id);
+        HttpHeaders headers = new HttpHeaders();
+        headers.setContentType(MediaType.APPLICATION_JSON);
+
+        return restTemplate.exchange(userInfoUrl, HttpMethod.POST, new HttpEntity<>(request, headers), String.class);
+    }
+
+    private ObjectNode createUserInfoRequest(String id) {
         ObjectNode root = mapper.createObjectNode();
         root.put("userName", id);
+
+        ObjectNode request = mapper.createObjectNode();
         request.put("request", root);
-        HttpHeaders headers = new HttpHeaders();
-        headers.setContentType(MediaType.APPLICATION_JSON);
-        try {
-            restTemplate.getMessageConverters().add(new MappingJackson2HttpMessageConverter());
-            ResponseEntity<String> response = restTemplate.exchange(
-                    userInfoUrl, HttpMethod.POST,
-                    new HttpEntity<>(request, headers), String.class);
-            if (response.getStatusCode() == HttpStatus.OK) {
+
+        return request;
+    }
+
+    private User handleUserInfoResponse(ResponseEntity<String> response, String id) {
+        if (response.getStatusCode() == HttpStatus.OK) {
+            try {
                 JsonNode responseBody = mapper.readTree(response.getBody());
                 User user = mapper.treeToValue(responseBody, User.class);
-                if(user != null) {
+
+                if (user != null) {
                     hashOperations.put(userRedisHashKey, user.getId(), user);
                     return user;
                 }
+            } catch (IOException e) {
+                log.error("Error parsing user info response for ID: {}", id, e);
             }
-            throw new RuntimeException("Error in getting user info.");
-        } catch (Exception e) {
-            e.printStackTrace();
-            throw new RuntimeException("Error in getting user info.");
         }
+
+        throw new UserInfoFetchException("Error in getting user info. Status: " + response.getStatusCode());
     }
 
+
     /**
      * Method to roles from user
      * @param id
-- 
GitLab