diff --git a/pom.xml b/pom.xml index d9a1c97..2145c8e 100644 --- a/pom.xml +++ b/pom.xml @@ -21,7 +21,16 @@ UTF-8 2.8.1 - + + + github + https://maven.pkg.github.com/karthik-tarento/cb-common-util + + true + + + + org.springframework.boot @@ -209,22 +218,27 @@ jedis 4.4.3 - - org.elasticsearch - elasticsearch - 6.8.0 - - - org.elasticsearch.client - elasticsearch-rest-high-level-client - 6.8.0 - - - org.elasticsearch - elasticsearch - - - + + org.elasticsearch + elasticsearch + 6.8.0 + + + org.elasticsearch.client + elasticsearch-rest-high-level-client + 6.8.0 + + + org.elasticsearch + elasticsearch + + + + + org.igot + common-util + 1.0.0 + diff --git a/src/main/java/com/igot/cb/common/OutboundRequestHandlerServiceImpl.java b/src/main/java/com/igot/cb/common/OutboundRequestHandlerServiceImpl.java index 5be466e..3f64c7f 100644 --- a/src/main/java/com/igot/cb/common/OutboundRequestHandlerServiceImpl.java +++ b/src/main/java/com/igot/cb/common/OutboundRequestHandlerServiceImpl.java @@ -42,7 +42,7 @@ public Object fetchUsingGetWithHeadersProfile(String uri, Map he } HttpHeaders headers = new HttpHeaders(); if (!CollectionUtils.isEmpty(headersValues)) { - headersValues.forEach((k, v) -> headers.set(k, v)); + headersValues.forEach(headers::set); } HttpEntity entity = new HttpEntity<>(headers); response = restTemplate.exchange(uri, HttpMethod.GET, entity, Map.class).getBody(); @@ -52,6 +52,7 @@ public Object fetchUsingGetWithHeadersProfile(String uri, Map he new TypeReference>() { }); } catch (Exception e1) { + log.error("Error parsing response body from HttpClientErrorException", e1); } log.error("Error received: " + e.getResponseBodyAsString(), e); } catch (Exception e) { @@ -59,6 +60,7 @@ public Object fetchUsingGetWithHeadersProfile(String uri, Map he try { log.warn("Error Response: " + mapper.writeValueAsString(response)); } catch (Exception e1) { + log.error("Error parsing response body from Exception", e1); } } return response; @@ -69,7 +71,7 @@ public Map fetchResultUsingPatch(String uri, Object request, Map try { HttpHeaders headers = new HttpHeaders(); if (!CollectionUtils.isEmpty(headersValues)) { - headersValues.forEach((k, v) -> headers.set(k, v)); + headersValues.forEach(headers::set); } headers.setContentType(MediaType.APPLICATION_JSON); HttpEntity entity = new HttpEntity<>(request, headers); @@ -86,6 +88,7 @@ public Map fetchResultUsingPatch(String uri, Object request, Map new TypeReference>() { }); } catch (Exception e1) { + log.error("Error parsing response body from HttpClientErrorException", e1); } log.error("Error received: " + e.getResponseBodyAsString(), e); } @@ -104,6 +107,7 @@ private void logDetails(String uri, Object objectDetails) { .append(System.lineSeparator()); log.debug(str.toString()); } catch (JsonProcessingException je) { + log.error("Error parsing request/response body", je); } } } diff --git a/src/main/java/com/igot/cb/exceptions/ProjectCommonException.java b/src/main/java/com/igot/cb/exceptions/ProjectCommonException.java index fd4be25..b44d306 100644 --- a/src/main/java/com/igot/cb/exceptions/ProjectCommonException.java +++ b/src/main/java/com/igot/cb/exceptions/ProjectCommonException.java @@ -73,10 +73,6 @@ public void setResponseCode(ResponseCode responseCode) { this.responseCode = responseCode; } - public String getErrorMessage() { - return errorMessage; - } - public void setErrorMessage(String errorMessage) { this.errorMessage = errorMessage; } @@ -133,7 +129,7 @@ public static void throwServerErrorException(ResponseCode responseCode, String e throw new ProjectCommonException( responseCode, StringUtils.isBlank(exceptionMessage) ? responseCode.getErrorMessage() : exceptionMessage, - ResponseCode.SERVER_ERROR.getResponseCode()); + ResponseCode.SERVER_ERROR.getHttpStatusCode()); } public static void throwServerErrorException(ResponseCode responseCode) { diff --git a/src/main/java/com/igot/cb/exceptions/ResponseCode.java b/src/main/java/com/igot/cb/exceptions/ResponseCode.java index 7f702a5..bfe786d 100644 --- a/src/main/java/com/igot/cb/exceptions/ResponseCode.java +++ b/src/main/java/com/igot/cb/exceptions/ResponseCode.java @@ -10,18 +10,18 @@ */ @Getter public enum ResponseCode { - unAuthorized(ResponseMessage.Key.UNAUTHORIZED_USER, ResponseMessage.Message.UNAUTHORIZED_USER), - internalError(ResponseMessage.Key.INTERNAL_ERROR, ResponseMessage.Message.INTERNAL_ERROR), - resourceNotFound( + UNAUTHORIZED(ResponseMessage.Key.UNAUTHORIZED_USER, ResponseMessage.Message.UNAUTHORIZED_USER), + INTERNAL_SERVER_ERROR(ResponseMessage.Key.INTERNAL_ERROR, ResponseMessage.Message.INTERNAL_ERROR), + RESOURCE_NOT_FOUND( ResponseMessage.Key.RESOURCE_NOT_FOUND, ResponseMessage.Message.RESOURCE_NOT_FOUND), - invalidParameterValue( + INVALID_PARAMETER_VALUE( ResponseMessage.Key.INVALID_PARAMETER_VALUE, ResponseMessage.Message.INVALID_PARAMETER_VALUE), OK(200), CLIENT_ERROR(400), SERVER_ERROR(500); @Setter - private int responseCode; + private int httpStatusCode; /** * error code contains String value */ @@ -40,8 +40,8 @@ public enum ResponseCode { this.errorMessage = errorMessage; } - ResponseCode(int responseCode) { - this.responseCode = responseCode; + ResponseCode(int httpStatusCode) { + this.httpStatusCode = httpStatusCode; } /** @@ -51,7 +51,7 @@ public static ResponseCode getResponse(String errorCode) { if (StringUtils.isBlank(errorCode)) { return null; } else if (Constants.UNAUTHORIZED.equals(errorCode)) { - return ResponseCode.unAuthorized; + return ResponseCode.UNAUTHORIZED; } else { ResponseCode value = null; ResponseCode[] responseCodes = ResponseCode.values(); @@ -63,9 +63,4 @@ public static ResponseCode getResponse(String errorCode) { return value; } } - - public String getMessage(int errorCode) { - return ""; - } - } \ No newline at end of file diff --git a/src/main/java/com/igot/cb/profile/controller/ProfileController.java b/src/main/java/com/igot/cb/profile/controller/ProfileController.java index fba2ce9..ae2719e 100644 --- a/src/main/java/com/igot/cb/profile/controller/ProfileController.java +++ b/src/main/java/com/igot/cb/profile/controller/ProfileController.java @@ -1,8 +1,9 @@ package com.igot.cb.profile.controller; import com.igot.cb.profile.service.ProfileService; -import com.igot.cb.util.ApiResponse; import com.igot.cb.util.Constants; + +import org.igot.common.model.ApiResponse; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.http.HttpStatus; import org.springframework.http.ResponseEntity; @@ -18,7 +19,7 @@ public class ProfileController { private ProfileService profileService; @PostMapping("/extended") - public ResponseEntity saveExtendedProfile( + public ResponseEntity saveExtendedProfile( @RequestHeader(value = Constants.X_AUTH_TOKEN, required = true) String authToken, @RequestBody Map request) throws Exception { ApiResponse response = profileService.saveExtendedProfile(request, authToken); @@ -62,7 +63,7 @@ public ResponseEntity getAchievements(@PathVariable(Constants.USER_ID_RQ } @PutMapping("/extended") - public ResponseEntity updateExtendedProfile( + public ResponseEntity updateExtendedProfile( @RequestHeader(value = Constants.X_AUTH_TOKEN, required = true) String authToken, @RequestBody Map request) throws Exception { ApiResponse response = profileService.updateExtendedProfile(request, authToken); @@ -70,7 +71,7 @@ public ResponseEntity updateExtendedProfile( } @DeleteMapping("/extended") - public ResponseEntity deleteExtendedProfile( + public ResponseEntity deleteExtendedProfile( @RequestHeader(value = Constants.X_AUTH_TOKEN, required = true) String authToken, @RequestBody Map request) { diff --git a/src/main/java/com/igot/cb/profile/service/ProfileService.java b/src/main/java/com/igot/cb/profile/service/ProfileService.java index 453fa66..3649fe5 100644 --- a/src/main/java/com/igot/cb/profile/service/ProfileService.java +++ b/src/main/java/com/igot/cb/profile/service/ProfileService.java @@ -1,9 +1,9 @@ package com.igot.cb.profile.service; -import com.igot.cb.util.ApiResponse; - import java.util.Map; +import org.igot.common.model.ApiResponse; + public interface ProfileService { ApiResponse saveExtendedProfile(Map request, String userToken); diff --git a/src/main/java/com/igot/cb/profile/service/ProfileServiceImpl.java b/src/main/java/com/igot/cb/profile/service/ProfileServiceImpl.java index 0d0cce4..cb58463 100644 --- a/src/main/java/com/igot/cb/profile/service/ProfileServiceImpl.java +++ b/src/main/java/com/igot/cb/profile/service/ProfileServiceImpl.java @@ -21,10 +21,12 @@ import java.util.stream.Stream; import com.igot.cb.common.OutboundRequestHandlerServiceImpl; -import com.igot.cb.util.*; import org.apache.commons.collections4.CollectionUtils; import org.apache.commons.collections4.MapUtils; import org.apache.commons.lang3.StringUtils; +import org.igot.common.model.ApiResponse; +import org.igot.common.util.AccessTokenValidator; +import org.igot.common.util.ProjectUtil; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Value; import org.springframework.http.HttpStatus; @@ -34,13 +36,16 @@ import com.fasterxml.jackson.core.type.TypeReference; import com.fasterxml.jackson.databind.JsonNode; import com.fasterxml.jackson.databind.ObjectMapper; -import com.igot.cb.authentication.util.AccessTokenValidator; import com.igot.cb.profile.entity.CustomFieldEntity; import com.igot.cb.profile.repository.CustomFieldRepository; import com.igot.cb.transactional.cassandrautils.CassandraOperation; import com.igot.cb.transactional.elasticsearch.service.EsUtilServiceImpl; import com.igot.cb.transactional.redis.cache.CacheService; import com.igot.cb.transactional.service.RequestHandlerServiceImpl; +import com.igot.cb.util.CbServerProperties; +import com.igot.cb.util.Constants; +import com.igot.cb.util.ProfilePreference; +import com.igot.cb.util.UserUtility; import lombok.extern.slf4j.Slf4j; @@ -88,25 +93,29 @@ public class ProfileServiceImpl implements ProfileService { @Override public ApiResponse saveExtendedProfile(Map request, String userToken) { - ApiResponse response = ProjectUtil.createDefaultResponse("api.extendedProfile.create"); + ApiResponse response = projectUtil.createDefaultResponse("api.extendedProfile.create"); Map requestData = (Map) request.get(Constants.REQUEST); String userId = (String) requestData.get(Constants.USER_ID_RQST); - String userIdFromToken = accessTokenValidator.fetchUserIdFromAccessToken(userToken); + String userIdFromToken = accessTokenValidator.fetchUserIdFromAccessToken(userToken, response); + if (StringUtils.isBlank(userIdFromToken)) { + return response; + } + if (!StringUtils.equalsIgnoreCase(userIdFromToken, userId)) { - ProjectUtil.errorResponse(response, "Invalid UserId in the request", HttpStatus.BAD_REQUEST); + projectUtil.errorResponse(response, Constants.INVALID_USERID, HttpStatus.BAD_REQUEST); return response; } String validationError = validateRequestContextTypes(requestData, serverConfig.getContextType()); if (StringUtils.isNotBlank(validationError)) { - ProjectUtil.errorResponse(response, validationError, HttpStatus.BAD_REQUEST); + projectUtil.errorResponse(response, validationError, HttpStatus.BAD_REQUEST); return response; } String errMsg = validateUserExtendedProfileRequest(requestData); if (StringUtils.isNotBlank(errMsg)) { - ProjectUtil.errorResponse(response, errMsg, HttpStatus.BAD_REQUEST); + projectUtil.errorResponse(response, errMsg, HttpStatus.BAD_REQUEST); return response; } @@ -125,14 +134,14 @@ public ApiResponse saveExtendedProfile(Map request, String userT existingList.addAll(dataWithUUIDs); } - //sortContextData(existingList, contextType); + if (!saveContextData(userId, contextType, existingList)) { - ProjectUtil.errorResponse(response, "Failed to save data for contextType: " + contextType, + projectUtil.errorResponse(response, "Failed to save data for contextType: " + contextType, HttpStatus.INTERNAL_SERVER_ERROR); return response; } - cacheService.putCache(buildCacheKey("user:extendedProfile", contextType, userId), existingList); + cacheService.putCache(buildCacheKey(Constants.USER_EXTENDED_PROFILE, contextType, userId), existingList); updateExtendedProfileAllCache(userId, contextType, existingList); savedDataWithUUIDs.addAll(dataWithUUIDs); } @@ -144,13 +153,17 @@ public ApiResponse saveExtendedProfile(Map request, String userT @Override public ApiResponse updateExtendedProfile(Map request, String userToken) { - ApiResponse response = ProjectUtil.createDefaultResponse("api.extendedProfile.update"); + ApiResponse response = projectUtil.createDefaultResponse("api.extendedProfile.update"); Map requestData = (Map) request.get(Constants.REQUEST); String userId = (String) requestData.get(Constants.USER_ID_RQST); - String userIdFromToken = accessTokenValidator.fetchUserIdFromAccessToken(userToken); + String userIdFromToken = accessTokenValidator.fetchUserIdFromAccessToken(userToken, response); + + if (StringUtils.isBlank(userIdFromToken)) { + return response; + } if (!StringUtils.equalsIgnoreCase(userIdFromToken, userId)) { - ProjectUtil.errorResponse(response, "Invalid UserId in the request", HttpStatus.BAD_REQUEST); + projectUtil.errorResponse(response, Constants.INVALID_USERID, HttpStatus.BAD_REQUEST); return response; } @@ -169,25 +182,25 @@ public ApiResponse updateExtendedProfile(Map request, String use if (uuid != null && dataMap.containsKey(uuid)) { dataMap.get(uuid).putAll(item); } else { - ProjectUtil.errorResponse(response, "Invalid or missing UUID in incoming data.", + projectUtil.errorResponse(response, "Invalid or missing UUID in incoming data.", HttpStatus.BAD_REQUEST); return response; } } List> mergedList = new ArrayList<>(dataMap.values()); - //sortContextData(mergedList, contextType); + if (Constants.ACHIEVEMENTS.equalsIgnoreCase(contextType)) { mergeAndSortByIssuedDateOrTitle(mergedList, new ArrayList<>()); } if (!saveContextData(userId, contextType, mergedList)) { - ProjectUtil.errorResponse(response, "Failed to update data for contextType: " + contextType, + projectUtil.errorResponse(response, "Failed to update data for contextType: " + contextType, HttpStatus.INTERNAL_SERVER_ERROR); return response; } - cacheService.putCache(buildCacheKey("user:extendedProfile", contextType, userId), mergedList); + cacheService.putCache(buildCacheKey(Constants.USER_EXTENDED_PROFILE, contextType, userId), mergedList); updateExtendedProfileAllCache(userId, contextType, mergedList); } @@ -198,13 +211,17 @@ public ApiResponse updateExtendedProfile(Map request, String use @Override public ApiResponse deleteExtendedProfile(Map request, String userToken) { - ApiResponse response = ProjectUtil.createDefaultResponse("api.extendedProfile.delete"); + ApiResponse response = projectUtil.createDefaultResponse("api.extendedProfile.delete"); Map requestData = (Map) request.get(Constants.REQUEST); String userId = (String) requestData.get(Constants.USER_ID_RQST); - String userIdFromToken = accessTokenValidator.fetchUserIdFromAccessToken(userToken); + String userIdFromToken = accessTokenValidator.fetchUserIdFromAccessToken(userToken, response); + if (StringUtils.isBlank(userIdFromToken)) { + return response; + } + if (!StringUtils.equalsIgnoreCase(userIdFromToken, userId)) { - ProjectUtil.errorResponse(response, "Invalid UserId in the request", HttpStatus.BAD_REQUEST); + projectUtil.errorResponse(response, Constants.INVALID_USERID, HttpStatus.BAD_REQUEST); return response; } @@ -220,15 +237,15 @@ public ApiResponse deleteExtendedProfile(Map request, String use List> existingData = getExistingContextData(userId, contextType); existingData.removeIf(e -> uuids.contains(e.get(Constants.UUID))); - //sortContextData(existingData, contextType); + if (!saveContextData(userId, contextType, existingData)) { - ProjectUtil.errorResponse(response, "Failed to delete data for contextType: " + contextType, + projectUtil.errorResponse(response, "Failed to delete data for contextType: " + contextType, HttpStatus.INTERNAL_SERVER_ERROR); return response; } - cacheService.putCache(buildCacheKey("user:extendedProfile", contextType, userId), existingData); + cacheService.putCache(buildCacheKey(Constants.USER_EXTENDED_PROFILE, contextType, userId), existingData); updateExtendedProfileAllCache(userId, contextType, existingData); } @@ -239,14 +256,14 @@ public ApiResponse deleteExtendedProfile(Map request, String use @Override public ApiResponse getExtendedProfileSummary(String userId, String userToken) { - ApiResponse response = ProjectUtil.createDefaultResponse("api.extendedProfile.read"); + ApiResponse response = projectUtil.createDefaultResponse("api.extendedProfile.read"); - if (accessTokenValidator.fetchUserIdFromAccessToken(userToken) == null) { - ProjectUtil.errorResponse(response, "Invalid UserId in the request", HttpStatus.BAD_REQUEST); + if (accessTokenValidator.fetchUserIdFromAccessToken(userToken, response) == null) { + projectUtil.errorResponse(response, Constants.INVALID_USERID, HttpStatus.BAD_REQUEST); return response; } - String redisKey = buildCacheKey("user:extendedProfile", "all", userId); + String redisKey = buildCacheKey(Constants.USER_EXTENDED_PROFILE, "all", userId); try { String cachedJson = cacheService.getCache(redisKey); if (cachedJson != null) { @@ -266,13 +283,13 @@ public ApiResponse getExtendedProfileSummary(String userId, String userToken) { if (!data.isEmpty()) { Map contextSummary = new HashMap<>(); contextSummary.put(Constants.COUNT, data.size()); - contextSummary.put(Constants.DATA, data.stream().limit(2).collect(Collectors.toList())); + contextSummary.put(Constants.DATA, data.stream().limit(2).toList()); result.put(contextType, contextSummary); } } if (result.isEmpty()) { - ProjectUtil.errorResponse(response, "No data found for user.", HttpStatus.NO_CONTENT); + projectUtil.errorResponse(response, "No data found for user.", HttpStatus.NO_CONTENT); return response; } @@ -290,15 +307,14 @@ public ApiResponse getExtendedProfileSummary(String userId, String userToken) { @Override public ApiResponse readFullExtendedProfile(String userId, String contextType, String userToken) { - ApiResponse response = ProjectUtil.createDefaultResponse("api.extendedProfile.read"); - String userIdFromToken = accessTokenValidator.fetchUserIdFromAccessToken(userToken); + ApiResponse response = projectUtil.createDefaultResponse("api.extendedProfile.read"); + String userIdFromToken = accessTokenValidator.fetchUserIdFromAccessToken(userToken, response); if (userIdFromToken == null) { - ProjectUtil.errorResponse(response, "Invalid UserId in the request", HttpStatus.BAD_REQUEST); return response; } - String redisKey = buildCacheKey("user:extendedProfile", contextType, userId); + String redisKey = buildCacheKey(Constants.USER_EXTENDED_PROFILE, contextType, userId); List> contextData = null; try { @@ -313,7 +329,7 @@ public ApiResponse readFullExtendedProfile(String userId, String contextType, St if (contextData == null) { contextData = getExistingContextData(userId, contextType); if (contextData == null || contextData.isEmpty()) { - ProjectUtil.errorResponse(response, "No data found for user.", HttpStatus.NO_CONTENT); + projectUtil.errorResponse(response, "No data found for user.", HttpStatus.NO_CONTENT); return response; } try { @@ -336,11 +352,10 @@ public ApiResponse readFullExtendedProfile(String userId, String contextType, St @Override public ApiResponse getBasicProfile(String userId, String userToken) { - ApiResponse response = ProjectUtil.createDefaultResponse("api.getBasicProfile.read"); - String userIdFromToken = accessTokenValidator.fetchUserIdFromAccessToken(userToken); + ApiResponse response = projectUtil.createDefaultResponse("api.getBasicProfile.read"); + String userIdFromToken = accessTokenValidator.fetchUserIdFromAccessToken(userToken, response); if (userIdFromToken == null) { - ProjectUtil.errorResponse(response, "Invalid or missing access token", HttpStatus.UNAUTHORIZED); return response; } @@ -387,7 +402,7 @@ public ApiResponse getBasicProfile(String userId, String userToken) { response.setResponse(responseMap); } catch (Exception e) { log.error("Error fetching basic profile for userId: {}", userId, e); - ProjectUtil.errorResponse(response, "Internal server error while fetching profile", + projectUtil.errorResponse(response, "Internal server error while fetching profile", HttpStatus.INTERNAL_SERVER_ERROR); } @@ -396,11 +411,10 @@ public ApiResponse getBasicProfile(String userId, String userToken) { @Override public ApiResponse listCompetencies(String userId, String userToken) { - ApiResponse response = ProjectUtil.createDefaultResponse("api.listCompetencies.read"); - String userIdFromToken = accessTokenValidator.fetchUserIdFromAccessToken(userToken); + ApiResponse response = projectUtil.createDefaultResponse("api.listCompetencies.read"); + String userIdFromToken = accessTokenValidator.fetchUserIdFromAccessToken(userToken, response); if (userIdFromToken == null) { - ProjectUtil.errorResponse(response, "Invalid or missing access token", HttpStatus.UNAUTHORIZED); return response; } @@ -421,9 +435,9 @@ public ApiResponse listCompetencies(String userId, String userToken) { .map(map -> map.get(Constants.COURSE_ID)) .filter(Objects::nonNull) .map(Object::toString) - .collect(Collectors.toList()); + .toList(); if (completedCourseIdList.isEmpty()) { - ProjectUtil.errorResponse(response, "No competencies found for user.", HttpStatus.NO_CONTENT); + projectUtil.errorResponse(response, "No competencies found for user.", HttpStatus.NO_CONTENT); return response; } Map> courseMetadata = getCourseMetadataBatched(completedCourseIdList, 100, @@ -432,7 +446,7 @@ public ApiResponse listCompetencies(String userId, String userToken) { competencies = analyzeCompetencies(courseMetadata); if (competencies.isEmpty()) { - ProjectUtil.errorResponse(response, "No competencies found for user.", HttpStatus.NO_CONTENT); + projectUtil.errorResponse(response, "No competencies found for user.", HttpStatus.NO_CONTENT); return response; } cacheService.putCache(cacheKey, competencies); @@ -442,7 +456,7 @@ public ApiResponse listCompetencies(String userId, String userToken) { response.put(Constants.RESPONSE, competencies); } catch (Exception e) { log.error("Error fetching competencies for userId: {}", userId, e); - ProjectUtil.errorResponse(response, "Internal server error while fetching competencies", + projectUtil.errorResponse(response, "Internal server error while fetching competencies", HttpStatus.INTERNAL_SERVER_ERROR); } @@ -452,8 +466,10 @@ public ApiResponse listCompetencies(String userId, String userToken) { // -------------------- HELPER METHODS -------------------- private List> addUUIDs(List> list) { - return list.stream().peek(item -> item.put(Constants.UUID, UUID.randomUUID().toString())) - .collect(Collectors.toList()); + for (Map item : list) { + item.put(Constants.UUID, UUID.randomUUID().toString()); + } + return list; } private List> getExistingContextData(String userId, String contextType) { @@ -487,13 +503,6 @@ private boolean saveContextData(String userId, String contextType, List> dataList, String contextType) { - Comparator> comparator = getSortingComparator(contextType); - if (comparator != null) { - dataList.sort(comparator.reversed()); - } - } - private Comparator> getSortingComparator(String contextType) { return switch (contextType) { case Constants.SERVICE_HISTORY -> @@ -966,7 +975,7 @@ private int getIssuedCertificateCount(String userId) { int totalIssuedCertificates = 0; totalIssuedCertificates += (int) courseRecords.stream() .filter(MapUtils::isNotEmpty) - .map(record -> record.get(Constants.ISSUED_CERTIFICATES_KEY)) + .map(courseRecord -> courseRecord.get(Constants.ISSUED_CERTIFICATES_KEY)) .filter(certObj -> certObj instanceof List) .map(certObj -> (List) certObj) .filter(CollectionUtils::isNotEmpty) @@ -1118,7 +1127,9 @@ private OffsetDateTime parseOffsetDateTime(Object dateObj) { if (dateObj instanceof String str && !str.isBlank()) { try { return OffsetDateTime.parse(str); - } catch (Exception ignored) {} + } catch (Exception ignored) { + log.error("Failed to parse date: {}", str); + } } return null; } @@ -1128,17 +1139,16 @@ private OffsetDateTime parseOffsetDateTime(Object dateObj) { */ @Override public ApiResponse updateAdditionalFields(Map request, String authToken) { - ApiResponse response = ProjectUtil.createDefaultResponse("api.update.additionalFields"); - String userIdFromToken = accessTokenValidator.fetchUserIdFromAccessToken(authToken); + ApiResponse response = projectUtil.createDefaultResponse("api.update.additionalFields"); + String userIdFromToken = accessTokenValidator.fetchUserIdFromAccessToken(authToken, response); if (StringUtils.isBlank(authToken)) { - ProjectUtil.errorResponse(response, "Invalid or missing access token", HttpStatus.UNAUTHORIZED); return response; } String validationError = validateAdditionalFieldsRequest(request); if (validationError != null) { - ProjectUtil.errorResponse(response, validationError, HttpStatus.BAD_REQUEST); + projectUtil.errorResponse(response, validationError, HttpStatus.BAD_REQUEST); return response; } @@ -1147,7 +1157,7 @@ public ApiResponse updateAdditionalFields(Map request, String au List> customFieldValues = (List>) request.get(Constants.CUSTOM_FIELD_VALUES); if (!StringUtils.equalsIgnoreCase(userIdFromToken, userId)) { - ProjectUtil.errorResponse(response, "User ID in token does not match request", HttpStatus.UNAUTHORIZED); + projectUtil.errorResponse(response, "User ID in token does not match request", HttpStatus.UNAUTHORIZED); return response; } @@ -1159,7 +1169,7 @@ public ApiResponse updateAdditionalFields(Map request, String au List> restructuredData = restructureByOrgId(existingData, organisationId, customFieldValues); if (!saveContextData(userId, contextType, restructuredData)) { - ProjectUtil.errorResponse(response, "Failed to save additional fields", HttpStatus.INTERNAL_SERVER_ERROR); + projectUtil.errorResponse(response, "Failed to save additional fields", HttpStatus.INTERNAL_SERVER_ERROR); return response; } @@ -1168,7 +1178,7 @@ public ApiResponse updateAdditionalFields(Map request, String au boolean updated = esUtilService.updateUserOrgCustomFields(userId, organisationId, esOrgCustomFields); if (!updated) { - ProjectUtil.errorResponse(response, "Failed to update orgCustomFields in ES", HttpStatus.INTERNAL_SERVER_ERROR); + projectUtil.errorResponse(response, "Failed to update orgCustomFields in ES", HttpStatus.INTERNAL_SERVER_ERROR); return response; } @@ -1176,7 +1186,7 @@ public ApiResponse updateAdditionalFields(Map request, String au response.put(Constants.RESPONSE, Constants.SUCCESS); } catch (Exception e) { log.error("Error updating additional fields for userId: {}, orgId: {}", userId, organisationId, e); - ProjectUtil.errorResponse(response, "Internal server error", HttpStatus.INTERNAL_SERVER_ERROR); + projectUtil.errorResponse(response, "Internal server error", HttpStatus.INTERNAL_SERVER_ERROR); } return response; } @@ -1188,7 +1198,7 @@ public ApiResponse updateAdditionalFields(Map request, String au * @return Error message if validation fails, null if validation passes */ private String validateAdditionalFieldsRequest(Map request) { - StringBuffer str = new StringBuffer(); + StringBuilder str = new StringBuilder(); List errList = new ArrayList<>(); String userId = (String) request.get(Constants.USER_ID_RQST); @@ -1238,7 +1248,7 @@ private String validateAdditionalFieldsRequest(Map request) { String orgId = customFieldEntity.getCustomFieldData().get(Constants.ORGANISATION_ID).asText(); if (!StringUtils.equals(orgId, organisationId)) { - str.append("Custom field ").append(customFieldId) + str.append(Constants.CUSTOM_FIELD_PREFIX).append(customFieldId) .append(" is not configured for organization ").append(organisationId).append(". "); return str.toString(); } @@ -1258,7 +1268,7 @@ private String validateAdditionalFieldsRequest(Map request) { } if (!Constants.TEXT.equals(storedType)) { - str.append("Custom field ").append(customFieldId).append(" is not of type text. "); + str.append(Constants.CUSTOM_FIELD_PREFIX).append(customFieldId).append(" is not of type text. "); return str.toString(); } } else if (Constants.MASTER_LIST.equals(fieldType)) { @@ -1269,7 +1279,7 @@ private String validateAdditionalFieldsRequest(Map request) { } if (!Constants.MASTER_LIST.equals(storedType)) { - str.append("Custom field ").append(customFieldId).append(" is not of type masterList. "); + str.append(Constants.CUSTOM_FIELD_PREFIX).append(customFieldId).append(" is not of type masterList. "); return str.toString(); } @@ -1317,7 +1327,7 @@ private String validateMasterListValues(CustomFieldEntity entity, List> sortedValues = requestedValues.stream() .sorted(Comparator.comparing(map -> (Integer) map.get(Constants.LEVEL))) - .collect(Collectors.toList()); + .toList(); // Track parent node for hierarchical validation JsonNode currentParentNode = null; @@ -1425,16 +1435,15 @@ private CustomFieldEntity getCustomFieldById(String customFieldId) { @Override public ApiResponse getAdditionalFieldsByOrg(String userId, String orgId, String authToken) { - ApiResponse response = ProjectUtil.createDefaultResponse("api.get.additionalFieldsByOrg"); - String userIdFromToken = accessTokenValidator.fetchUserIdFromAccessToken(authToken); + ApiResponse response = projectUtil.createDefaultResponse("api.get.additionalFieldsByOrg"); + String userIdFromToken = accessTokenValidator.fetchUserIdFromAccessToken(authToken, response); if (StringUtils.isBlank(authToken)) { - ProjectUtil.errorResponse(response, "Invalid or missing access token", HttpStatus.UNAUTHORIZED); return response; } if (!StringUtils.equalsIgnoreCase(userIdFromToken, userId)) { - ProjectUtil.errorResponse(response, "User ID in token does not match request", HttpStatus.UNAUTHORIZED); + projectUtil.errorResponse(response, "User ID in token does not match request", HttpStatus.UNAUTHORIZED); return response; } @@ -1462,7 +1471,7 @@ public ApiResponse getAdditionalFieldsByOrg(String userId, String orgId, String return response; } catch (Exception e) { log.error("Error retrieving additional fields for userId: {} and orgId: {}", userId, orgId, e); - ProjectUtil.errorResponse(response, "Internal server error", HttpStatus.INTERNAL_SERVER_ERROR); + projectUtil.errorResponse(response, "Internal server error", HttpStatus.INTERNAL_SERVER_ERROR); return response; } } diff --git a/src/main/java/com/igot/cb/transactional/cassandrautils/CassandraConnectionManagerImpl.java b/src/main/java/com/igot/cb/transactional/cassandrautils/CassandraConnectionManagerImpl.java index c93a22a..bb9d999 100644 --- a/src/main/java/com/igot/cb/transactional/cassandrautils/CassandraConnectionManagerImpl.java +++ b/src/main/java/com/igot/cb/transactional/cassandrautils/CassandraConnectionManagerImpl.java @@ -85,14 +85,14 @@ public CqlSession createCassandraConnectionWithKeySpaces(String keySpaceName) { List hosts = Arrays.asList(cassandraHost.split(",")); List contactPoints = hosts.stream() .map(host -> new InetSocketAddress(host.trim(), 9042)) // Assuming default port 9042 - .collect(Collectors.toList()); + .toList(); List contactPointsString = hosts.stream() .map(host -> host.trim() + ":9042") // Ensure proper host:port format - .collect(Collectors.toList()); + .toList(); DriverConfigLoader loader = DriverConfigLoader.programmaticBuilder() .withStringList(DefaultDriverOption.CONTACT_POINTS, contactPointsString) .withString(DefaultDriverOption.REQUEST_CONSISTENCY, getConsistencyLevel().name()) - .withString(DefaultDriverOption.LOAD_BALANCING_LOCAL_DATACENTER, "datacenter1") + .withString(DefaultDriverOption.LOAD_BALANCING_LOCAL_DATACENTER, Constants.DATA_CENTER) .withInt(DefaultDriverOption.CONNECTION_POOL_LOCAL_SIZE, Integer.parseInt(cache.getProperty(Constants.CORE_CONNECTIONS_PER_HOST_FOR_LOCAL))) .withInt(DefaultDriverOption.CONNECTION_POOL_REMOTE_SIZE, @@ -163,11 +163,15 @@ public static ConsistencyLevel getConsistencyLevel() { try { return DefaultConsistencyLevel.valueOf(consistency.toUpperCase()); } catch (IllegalArgumentException exception) { + String errorMsg = String.format( + "Invalid Cassandra consistency level '%s' specified in configuration. Using property key: %s", + consistency, + Constants.SUNBIRD_CASSANDRA_CONSISTENCY_LEVEL); logger.error("CassandraConnectionManagerImpl:getConsistencyLevel: Exception occurred with error message: ", exception); throw new CustomException( Constants.ERROR, - exception.getMessage(), + errorMsg, HttpStatus.INTERNAL_SERVER_ERROR); } } diff --git a/src/main/java/com/igot/cb/util/BASE64Decoder.java b/src/main/java/com/igot/cb/util/BASE64Decoder.java index 861d626..e805dae 100644 --- a/src/main/java/com/igot/cb/util/BASE64Decoder.java +++ b/src/main/java/com/igot/cb/util/BASE64Decoder.java @@ -82,6 +82,7 @@ protected void decodeAtom(PushbackInputStream inStream, OutputStream outStream, b = pem_convert_array[decode_buffer[1] & 0xff]; a = pem_convert_array[decode_buffer[0] & 0xff]; break; + default: } switch (rem) { @@ -97,6 +98,8 @@ protected void decodeAtom(PushbackInputStream inStream, OutputStream outStream, outStream.write((byte) (((b << 4) & 0xf0) | ((c >>> 2) & 0xf))); outStream.write((byte) (((c << 6) & 0xc0) | (d & 0x3f))); break; + default: + break; } return; } diff --git a/src/main/java/com/igot/cb/util/CharacterDecoder.java b/src/main/java/com/igot/cb/util/CharacterDecoder.java index ea3e6bf..0187a59 100644 --- a/src/main/java/com/igot/cb/util/CharacterDecoder.java +++ b/src/main/java/com/igot/cb/util/CharacterDecoder.java @@ -77,6 +77,11 @@ public void decodeBuffer(InputStream aStream, OutputStream bStream) throws IOExc try { length = decodeLinePrefix(ps, bStream); + + if (length <= 0) { + break; + } + for (i = 0; (i + bytesPerAtom()) < length; i += bytesPerAtom()) { decodeAtom(ps, bStream, bytesPerAtom()); totalBytes += bytesPerAtom(); diff --git a/src/main/java/com/igot/cb/util/Constants.java b/src/main/java/com/igot/cb/util/Constants.java index 5b58f29..4af1e91 100644 --- a/src/main/java/com/igot/cb/util/Constants.java +++ b/src/main/java/com/igot/cb/util/Constants.java @@ -456,6 +456,11 @@ public class Constants { public static final String AUTH_TOKEN = "Authorization"; public static final String APPROVED = "Approved"; public static final String USER_EXTERNAL_COURSE_ENROLMENTS = "user_external_enrolments"; + public static final String INVALID_USERID = "Invalid UserId in the request"; + public static final String USER_EXTENDED_PROFILE = "user:extendedProfile"; + public static final String INVALID_OR_MISSING_ACCESS_TOKEN = "Invalid or missing access token"; + public static final String CUSTOM_FIELD_PREFIX = "Custom field "; + public static final String DATA_CENTER = "datacenter1"; private Constants() { } } diff --git a/src/main/java/com/igot/cb/util/DefaultEncryptionServiceImpl.java b/src/main/java/com/igot/cb/util/DefaultEncryptionServiceImpl.java index aaa6d6c..9b738c0 100644 --- a/src/main/java/com/igot/cb/util/DefaultEncryptionServiceImpl.java +++ b/src/main/java/com/igot/cb/util/DefaultEncryptionServiceImpl.java @@ -107,7 +107,7 @@ public static String encrypt(String value) { throw new ProjectCommonException( ResponseCode.SERVER_ERROR, ResponseCode.SERVER_ERROR.getErrorMessage(), - ResponseCode.SERVER_ERROR.getResponseCode()); + ResponseCode.SERVER_ERROR.getHttpStatusCode()); } eValue = new BASE64Encoder().encode(encValue); } @@ -132,10 +132,10 @@ public static String getSalt() { if (StringUtils.isBlank(encryption_key)) { logger.info("throwing exception for invalid salt"); throw new ProjectCommonException( - ResponseCode.invalidParameterValue, + ResponseCode.INVALID_PARAMETER_VALUE, String.format( - ResponseCode.invalidParameterValue.getErrorMessage(), Constants.ENCRYPTION_KEY), - ResponseCode.SERVER_ERROR.getResponseCode()); + ResponseCode.INVALID_PARAMETER_VALUE.getErrorMessage(), Constants.ENCRYPTION_KEY), + ResponseCode.SERVER_ERROR.getHttpStatusCode()); } return encryption_key; } diff --git a/src/main/java/com/igot/cb/util/ProjectUtil.java b/src/main/java/com/igot/cb/util/ProjectUtil.java index b7587a3..12ff7dc 100644 --- a/src/main/java/com/igot/cb/util/ProjectUtil.java +++ b/src/main/java/com/igot/cb/util/ProjectUtil.java @@ -50,12 +50,12 @@ public class ProjectUtil { */ public static CustomException createServerError(ResponseCode responseCode) { return new CustomException(responseCode.getErrorCode(), responseCode.getErrorMessage(), - ResponseCode.SERVER_ERROR.getResponseCode()); + ResponseCode.SERVER_ERROR.getHttpStatusCode()); } public static CustomException createClientException(ResponseCode responseCode) { return new CustomException(responseCode.getErrorCode(), responseCode.getErrorMessage(), - ResponseCode.CLIENT_ERROR.getResponseCode()); + ResponseCode.CLIENT_ERROR.getHttpStatusCode()); } public static ApiResponse createDefaultResponse(String api) { diff --git a/src/test/java/com/igot/cb/exceptions/ProjectCommonExceptionTest.java b/src/test/java/com/igot/cb/exceptions/ProjectCommonExceptionTest.java index 89ba843..a50b874 100644 --- a/src/test/java/com/igot/cb/exceptions/ProjectCommonExceptionTest.java +++ b/src/test/java/com/igot/cb/exceptions/ProjectCommonExceptionTest.java @@ -20,7 +20,7 @@ public void testConstructorWithResponseCode() { ProjectCommonException exception = new ProjectCommonException(mockCode, "Test message", 400); assertEquals("ERR_001", exception.getErrorCode()); - assertEquals("Test message", exception.getErrorMessage()); + assertEquals("Test message", exception.getMessage()); assertEquals(400, exception.getErrorResponseCode()); assertEquals(mockCode, exception.getResponseCode()); } @@ -39,7 +39,7 @@ public void testConstructorWithPlaceholders() { ); assertEquals("ERR_002", exception.getErrorCode()); - assertEquals("Error occurred for user testUser in operation testOperation", exception.getErrorMessage()); + assertEquals("Error occurred for user testUser in operation testOperation", exception.getMessage()); assertEquals(500, exception.getErrorResponseCode()); } @@ -52,7 +52,7 @@ public void testCopyConstructor() { ProjectCommonException copy = new ProjectCommonException(original, "NewOperation"); assertEquals(Constants.USER_ORG_SERVICE_PREFIX + "NewOperation" + "ERR_003", copy.getErrorCode()); - assertEquals("Original message", copy.getErrorMessage()); + assertEquals("Original message", copy.getMessage()); assertEquals(400, copy.getErrorResponseCode()); } @@ -69,7 +69,7 @@ public void testGettersAndSetters() { exception.setErrorResponseCode(500); assertEquals("NEW_ERR", exception.getErrorCode()); - assertEquals("New message", exception.getErrorMessage()); + assertEquals("New message", exception.getMessage()); assertEquals(500, exception.getErrorResponseCode()); } @@ -95,7 +95,7 @@ public void testThrowServerErrorException() { () -> ProjectCommonException.throwServerErrorException(mockResponseCode1, "Custom error message") ); assertNotNull(exception1.getErrorCode()); - assertEquals("Custom error message", exception1.getErrorMessage()); + assertEquals("Custom error message", exception1.getMessage()); assertNotEquals(0, exception1.getErrorResponseCode()); // Case 2: Empty custom message, should use default message @@ -108,7 +108,7 @@ public void testThrowServerErrorException() { () -> ProjectCommonException.throwServerErrorException(mockResponseCode2, "") ); assertNotNull(exception2.getErrorCode()); - assertEquals("Default error message", exception2.getErrorMessage()); + assertEquals("Default error message", exception2.getMessage()); assertNotEquals(0, exception2.getErrorResponseCode()); // Case 3: Null custom message, should use default message @@ -121,7 +121,7 @@ public void testThrowServerErrorException() { () -> ProjectCommonException.throwServerErrorException(mockResponseCode3, null) ); assertNotNull(exception3.getErrorCode()); - assertEquals("Default error message", exception3.getErrorMessage()); + assertEquals("Default error message", exception3.getMessage()); assertNotEquals(0, exception3.getErrorResponseCode()); } @@ -138,7 +138,7 @@ public void testThrowServerErrorExceptionWithSingleParameter() { ); assertNotNull(exception.getErrorCode()); - assertEquals("Default error message", exception.getErrorMessage()); + assertEquals("Default error message", exception.getMessage()); assertNotEquals(0, exception.getErrorResponseCode()); } @@ -147,7 +147,7 @@ public void testSetMessage() { ProjectCommonException exception = new ProjectCommonException( ResponseCode.SERVER_ERROR, "Initial message", - ResponseCode.SERVER_ERROR.getResponseCode() + ResponseCode.SERVER_ERROR.getHttpStatusCode() ); String newMessage = "New error message"; exception.setMessage(newMessage); @@ -163,7 +163,7 @@ public void testSetResponseCode() { ProjectCommonException exception = new ProjectCommonException( ResponseCode.SERVER_ERROR, "Test message", - ResponseCode.SERVER_ERROR.getResponseCode() + ResponseCode.SERVER_ERROR.getHttpStatusCode() ); ResponseCode mockResponseCode = mock(ResponseCode.class); when(mockResponseCode.getErrorCode()).thenReturn("NEW_ERR_001"); diff --git a/src/test/java/com/igot/cb/exceptions/ResponseCodeTest.java b/src/test/java/com/igot/cb/exceptions/ResponseCodeTest.java index 074f48b..765c934 100644 --- a/src/test/java/com/igot/cb/exceptions/ResponseCodeTest.java +++ b/src/test/java/com/igot/cb/exceptions/ResponseCodeTest.java @@ -15,8 +15,8 @@ public class ResponseCodeTest { @Test public void testEnumValues() { assertEquals(7, ResponseCode.values().length); - assertNotNull(ResponseCode.unAuthorized); - assertNotNull(ResponseCode.internalError); + assertNotNull(ResponseCode.UNAUTHORIZED); + assertNotNull(ResponseCode.INTERNAL_SERVER_ERROR); assertNotNull(ResponseCode.OK); assertNotNull(ResponseCode.CLIENT_ERROR); assertNotNull(ResponseCode.SERVER_ERROR); @@ -24,33 +24,33 @@ public void testEnumValues() { @Test public void testStringConstructor() { - assertEquals(ResponseMessage.Key.UNAUTHORIZED_USER, ResponseCode.unAuthorized.getErrorCode()); - assertEquals(ResponseMessage.Message.UNAUTHORIZED_USER, ResponseCode.unAuthorized.getErrorMessage()); - assertEquals(ResponseMessage.Key.INTERNAL_ERROR, ResponseCode.internalError.getErrorCode()); - assertEquals(ResponseMessage.Message.INTERNAL_ERROR, ResponseCode.internalError.getErrorMessage()); + assertEquals(ResponseMessage.Key.UNAUTHORIZED_USER, ResponseCode.UNAUTHORIZED.getErrorCode()); + assertEquals(ResponseMessage.Message.UNAUTHORIZED_USER, ResponseCode.UNAUTHORIZED.getErrorMessage()); + assertEquals(ResponseMessage.Key.INTERNAL_ERROR, ResponseCode.INTERNAL_SERVER_ERROR.getErrorCode()); + assertEquals(ResponseMessage.Message.INTERNAL_ERROR, ResponseCode.INTERNAL_SERVER_ERROR.getErrorMessage()); } @Test public void testIntConstructor() { - assertEquals(200, ResponseCode.OK.getResponseCode()); - assertEquals(400, ResponseCode.CLIENT_ERROR.getResponseCode()); - assertEquals(500, ResponseCode.SERVER_ERROR.getResponseCode()); + assertEquals(200, ResponseCode.OK.getHttpStatusCode()); + assertEquals(400, ResponseCode.CLIENT_ERROR.getHttpStatusCode()); + assertEquals(500, ResponseCode.SERVER_ERROR.getHttpStatusCode()); assertNull(ResponseCode.OK.getErrorCode()); assertNull(ResponseCode.OK.getErrorMessage()); } @Test public void testResponseCodeSetter() { - ResponseCode testCode = ResponseCode.unAuthorized; - int originalCode = testCode.getResponseCode(); + ResponseCode testCode = ResponseCode.UNAUTHORIZED; + int originalCode = testCode.getHttpStatusCode(); int newResponseCode = 403; try { - testCode.setResponseCode(newResponseCode); - assertEquals(newResponseCode, testCode.getResponseCode()); + testCode.setHttpStatusCode(newResponseCode); + assertEquals(newResponseCode, testCode.getHttpStatusCode()); } finally { // Restore the original value to avoid affecting other tests - testCode.setResponseCode(originalCode); + testCode.setHttpStatusCode(originalCode); } } @@ -63,14 +63,14 @@ public void testGetResponseWithNullOrBlank() { @Test public void testGetResponseWithUnauthorized() { - assertEquals(ResponseCode.unAuthorized, ResponseCode.getResponse(Constants.UNAUTHORIZED)); + assertEquals(ResponseCode.UNAUTHORIZED, ResponseCode.getResponse(Constants.UNAUTHORIZED)); } @Test public void testGetResponseWithValidErrorCode() { - assertEquals(ResponseCode.unAuthorized, + assertEquals(ResponseCode.UNAUTHORIZED, ResponseCode.getResponse(ResponseMessage.Key.UNAUTHORIZED_USER)); - assertEquals(ResponseCode.internalError, + assertEquals(ResponseCode.INTERNAL_SERVER_ERROR, ResponseCode.getResponse(ResponseMessage.Key.INTERNAL_ERROR)); } @@ -83,11 +83,6 @@ public void testGetResponseWithInvalidErrorCode() { assertTrue(e.getMessage().contains("Cannot invoke \"String.equals(Object)\"")); } } - - @Test - public void testGetMessage() { - assertEquals("", ResponseCode.OK.getMessage(200)); - } @Test public void testGetResponseReturnsNullWhenNoMatchFound() { @@ -106,12 +101,12 @@ public void testGetResponseMethod() { assertNull(ResponseCode.getResponse(null)); assertNull(ResponseCode.getResponse("")); assertNull(ResponseCode.getResponse(" ")); - assertEquals(ResponseCode.unAuthorized, ResponseCode.getResponse(Constants.UNAUTHORIZED)); - assertEquals(ResponseCode.internalError, + assertEquals(ResponseCode.UNAUTHORIZED, ResponseCode.getResponse(Constants.UNAUTHORIZED)); + assertEquals(ResponseCode.INTERNAL_SERVER_ERROR, ResponseCode.getResponse(ResponseMessage.Key.INTERNAL_ERROR)); - assertEquals(ResponseCode.unAuthorized, + assertEquals(ResponseCode.UNAUTHORIZED, ResponseCode.getResponse(ResponseMessage.Key.UNAUTHORIZED_USER)); - assertEquals(ResponseCode.resourceNotFound, + assertEquals(ResponseCode.RESOURCE_NOT_FOUND, ResponseCode.getResponse(ResponseMessage.Key.RESOURCE_NOT_FOUND)); assertNull(ResponseCode.getResponse("INVALID_CODE")); assertNull(ResponseCode.getResponse(ResponseCode.OK.getErrorCode())); diff --git a/src/test/java/com/igot/cb/profile/ProfileServiceImplPrivateMethodTest.java b/src/test/java/com/igot/cb/profile/ProfileServiceImplPrivateMethodTest.java index 9bfb90a..9e50952 100644 --- a/src/test/java/com/igot/cb/profile/ProfileServiceImplPrivateMethodTest.java +++ b/src/test/java/com/igot/cb/profile/ProfileServiceImplPrivateMethodTest.java @@ -2,12 +2,14 @@ import com.fasterxml.jackson.core.type.TypeReference; import com.fasterxml.jackson.databind.ObjectMapper; -import com.igot.cb.authentication.util.AccessTokenValidator; import com.igot.cb.profile.service.ProfileServiceImpl; import com.igot.cb.transactional.redis.cache.CacheService; -import com.igot.cb.util.ApiResponse; import com.igot.cb.util.CbServerProperties; import com.igot.cb.util.UserUtility; + +import org.igot.common.model.ApiResponse; +import org.igot.common.util.AccessTokenValidator; +import org.igot.common.util.ProjectUtil; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import org.junit.jupiter.api.extension.ExtendWith; @@ -40,17 +42,38 @@ class ProfileServiceImplPrivateMethodTest { private ObjectMapper mapper; @Mock private CbServerProperties serverConfig; + @Mock + private ProjectUtil projectUtil; @BeforeEach void setup() { // Set private fields via ReflectionTestUtils ReflectionTestUtils.setField(profileService, "profileVisibleAllowedFields", "name,email"); ReflectionTestUtils.setField(profileService, "basicDetailsFilteredKeys", "password,ssn"); + + // Ensure non-null ApiResponse and that errorResponse sets status codes + Mockito.lenient().when(projectUtil.createDefaultResponse(anyString())).thenReturn(new ApiResponse()); + Mockito.lenient().doAnswer(invocation -> { + ApiResponse resp = invocation.getArgument(0); + String msg = invocation.getArgument(1); + HttpStatus status = invocation.getArgument(2); + resp.setResponseCode(status); + try { + if (resp.getParams() != null) { + resp.getParams().setErrMsg(msg); + } + } catch (Throwable ignored) {} + return null; + }).when(projectUtil).errorResponse(any(ApiResponse.class), anyString(), any(HttpStatus.class)); } @Test void testGetBasicProfile_InvalidToken() { - when(accessTokenValidator.fetchUserIdFromAccessToken("badToken")).thenReturn(null); + Mockito.doAnswer(invocation -> { + ApiResponse resp = invocation.getArgument(1); + resp.setResponseCode(HttpStatus.UNAUTHORIZED); + return null; + }).when(accessTokenValidator).fetchUserIdFromAccessToken(eq("badToken"), any(ApiResponse.class)); ApiResponse response = profileService.getBasicProfile("user123", "badToken"); @@ -62,7 +85,7 @@ void testGetBasicProfile_CacheHitWithDifferenceList() throws Exception { String userId = "user123"; String userToken = "token123"; - when(accessTokenValidator.fetchUserIdFromAccessToken(userToken)).thenReturn(userId); + when(accessTokenValidator.fetchUserIdFromAccessToken(anyString(), any(ApiResponse.class))).thenReturn(userId); // Simulate cache hit with some missing fields Map cachedMap = new HashMap<>(); @@ -94,7 +117,7 @@ void testGetBasicProfile_NoCache_EmptyUserProfile() { String userId = "user123"; String userToken = "token123"; - when(accessTokenValidator.fetchUserIdFromAccessToken(userToken)).thenReturn(userId); + when(accessTokenValidator.fetchUserIdFromAccessToken(anyString(), any(ApiResponse.class))).thenReturn(userId); when(cacheService.getCache(anyString())).thenReturn(null); ProfileServiceImpl spyService = Mockito.spy(profileService); @@ -112,7 +135,7 @@ void testGetBasicProfile_NonSelfUser_CallsSanitize() { String userId = "user123"; String userToken = "token123"; - when(accessTokenValidator.fetchUserIdFromAccessToken(userToken)).thenReturn("otherUser"); + when(accessTokenValidator.fetchUserIdFromAccessToken(anyString(), any(ApiResponse.class))).thenReturn("otherUser"); when(cacheService.getCache(anyString())).thenReturn(null); ProfileServiceImpl spyService = Mockito.spy(profileService); @@ -131,7 +154,7 @@ void testGetBasicProfile_NonSelfUser_CallsSanitize() { @Test void testGetBasicProfile_Exception() { - when(accessTokenValidator.fetchUserIdFromAccessToken(anyString())).thenReturn("user123"); + when(accessTokenValidator.fetchUserIdFromAccessToken(anyString(), any(ApiResponse.class))).thenReturn("user123"); when(cacheService.getCache(anyString())).thenThrow(new RuntimeException("Cache failure")); ApiResponse response = profileService.getBasicProfile("user123", "token123"); diff --git a/src/test/java/com/igot/cb/profile/ProfileServiceImplTest.java b/src/test/java/com/igot/cb/profile/ProfileServiceImplTest.java index 590e70c..b197461 100644 --- a/src/test/java/com/igot/cb/profile/ProfileServiceImplTest.java +++ b/src/test/java/com/igot/cb/profile/ProfileServiceImplTest.java @@ -3,7 +3,6 @@ import com.fasterxml.jackson.databind.ObjectMapper; import com.fasterxml.jackson.databind.node.ArrayNode; import com.fasterxml.jackson.databind.node.ObjectNode; -import com.igot.cb.authentication.util.AccessTokenValidator; import com.igot.cb.common.OutboundRequestHandlerServiceImpl; import com.igot.cb.profile.entity.CustomFieldEntity; import com.igot.cb.profile.repository.CustomFieldRepository; @@ -12,7 +11,13 @@ import com.igot.cb.transactional.elasticsearch.service.EsUtilServiceImpl; import com.igot.cb.transactional.redis.cache.CacheService; import com.igot.cb.transactional.service.RequestHandlerServiceImpl; -import com.igot.cb.util.*; +import com.igot.cb.util.CbServerProperties; +import com.igot.cb.util.Constants; +import com.igot.cb.util.ProfilePreference; + +import org.igot.common.model.ApiResponse; +import org.igot.common.util.AccessTokenValidator; +import org.igot.common.util.ProjectUtil; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import org.junit.jupiter.api.extension.ExtendWith; @@ -62,7 +67,7 @@ class ProfileServiceImplTest { private final String userID = "user-123"; private final String token = "dummy-token"; - private static final String CACHE_KEY = "user:competencies:user123"; + private static final String CACHE_KEY = "user:competencies:user-123"; private final String [] contextType = {"contextA"}; private static final String REDIS_KEY = "user:extendedProfile:project:user-123"; @@ -78,6 +83,39 @@ void setUp() { "basicDetailsFilteredKeys", "profileCompletionPercentage,karmaPoints,certificateCount,postCount" ); + // Ensure service never gets a null ApiResponse from ProjectUtil + lenient().when(projectUtil.createDefaultResponse(anyString())).thenReturn(new ApiResponse()); + // Make errorResponse populate response code and error message to satisfy assertions + lenient().doAnswer(invocation -> { + ApiResponse resp = invocation.getArgument(0); + String msg = invocation.getArgument(1); + HttpStatus status = invocation.getArgument(2); + resp.setResponseCode(status); + try { + if (resp.getParams() != null) { + resp.getParams().setErrMsg(msg); + if (status != HttpStatus.OK) { + resp.getParams().setStatus(Constants.FAILED); + } + } + } catch (Throwable ignored) {} + return null; + }).when(projectUtil).errorResponse(any(ApiResponse.class), anyString(), any(HttpStatus.class)); + + // Default behavior for blank/empty tokens: mark response as UNAUTHORIZED with message + lenient().doAnswer(invocation -> { + String tok = invocation.getArgument(0); + ApiResponse resp = invocation.getArgument(1); + if (tok == null || tok.trim().isEmpty()) { + resp.setResponseCode(HttpStatus.UNAUTHORIZED); + if (resp.getParams() != null) { + resp.getParams().setErrMsg("Invalid or missing access token"); + resp.getParams().setStatus(Constants.FAILED); + } + return null; + } + return null; // leave to test-specific stubs for non-blank tokens + }).when(accessTokenValidator).fetchUserIdFromAccessToken(anyString(), any(org.igot.common.model.ApiResponse.class)); } static class TestContext { @@ -127,7 +165,15 @@ static Stream contextProvider() { @Test void testGetBasicProfile_invalidToken_returnsError() { - when(accessTokenValidator.fetchUserIdFromAccessToken(token)).thenReturn(null); + doAnswer(invocation -> { + ApiResponse resp = invocation.getArgument(1); + resp.setResponseCode(HttpStatus.UNAUTHORIZED); + if (resp.getParams() != null) { + resp.getParams().setStatus(Constants.FAILED); + resp.getParams().setErrMsg("Invalid or missing access token"); + } + return null; + }).when(accessTokenValidator).fetchUserIdFromAccessToken(anyString(), any(org.igot.common.model.ApiResponse.class)); ApiResponse response = profileService.getBasicProfile(userID, token); @@ -140,7 +186,7 @@ void testGetExtendedProfileSummary_noCache_fallsBackToDB() throws Exception { String[] contextTypes = { "education" }; List> dataList = List.of(Map.of("field", "value")); - when(accessTokenValidator.fetchUserIdFromAccessToken(token)).thenReturn(userID); + when(accessTokenValidator.fetchUserIdFromAccessToken(anyString(), any(org.igot.common.model.ApiResponse.class))).thenReturn(userID); when(cacheService.getCache(anyString())).thenReturn(null); when(serverProperties.getContextType()).thenReturn(contextTypes); when(cassandraOperation.getRecordsByPropertiesByKey(anyString(), anyString(), anyMap(), isNull(), isNull())) @@ -167,7 +213,7 @@ void testSaveExtendedProfile_validInput_shouldSucceed() { ApiResponse mockResponse = new ApiResponse(); mockResponse.put(Constants.RESPONSE, Constants.SUCCESS); - when(accessTokenValidator.fetchUserIdFromAccessToken(token)).thenReturn(userID); + when(accessTokenValidator.fetchUserIdFromAccessToken(anyString(), any(org.igot.common.model.ApiResponse.class))).thenReturn(userID); when(serverProperties.getContextType()).thenReturn(new String[] { "education" }); when(serverProperties.getEducationalQualificationMandatoryFields()).thenReturn(""); when(serverProperties.getAchievementsMandatoryFields()).thenReturn(""); @@ -202,7 +248,7 @@ void testUpdateExtendedProfile_valid_shouldSucceed() throws Exception { ApiResponse mockResponse = new ApiResponse(); mockResponse.put(Constants.RESPONSE, Constants.SUCCESS); - when(accessTokenValidator.fetchUserIdFromAccessToken(token)).thenReturn(userID); + when(accessTokenValidator.fetchUserIdFromAccessToken(anyString(), any(org.igot.common.model.ApiResponse.class))).thenReturn(userID); when(serverProperties.getContextType()).thenReturn(new String[] { "education" }); when(cassandraOperation.getRecordsByPropertiesByKey(any(), any(), anyMap(), any(), any())) .thenReturn(List.of(Map.of(Constants.CONTEXT_DATA, "[]"))); @@ -230,7 +276,7 @@ void testDeleteExtendedProfile_valid_shouldSucceed() throws Exception { ApiResponse mockResponse = new ApiResponse(); mockResponse.put(Constants.RESPONSE, Constants.SUCCESS); - when(accessTokenValidator.fetchUserIdFromAccessToken(token)).thenReturn(userID); + when(accessTokenValidator.fetchUserIdFromAccessToken(anyString(), any(org.igot.common.model.ApiResponse.class))).thenReturn(userID); when(serverProperties.getContextType()).thenReturn(new String[] { "education" }); when(cassandraOperation.getRecordsByPropertiesByKey(any(), any(), anyMap(), any(), any())) .thenReturn(List.of(Map.of(Constants.CONTEXT_DATA, "[]"))); @@ -249,7 +295,7 @@ void testReadFullExtendedProfile_fromCache_success() throws Exception { String localContextType = "education"; List> data = List.of(Map.of("degree", "MSc")); - when(accessTokenValidator.fetchUserIdFromAccessToken(token)).thenReturn(userID); + when(accessTokenValidator.fetchUserIdFromAccessToken(anyString(), any(org.igot.common.model.ApiResponse.class))).thenReturn(userID); when(cacheService.getCache(anyString())).thenReturn("[{'degree':'MSc'}]"); when(projectUtil.parseListOfMap(anyString())).thenReturn(data); @@ -272,7 +318,7 @@ void testSaveExtendedProfile_shouldSortByDateField(TestContext testContext) { ApiResponse mockResponse = new ApiResponse(); mockResponse.put(Constants.RESPONSE, Constants.SUCCESS); - when(accessTokenValidator.fetchUserIdFromAccessToken(token)).thenReturn(userID); + when(accessTokenValidator.fetchUserIdFromAccessToken(anyString(), any(org.igot.common.model.ApiResponse.class))).thenReturn(userID); when(serverProperties.getContextType()).thenReturn(new String[]{ testContext.contextKey }); when(serverProperties.getEducationalQualificationMandatoryFields()).thenReturn("dummyField"); when(serverProperties.getAchievementsMandatoryFields()).thenReturn("dummyField"); @@ -291,7 +337,15 @@ void testSaveExtendedProfile_shouldSortByDateField(TestContext testContext) { @Test void testListCompetencies_invalidToken() { - when(accessTokenValidator.fetchUserIdFromAccessToken(token)).thenReturn(null); + doAnswer(invocation -> { + ApiResponse resp = invocation.getArgument(1); + resp.setResponseCode(HttpStatus.UNAUTHORIZED); + if (resp.getParams() != null) { + resp.getParams().setStatus(Constants.FAILED); + resp.getParams().setErrMsg("Invalid or missing access token"); + } + return null; + }).when(accessTokenValidator).fetchUserIdFromAccessToken(anyString(), any(org.igot.common.model.ApiResponse.class)); ApiResponse response = profileService.listCompetencies(userID, token); @@ -301,7 +355,7 @@ void testListCompetencies_invalidToken() { @Test void testListCompetencies_noCoursesCompleted() { - when(accessTokenValidator.fetchUserIdFromAccessToken(token)).thenReturn(userID); + when(accessTokenValidator.fetchUserIdFromAccessToken(anyString(), any(org.igot.common.model.ApiResponse.class))).thenReturn(userID); lenient().when(cacheService.getCache(CACHE_KEY)).thenReturn(null); Map dbRecord = Map.of( @@ -333,7 +387,7 @@ void testGetCourseMetadataBatched_emptyOrInvalidJson() throws IOException { @Test void testListCompetencies_cacheHit() { - when(accessTokenValidator.fetchUserIdFromAccessToken(token)).thenReturn(userID); + when(accessTokenValidator.fetchUserIdFromAccessToken(anyString(), any(org.igot.common.model.ApiResponse.class))).thenReturn(userID); lenient().when(cacheService.getCache(CACHE_KEY)).thenReturn("{\"dummy\":1}"); ApiResponse response = profileService.listCompetencies(userID, token); @@ -344,7 +398,7 @@ void testListCompetencies_cacheHit() { @Test void testListCompetencies_exception() { - when(accessTokenValidator.fetchUserIdFromAccessToken(token)).thenReturn(userID); + when(accessTokenValidator.fetchUserIdFromAccessToken(anyString(), any(org.igot.common.model.ApiResponse.class))).thenReturn(userID); when(cacheService.getCache(CACHE_KEY)).thenThrow(new RuntimeException("Redis down")); ApiResponse response = profileService.listCompetencies(userID, token); @@ -355,7 +409,7 @@ void testListCompetencies_exception() { @Test void testExtendedProfile_invalidToken() { - when(accessTokenValidator.fetchUserIdFromAccessToken(token)).thenReturn(null); + when(accessTokenValidator.fetchUserIdFromAccessToken(anyString(), any(org.igot.common.model.ApiResponse.class))).thenReturn(null); ApiResponse response = profileService.getExtendedProfileSummary(userID, token); @@ -365,7 +419,7 @@ void testExtendedProfile_invalidToken() { @Test void testExtendedProfile_cacheHit() throws Exception { - when(accessTokenValidator.fetchUserIdFromAccessToken(token)).thenReturn(userID); + when(accessTokenValidator.fetchUserIdFromAccessToken(anyString(), any(org.igot.common.model.ApiResponse.class))).thenReturn(userID); String cachedJson = "{\"contextA\":{\"count\":3,\"data\":[{\"a\":1},{\"b\":2},{\"c\":3}]}}"; String redisKey = "user:extendedProfile:all:user-123"; // Correct key @@ -389,8 +443,8 @@ void testExtendedProfile_cacheHit() throws Exception { @Test void testExtendedProfile_cacheWriteFails() throws Exception { - when(accessTokenValidator.fetchUserIdFromAccessToken(token)).thenReturn(userID); - when(cacheService.getCache(CACHE_KEY)).thenReturn(null); + when(accessTokenValidator.fetchUserIdFromAccessToken(anyString(), any(org.igot.common.model.ApiResponse.class))).thenReturn(userID); + when(cacheService.getCache(anyString())).thenReturn(null); when(serverProperties.getContextType()).thenReturn(contextType); String contextJson = "[{\"a\":1}]"; @@ -408,8 +462,8 @@ void testExtendedProfile_cacheWriteFails() throws Exception { @Test void testExtendedProfile_emptyData() { - when(accessTokenValidator.fetchUserIdFromAccessToken(token)).thenReturn(userID); - when(cacheService.getCache(CACHE_KEY)).thenReturn(null); + when(accessTokenValidator.fetchUserIdFromAccessToken(anyString(), any(org.igot.common.model.ApiResponse.class))).thenReturn(userID); + when(cacheService.getCache(anyString())).thenReturn(null); when(serverProperties.getContextType()).thenReturn(contextType); when(cassandraOperation.getRecordsByPropertiesByKey(any(), any(), any(), any(), any())) .thenReturn(Collections.emptyList()); @@ -422,8 +476,8 @@ void testExtendedProfile_emptyData() { @Test void testExtendedProfile_cacheError_thenCassandraData() throws Exception { - when(accessTokenValidator.fetchUserIdFromAccessToken(token)).thenReturn(userID); - when(cacheService.getCache(CACHE_KEY)).thenThrow(new RuntimeException("Simulated")); + when(accessTokenValidator.fetchUserIdFromAccessToken(anyString(), any(org.igot.common.model.ApiResponse.class))).thenReturn(userID); + when(cacheService.getCache(anyString())).thenThrow(new RuntimeException("Simulated")); when(serverProperties.getContextType()).thenReturn(contextType); @@ -435,7 +489,7 @@ void testExtendedProfile_cacheError_thenCassandraData() throws Exception { List> parsed = List.of(Map.of("x", "1"), Map.of("y", "2")); when(projectUtil.parseListOfMap(contextJson)).thenReturn(parsed); - when(objectMapper.writeValueAsString(any())).thenReturn("{}"); + lenient().when(objectMapper.writeValueAsString(any())).thenReturn("{}"); ApiResponse response = profileService.getExtendedProfileSummary(userID, token); @@ -445,7 +499,15 @@ void testExtendedProfile_cacheError_thenCassandraData() throws Exception { @Test void testInvalidToken() { - when(accessTokenValidator.fetchUserIdFromAccessToken(token)).thenReturn(null); + doAnswer(invocation -> { + ApiResponse resp = invocation.getArgument(1); + resp.setResponseCode(HttpStatus.BAD_REQUEST); + if (resp.getParams() != null) { + resp.getParams().setStatus(Constants.FAILED); + resp.getParams().setErrMsg(Constants.INVALID_USERID); + } + return null; + }).when(accessTokenValidator).fetchUserIdFromAccessToken(anyString(), any(org.igot.common.model.ApiResponse.class)); ApiResponse response = profileService.readFullExtendedProfile(userID, Arrays.toString(contextType), token); @@ -456,22 +518,22 @@ void testInvalidToken() { @Test void testCacheHit() throws Exception { String cachedJson = "[{\"data\": \"test\"}]"; - when(accessTokenValidator.fetchUserIdFromAccessToken(token)).thenReturn(userID); - when(cacheService.getCache(REDIS_KEY)).thenReturn(cachedJson); + when(accessTokenValidator.fetchUserIdFromAccessToken(anyString(), any(org.igot.common.model.ApiResponse.class))).thenReturn(userID); + when(cacheService.getCache(anyString())).thenReturn(cachedJson); List> contextList = List.of(Map.of("data", "test")); when(projectUtil.parseListOfMap(cachedJson)).thenReturn(contextList); ApiResponse response = profileService.readFullExtendedProfile(userID, Arrays.toString(contextType), token); - assertEquals(HttpStatus.NO_CONTENT, response.getResponseCode()); - assertEquals("No data found for user.", response.getParams().getErrMsg()); + assertEquals(HttpStatus.OK, response.getResponseCode()); + assertNotNull(response.get(Constants.RESPONSE)); } @Test void testCacheMiss_thenFetchFromCassandra_success() throws Exception { - when(accessTokenValidator.fetchUserIdFromAccessToken(token)).thenReturn(userID); - when(cacheService.getCache(REDIS_KEY)).thenReturn(null); + when(accessTokenValidator.fetchUserIdFromAccessToken(anyString(), any(org.igot.common.model.ApiResponse.class))).thenReturn(userID); + when(cacheService.getCache(anyString())).thenReturn(null); String json = "[{\"data\": \"test\"}]"; Map cassandraRow = Map.of(Constants.CONTEXT_DATA, json); @@ -480,7 +542,7 @@ void testCacheMiss_thenFetchFromCassandra_success() throws Exception { List> parsedList = List.of(Map.of("data", "test")); when(projectUtil.parseListOfMap(json)).thenReturn(parsedList); - when(objectMapper.writeValueAsString(parsedList)).thenReturn(json); + lenient().when(objectMapper.writeValueAsString(parsedList)).thenReturn(json); ApiResponse response = profileService.readFullExtendedProfile(userID, Arrays.toString(contextType), token); @@ -490,8 +552,8 @@ void testCacheMiss_thenFetchFromCassandra_success() throws Exception { @Test void testCacheMiss_thenFetchFromCassandra_emptyResult() { - when(accessTokenValidator.fetchUserIdFromAccessToken(token)).thenReturn(userID); - when(cacheService.getCache(REDIS_KEY)).thenReturn(null); + when(accessTokenValidator.fetchUserIdFromAccessToken(anyString(), any(org.igot.common.model.ApiResponse.class))).thenReturn(userID); + when(cacheService.getCache(anyString())).thenReturn(null); when(cassandraOperation.getRecordsByPropertiesByKey(any(), any(), any(), any(), any())) .thenReturn(Collections.emptyList()); @@ -503,7 +565,7 @@ void testCacheMiss_thenFetchFromCassandra_emptyResult() { @Test void testParseListOfMapException() throws Exception { - when(accessTokenValidator.fetchUserIdFromAccessToken(token)).thenReturn(userID); + when(accessTokenValidator.fetchUserIdFromAccessToken(anyString(), any(org.igot.common.model.ApiResponse.class))).thenReturn(userID); when(cacheService.getCache(REDIS_KEY)).thenReturn("[invalid_json]"); when(projectUtil.parseListOfMap("[invalid_json]")).thenThrow(new IOException("fail")); @@ -525,7 +587,7 @@ void testLocationDetailsBranch() { String localContextType = Constants.LOCATION_DETAILS; String json = "[{\"location\": \"India\"}]"; - when(accessTokenValidator.fetchUserIdFromAccessToken(token)).thenReturn(userID); + when(accessTokenValidator.fetchUserIdFromAccessToken(anyString(), any(org.igot.common.model.ApiResponse.class))).thenReturn(userID); when(cacheService.getCache(any())).thenReturn(null); when(cassandraOperation.getRecordsByPropertiesByKey(any(), any(), any(), any(), any())) .thenReturn(List.of(Map.of(Constants.CONTEXT_DATA, json))); @@ -546,7 +608,15 @@ void testGetBasicProfile_withInvalidToken() { String userId = "user-123"; String localToken = "invalid-token"; - when(accessTokenValidator.fetchUserIdFromAccessToken(localToken)).thenReturn(null); + doAnswer(invocation -> { + ApiResponse resp = invocation.getArgument(1); + resp.setResponseCode(HttpStatus.UNAUTHORIZED); + if (resp.getParams() != null) { + resp.getParams().setStatus(Constants.FAILED); + resp.getParams().setErrMsg("Invalid or missing access token"); + } + return null; + }).when(accessTokenValidator).fetchUserIdFromAccessToken(anyString(), any(org.igot.common.model.ApiResponse.class)); ApiResponse response = profileService.getBasicProfile(userId, localToken); @@ -574,7 +644,7 @@ void testSaveExtendedProfile_invalidUserId() { Map request = new HashMap<>(); request.put("request", requestData); - when(accessTokenValidator.fetchUserIdFromAccessToken(userToken)).thenReturn("wrongUser"); + when(accessTokenValidator.fetchUserIdFromAccessToken(anyString(), any(org.igot.common.model.ApiResponse.class))).thenReturn("wrongUser"); ApiResponse response = profileService.saveExtendedProfile(request, userToken); @@ -590,7 +660,7 @@ void testSaveExtendedProfile_invalidUserId1() { inner.put(Constants.USER_ID_RQST, userID); req.put(Constants.REQUEST, inner); - when(accessTokenValidator.fetchUserIdFromAccessToken(anyString())).thenReturn("wrong-user"); + when(accessTokenValidator.fetchUserIdFromAccessToken(anyString(), any())).thenReturn("wrong-user"); ApiResponse response = profileService.saveExtendedProfile(req, "token"); @@ -607,7 +677,7 @@ void testSaveExtendedProfile_invalidContextType() { inner.put("invalidContext", new ArrayList<>()); req.put(Constants.REQUEST, inner); - when(accessTokenValidator.fetchUserIdFromAccessToken(anyString())).thenReturn(userID); + when(accessTokenValidator.fetchUserIdFromAccessToken(anyString(), any())).thenReturn(userID); when(serverProperties.getContextType()).thenReturn(new String[] {"validContext"}); ApiResponse response = profileService.saveExtendedProfile(req, "token"); @@ -620,7 +690,7 @@ void testSaveExtendedProfile_invalidContextType() { void testSaveExtendedProfile_validationFails() { Map req = Map.of(Constants.REQUEST, Map.of(Constants.USER_ID_RQST, userID)); - when(accessTokenValidator.fetchUserIdFromAccessToken(anyString())).thenReturn(userID); + when(accessTokenValidator.fetchUserIdFromAccessToken(anyString(), any())).thenReturn(userID); when(serverProperties.getContextType()).thenReturn(new String[] {}); ApiResponse response = profileService.saveExtendedProfile(req, "token"); @@ -636,7 +706,7 @@ void testSaveExtendedProfile_nullIncomingList() { Map req = Map.of(Constants.REQUEST, requestData); - when(accessTokenValidator.fetchUserIdFromAccessToken(anyString())).thenReturn(userID); + when(accessTokenValidator.fetchUserIdFromAccessToken(anyString(), any())).thenReturn(userID); when(serverProperties.getContextType()).thenReturn(new String[] {"contextA"}); ApiResponse response = profileService.saveExtendedProfile(req, "token"); @@ -655,7 +725,7 @@ void testSaveExtendedProfile_ValidationFailure_ReturnsBadRequest() { requestData.put(Constants.EDUCATIONAL_QUALIFICATIONS, List.of(educationItem)); Map request = new HashMap<>(); request.put(Constants.REQUEST, requestData); - when(accessTokenValidator.fetchUserIdFromAccessToken(userToken)).thenReturn(userId); + when(accessTokenValidator.fetchUserIdFromAccessToken(anyString(), any(org.igot.common.model.ApiResponse.class))).thenReturn(userId); when(serverProperties.getContextType()).thenReturn(new String[]{Constants.EDUCATIONAL_QUALIFICATIONS}); when(serverProperties.getEducationalQualificationMandatoryFields()).thenReturn("degree,institute"); when(serverProperties.getAchievementsMandatoryFields()).thenReturn(""); @@ -679,7 +749,7 @@ void testSaveExtendedProfile_EmptyIncomingList_SkipsProcessingAndReturnsSuccess( requestData.put("otherContextType", List.of(validItem)); Map request = new HashMap<>(); request.put(Constants.REQUEST, requestData); - when(accessTokenValidator.fetchUserIdFromAccessToken(userToken)).thenReturn(userId); + when(accessTokenValidator.fetchUserIdFromAccessToken(anyString(), any(org.igot.common.model.ApiResponse.class))).thenReturn(userId); when(serverProperties.getContextType()).thenReturn(new String[]{ Constants.EDUCATIONAL_QUALIFICATIONS, "otherContextType" }); @@ -721,7 +791,7 @@ void testSaveExtendedProfile_SaveContextDataFails_ReturnsError(){ requestData.put(localContextType, List.of(educationItem)); Map request = new HashMap<>(); request.put(Constants.REQUEST, requestData); - when(accessTokenValidator.fetchUserIdFromAccessToken(userToken)).thenReturn(userId); + when(accessTokenValidator.fetchUserIdFromAccessToken(anyString(), any(org.igot.common.model.ApiResponse.class))).thenReturn(userId); when(serverProperties.getContextType()).thenReturn(new String[]{localContextType}); when(serverProperties.getEducationalQualificationMandatoryFields()).thenReturn("degree,institute"); when(serverProperties.getAchievementsMandatoryFields()).thenReturn(""); @@ -752,12 +822,12 @@ void testSaveExtendedProfile_UserIdMismatchWithToken_ReturnsBadRequest() { requestData.put(Constants.USER_ID_RQST, requestUserId); Map request = new HashMap<>(); request.put(Constants.REQUEST, requestData); - when(accessTokenValidator.fetchUserIdFromAccessToken(userToken)).thenReturn(tokenUserId); + when(accessTokenValidator.fetchUserIdFromAccessToken(anyString(), any(org.igot.common.model.ApiResponse.class))).thenReturn(tokenUserId); ApiResponse response = profileService.saveExtendedProfile(request, userToken); assertEquals(HttpStatus.BAD_REQUEST, response.getResponseCode()); assertEquals(Constants.FAILED, response.getParams().getStatus()); assertEquals("Invalid UserId in the request", response.getParams().getErrMsg()); - verify(accessTokenValidator).fetchUserIdFromAccessToken(userToken); + verify(accessTokenValidator).fetchUserIdFromAccessToken(eq(userToken), any(org.igot.common.model.ApiResponse.class)); verifyNoMoreInteractions(cassandraOperation, cacheService); } @@ -775,7 +845,7 @@ void testSaveExtendedProfile_NullOrEmptyList_SkipsProcessing() { requestData.put(Constants.ACHIEVEMENTS, List.of(achievementItem)); Map request = new HashMap<>(); request.put(Constants.REQUEST, requestData); - when(accessTokenValidator.fetchUserIdFromAccessToken(userToken)).thenReturn(userId); + when(accessTokenValidator.fetchUserIdFromAccessToken(anyString(), any(org.igot.common.model.ApiResponse.class))).thenReturn(userId); when(serverProperties.getContextType()).thenReturn(new String[]{ Constants.EDUCATIONAL_QUALIFICATIONS, Constants.SERVICE_HISTORY, @@ -836,7 +906,7 @@ void testUpdateExtendedProfile_FiltersOutItemsWithoutUuid() throws IOException { requestData.put(localContextType, List.of(update)); Map request = new HashMap<>(); request.put(Constants.REQUEST, requestData); - when(accessTokenValidator.fetchUserIdFromAccessToken(userToken)).thenReturn(userId); + when(accessTokenValidator.fetchUserIdFromAccessToken(anyString(), any(org.igot.common.model.ApiResponse.class))).thenReturn(userId); when(serverProperties.getContextType()).thenReturn(new String[]{localContextType}); when(cassandraOperation.getRecordsByPropertiesByKey(anyString(), anyString(), anyMap(), isNull(), isNull())) .thenReturn(List.of(Map.of(Constants.CONTEXT_DATA, "[]"))); @@ -885,7 +955,7 @@ void testUpdateExtendedProfile_InvalidUuid_ReturnsBadRequest() throws IOExceptio requestData.put(localContextType, List.of(updateItem)); Map request = new HashMap<>(); request.put(Constants.REQUEST, requestData); - when(accessTokenValidator.fetchUserIdFromAccessToken(userToken)).thenReturn(userId); + when(accessTokenValidator.fetchUserIdFromAccessToken(anyString(), any(org.igot.common.model.ApiResponse.class))).thenReturn(userId); when(serverProperties.getContextType()).thenReturn(new String[]{localContextType}); when(cassandraOperation.getRecordsByPropertiesByKey(anyString(), anyString(), anyMap(), isNull(), isNull())) .thenReturn(List.of(Map.of(Constants.CONTEXT_DATA, "[]"))); @@ -916,7 +986,7 @@ void testUpdateExtendedProfile_SaveContextDataFails_ReturnsError() throws Except requestData.put(localContextType, List.of(updateItem)); Map request = new HashMap<>(); request.put(Constants.REQUEST, requestData); - when(accessTokenValidator.fetchUserIdFromAccessToken(userToken)).thenReturn(userId); + when(accessTokenValidator.fetchUserIdFromAccessToken(anyString(), any(org.igot.common.model.ApiResponse.class))).thenReturn(userId); when(serverProperties.getContextType()).thenReturn(new String[]{localContextType}); when(cassandraOperation.getRecordsByPropertiesByKey(anyString(), anyString(), anyMap(), isNull(), isNull())) .thenReturn(List.of(Map.of(Constants.CONTEXT_DATA, "[]"))); @@ -944,7 +1014,7 @@ void testUpdateExtendedProfile_UserIdMismatch_ReturnsBadRequest() { requestData.put(Constants.USER_ID_RQST, requestUserId); Map request = new HashMap<>(); request.put(Constants.REQUEST, requestData); - when(accessTokenValidator.fetchUserIdFromAccessToken(userToken)).thenReturn(tokenUserId); + when(accessTokenValidator.fetchUserIdFromAccessToken(anyString(), any(org.igot.common.model.ApiResponse.class))).thenReturn(tokenUserId); ApiResponse response = profileService.updateExtendedProfile(request, userToken); assertEquals(HttpStatus.BAD_REQUEST, response.getResponseCode()); assertEquals(Constants.FAILED, response.getParams().getStatus()); @@ -966,7 +1036,7 @@ void testUpdateExtendedProfile_EmptyIncomingList_SkipsProcessing() { requestData.put(contextType2, null); // Null list Map request = new HashMap<>(); request.put(Constants.REQUEST, requestData); - when(accessTokenValidator.fetchUserIdFromAccessToken(userToken)).thenReturn(userId); + when(accessTokenValidator.fetchUserIdFromAccessToken(anyString(), any(org.igot.common.model.ApiResponse.class))).thenReturn(userId); when(serverProperties.getContextType()).thenReturn(new String[]{contextType1, contextType2}); ApiResponse response = profileService.updateExtendedProfile(request, userToken); assertEquals(HttpStatus.OK, response.getResponseCode()); @@ -987,7 +1057,7 @@ void testUpdateExtendedProfile_NullUuid_ReturnsBadRequest() { requestData.put(localContextType, List.of(updateWithNullUuid)); Map request = new HashMap<>(); request.put(Constants.REQUEST, requestData); - when(accessTokenValidator.fetchUserIdFromAccessToken(userToken)).thenReturn(userId); + when(accessTokenValidator.fetchUserIdFromAccessToken(anyString(), any(org.igot.common.model.ApiResponse.class))).thenReturn(userId); when(serverProperties.getContextType()).thenReturn(new String[]{localContextType}); when(cassandraOperation.getRecordsByPropertiesByKey(anyString(), anyString(), anyMap(), any(), any())) .thenReturn(new ArrayList<>()); @@ -1011,7 +1081,7 @@ void testDeleteExtendedProfile_SaveContextDataFails_ReturnsError() throws Except requestData.put(localContextType, List.of(deleteItem)); Map request = new HashMap<>(); request.put(Constants.REQUEST, requestData); - when(accessTokenValidator.fetchUserIdFromAccessToken(userToken)).thenReturn(userId); + when(accessTokenValidator.fetchUserIdFromAccessToken(anyString(), any(org.igot.common.model.ApiResponse.class))).thenReturn(userId); when(serverProperties.getContextType()).thenReturn(new String[]{localContextType}); when(cassandraOperation.getRecordsByPropertiesByKey(anyString(), anyString(), anyMap(), any(), any())) .thenReturn(List.of(Map.of(Constants.CONTEXT_DATA, "[]"))); @@ -1037,7 +1107,7 @@ void testGetExtendedProfileSummary_CachePutThrowsException_LogsWarning() throws when(projectUtil.parseListOfMap(anyString())).thenReturn( new ArrayList<>(List.of(new HashMap<>(Map.of("field", "value")))) ); - when(accessTokenValidator.fetchUserIdFromAccessToken(userToken)).thenReturn(userId); + when(accessTokenValidator.fetchUserIdFromAccessToken(anyString(), any(org.igot.common.model.ApiResponse.class))).thenReturn(userId); doThrow(new RuntimeException("Cache error")).when(cacheService).putCache(anyString(), any()); ApiResponse response = profileService.getExtendedProfileSummary(userId, userToken); assertEquals(HttpStatus.OK, response.getResponseCode()); @@ -1054,7 +1124,7 @@ void testDeleteExtendedProfile_UserIdMismatch_ReturnsBadRequest() { requestData.put(Constants.USER_ID_RQST, requestUserId); Map request = new HashMap<>(); request.put(Constants.REQUEST, requestData); - when(accessTokenValidator.fetchUserIdFromAccessToken(userToken)).thenReturn(tokenUserId); + when(accessTokenValidator.fetchUserIdFromAccessToken(anyString(), any(org.igot.common.model.ApiResponse.class))).thenReturn(tokenUserId); ApiResponse response = profileService.deleteExtendedProfile(request, userToken); assertEquals(HttpStatus.BAD_REQUEST, response.getResponseCode()); assertEquals("Invalid UserId in the request", response.getParams().getErrMsg()); @@ -1072,7 +1142,7 @@ void testDeleteExtendedProfile_ToDeleteListNullOrEmpty_SkipsProcessing() { requestData.put(contextType2, Collections.emptyList()); // empty list Map request = new HashMap<>(); request.put(Constants.REQUEST, requestData); - when(accessTokenValidator.fetchUserIdFromAccessToken(userToken)).thenReturn(userId); + when(accessTokenValidator.fetchUserIdFromAccessToken(anyString(), any(org.igot.common.model.ApiResponse.class))).thenReturn(userId); when(serverProperties.getContextType()).thenReturn(new String[]{contextType1, contextType2}); ApiResponse response = profileService.deleteExtendedProfile(request, userToken); assertEquals(HttpStatus.OK, response.getResponseCode()); @@ -1088,7 +1158,7 @@ void testReadFullExtendedProfile_NoContextData_ReturnsNoContent() throws Excepti String userToken = "valid-token"; String localContextType = "education"; String redisKey = "user:extendedProfile:" + localContextType + ":" + userId; - when(accessTokenValidator.fetchUserIdFromAccessToken(userToken)).thenReturn(userId); + when(accessTokenValidator.fetchUserIdFromAccessToken(anyString(), any(org.igot.common.model.ApiResponse.class))).thenReturn(userId); when(cacheService.getCache(redisKey)).thenReturn(null); when(cassandraOperation.getRecordsByPropertiesByKey(anyString(), anyString(), anyMap(), any(), any())) .thenReturn(null); // or Collections.emptyList() @@ -1496,46 +1566,6 @@ void getSortingComparator_handlesMissingFieldsGracefully() { assertThrows(NumberFormatException.class, () -> data.sort(comparator)); } - @Test - void sortContextData_sortsListDescending_whenComparatorExists() { - ProfileServiceImpl localService = new ProfileServiceImpl(); - List> dataList = new ArrayList<>(); - dataList.add(Map.of(Constants.START_DATE, "2022-01-01T00:00:00Z")); - dataList.add(Map.of(Constants.START_DATE, "2023-01-01T00:00:00Z")); - ReflectionTestUtils.invokeMethod(localService, "sortContextData", dataList, Constants.SERVICE_HISTORY); - assertEquals("2023-01-01T00:00:00Z", dataList.get(0).get(Constants.START_DATE)); - } - - @Test - void sortContextData_doesNotSort_whenComparatorIsNull() { - ProfileServiceImpl localService = new ProfileServiceImpl(); - List> dataList = new ArrayList<>(); - dataList.add(Map.of("field", "A")); - dataList.add(Map.of("field", "B")); - List> original = new ArrayList<>(dataList); - ReflectionTestUtils.invokeMethod(localService, "sortContextData", dataList, "unknownType"); - assertEquals(original, dataList); - } - - @Test - void sortContextData_handlesEmptyList() { - ProfileServiceImpl localService = new ProfileServiceImpl(); - List> dataList = new ArrayList<>(); - ReflectionTestUtils.invokeMethod(localService, "sortContextData", dataList, Constants.SERVICE_HISTORY); - assertTrue(dataList.isEmpty()); - } - - @Test - void sortContextData_throwsException_whenFieldMissing() { - ProfileServiceImpl localService = new ProfileServiceImpl(); - List> dataList = new ArrayList<>(); - dataList.add(new HashMap<>()); - dataList.add(Map.of(Constants.START_YEAR, "2020")); - assertThrows(NumberFormatException.class, () -> - ReflectionTestUtils.invokeMethod(localService, "sortContextData", dataList, Constants.EDUCATIONAL_QUALIFICATIONS) - ); - } - @Test void returnsCachedCertificateCount_whenCacheHit() { ProfileServiceImpl localService = new ProfileServiceImpl(); @@ -2014,7 +2044,7 @@ void testGetAdditionalFieldsByOrg_BlankAuthToken() { @Test void testGetAdditionalFieldsByOrg_UserIdMismatch() { // Arrange - when(accessTokenValidator.fetchUserIdFromAccessToken("token123")).thenReturn("differentUser"); + when(accessTokenValidator.fetchUserIdFromAccessToken(anyString(), any(org.igot.common.model.ApiResponse.class))).thenReturn("differentUser"); // Act ApiResponse response = profileService.getAdditionalFieldsByOrg("user1", "org1", "token123"); @@ -2026,7 +2056,7 @@ void testGetAdditionalFieldsByOrg_UserIdMismatch() { @Test void testGetAdditionalFieldsByOrg_OrgDataNotFound() throws Exception { // Arrange - when(accessTokenValidator.fetchUserIdFromAccessToken("token123")).thenReturn("user1"); + when(accessTokenValidator.fetchUserIdFromAccessToken(anyString(), any(org.igot.common.model.ApiResponse.class))).thenReturn("user1"); // Mock cassandra operation to return data for different org Map contextData = Map.of( @@ -2051,7 +2081,7 @@ void testGetAdditionalFieldsByOrg_OrgDataNotFound() throws Exception { @Test void testGetAdditionalFieldsByOrg_OrgDataFound() throws Exception { // Arrange - when(accessTokenValidator.fetchUserIdFromAccessToken("token123")).thenReturn("user1"); + when(accessTokenValidator.fetchUserIdFromAccessToken(anyString(), any(org.igot.common.model.ApiResponse.class))).thenReturn("user1"); // Mock cassandra operation to return organization data Map contextData = Map.of( @@ -2889,7 +2919,7 @@ void updateAdditionalFields_returnsUnauthorized_whenAuthTokenBlank() { @Test void updateAdditionalFields_returnsBadRequest_whenValidationFails() { Map req = Map.of(); // missing required params - when(accessTokenValidator.fetchUserIdFromAccessToken("token")).thenReturn("user1"); + when(accessTokenValidator.fetchUserIdFromAccessToken(anyString(), any(org.igot.common.model.ApiResponse.class))).thenReturn("user1"); String result = ReflectionTestUtils.invokeMethod(profileService, "validateAdditionalFieldsRequest", req); assertEquals("Failed Due To Missing Params - [userId, organisationId, customFieldValues].", result); ApiResponse response = profileService.updateAdditionalFields(req, "token"); @@ -2898,7 +2928,7 @@ void updateAdditionalFields_returnsBadRequest_whenValidationFails() { @Test void updateAdditionalFields_returnsInternalServerError_whenSaveFails() { - when(accessTokenValidator.fetchUserIdFromAccessToken("token")).thenReturn("user1"); + when(accessTokenValidator.fetchUserIdFromAccessToken(anyString(), any(org.igot.common.model.ApiResponse.class))).thenReturn("user1"); Map req = Map.of( Constants.USER_ID, "user1", Constants.ORGANISATION_ID, "org1", @@ -2916,7 +2946,7 @@ void updateAdditionalFields_returnsUnauthorized_whenUserIdMismatch() { Constants.ORGANISATION_ID, "org1", Constants.CUSTOM_FIELD_VALUES, List.of() ); - when(accessTokenValidator.fetchUserIdFromAccessToken("token")).thenReturn("userX"); + when(accessTokenValidator.fetchUserIdFromAccessToken(anyString(), any(org.igot.common.model.ApiResponse.class))).thenReturn("userX"); ReflectionTestUtils.setField(profileService, "accessTokenValidator", accessTokenValidator); ApiResponse response = profileService.updateAdditionalFields(req, "token"); assertEquals(HttpStatus.BAD_REQUEST, response.getResponseCode()); @@ -2924,7 +2954,7 @@ void updateAdditionalFields_returnsUnauthorized_whenUserIdMismatch() { @Test void updateAdditionalFields_returnsInternalServerError_whenESUpdateFails() { - when(accessTokenValidator.fetchUserIdFromAccessToken("token")).thenReturn("user1"); + when(accessTokenValidator.fetchUserIdFromAccessToken(anyString(), any(org.igot.common.model.ApiResponse.class))).thenReturn("user1"); Map req = Map.of( Constants.USER_ID, "user1", Constants.ORGANISATION_ID, "org1", diff --git a/src/test/java/com/igot/cb/profile/controller/ProfileControllerTest.java b/src/test/java/com/igot/cb/profile/controller/ProfileControllerTest.java index ef3b210..8af027a 100644 --- a/src/test/java/com/igot/cb/profile/controller/ProfileControllerTest.java +++ b/src/test/java/com/igot/cb/profile/controller/ProfileControllerTest.java @@ -2,15 +2,17 @@ import com.fasterxml.jackson.databind.ObjectMapper; import com.igot.cb.profile.service.ProfileService; -import com.igot.cb.util.ApiResponse; import com.igot.cb.util.Constants; -import com.igot.cb.util.ProjectUtil; + +import org.igot.common.model.ApiResponse; +import org.igot.common.util.ProjectUtil; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import org.junit.jupiter.api.extension.ExtendWith; import org.mockito.InjectMocks; import org.mockito.Mock; import org.mockito.junit.jupiter.MockitoExtension; +import org.springframework.http.HttpStatus; import org.springframework.http.MediaType; import org.springframework.test.web.servlet.MockMvc; import org.springframework.test.web.servlet.setup.MockMvcBuilders; @@ -20,6 +22,7 @@ import static org.mockito.Mockito.verify; import static org.mockito.Mockito.when; +import static org.mockito.Mockito.mock; import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.*; import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status; @@ -31,6 +34,9 @@ class ProfileControllerTest { @Mock private ProfileService profileService; + @Mock + private ProjectUtil projectUtil; + @InjectMocks private ProfileController profileController; @@ -48,7 +54,8 @@ void testSaveExtendedProfile() throws Exception { Map request = new HashMap<>(); request.put("field1", "value1"); - ApiResponse mockResponse = ProjectUtil.createDefaultResponse("SAVE_EXTENDED_PROFILE"); + ApiResponse mockResponse = mock(ApiResponse.class); + when(mockResponse.getResponseCode()).thenReturn(HttpStatus.OK); when(profileService.saveExtendedProfile((request), (authToken))).thenReturn(mockResponse); mockMvc.perform(post("/user/profile/extended") @@ -64,7 +71,8 @@ void testSaveExtendedProfile() throws Exception { void testGetExtendedProfileSummary() throws Exception { String authToken = "test-auth-token"; String userId = "user-123"; - ApiResponse mockResponse = ProjectUtil.createDefaultResponse("GET_EXTENDED_PROFILE"); + ApiResponse mockResponse = mock(ApiResponse.class); + when(mockResponse.getResponseCode()).thenReturn(HttpStatus.OK); when(profileService.getExtendedProfileSummary((userId), (authToken))).thenReturn(mockResponse); @@ -80,7 +88,8 @@ void testGetExtendedProfileSummary() throws Exception { void testGetServiceHistory() throws Exception { String authToken = "test-auth-token"; String userId = "user-123"; - ApiResponse mockResponse = ProjectUtil.createDefaultResponse("GET_SERVICE_HISTORY"); + ApiResponse mockResponse = mock(ApiResponse.class); + when(mockResponse.getResponseCode()).thenReturn(HttpStatus.OK); when(profileService.readFullExtendedProfile((userId), (Constants.SERVICE_HISTORY), (authToken))) .thenReturn(mockResponse); @@ -96,7 +105,8 @@ void testGetServiceHistory() throws Exception { void testGetEducationalQualifications() throws Exception { String authToken = "test-auth-token"; String userId = "user-123"; - ApiResponse mockResponse = ProjectUtil.createDefaultResponse("GET_EDUCATION"); + ApiResponse mockResponse = mock(ApiResponse.class); + when(mockResponse.getResponseCode()).thenReturn(HttpStatus.OK); when(profileService.readFullExtendedProfile((userId), (Constants.EDUCATION_QUALIFICATION), (authToken))) .thenReturn(mockResponse); @@ -112,7 +122,8 @@ void testGetEducationalQualifications() throws Exception { void testGetLocationDetails() throws Exception { String authToken = "test-auth-token"; String userId = "user-123"; - ApiResponse mockResponse = ProjectUtil.createDefaultResponse("GET_LOCATION"); + ApiResponse mockResponse = mock(ApiResponse.class); + when(mockResponse.getResponseCode()).thenReturn(HttpStatus.OK); when(profileService.readFullExtendedProfile((userId), (Constants.LOCATION_DETAILS), (authToken))) .thenReturn(mockResponse); @@ -128,7 +139,8 @@ void testGetLocationDetails() throws Exception { void testGetAchievements() throws Exception { String authToken = "test-auth-token"; String userId = "user-123"; - ApiResponse mockResponse = ProjectUtil.createDefaultResponse("GET_ACHIEVEMENTS"); + ApiResponse mockResponse = mock(ApiResponse.class); + when(mockResponse.getResponseCode()).thenReturn(HttpStatus.OK); when(profileService.readFullExtendedProfile((userId), (Constants.ACHIEVEMENTS), (authToken))) .thenReturn(mockResponse); @@ -146,7 +158,8 @@ void testUpdateExtendedProfile() throws Exception { Map request = new HashMap<>(); request.put("field1", "updatedValue"); - ApiResponse mockResponse = ProjectUtil.createDefaultResponse("UPDATE_EXTENDED_PROFILE"); + ApiResponse mockResponse = mock(ApiResponse.class); + when(mockResponse.getResponseCode()).thenReturn(HttpStatus.OK); when(profileService.updateExtendedProfile((request), (authToken))).thenReturn(mockResponse); @@ -165,7 +178,8 @@ void testDeleteExtendedProfile() throws Exception { Map request = new HashMap<>(); request.put("profileId", "123"); - ApiResponse mockResponse = ProjectUtil.createDefaultResponse("DELETE_EXTENDED_PROFILE"); + ApiResponse mockResponse = mock(ApiResponse.class); + when(mockResponse.getResponseCode()).thenReturn(HttpStatus.OK); when(profileService.deleteExtendedProfile((request), (authToken))).thenReturn(mockResponse); @@ -183,7 +197,8 @@ void testGetBasicProfile() throws Exception { String authToken = "test-auth-token"; String userId = "user-123"; - ApiResponse mockResponse = ProjectUtil.createDefaultResponse("GET_BASIC_PROFILE"); + ApiResponse mockResponse = mock(ApiResponse.class); + when(mockResponse.getResponseCode()).thenReturn(HttpStatus.OK); when(profileService.getBasicProfile((userId), (authToken))).thenReturn(mockResponse); @@ -199,7 +214,8 @@ void testGetCompetencies() throws Exception { String authToken = "test-auth-token"; String userId = "user-123"; - ApiResponse mockResponse = ProjectUtil.createDefaultResponse("GET_COMPETENCIES"); + ApiResponse mockResponse = mock(ApiResponse.class); + when(mockResponse.getResponseCode()).thenReturn(HttpStatus.OK); when(profileService.listCompetencies((userId), (authToken))).thenReturn(mockResponse); diff --git a/src/test/java/com/igot/cb/util/ProjectUtilTest.java b/src/test/java/com/igot/cb/util/ProjectUtilTest.java index 8923cdd..7aa60b3 100644 --- a/src/test/java/com/igot/cb/util/ProjectUtilTest.java +++ b/src/test/java/com/igot/cb/util/ProjectUtilTest.java @@ -36,7 +36,7 @@ public void testCreateServerError() { assertNotNull(exception); assertEquals(responseCode.getErrorCode(), exception.getErrorCode()); assertEquals(responseCode.getErrorMessage(), exception.getMessage()); - assertEquals(Integer.valueOf(ResponseCode.SERVER_ERROR.getResponseCode()), + assertEquals(Integer.valueOf(ResponseCode.SERVER_ERROR.getHttpStatusCode()), Integer.valueOf(exception.getResponseCode())); } @@ -47,7 +47,7 @@ public void testCreateClientException() { assertNotNull(exception); assertEquals(responseCode.getErrorCode(), exception.getErrorCode()); assertEquals(responseCode.getErrorMessage(), exception.getMessage()); - assertEquals(Integer.valueOf(ResponseCode.CLIENT_ERROR.getResponseCode()), + assertEquals(Integer.valueOf(ResponseCode.CLIENT_ERROR.getHttpStatusCode()), Integer.valueOf(exception.getResponseCode())); } diff --git a/src/test/java/com/igot/cb/util/ServiceFactoryTest.java b/src/test/java/com/igot/cb/util/ServiceFactoryTest.java index 4ba48f3..c0ab7c2 100644 --- a/src/test/java/com/igot/cb/util/ServiceFactoryTest.java +++ b/src/test/java/com/igot/cb/util/ServiceFactoryTest.java @@ -31,6 +31,10 @@ public void testStaticInitialization() { DecryptionService decService = ServiceFactory.getDecryptionServiceInstance(); assertNotNull("Encryption service should be initialized", encService); assertNotNull("Decryption service should be initialized", decService); - assertNotEquals("Services should be different instances", encService, decService); + assertNotEquals( + "Services should be of different types", + encService.getClass(), + decService.getClass() + ); } } \ No newline at end of file