diff --git a/src/main/java/org/sunbird/assessment/controller/AssessmentController.java b/src/main/java/org/sunbird/assessment/controller/AssessmentController.java index 0c6562a1..b3dd59cc 100644 --- a/src/main/java/org/sunbird/assessment/controller/AssessmentController.java +++ b/src/main/java/org/sunbird/assessment/controller/AssessmentController.java @@ -110,8 +110,7 @@ public ResponseEntity> getUserAssessmentByContent(@RequestHe */ @GetMapping("/v2/{courseId}/assessment/{assessmentContentId}") public ResponseEntity> getAssessmentContent(@PathVariable("courseId") String courseId, - @PathVariable("assessmentContentId") String assessmentContentId, @RequestHeader("rootOrg") String rootOrg) - throws Exception { + @PathVariable("assessmentContentId") String assessmentContentId, @RequestHeader("rootOrg") String rootOrg) { return new ResponseEntity<>(assessmentService.getAssessmentContent(courseId, assessmentContentId), HttpStatus.OK); } @@ -119,10 +118,10 @@ public ResponseEntity> getAssessmentContent(@PathVariable("c // ======================= // QUML based Assessment APIs @PostMapping("/v3/user/assessment/submit") - public ResponseEntity submitUserAssessmentV3(@Valid @RequestBody Map requestBody, + public ResponseEntity submitUserAssessmentV3(@Valid @RequestBody Map requestBody, @RequestHeader("x-authenticated-user-token") String authUserToken , @RequestParam(name = "editMode" ,required = false) String editMode) throws Exception { - Boolean edit = StringUtils.isEmpty(editMode) ? false : Boolean.parseBoolean(editMode); + Boolean edit = StringUtils.isEmpty(editMode) ? Boolean.FALSE : Boolean.parseBoolean(editMode); SBApiResponse submitResponse = assessmentServiceV2.submitAssessment(requestBody, authUserToken,edit); return new ResponseEntity<>(submitResponse, submitResponse.getResponseCode()); } @@ -144,8 +143,8 @@ public ResponseEntity readAssessment( } @PostMapping("/v1/quml/question/list") - public ResponseEntity readQuestionList(@Valid @RequestBody Map requestBody, - @RequestHeader("x-authenticated-user-token") String authUserToken) throws Exception { + public ResponseEntity readQuestionList(@Valid @RequestBody Map requestBody, + @RequestHeader("x-authenticated-user-token") String authUserToken) { SBApiResponse response = assessmentServiceV2.readQuestionList(requestBody, authUserToken); return new ResponseEntity<>(response, response.getResponseCode()); } @@ -153,7 +152,7 @@ public ResponseEntity readQuestionList(@Valid @RequestBody Map retakeAssessment( @PathVariable("assessmentIdentifier") String assessmentIdentifier, - @RequestHeader(Constants.X_AUTH_TOKEN) String token) throws Exception { + @RequestHeader(Constants.X_AUTH_TOKEN) String token) { SBApiResponse readResponse = assessmentServiceV2.retakeAssessment(assessmentIdentifier, token); return new ResponseEntity<>(readResponse, readResponse.getResponseCode()); } @@ -163,9 +162,9 @@ public ResponseEntity retakeAssessment( // Async capability and not using Redis // ======================= @PostMapping("/v4/user/assessment/submit") - public ResponseEntity submitUserAssessmentV4(@Valid @RequestBody Map requestBody, + public ResponseEntity submitUserAssessmentV4(@Valid @RequestBody Map requestBody, @RequestHeader("x-authenticated-user-token") String authUserToken,@RequestParam(name = "editMode" ,required = false) String editMode) { - Boolean edit = StringUtils.isEmpty(editMode) ? false : Boolean.parseBoolean(editMode); + Boolean edit = StringUtils.isEmpty(editMode) ? Boolean.FALSE : Boolean.parseBoolean(editMode); SBApiResponse submitResponse = assessmentServiceV4.submitAssessmentAsync(requestBody, authUserToken,edit); return new ResponseEntity<>(submitResponse, submitResponse.getResponseCode()); } @@ -182,15 +181,15 @@ public ResponseEntity submitUserAssessmentV4(@Valid @RequestBody Map readAssessmentV4( @PathVariable("assessmentIdentifier") String assessmentIdentifier, @RequestHeader(Constants.X_AUTH_TOKEN) String token,@RequestParam(name = "editMode" ,required = false) String editMode) { - Boolean edit = StringUtils.isEmpty(editMode) ? false : Boolean.parseBoolean(editMode); + Boolean edit = StringUtils.isEmpty(editMode) ? Boolean.FALSE: Boolean.parseBoolean(editMode); SBApiResponse readResponse = assessmentServiceV4.readAssessment(assessmentIdentifier, token,edit); return new ResponseEntity<>(readResponse, readResponse.getResponseCode()); } @PostMapping("/v4/quml/question/list") - public ResponseEntity readQuestionListV4(@Valid @RequestBody Map requestBody, + public ResponseEntity readQuestionListV4(@Valid @RequestBody Map requestBody, @RequestHeader("x-authenticated-user-token") String authUserToken,@RequestParam(name = "editMode" ,required = false) String editMode) { - Boolean edit = StringUtils.isEmpty(editMode) ? false : Boolean.parseBoolean(editMode); + Boolean edit = StringUtils.isEmpty(editMode) ? Boolean.FALSE: Boolean.parseBoolean(editMode); SBApiResponse response = assessmentServiceV4.readQuestionList(requestBody, authUserToken,edit); return new ResponseEntity<>(response, response.getResponseCode()); } @@ -199,13 +198,13 @@ public ResponseEntity readQuestionListV4(@Valid @RequestBody Map retakeAssessmentV4( @PathVariable("assessmentIdentifier") String assessmentIdentifier, @RequestHeader(Constants.X_AUTH_TOKEN) String token,@RequestParam(name = "editMode" ,required = false) String editMode) { - Boolean edit = StringUtils.isEmpty(editMode) ? false : Boolean.parseBoolean(editMode); + Boolean edit = StringUtils.isEmpty(editMode) ? Boolean.FALSE: Boolean.parseBoolean(editMode); SBApiResponse readResponse = assessmentServiceV4.retakeAssessment(assessmentIdentifier, token,edit); return new ResponseEntity<>(readResponse, readResponse.getResponseCode()); } @PostMapping("/v4/quml/assessment/result") - public ResponseEntity readAssessmentResultV4(@Valid @RequestBody Map requestBody, + public ResponseEntity readAssessmentResultV4(@Valid @RequestBody Map requestBody, @RequestHeader("x-authenticated-user-token") String authUserToken) { SBApiResponse response = assessmentServiceV4.readAssessmentResultV4(requestBody, authUserToken); return new ResponseEntity<>(response, response.getResponseCode()); diff --git a/src/main/java/org/sunbird/assessment/controller/CohortsController.java b/src/main/java/org/sunbird/assessment/controller/CohortsController.java index fa78f94c..a20d96a6 100644 --- a/src/main/java/org/sunbird/assessment/controller/CohortsController.java +++ b/src/main/java/org/sunbird/assessment/controller/CohortsController.java @@ -12,7 +12,6 @@ import org.springframework.web.bind.annotation.RestController; import org.sunbird.assessment.repo.CohortUsers; import org.sunbird.assessment.service.CohortsService; -import org.sunbird.common.model.Response; import org.sunbird.common.model.SBApiResponse; import org.sunbird.common.util.Constants; @@ -35,7 +34,7 @@ public class CohortsController { @GetMapping("/v2/resources/{resourceId}/user/{userUUID}/cohorts/top-performers") public ResponseEntity> getTopPerformers(@PathVariable("resourceId") String resourceId, @RequestHeader("rootOrg") String rootOrg, @PathVariable("userUUID") String userUUID, - @RequestParam(value = "count", defaultValue = "20", required = false) Integer count) throws Exception { + @RequestParam(value = "count", defaultValue = "20", required = false) Integer count) { return new ResponseEntity<>(cohortsServ.getTopPerformers(rootOrg, resourceId, userUUID, count), HttpStatus.OK); @@ -56,8 +55,7 @@ public ResponseEntity> getActiveUsers(@RequestHeader("Authoriz @PathVariable("resourceId") String contentId, @RequestHeader("rootOrg") String rootOrg, @PathVariable("userUUID") String userUUID, @RequestParam(value = "count", required = false, defaultValue = "50") Integer count, - @RequestParam(value = "filter", required = false, defaultValue = "false") Boolean toFilter) - throws Exception { + @RequestParam(value = "filter", required = false, defaultValue = "false") Boolean toFilter) { if (authUserToken.contains(" ")) { authUserToken = authUserToken.split(" ")[1]; } @@ -80,7 +78,7 @@ public ResponseEntity autoEnrollmentInCourse(@RequestHeader("Auth @RequestHeader(name = Constants.X_AUTH_USER_ORG_ID, required = false) String rootOrgId, @PathVariable("courseId") String contentId, @RequestHeader("rootOrg") String rootOrg, - @PathVariable("userUUID") String userUUID) throws Exception { + @PathVariable("userUUID") String userUUID) { if (authUserToken.contains(" ")) { authUserToken = authUserToken.split(" ")[1]; } @@ -103,7 +101,7 @@ public ResponseEntity autoEnrollmentInCourse(@RequestHeader("Auth @GetMapping("/v2/resources/user/cohorts/top-performers") public ResponseEntity> getTopPerformersForResource(@RequestHeader("resourceId") String resourceId, @RequestHeader("rootOrg") String rootOrg, @RequestHeader("userUUID") String userUUID, - @RequestParam(value = "count", defaultValue = "20", required = false) Integer count) throws Exception { + @RequestParam(value = "count", defaultValue = "20", required = false) Integer count) { return new ResponseEntity<>(cohortsServ.getTopPerformers(rootOrg, resourceId, userUUID, count), HttpStatus.OK); @@ -127,8 +125,7 @@ public ResponseEntity> getActiveUsersForResource(@RequestHeade @RequestHeader("resourceId") String contentId, @RequestHeader("rootOrg") String rootOrg, @RequestHeader("userUUID") String userUUID, @RequestParam(value = "count", required = false, defaultValue = "50") Integer count, - @RequestParam(value = "filter", required = false, defaultValue = "false") Boolean toFilter) - throws Exception { + @RequestParam(value = "filter", required = false, defaultValue = "false") Boolean toFilter) { return new ResponseEntity<>( cohortsServ.getActiveUsers(authUserToken, rootOrgId, rootOrg, contentId, userUUID, count, toFilter), HttpStatus.OK); @@ -148,7 +145,7 @@ public ResponseEntity userAutoEnrollment(@RequestHeader("x-authen @RequestHeader(name = Constants.X_AUTH_USER_ORG_ID, required = false) String rootOrgId, @RequestHeader("courseId") String contentId, @RequestHeader("rootOrg") String rootOrg, - @RequestHeader("userUUID") String userUUID)throws Exception { + @RequestHeader("userUUID") String userUUID) { SBApiResponse response = cohortsServ.autoEnrollmentInCourseV2(authUserToken, rootOrgId, rootOrg, contentId, userUUID); return new ResponseEntity<>(response, response.getResponseCode()); diff --git a/src/main/java/org/sunbird/assessment/controller/OffensiveDataReportController.java b/src/main/java/org/sunbird/assessment/controller/OffensiveDataReportController.java index 4d2be72f..052edb63 100644 --- a/src/main/java/org/sunbird/assessment/controller/OffensiveDataReportController.java +++ b/src/main/java/org/sunbird/assessment/controller/OffensiveDataReportController.java @@ -18,7 +18,7 @@ public class OffensiveDataReportController { @PostMapping("/v1/offensive/data/flag") public ResponseEntity createFlag( - @Valid @RequestBody Map requestBody, @RequestHeader(Constants.X_AUTH_TOKEN) String token) throws Exception { + @Valid @RequestBody Map requestBody, @RequestHeader(Constants.X_AUTH_TOKEN) String token) { SBApiResponse readResponse = offensiveDataFlagService.createFlag(requestBody, token); return new ResponseEntity<>(readResponse, readResponse.getResponseCode()); } @@ -31,7 +31,7 @@ public ResponseEntity updateFlag(@RequestHeader(Constants.X_AUTH_ } @GetMapping("/v1/offensive/data/flag/getFlaggedData") - public ResponseEntity getFlaggedData(@RequestHeader(Constants.X_AUTH_TOKEN) String token) throws Exception { + public ResponseEntity getFlaggedData(@RequestHeader(Constants.X_AUTH_TOKEN) String token) { SBApiResponse readResponse = offensiveDataFlagService.getFlaggedData(token); return new ResponseEntity<>(readResponse, readResponse.getResponseCode()); } diff --git a/src/main/java/org/sunbird/assessment/repo/AssessmentRepository.java b/src/main/java/org/sunbird/assessment/repo/AssessmentRepository.java index 62891dc7..a773b94d 100644 --- a/src/main/java/org/sunbird/assessment/repo/AssessmentRepository.java +++ b/src/main/java/org/sunbird/assessment/repo/AssessmentRepository.java @@ -46,8 +46,7 @@ public Map insertQuizOrAssessment(Map persist, B * @return * @throws Exception */ - public List> getAssessmentbyContentUser(String rootOrg, String courseId, String userId) - throws Exception; + public List> getAssessmentbyContentUser(String rootOrg, String courseId, String userId); List> fetchUserAssessmentDataFromDB(String userId, String assessmentIdentifier); diff --git a/src/main/java/org/sunbird/assessment/repo/AssessmentRepositoryImpl.java b/src/main/java/org/sunbird/assessment/repo/AssessmentRepositoryImpl.java index 2bd64e58..ec3a7e50 100644 --- a/src/main/java/org/sunbird/assessment/repo/AssessmentRepositoryImpl.java +++ b/src/main/java/org/sunbird/assessment/repo/AssessmentRepositoryImpl.java @@ -2,6 +2,7 @@ import java.math.BigDecimal; import java.sql.Timestamp; +import java.text.ParseException; import java.text.SimpleDateFormat; import java.util.Collections; import java.util.Date; @@ -17,8 +18,6 @@ import org.sunbird.cassandra.utils.CassandraOperation; import org.sunbird.common.model.SBApiResponse; import org.sunbird.common.util.Constants; -import org.sunbird.core.logger.CbExtLogger; - import com.datastax.driver.core.utils.UUIDs; import com.google.gson.Gson; @@ -29,7 +28,6 @@ public class AssessmentRepositoryImpl implements AssessmentRepository { public static final String RESULT = "result"; public static final String SOURCE_ID = "sourceId"; public static final String USER_ID = "userId"; - private CbExtLogger logger = new CbExtLogger(getClass().getName()); @Autowired UserAssessmentSummaryRepository userAssessmentSummaryRepo; @@ -46,15 +44,15 @@ public class AssessmentRepositoryImpl implements AssessmentRepository { SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd"); @Override - public Map getAssessmentAnswerKey(String artifactUrl) throws Exception { - // TODO Auto-generated method stub - return null; + public Map getAssessmentAnswerKey(String artifactUrl) { + + return new HashMap<>(); } @Override - public Map getQuizAnswerKey(AssessmentSubmissionDTO quizMap) throws Exception { - // TODO Auto-generated method stub - return null; + public Map getQuizAnswerKey(AssessmentSubmissionDTO quizMap) { + + return new HashMap<>(); } @Override @@ -65,15 +63,8 @@ public Map insertQuizOrAssessment(Map persist, B // insert assessment and assessment summary if (Boolean.TRUE.equals(isAssessment)) { - UserAssessmentMasterModel assessment = new UserAssessmentMasterModel( - new UserAssessmentMasterPrimaryKeyModel(persist.get(ROOT_ORG).toString(), date, - persist.get("parent").toString(), BigDecimal.valueOf((Double) persist.get(RESULT)), - UUIDs.timeBased()), - Integer.parseInt(persist.get("correct").toString()), formatter.parse(formatter.format(date)), - Integer.parseInt(persist.get("incorrect").toString()), - Integer.parseInt(persist.get("blank").toString()), persist.get("parentContentType").toString(), - new BigDecimal(60), persist.get(SOURCE_ID).toString(), persist.get("title").toString(), - persist.get(USER_ID).toString()); + Map userAssessmentMasterModelDate = this.getUserAssessmentMasterModelData(persist, date); + UserAssessmentMasterModel assessment = new UserAssessmentMasterModel(); UserAssessmentSummaryModel summary = new UserAssessmentSummaryModel(); UserAssessmentSummaryModel data = userAssessmentSummaryRepo .findById(new UserAssessmentSummaryPrimaryKeyModel(persist.get(ROOT_ORG).toString(), @@ -129,9 +120,7 @@ public Map insertQuizOrAssessment(Map persist, B } @Override - public List> getAssessmentbyContentUser(String rootOrg, String courseId, String userId) - throws Exception { - // TODO Auto-generated method stub + public List> getAssessmentbyContentUser(String rootOrg, String courseId, String userId) { return Collections.emptyList(); } @@ -155,9 +144,8 @@ public List> fetchUserAssessmentDataFromDB(String userId, St Map request = new HashMap<>(); request.put(Constants.USER_ID, userId); request.put(Constants.ASSESSMENT_ID_KEY, assessmentIdentifier); - List> existingDataList = cassandraOperation.getRecordsByProperties( + return cassandraOperation.getRecordsByProperties( Constants.KEYSPACE_SUNBIRD, Constants.TABLE_USER_ASSESSMENT_DATA, request, null); - return existingDataList; } @Override @@ -182,4 +170,21 @@ public Boolean updateUserAssesmentDataToDB(String userId, String assessmentIdent fieldsToBeUpdated, compositeKeys); return true; } + + + private Map getUserAssessmentMasterModelData(Map persist, Date date) throws ParseException { + Map userAssessmentMasterModelData = new HashMap<>(); + userAssessmentMasterModelData.put("primaryKey", new UserAssessmentMasterPrimaryKeyModel(persist.get(ROOT_ORG).toString(), date, + persist.get("parent").toString(), BigDecimal.valueOf((Double) persist.get(RESULT)), UUIDs.timeBased())); + userAssessmentMasterModelData.put(Constants.CORRECT_COUNT, Integer.parseInt(persist.get(Constants.CORRECT).toString())); + userAssessmentMasterModelData.put(Constants.DATE_CREATED_ON, formatter.parse(formatter.format(date))); + userAssessmentMasterModelData.put(Constants.INCORRECT_COUNT, Integer.parseInt(persist.get(Constants.INCORRECT).toString())); + userAssessmentMasterModelData.put(Constants.NOT_ANSWERED_COUNT, Integer.parseInt(persist.get(Constants.BLANK).toString())); + userAssessmentMasterModelData.put(Constants.PARENT_CONTENT_TYPE, persist.get(Constants.PARENT_CONTENT_TYPE).toString()); + userAssessmentMasterModelData.put(Constants.PASS_PERCENTAGE, new BigDecimal(60)); + userAssessmentMasterModelData.put(Constants.SOURCE_ID, persist.get(SOURCE_ID).toString()); + userAssessmentMasterModelData.put(Constants.SOURCE_TITLE, persist.get(Constants.TITLE).toString()); + userAssessmentMasterModelData.put(Constants.USER_ID, persist.get(USER_ID).toString()); + return userAssessmentMasterModelData; + } } \ No newline at end of file diff --git a/src/main/java/org/sunbird/assessment/repo/CohortUsers.java b/src/main/java/org/sunbird/assessment/repo/CohortUsers.java index 78520770..802d2fb1 100644 --- a/src/main/java/org/sunbird/assessment/repo/CohortUsers.java +++ b/src/main/java/org/sunbird/assessment/repo/CohortUsers.java @@ -4,13 +4,13 @@ @JsonIgnoreProperties(ignoreUnknown = true) public class CohortUsers { - private String first_name; - private String last_name; + private String firstName; + private String lastName; private String email; private String desc; - private String user_id; + private String userId; private String department; - private String phone_No; + private String phoneNo; private String designation; private String userLocation; private String city; @@ -21,20 +21,20 @@ public String getDesc() { public void setDesc(String desc) { this.desc = desc; } - public String getFirst_name() { - return first_name; + public String getFirstName() { + return firstName; } - public void setFirst_name(String first_name) { - this.first_name = first_name; + public void setFirstName(String firstName) { + this.firstName = firstName; } - public String getLast_name() { - return last_name; + public String getLastName() { + return lastName; } - public void setLast_name(String last_name) { - this.last_name = last_name; + public void setLastName(String lastName) { + this.lastName = lastName; } public String getEmail() { @@ -45,12 +45,12 @@ public void setEmail(String email) { this.email = email; } - public String getUser_id() { - return user_id; + public String getUserId() { + return userId; } - public void setUser_id(String user_id) { - this.user_id = user_id; + public void setUserId(String userId) { + this.userId = userId; } public String getDesignation() { @@ -69,12 +69,12 @@ public void setDepartment(String department) { this.department = department; } - public String getPhone_No() { - return phone_No; + public String getPhoneNo() { + return phoneNo; } - public void setPhone_No(String phone_No) { - this.phone_No = phone_No; + public void setPhoneNo(String phoneNo) { + this.phoneNo = phoneNo; } public String getUserLocation() { diff --git a/src/main/java/org/sunbird/assessment/repo/UserAssessmentMasterModel.java b/src/main/java/org/sunbird/assessment/repo/UserAssessmentMasterModel.java index 12512337..2c6d9fad 100644 --- a/src/main/java/org/sunbird/assessment/repo/UserAssessmentMasterModel.java +++ b/src/main/java/org/sunbird/assessment/repo/UserAssessmentMasterModel.java @@ -2,10 +2,12 @@ import java.math.BigDecimal; import java.util.Date; +import java.util.Map; import org.springframework.data.cassandra.core.mapping.Column; import org.springframework.data.cassandra.core.mapping.PrimaryKey; import org.springframework.data.cassandra.core.mapping.Table; +import org.sunbird.common.util.Constants; @Table("user_assessment_master") public class UserAssessmentMasterModel { @@ -108,24 +110,22 @@ public String getUserId() { return userId; } - public void setUser_id(String userId) { + public void setUserId(String userId) { this.userId = userId; } - public UserAssessmentMasterModel(UserAssessmentMasterPrimaryKeyModel primaryKey, Integer correctCount, - Date dateCreated, Integer incorrectCount, Integer notAnsweredCount, String parentContentType, - BigDecimal passPercent, String sourceId, String sourceTitle, String userId) { + public UserAssessmentMasterModel(Map userAssessmentMasterModelData) { super(); - this.primaryKey = primaryKey; - this.correctCount = correctCount; - this.dateCreated = dateCreated; - this.incorrectCount = incorrectCount; - this.notAnsweredCount = notAnsweredCount; - this.parentContentType = parentContentType; - this.passPercent = passPercent; - this.sourceId = sourceId; - this.sourceTitle = sourceTitle; - this.userId = userId; + this.primaryKey = (UserAssessmentMasterPrimaryKeyModel) userAssessmentMasterModelData.get("primaryKey"); + this.correctCount = (java.lang.Integer) userAssessmentMasterModelData.get("correctCount"); + this.dateCreated = (Date) userAssessmentMasterModelData.get(Constants.DATE_CREATED_ON); + this.incorrectCount = (java.lang.Integer) userAssessmentMasterModelData.get(Constants.INCORRECT_COUNT); + this.notAnsweredCount = (java.lang.Integer) userAssessmentMasterModelData.get(Constants.NOT_ANSWERED_COUNT); + this.parentContentType = (String) userAssessmentMasterModelData.get(Constants.PARENT_CONTENT_TYPE); + this.passPercent = (BigDecimal) userAssessmentMasterModelData.get(Constants.PASS_PERCENTAGE); + this.sourceId = (String) userAssessmentMasterModelData.get(Constants.SOURCE_ID); + this.sourceTitle = (String) userAssessmentMasterModelData.get("sourceTitle"); + this.userId = (String) userAssessmentMasterModelData.get("userId"); } public UserAssessmentMasterModel() { diff --git a/src/main/java/org/sunbird/assessment/repo/UserAssessmentTopPerformerPrimaryKeyModel.java b/src/main/java/org/sunbird/assessment/repo/UserAssessmentTopPerformerPrimaryKeyModel.java index 3da22c8e..0e7eb230 100644 --- a/src/main/java/org/sunbird/assessment/repo/UserAssessmentTopPerformerPrimaryKeyModel.java +++ b/src/main/java/org/sunbird/assessment/repo/UserAssessmentTopPerformerPrimaryKeyModel.java @@ -74,7 +74,6 @@ public UserAssessmentTopPerformerPrimaryKeyModel() { public UserAssessmentTopPerformerPrimaryKeyModel(String rootOrg, String parentSourceId, Date tsCreated, BigDecimal resultPercent, UUID id) { - this.rootOrg = rootOrg; this.parentSourceId = parentSourceId; this.tsCreated = tsCreated; this.resultPercent = resultPercent; diff --git a/src/main/java/org/sunbird/assessment/service/AssessmentAsyncSubmitConsumer.java b/src/main/java/org/sunbird/assessment/service/AssessmentAsyncSubmitConsumer.java index 3164ec68..be00e3f8 100644 --- a/src/main/java/org/sunbird/assessment/service/AssessmentAsyncSubmitConsumer.java +++ b/src/main/java/org/sunbird/assessment/service/AssessmentAsyncSubmitConsumer.java @@ -30,7 +30,7 @@ public void processMessage(ConsumerRecord data) { }); assessmentServiceV4.handleAssessmentSubmitRequest(asyncRequest,false,null); } catch (Exception e) { - String errMsg = String.format("", e.getMessage()); + String errMsg = String.format("Error: %s", e.getMessage()); LOGGER.error(errMsg, e); } } diff --git a/src/main/java/org/sunbird/assessment/service/AssessmentServiceImpl.java b/src/main/java/org/sunbird/assessment/service/AssessmentServiceImpl.java index 9b9968ee..b4d1d228 100644 --- a/src/main/java/org/sunbird/assessment/service/AssessmentServiceImpl.java +++ b/src/main/java/org/sunbird/assessment/service/AssessmentServiceImpl.java @@ -1,6 +1,7 @@ package org.sunbird.assessment.service; import java.math.BigDecimal; +import java.math.RoundingMode; import java.util.ArrayList; import java.util.HashMap; import java.util.List; @@ -71,7 +72,7 @@ public Map submitAssessment(String rootOrg, AssessmentSubmission Map ret = new HashMap<>(); - // TODO - Need to get the Assessment ContentMeta Data + // Need to get the Assessment ContentMeta Data // Get the assessment-key.json file. Current version has both the answers Map resultMap = assessUtilServ.validateAssessment(data.getQuestions()); @@ -117,8 +118,7 @@ public Map submitAssessment(String rootOrg, AssessmentSubmission } @Override - public Map getAssessmentByContentUser(String rootOrg, String courseId, String userId) - throws Exception { + public Map getAssessmentByContentUser(String rootOrg, String courseId, String userId) throws ApplicationLogicError { Map result = new TreeMap<>(); try { // get all submission data from cassandra @@ -185,8 +185,7 @@ public Map getAssessmentByContentUser(String rootOrg, String cou @Override public Map submitAssessmentByIframe(String rootOrg, Map request) throws Exception { - // TODO Auto-generated method stub - return null; + return new HashMap<>(); } // A method to Format Data in the FrontEndFormat @@ -195,7 +194,7 @@ private List> getAssessments(List> resul for (Map map : result) { Map assessmentData = new HashMap<>(); String res = map.get("result_percent").toString(); - assessmentData.put(RESULT, new BigDecimal(res).setScale(2, BigDecimal.ROUND_UP)); + assessmentData.put(RESULT, new BigDecimal(res).setScale(2, RoundingMode.UP)); assessmentData.put("correctlyAnswered", map.get("correct_count")); assessmentData.put("wronglyAnswered", map.get("incorrect_count")); assessmentData.put("notAttempted", map.get("not_answered_count")); diff --git a/src/main/java/org/sunbird/assessment/service/AssessmentServiceV2.java b/src/main/java/org/sunbird/assessment/service/AssessmentServiceV2.java index 904a2793..480a951b 100644 --- a/src/main/java/org/sunbird/assessment/service/AssessmentServiceV2.java +++ b/src/main/java/org/sunbird/assessment/service/AssessmentServiceV2.java @@ -14,9 +14,9 @@ public interface AssessmentServiceV2 { */ public SBApiResponse submitAssessment(Map data, String userEmail,boolean editMode) throws Exception; - public SBApiResponse readAssessment(String assessmentIdentifier, String token) throws Exception; + public SBApiResponse readAssessment(String assessmentIdentifier, String token); - public SBApiResponse readQuestionList(Map requestBody, String authUserToken) throws Exception; + public SBApiResponse readQuestionList(Map requestBody, String authUserToken); - public SBApiResponse retakeAssessment(String assessmentIdentifier, String token) throws Exception; + public SBApiResponse retakeAssessment(String assessmentIdentifier, String token); } diff --git a/src/main/java/org/sunbird/assessment/service/AssessmentServiceV2Impl.java b/src/main/java/org/sunbird/assessment/service/AssessmentServiceV2Impl.java index fd99cc25..994f9106 100644 --- a/src/main/java/org/sunbird/assessment/service/AssessmentServiceV2Impl.java +++ b/src/main/java/org/sunbird/assessment/service/AssessmentServiceV2Impl.java @@ -70,11 +70,11 @@ public SBApiResponse readAssessment(String assessmentIdentifier, String token) { try { String userId = validateAuthTokenAndFetchUserId(token); if (userId != null) { - logger.info("readAssessment.. userId :" + userId); + logger.info("readAssessment.. userId : {}" , userId); Map assessmentAllDetail = new HashMap<>(); errMsg = fetchReadHierarchyDetails(assessmentAllDetail, token, assessmentIdentifier); if (errMsg.isEmpty() && !((String) assessmentAllDetail.get(Constants.PRIMARY_CATEGORY)).equalsIgnoreCase(Constants.PRACTICE_QUESTION_SET)) { - logger.info("Fetched assessment Details... for : " + assessmentIdentifier); + logger.info("Fetched assessment Details... for : {}" ,assessmentIdentifier); List> existingDataList = assessmentRepository.fetchUserAssessmentDataFromDB(userId, assessmentIdentifier); Timestamp assessmentStartTime = new Timestamp(new java.util.Date().getTime()); if (existingDataList.isEmpty()) { @@ -148,7 +148,6 @@ public SBApiResponse readAssessment(String assessmentIdentifier, String token) { public SBApiResponse readQuestionList(Map requestBody, String authUserToken) { SBApiResponse response = createDefaultResponse(Constants.API_SUBMIT_ASSESSMENT); String errMsg; - String primaryCategory = ""; Map result = new HashMap<>(); try { List identifierList = new ArrayList<>(); @@ -222,7 +221,7 @@ private String fetchReadHierarchyDetails(Map assessmentAllDetail redisCacheMgr.putCache(Constants.ASSESSMENT_ID + assessmentIdentifier, ((Map) readHierarchyApiResponse.get(Constants.RESULT)).get(Constants.QUESTION_SET)); } } catch (Exception e) { - logger.info("Error while fetching or mapping read hierarchy data" + e.getMessage()); + logger.info("Error while fetching or mapping read hierarchy data : {}" , e.getMessage()); return Constants.ASSESSMENT_HIERARCHY_READ_FAILED; } return StringUtils.EMPTY; @@ -285,7 +284,7 @@ private Map validateQuestionListAPI(Map requestB // Fetching all the remaining questions details from the Redis questionsFromAssessment.addAll((List) section.get(Constants.CHILD_NODES)); } - if (validateQuestionListRequest(identifierList, questionsFromAssessment)) { + if (Boolean.TRUE.equals(validateQuestionListRequest(identifierList, questionsFromAssessment))) { result.put(Constants.ERROR_MESSAGE, StringUtils.EMPTY); } else { result.put(Constants.ERROR_MESSAGE, Constants.THE_QUESTIONS_IDS_PROVIDED_DONT_MATCH); @@ -310,7 +309,7 @@ public SBApiResponse submitAssessment(Map submitRequest, String if (errMsg.isEmpty()) { String userId = validateAuthTokenAndFetchUserId(authUserToken); String scoreCutOffType = ((String) assessmentHierarchy.get(Constants.SCORE_CUTOFF_TYPE)).toLowerCase(); - List> existingDataList = new ArrayList<>(); + List> existingDataList; List> sectionLevelsResults = new ArrayList<>(); Map questionSetFromAssessment = new HashMap<>(); for (Map hierarchySection : hierarchySectionList) { @@ -426,17 +425,14 @@ private void writeDataToDatabaseAndTriggerKafkaEvent(Map submitR kafkaResult.put(Constants.ASSESSMENT_ID_KEY, submitRequest.get(Constants.IDENTIFIER)); kafkaResult.put(Constants.PRIMARY_CATEGORY, primaryCategory); kafkaResult.put(Constants.TOTAL_SCORE, result.get(Constants.OVERALL_RESULT)); - if ((primaryCategory.equalsIgnoreCase("Competency Assessment") && submitRequest.containsKey("competencies_v3") && submitRequest.get("competencies_v3") != null)) { - Object[] obj = (Object[]) JSON.parse((String) submitRequest.get("competencies_v3")); + if ((primaryCategory.equalsIgnoreCase("Competency Assessment") && submitRequest.containsKey(Constants.COMPETENCIES_V3) && submitRequest.get(Constants.COMPETENCIES_V3) != null)) { + Object[] obj = (Object[]) JSON.parse((String) submitRequest.get(Constants.COMPETENCIES_V3)); if (obj != null) { Object map = obj[0]; ObjectMapper m = new ObjectMapper(); Map props = m.convertValue(map, Map.class); kafkaResult.put(Constants.COMPETENCY, props.isEmpty() ? "" : props); - System.out.println(obj); - } - System.out.println(obj); } logger.info(kafkaResult.toString()); kafkaProducer.push(serverProperties.getAssessmentSubmitTopic(), kafkaResult); @@ -703,7 +699,7 @@ private Boolean validateQuestionListRequest(List identifierList, List(questionsFromAssessment).containsAll(identifierList)) ? Boolean.TRUE : Boolean.FALSE; } - public SBApiResponse retakeAssessment(String assessmentIdentifier, String token) throws Exception { + public SBApiResponse retakeAssessment(String assessmentIdentifier, String token) { logger.info("AssessmentServiceV2Impl::retakeAssessment... Started"); SBApiResponse response = createDefaultResponse(Constants.API_RETAKE_ASSESSMENT_GET); String errMsg = ""; diff --git a/src/main/java/org/sunbird/assessment/service/AssessmentServiceV4Impl.java b/src/main/java/org/sunbird/assessment/service/AssessmentServiceV4Impl.java index 7e533c95..fd13815f 100644 --- a/src/main/java/org/sunbird/assessment/service/AssessmentServiceV4Impl.java +++ b/src/main/java/org/sunbird/assessment/service/AssessmentServiceV4Impl.java @@ -4,15 +4,7 @@ import java.io.IOException; import java.sql.Timestamp; -import java.util.ArrayList; -import java.util.Calendar; -import java.util.Collections; -import java.util.Date; -import java.util.HashMap; -import java.util.HashSet; -import java.util.List; -import java.util.Map; -import java.util.Objects; +import java.util.*; import java.util.stream.Collectors; import org.apache.commons.collections.CollectionUtils; @@ -326,6 +318,7 @@ public SBApiResponse submitAssessmentAsync(Map submitRequest, St String scoreCutOffType = ((String) assessmentHierarchy.get(Constants.SCORE_CUTOFF_TYPE)).toLowerCase(); List> sectionLevelsResults = new ArrayList<>(); + boolean assessmentLevelScoreCutOff = false; for (Map hierarchySection : hierarchySectionList) { String hierarchySectionId = (String) hierarchySection.get(Constants.IDENTIFIER); String userSectionId = ""; @@ -352,18 +345,17 @@ public SBApiResponse submitAssessmentAsync(Map submitRequest, St .map(object -> Objects.toString(object, null)).collect(Collectors.toList()); Map result = new HashMap<>(); switch (scoreCutOffType) { - case Constants.ASSESSMENT_LEVEL_SCORE_CUTOFF: { + case Constants.ASSESSMENT_LEVEL_SCORE_CUTOFF: result.putAll(createResponseMapWithProperStructure(hierarchySection, assessUtilServ.validateQumlAssessment(questionsListFromAssessmentHierarchy, - questionsListFromSubmitRequest,assessUtilServ.readQListfromCache(questionsListFromAssessmentHierarchy,assessmentIdFromRequest,editMode,userAuthToken)))); - Map finalRes= calculateAssessmentFinalResults(result); + questionsListFromSubmitRequest, assessUtilServ.readQListfromCache(questionsListFromAssessmentHierarchy, assessmentIdFromRequest, editMode, userAuthToken)))); + Map finalRes = calculateAssessmentFinalResults(result); outgoingResponse.getResult().putAll(finalRes); outgoingResponse.getResult().put(Constants.PRIMARY_CATEGORY, assessmentPrimaryCategory); if (!Constants.PRACTICE_QUESTION_SET.equalsIgnoreCase(assessmentPrimaryCategory) && !editMode) { - String questionSetFromAssessmentString = (String) existingAssessmentData .get(Constants.ASSESSMENT_READ_RESPONSE_KEY); - Map questionSetFromAssessment = null; + Map questionSetFromAssessment = null; if (StringUtils.isNotBlank(questionSetFromAssessmentString)) { questionSetFromAssessment = mapper.readValue(questionSetFromAssessmentString, new TypeReference>() { @@ -372,19 +364,19 @@ public SBApiResponse submitAssessmentAsync(Map submitRequest, St writeDataToDatabaseAndTriggerKafkaEvent(submitRequest, userId, questionSetFromAssessment, finalRes, (String) assessmentHierarchy.get(Constants.PRIMARY_CATEGORY)); } - - return outgoingResponse; - } - case Constants.SECTION_LEVEL_SCORE_CUTOFF: { + assessmentLevelScoreCutOff = true; + break; + case Constants.SECTION_LEVEL_SCORE_CUTOFF: result.putAll(createResponseMapWithProperStructure(hierarchySection, assessUtilServ.validateQumlAssessment(questionsListFromAssessmentHierarchy, - questionsListFromSubmitRequest,assessUtilServ.readQListfromCache(questionsListFromAssessmentHierarchy,assessmentIdFromRequest,editMode,userAuthToken)))); + questionsListFromSubmitRequest, assessUtilServ.readQListfromCache(questionsListFromAssessmentHierarchy, assessmentIdFromRequest, editMode, userAuthToken)))); sectionLevelsResults.add(result); - } break; default: break; } + if(assessmentLevelScoreCutOff) + return outgoingResponse; } if (Constants.SECTION_LEVEL_SCORE_CUTOFF.equalsIgnoreCase(scoreCutOffType)) { Map result = calculateSectionFinalResults(sectionLevelsResults); @@ -408,7 +400,7 @@ public SBApiResponse submitAssessmentAsync(Map submitRequest, St } } catch (Exception e) { - String errMsg = String.format("Failed to process assessment submit request. Exception: ", e.getMessage()); + String errMsg = String.format("Failed to process assessment submit request. Exception: %s", e.getMessage()); logger.error(errMsg, e); updateErrorDetails(outgoingResponse, errMsg, HttpStatus.INTERNAL_SERVER_ERROR); } @@ -511,14 +503,15 @@ public void handleAssessmentSubmitRequest(Map asyncRequest,boole finalResult.put(Constants.STATUS_IS_IN_PROGRESS, false); writeDataToDatabaseAndTriggerKafkaEvent(submitRequest, userId, questionSetFromAssessment, finalResult, (String) assessmentHierarchy.get(Constants.PRIMARY_CATEGORY)); + break; } case Constants.SECTION_LEVEL_SCORE_CUTOFF: { result.putAll(createResponseMapWithProperStructure(hierarchySection, assessUtilServ.validateQumlAssessment(questionsListFromAssessmentHierarchy, questionsListFromSubmitRequest,assessUtilServ.readQListfromCache(questionsListFromAssessmentHierarchy,assessmentIdFromRequest,editMode,token)))); sectionLevelsResults.add(result); - } break; + } default: break; } @@ -533,7 +526,7 @@ public void handleAssessmentSubmitRequest(Map asyncRequest,boole (String) assessmentHierarchy.get(Constants.PRIMARY_CATEGORY)); } } catch (Exception e) { - errMsg = String.format("Failed to process assessent submit request. Exception: ", e.getMessage()); + errMsg = String.format("Failed to process assessent submit request. Exception: %s", e.getMessage()); logger.error(errMsg, e); } } @@ -640,7 +633,7 @@ private Map validateQuestionListAPI(Map requestB return result; } - Map userAssessmentAllDetail = new HashMap(); + Map userAssessmentAllDetail = new HashMap<>(); List> existingDataList = assessUtilServ.readUserSubmittedAssessmentRecords( userId, assessmentIdFromRequest); @@ -667,7 +660,7 @@ private Map validateQuestionListAPI(Map requestB // Fetching all the remaining questions details from the Redis questionsFromAssessment.addAll((List) section.get(Constants.CHILD_NODES)); } - if (validateQuestionListRequest(identifierList, questionsFromAssessment)) { + if (Boolean.TRUE.equals(validateQuestionListRequest(identifierList, questionsFromAssessment))) { result.put(Constants.ERROR_MESSAGE, StringUtils.EMPTY); } else { result.put(Constants.ERROR_MESSAGE, Constants.THE_QUESTIONS_IDS_PROVIDED_DONT_MATCH); @@ -703,7 +696,7 @@ private Boolean validateQuestionListRequest(List identifierList, List submitRequest, String userId, List> hierarchySectionList, List> sectionListFromSubmitRequest, - Map assessmentHierarchy, Map existingAssessmentData,String token,boolean editMode) throws Exception { + Map assessmentHierarchy, Map existingAssessmentData,String token,boolean editMode) throws IOException { submitRequest.put(Constants.USER_ID, userId); if (StringUtils.isEmpty((String) submitRequest.get(Constants.IDENTIFIER))) { return Constants.INVALID_ASSESSMENT_ID; @@ -727,11 +720,6 @@ private String validateSubmitAssessmentRequest(Map submitRequest } else { existingAssessmentData.putAll(existingDataList.get(0)); } - - //if (Constants.SUBMITTED.equalsIgnoreCase((String) existingAssessmentData.get(Constants.STATUS))) { - // return Constants.ASSESSMENT_ALREADY_SUBMITTED; - //} - Date assessmentStartTime = (Date) existingAssessmentData.get(Constants.START_TIME); if (assessmentStartTime == null) { return Constants.READ_ASSESSMENT_START_TIME_FAILED; @@ -765,7 +753,7 @@ private String validateSubmitAssessmentRequest(Map submitRequest private String validateIfQuestionIdsAreSame(Map submitRequest, List> sectionListFromSubmitRequest, List desiredKeys, String userId, - Map existingAssessmentData) throws Exception { + Map existingAssessmentData) throws IOException { String questionSetFromAssessmentString = (String) existingAssessmentData .get(Constants.ASSESSMENT_READ_RESPONSE_KEY); if (StringUtils.isNotBlank(questionSetFromAssessmentString)) { @@ -875,18 +863,15 @@ private void writeDataToDatabaseAndTriggerKafkaEvent(Map submitR kafkaResult.put(Constants.PRIMARY_CATEGORY, primaryCategory); kafkaResult.put(Constants.TOTAL_SCORE, result.get(Constants.OVERALL_RESULT)); if ((primaryCategory.equalsIgnoreCase("Competency Assessment") - && submitRequest.containsKey("competencies_v3") - && submitRequest.get("competencies_v3") != null)) { - Object[] obj = (Object[]) JSON.parse((String) submitRequest.get("competencies_v3")); + && submitRequest.containsKey(Constants.COMPETENCIES_V3) + && submitRequest.get(Constants.COMPETENCIES_V3) != null)) { + Object[] obj = (Object[]) JSON.parse((String) submitRequest.get(Constants.COMPETENCIES_V3)); if (obj != null) { Object map = obj[0]; ObjectMapper m = new ObjectMapper(); Map props = m.convertValue(map, Map.class); kafkaResult.put(Constants.COMPETENCY, props.isEmpty() ? "" : props); - System.out.println(obj); - } - System.out.println(obj); } kafkaProducer.push(serverProperties.getAssessmentSubmitTopic(), kafkaResult); } @@ -941,7 +926,7 @@ private String validateAssessmentReadResult(Map request) { if (MapUtils.isEmpty(requestBody)) { return Constants.INVALID_REQUEST; } - List missingAttribs = new ArrayList(); + List missingAttribs = new ArrayList<>(); if (!requestBody.containsKey(Constants.ASSESSMENT_ID_KEY) || StringUtils.isBlank((String) requestBody.get(Constants.ASSESSMENT_ID_KEY))) { missingAttribs.add(Constants.ASSESSMENT_ID_KEY); diff --git a/src/main/java/org/sunbird/assessment/service/AssessmentUtilServiceImpl.java b/src/main/java/org/sunbird/assessment/service/AssessmentUtilServiceImpl.java index 6c440920..a26d4234 100644 --- a/src/main/java/org/sunbird/assessment/service/AssessmentUtilServiceImpl.java +++ b/src/main/java/org/sunbird/assessment/service/AssessmentUtilServiceImpl.java @@ -218,7 +218,7 @@ public Map validateAssessment(List> question @SuppressWarnings("unchecked") @Override public Map getAnswerKeyForAssessmentAuthoringPreview(Map contentMeta) { - return null; + return new HashMap<>(); } /** diff --git a/src/main/java/org/sunbird/assessment/service/AssessmentUtilServiceV2Impl.java b/src/main/java/org/sunbird/assessment/service/AssessmentUtilServiceV2Impl.java index 680af8e4..11290281 100644 --- a/src/main/java/org/sunbird/assessment/service/AssessmentUtilServiceV2Impl.java +++ b/src/main/java/org/sunbird/assessment/service/AssessmentUtilServiceV2Impl.java @@ -50,7 +50,6 @@ public Map validateQumlAssessment(List originalQuestionL Integer correct = 0; Integer blank = 0; Integer inCorrect = 0; - Double result; Integer total = 0; Map resultMap = new HashMap<>(); Map answers = getQumlAnswers(originalQuestionList,questionMap); @@ -126,12 +125,8 @@ public Map validateQumlAssessment(List originalQuestionL private Map getQumlAnswers(List questions,Map questionMap) throws Exception { Map ret = new HashMap<>(); - - //Map> questionMap = new HashMap>(); - for (String questionId : questions) { List correctOption = new ArrayList<>(); - //questionMap = fetchQuestionMapDetails(questionId); Map question = (Map) questionMap.get(questionId); if (question.containsKey(Constants.QUESTION_TYPE)) { String questionType = ((String) question.get(Constants.QUESTION_TYPE)).toLowerCase(); @@ -198,9 +193,7 @@ private Map> fetchQuestionMapDetails(String question } @Override - public String fetchQuestionIdentifierValue(List identifierList, List questionList, - String primaryCategory) - throws Exception { + public String fetchQuestionIdentifierValue(List identifierList, List questionList, String primaryCategory) { List newIdentifierList = new ArrayList<>(); newIdentifierList.addAll(identifierList); String errMsg = ""; @@ -345,7 +338,7 @@ public Map readAssessmentHierarchyFromCache(String assessmentIde questStr = redisCacheMgr.getCache(Constants.ASSESSMENT_ID + assessmentIdentifier + Constants.UNDER_SCORE + Constants.QUESTION_SET); } if(StringUtils.isEmpty(questStr)) { - Map propertyMap = new HashMap(); + Map propertyMap = new HashMap<>(); propertyMap.put(Constants.IDENTIFIER, assessmentIdentifier); List> hierarchyList = cassandraOperation.getRecordsByPropertiesWithoutFiltering( serverProperties.getAssessmentHierarchyNameSpace(), @@ -378,7 +371,7 @@ public Map readAssessmentHierarchyFromCache(String assessmentIde } public List> readUserSubmittedAssessmentRecords(String userId, String assessmentId) { - Map propertyMap = new HashMap(); + Map propertyMap = new HashMap<>(); propertyMap.put(Constants.USER_ID, userId); propertyMap.put(Constants.ASSESSMENT_ID_KEY, assessmentId); return cassandraOperation.getRecordsByPropertiesWithoutFiltering( diff --git a/src/main/java/org/sunbird/assessment/service/CohortsService.java b/src/main/java/org/sunbird/assessment/service/CohortsService.java index 7dd2bf59..3d297bb3 100644 --- a/src/main/java/org/sunbird/assessment/service/CohortsService.java +++ b/src/main/java/org/sunbird/assessment/service/CohortsService.java @@ -3,15 +3,13 @@ import java.util.List; import org.sunbird.assessment.repo.CohortUsers; -import org.sunbird.common.model.Response; import org.sunbird.common.model.SBApiResponse; public interface CohortsService { - List getTopPerformers(String rootOrg, String resourceId, String userUUID, int count) throws Exception; + List getTopPerformers(String rootOrg, String resourceId, String userUUID, int count); - List getActiveUsers(String xAuthUser, String rootOrgId, String rootOrg, String contentId, String userUUID, int count, Boolean toFilter) - throws Exception; - SBApiResponse autoEnrollmentInCourse(String authUserToken, String rootOrgId, String rootOrg, String contentId, String userUUID)throws Exception; + List getActiveUsers(String xAuthUser, String rootOrgId, String rootOrg, String contentId, String userUUID, int count, Boolean toFilter); + SBApiResponse autoEnrollmentInCourse(String authUserToken, String rootOrgId, String rootOrg, String contentId, String userUUID); - SBApiResponse autoEnrollmentInCourseV2(String authUserToken, String rootOrgId, String rootOrg, String contentId, String userUUID)throws Exception; + SBApiResponse autoEnrollmentInCourseV2(String authUserToken, String rootOrgId, String rootOrg, String contentId, String userUUID); } diff --git a/src/main/java/org/sunbird/assessment/service/CohortsServiceImpl.java b/src/main/java/org/sunbird/assessment/service/CohortsServiceImpl.java index 98fe3e92..f92e70a6 100644 --- a/src/main/java/org/sunbird/assessment/service/CohortsServiceImpl.java +++ b/src/main/java/org/sunbird/assessment/service/CohortsServiceImpl.java @@ -60,10 +60,6 @@ public class CohortsServiceImpl implements CohortsService { @Override public List getTopPerformers(String rootOrg, String contentId, String userId, int count) { // Check User exists -// if (!userUtilService.validateUser(rootOrg, userId)) { -// throw new BadRequestException("Invalid UserId."); -// } - // This contains the list of all the children for provided course(resourceId) if // it is a learning-path. // Else, it will contain the parents for provided course(resourceId) @@ -114,9 +110,9 @@ public List getTopPerformers(String rootOrg, String contentId, Stri && !topLearnerUUID.equalsIgnoreCase(userId)) { CohortUsers user = new CohortUsers(); user.setDesc("Top Learner"); - user.setUser_id(userProfile.getPersonalDetails().getPrimaryEmail()); + user.setUserId(userProfile.getPersonalDetails().getPrimaryEmail()); user.setEmail(userProfile.getPersonalDetails().getPrimaryEmail()); - user.setFirst_name(userProfile.getPersonalDetails().getFirstname()); + user.setFirstName(userProfile.getPersonalDetails().getFirstname()); userNames.add(userProfile.getPersonalDetails().getPrimaryEmail()); topPerformers.add(user); if (counter == count) @@ -132,7 +128,7 @@ public List getTopPerformers(String rootOrg, String contentId, Stri @Override @SuppressWarnings("unchecked") public List getActiveUsers(String xAuthUser, String rootOrgId, String rootOrg, String contentId, String userId, - int count, Boolean toFilter) throws Exception { + int count, Boolean toFilter) { // Check User exists // if (!userUtilService.validateUser(rootOrg, userId)) { // throw new BadRequestException("Invalid UserId."); @@ -154,8 +150,7 @@ public List getActiveUsers(String xAuthUser, String rootOrgId, Stri } @Override - public SBApiResponse autoEnrollmentInCourse(String authUserToken, String rootOrgId, String rootOrg, String contentId, String userUUID) - throws Exception { + public SBApiResponse autoEnrollmentInCourse(String authUserToken, String rootOrgId, String rootOrg, String contentId, String userUUID){ SBApiResponse finalResponse = ProjectUtil.createDefaultResponse(Constants.API_USER_ENROLMENT); try { List batchResp = fetchBatchDetails(rootOrgId, contentId); @@ -190,7 +185,7 @@ public SBApiResponse autoEnrollmentInCourse(String authUserToken, String rootOrg boolean isUserEnrolled = false; for (SunbirdApiBatchResp batch : batchResp) { if (StringUtils.isEmpty(batch.getEndDate())) { - Map enrollResponse = new HashMap<>(); + Map enrollResponse; enrollResponse = enrollInCourse(contentId, userUUID, headers, batch.getBatchId()); if (!ObjectUtils.isEmpty(enrollResponse) && Constants.OK.equalsIgnoreCase((String) enrollResponse.get(Constants.RESPONSE_CODE))) { finalResponse = constructAutoEnrollResponse(batch); @@ -210,7 +205,7 @@ public SBApiResponse autoEnrollmentInCourse(String authUserToken, String rootOrg boolean isUserEnrolled = false; for (SunbirdApiBatchResp batch : batchResp) { if (StringUtils.isEmpty(batch.getEndDate())) { - Map enrollResponse = new HashMap<>(); + Map enrollResponse; enrollResponse = enrollInCourse(contentId, userUUID, headers, batch.getBatchId()); if (!ObjectUtils.isEmpty(enrollResponse) && Constants.OK == enrollResponse.get(Constants.RESPONSE_CODE)) { finalResponse = constructAutoEnrollResponse(batch); @@ -242,8 +237,8 @@ private SBApiResponse createBatchAndEnroll(String contentId, String userUUID, Ma Map enrollResponse = new HashMap<>(); String date = new SimpleDateFormat("yyyy-MM-dd").format(new Date()); batchObj.put("courseId", contentId); - batchObj.put("name", "Open Batch"); - batchObj.put("description", "Open Batch"); + batchObj.put("name", Constants.OPEN_BATCH); + batchObj.put("description", Constants.OPEN_BATCH); batchObj.put("enrollmentType", "open"); batchObj.put("startDate", date); batchObj.put("createdBy", userUUID); @@ -262,7 +257,7 @@ private SBApiResponse createBatchAndEnroll(String contentId, String userUUID, Ma selectedBatch.setCreatedFor(new ArrayList<>()); selectedBatch.setEnrollmentEndDate(null); selectedBatch.setEnrollmentType("open"); - selectedBatch.setName("Open Batch"); + selectedBatch.setName(Constants.OPEN_BATCH); selectedBatch.setStartDate(date); selectedBatch.setStatus(1); selectedBatch.setBatchId(batchId); @@ -295,10 +290,9 @@ private Map enrollInCourse(String contentId, String userUUID, Ma enrollObj.put("courseId", contentId); enrollObj.put("batchId", batchId); req.put("request", enrollObj); - Map enrollMentResponse = outboundRequestHandlerService.fetchResultUsingPost( + return outboundRequestHandlerService.fetchResultUsingPost( cbExtServerProperties.getCourseServiceHost() + cbExtServerProperties.getUserCourseEnroll(), req, headers); - return enrollMentResponse; } private void processChildContentId(String givenContentId, List assessmentIdList) { @@ -387,7 +381,7 @@ private List fetchParticipantsList(String xAuthUser, String rootOrg List activeUserCollection = new ArrayList<>(); if (participantList.size() > count) { participantList = participantList.stream().limit(count).collect(Collectors.toList()); - } else if (participantList.size() == 0) { + } else if (participantList.isEmpty()) { return activeUserCollection; } try { @@ -404,9 +398,9 @@ private List fetchParticipantsList(String xAuthUser, String rootOrg SearchUserApiContent userInfo = (SearchUserApiContent) participantMap.get(userId); CohortUsers user = new CohortUsers(); // User Id is assigning instead of email - user.setUser_id(userInfo.getUserId()); + user.setUserId(userInfo.getUserId()); user.setEmail(userInfo.getEmail()); - user.setFirst_name(userInfo.getFirstName()); + user.setFirstName(userInfo.getFirstName()); user.setDesc(desc); user.setDepartment(userInfo.getChannel()); if (userInfo.getProfileDetails() != null @@ -432,7 +426,7 @@ private List fetchParticipantsList(String xAuthUser, String rootOrg } @Override - public SBApiResponse autoEnrollmentInCourseV2(String authUserToken, String rootOrgId, String rootOrg, String contentId, String userUUID) throws Exception { + public SBApiResponse autoEnrollmentInCourseV2(String authUserToken, String rootOrgId, String rootOrg, String contentId, String userUUID) { SBApiResponse finalResponse = ProjectUtil.createDefaultResponse(Constants.API_USER_ENROLMENT); try { Map contentResponse = contentService.readContent(contentId); @@ -466,7 +460,7 @@ public SBApiResponse autoEnrollmentInCourseV2(String authUserToken, String rootO List batchIdList = batchDetails.stream().map(batchDetail -> batchDetail.getBatchId()).collect(Collectors.toList()); List> userActiveEnrollmentForBatch = getActiveEnrollmentForUser(batchIdList, userUUID); boolean isEnrolledWithBatch = false; - if (userActiveEnrollmentForBatch.size() > 0) { + if (!userActiveEnrollmentForBatch.isEmpty()) { ProjectUtil.updateErrorDetails(finalResponse, Constants.BATCH_ALREADY_ENROLLED_MSG, HttpStatus.BAD_REQUEST); return finalResponse; } diff --git a/src/main/java/org/sunbird/assessment/service/OffensiveDataFlagServiceImpl.java b/src/main/java/org/sunbird/assessment/service/OffensiveDataFlagServiceImpl.java index 4ced5927..e7955b90 100644 --- a/src/main/java/org/sunbird/assessment/service/OffensiveDataFlagServiceImpl.java +++ b/src/main/java/org/sunbird/assessment/service/OffensiveDataFlagServiceImpl.java @@ -88,7 +88,7 @@ public SBApiResponse updateFlag(String token, Map requestBody) { response.getResult().put(Constants.STATUS, Constants.UPDATED); } } catch (Exception e) { - errMsg = String.format("Failed to update an offensive flag with the details. Exception: ", e.getMessage()); + errMsg = String.format("Failed to update an offensive flag with the details. Exception: %s", e.getMessage()); logger.error(errMsg, e); } } diff --git a/src/main/java/org/sunbird/audit/model/AuditModel.java b/src/main/java/org/sunbird/audit/model/AuditModel.java index d6d7767a..8391b27f 100644 --- a/src/main/java/org/sunbird/audit/model/AuditModel.java +++ b/src/main/java/org/sunbird/audit/model/AuditModel.java @@ -70,9 +70,6 @@ public void setTrainingBudgetUtilization(long trainingBudgetUtilization) { this.trainingBudgetUtilization = trainingBudgetUtilization; } -// public void setTransactionDetails(StaffInfo transactionDetails) { -// this.transactionDetails = transactionDetails; -// } public String getPosition() { return position; } diff --git a/src/main/java/org/sunbird/budget/controller/BudgetController.java b/src/main/java/org/sunbird/budget/controller/BudgetController.java index 50ca2bb9..76539352 100644 --- a/src/main/java/org/sunbird/budget/controller/BudgetController.java +++ b/src/main/java/org/sunbird/budget/controller/BudgetController.java @@ -25,52 +25,52 @@ public class BudgetController { BudgetService budgetService; @PostMapping("/budget/scheme") - public ResponseEntity createBudgetDetails(@RequestHeader("x-authenticated-userid") String userId, - @Valid @RequestBody BudgetInfo requestBody) throws Exception { + public ResponseEntity createBudgetDetails(@RequestHeader("x-authenticated-userid") String userId, + @Valid @RequestBody BudgetInfo requestBody) { SBApiResponse response = budgetService.submitBudgetDetails(requestBody, userId); return new ResponseEntity<>(response, response.getResponseCode()); } @PostMapping("/budget/scheme/proof") - public ResponseEntity createBudgeProofDetails(@RequestHeader("x-authenticated-userid") String userId, - @Valid @RequestBody BudgetDocInfo requestBody) throws Exception { + public ResponseEntity createBudgeProofDetails(@RequestHeader("x-authenticated-userid") String userId, + @Valid @RequestBody BudgetDocInfo requestBody) { SBApiResponse response = budgetService.submitBudgetDocDetails(requestBody, userId); return new ResponseEntity<>(response, response.getResponseCode()); } @GetMapping("budget/scheme/{orgId}/{budgetYear}") - public ResponseEntity getBudgetDetails(@PathVariable("orgId") String orgId, - @PathVariable("budgetYear") String budgetYear) throws Exception { + public ResponseEntity getBudgetDetails(@PathVariable("orgId") String orgId, + @PathVariable("budgetYear") String budgetYear) { SBApiResponse response = budgetService.getBudgetDetails(orgId, budgetYear); return new ResponseEntity<>(response, response.getResponseCode()); } @PatchMapping("/budget/scheme") - public ResponseEntity updateBudgetDetails(@RequestHeader("x-authenticated-userid") String userId, - @Valid @RequestBody BudgetInfo requestBody) throws Exception { + public ResponseEntity updateBudgetDetails(@RequestHeader("x-authenticated-userid") String userId, + @Valid @RequestBody BudgetInfo requestBody) { SBApiResponse response = budgetService.updateBudgetDetails(requestBody, userId); return new ResponseEntity<>(response, response.getResponseCode()); } @DeleteMapping("/budget/scheme") - public ResponseEntity deleteBudgetDetails(@RequestParam(name = "orgId", required = true) String orgId, + public ResponseEntity deleteBudgetDetails(@RequestParam(name = "orgId", required = true) String orgId, @RequestParam(name = "id", required = true) String budgetDetailsId, - @RequestParam(name = "budgetYear", required = false) String budgetYear) throws Exception { + @RequestParam(name = "budgetYear", required = false) String budgetYear) { SBApiResponse response = budgetService.deleteBudgetDetails(orgId, budgetDetailsId, budgetYear); return new ResponseEntity<>(response, response.getResponseCode()); } @DeleteMapping("/budget/scheme/proof") - public ResponseEntity deleteBudgetDocDetails(@RequestParam(name = "orgId", required = true) String orgId, + public ResponseEntity deleteBudgetDocDetails(@RequestParam(name = "orgId", required = true) String orgId, @RequestParam(name = "id", required = true) String budgetDetailsId, @RequestParam(name = "budgetYear", required = true) String budgetYear, - @RequestParam(name = "proofDocId", required = true) String proofDocId) throws Exception { + @RequestParam(name = "proofDocId", required = true) String proofDocId) { SBApiResponse response = budgetService.deleteDocBudgetDetails(orgId, budgetDetailsId, budgetYear, proofDocId); return new ResponseEntity<>(response, response.getResponseCode()); } @GetMapping("/orghistory/{orgId}/budget") - public ResponseEntity getBudgetHistoryDetails(@PathVariable("orgId") String orgId) throws Exception { + public ResponseEntity getBudgetHistoryDetails(@PathVariable("orgId") String orgId) throws Exception { SBApiResponse response = budgetService.getBudgetAudit(orgId); return new ResponseEntity<>(response, response.getResponseCode()); } diff --git a/src/main/java/org/sunbird/budget/model/BudgetDocInfo.java b/src/main/java/org/sunbird/budget/model/BudgetDocInfo.java index f26ae586..e4ba946b 100644 --- a/src/main/java/org/sunbird/budget/model/BudgetDocInfo.java +++ b/src/main/java/org/sunbird/budget/model/BudgetDocInfo.java @@ -98,7 +98,7 @@ public void setUploadedBy(String uploadedBy) { } public Map getProofDoc() { - Map proofDoc = new HashMap(); + Map proofDoc = new HashMap<>(); proofDoc.put(Constants.BUDGET_DOC_FILE_NAME, fileName); proofDoc.put(Constants.BUDGET_DOC_FILE_SIZE, fileSize); proofDoc.put(Constants.BUDGET_DOC_FILE_TYPE, fileType); diff --git a/src/main/java/org/sunbird/budget/service/BudgetService.java b/src/main/java/org/sunbird/budget/service/BudgetService.java index 9414ab14..c73322b6 100644 --- a/src/main/java/org/sunbird/budget/service/BudgetService.java +++ b/src/main/java/org/sunbird/budget/service/BudgetService.java @@ -6,18 +6,18 @@ public interface BudgetService { - public SBApiResponse submitBudgetDetails(BudgetInfo data, String userId) throws Exception; + public SBApiResponse submitBudgetDetails(BudgetInfo data, String userId); - public SBApiResponse submitBudgetDocDetails(BudgetDocInfo docData, String userId) throws Exception; + public SBApiResponse submitBudgetDocDetails(BudgetDocInfo docData, String userId); - public SBApiResponse getBudgetDetails(String orgId, String budgetYear) throws Exception; + public SBApiResponse getBudgetDetails(String orgId, String budgetYear); - public SBApiResponse updateBudgetDetails(BudgetInfo data, String userId) throws Exception; + public SBApiResponse updateBudgetDetails(BudgetInfo data, String userId); - public SBApiResponse deleteBudgetDetails(String orgId, String id, String budgetYear) throws Exception; + public SBApiResponse deleteBudgetDetails(String orgId, String id, String budgetYear); public SBApiResponse deleteDocBudgetDetails(String orgId, String budgetDetailsId, String budgetYear, - String proofDocId) throws Exception; + String proofDocId); public SBApiResponse getBudgetAudit(String orgId) throws Exception; diff --git a/src/main/java/org/sunbird/budget/service/BudgetServiceImpl.java b/src/main/java/org/sunbird/budget/service/BudgetServiceImpl.java index b8c3478c..07c7ee3a 100644 --- a/src/main/java/org/sunbird/budget/service/BudgetServiceImpl.java +++ b/src/main/java/org/sunbird/budget/service/BudgetServiceImpl.java @@ -27,6 +27,7 @@ import com.fasterxml.jackson.core.JsonProcessingException; import com.fasterxml.jackson.core.type.TypeReference; import com.fasterxml.jackson.databind.ObjectMapper; +import org.sunbird.ratings.exception.ValidationException; @Service public class BudgetServiceImpl implements BudgetService { @@ -38,7 +39,7 @@ public class BudgetServiceImpl implements BudgetService { private CassandraOperation cassandraOperation; @Override - public SBApiResponse submitBudgetDetails(BudgetInfo data, String userId) throws Exception { + public SBApiResponse submitBudgetDetails(BudgetInfo data, String userId) { SBApiResponse response = new SBApiResponse(Constants.API_BUDGET_SCHEME_ADD); try { validateAddBudgetInfo(data); @@ -52,7 +53,7 @@ public SBApiResponse submitBudgetDetails(BudgetInfo data, String userId) throws if (!existingDataList.isEmpty()) { String errMsg = "Budget Scheme exist for given name. Failed to create BudgetInfo for OrgId: " - + data.getOrgId() + ", BudgetYear: " + data.getBudgetYear() + ", SchemeName: " + + data.getOrgId() + Constants.BUDGET_YEAR_CONSTANT + data.getBudgetYear() + ", SchemeName: " + data.getSchemeName(); logger.error(errMsg); response.getParams().setErr(errMsg); @@ -83,7 +84,7 @@ public SBApiResponse submitBudgetDetails(BudgetInfo data, String userId) throws return response; } - public SBApiResponse submitBudgetDocDetails(BudgetDocInfo docInfo, String userId) throws Exception { + public SBApiResponse submitBudgetDocDetails(BudgetDocInfo docInfo, String userId) { SBApiResponse response = new SBApiResponse(Constants.API_BUDGET_SCHEME_DOC_ADD); try { validateAddBudgetDocInfo(docInfo); @@ -96,8 +97,8 @@ public SBApiResponse submitBudgetDocDetails(BudgetDocInfo docInfo, String userId Constants.TABLE_ORG_BUDGET_SCHEME, propertyMap, new ArrayList<>()); if (existingBudgetInfo.isEmpty()) { - String errMsg = "Failed to find BudgetScheme for OrgId: " + docInfo.getOrgId() + ", Id: " - + docInfo.getId() + ", BudgetYear: " + docInfo.getBudgetYear(); + String errMsg = Constants.FAILED_BUDGET_SCHEME_FOR_ORGID + docInfo.getOrgId() +Constants.ID_CONSTANT + + docInfo.getId() + Constants.BUDGET_YEAR_CONSTANT + docInfo.getBudgetYear(); logger.error(errMsg); response.getParams().setErrmsg(errMsg); response.setResponseCode(HttpStatus.BAD_REQUEST); @@ -154,7 +155,7 @@ public SBApiResponse submitBudgetDocDetails(BudgetDocInfo docInfo, String userId } @Override - public SBApiResponse getBudgetDetails(String orgId, String budgetYear) throws Exception { + public SBApiResponse getBudgetDetails(String orgId, String budgetYear) { SBApiResponse response = new SBApiResponse(Constants.API_BUDGET_SCHEME_READ); List> budgetResponseList = null; String errMsg = null; @@ -162,7 +163,7 @@ public SBApiResponse getBudgetDetails(String orgId, String budgetYear) throws Ex errMsg = "No Budget Year Collection found for Org: " + orgId; } else { budgetResponseList = getSpecificBudgetYearDetails(orgId, budgetYear); - errMsg = "No Budget Scheme found for Org: " + orgId + ", BudgetYear: " + budgetYear; + errMsg = "No Budget Scheme found for Org: " + orgId + Constants.BUDGET_YEAR_CONSTANT + budgetYear; } if (CollectionUtils.isEmpty(budgetResponseList)) { @@ -178,7 +179,7 @@ public SBApiResponse getBudgetDetails(String orgId, String budgetYear) throws Ex } @Override - public SBApiResponse updateBudgetDetails(BudgetInfo data, String userId) throws Exception { + public SBApiResponse updateBudgetDetails(BudgetInfo data, String userId) { SBApiResponse response = new SBApiResponse(Constants.API_BUDGET_SCHEME_UPDATE); Map request = new HashMap<>(); Map keyMap = new HashMap<>(); @@ -191,8 +192,8 @@ public SBApiResponse updateBudgetDetails(BudgetInfo data, String userId) throws List> existingBudgetInfo = cassandraOperation.getRecordsByProperties(Constants.KEYSPACE_SUNBIRD, Constants.TABLE_ORG_BUDGET_SCHEME, keyMap, null); if (existingBudgetInfo.isEmpty()) { - String errMsg = "Failed to find BudgetScheme for OrgId: " + data.getOrgId() + ", Id: " + data.getId() - + ", BudgetYear: " + data.getBudgetYear(); + String errMsg = Constants.FAILED_BUDGET_SCHEME_FOR_ORGID + data.getOrgId() +Constants.ID_CONSTANT + data.getId() + + Constants.BUDGET_YEAR_CONSTANT + data.getBudgetYear(); logger.error(errMsg); response.getParams().setErrmsg(errMsg); response.setResponseCode(HttpStatus.BAD_REQUEST); @@ -215,7 +216,7 @@ public SBApiResponse updateBudgetDetails(BudgetInfo data, String userId) throws } if (isOtherRecordExist) { String errMsg = "Budget Scheme exist for given name. Failed to update BudgetInfo for OrgId: " - + data.getOrgId() + ", BudgetYear: " + data.getBudgetYear() + ", SchemeName: " + + data.getOrgId() + Constants.BUDGET_YEAR_CONSTANT + data.getBudgetYear() + ", SchemeName: " + data.getSchemeName(); logger.error(errMsg); response.getParams().setErr(errMsg); @@ -258,7 +259,7 @@ public SBApiResponse updateBudgetDetails(BudgetInfo data, String userId) throws } @Override - public SBApiResponse deleteBudgetDetails(String orgId, String id, String budgetYear) throws Exception { + public SBApiResponse deleteBudgetDetails(String orgId, String id, String budgetYear) { SBApiResponse response = new SBApiResponse(Constants.API_BUDGET_SCHEME_DELETE); Map keyMap = new HashMap<>(); keyMap.put(Constants.ORG_ID, orgId); @@ -272,7 +273,7 @@ public SBApiResponse deleteBudgetDetails(String orgId, String id, String budgetY response.getParams().setStatus(Constants.SUCCESSFUL); response.setResponseCode(HttpStatus.OK); } else { - String errMsg = "Failed to find BudgetScheme for OrgId: " + orgId + ", Id: " + id + ", BudgetYear: " + String errMsg = Constants.FAILED_BUDGET_SCHEME_FOR_ORGID + orgId +Constants.ID_CONSTANT + id + Constants.BUDGET_YEAR_CONSTANT + budgetYear; logger.error(errMsg); response.getParams().setErrmsg(errMsg); @@ -288,7 +289,7 @@ public SBApiResponse deleteBudgetDetails(String orgId, String id, String budgetY } public SBApiResponse deleteDocBudgetDetails(String orgId, String budgetDetailsId, String budgetYear, - String proofDocId) throws Exception { + String proofDocId) { SBApiResponse response = new SBApiResponse(Constants.API_BUDGET_SCHEME_DELETE); try { Map propertyMap = new HashMap<>(); @@ -301,8 +302,8 @@ public SBApiResponse deleteDocBudgetDetails(String orgId, String budgetDetailsId if (!budgetInfo.isEmpty()) { BudgetInfo budgetInfoModel = mapper.convertValue(budgetInfo.get(0), BudgetInfo.class); if (CollectionUtils.isEmpty(budgetInfoModel.getProofDocs())) { - String errMsg = "Failed to find BudgetScheme for OrgId: " + orgId + ", Id: " + budgetDetailsId - + ", BudgetYear: " + budgetYear; + String errMsg = Constants.FAILED_BUDGET_SCHEME_FOR_ORGID + orgId +Constants.ID_CONSTANT + budgetDetailsId + + Constants.BUDGET_YEAR_CONSTANT + budgetYear; logger.error(errMsg); response.getParams().setErrmsg(errMsg); response.setResponseCode(HttpStatus.BAD_REQUEST); @@ -334,8 +335,8 @@ public SBApiResponse deleteDocBudgetDetails(String orgId, String budgetDetailsId response.setResponseCode(HttpStatus.OK); } } else { - String errMsg = "Failed to find BudgetScheme for OrgId: " + orgId + ", Id: " + budgetDetailsId - + ", BudgetYear: " + budgetYear; + String errMsg = Constants.FAILED_BUDGET_SCHEME_FOR_ORGID + orgId +Constants.ID_CONSTANT + budgetDetailsId + + Constants.BUDGET_YEAR_CONSTANT + budgetYear; logger.error(errMsg); response.getParams().setErrmsg(errMsg); response.setResponseCode(HttpStatus.BAD_REQUEST); @@ -399,7 +400,7 @@ public SBApiResponse getBudgetAudit(String orgId) throws Exception { } private void validateAddBudgetInfo(BudgetInfo budgetInfo) throws Exception { - List errObjList = new ArrayList(); + List errObjList = new ArrayList<>(); if (StringUtils.isEmpty(budgetInfo.getOrgId())) { errObjList.add(Constants.ORG_ID); } @@ -424,12 +425,12 @@ private void validateAddBudgetInfo(BudgetInfo budgetInfo) throws Exception { } if (!CollectionUtils.isEmpty(errObjList)) { - throw new Exception("One or more required fields are empty. Empty fields " + errObjList.toString()); + throw new Exception(Constants.ONE_OR_MORE_ERROR_FIELD_VALIDATION + errObjList.toString()); } } private void validateUpdateBudgetInfo(BudgetInfo budgetInfo) throws Exception { - List errObjList = new ArrayList(); + List errObjList = new ArrayList<>(); if (StringUtils.isEmpty(budgetInfo.getOrgId())) { errObjList.add(Constants.ORG_ID); } @@ -440,7 +441,10 @@ private void validateUpdateBudgetInfo(BudgetInfo budgetInfo) throws Exception { errObjList.add(Constants.BUDGET_YEAR); } - boolean schemeName = false, sBudgetAllocated = false, tBudgetAllocated = false, tBudgetUtilization = false; + boolean schemeName = false; + boolean sBudgetAllocated = false; + boolean tBudgetAllocated = false; + boolean tBudgetUtilization = false; if (budgetInfo.getSchemeName() != null) { if (StringUtils.isEmpty(budgetInfo.getSchemeName())) { errObjList.add(Constants.SCHEME_NAME); @@ -477,7 +481,7 @@ private void validateUpdateBudgetInfo(BudgetInfo budgetInfo) throws Exception { } if (schemeName && sBudgetAllocated && tBudgetAllocated && tBudgetUtilization) { - throw new Exception("One or more required fields are empty. Empty fields " + errObjList.toString()); + throw new Exception(Constants.ONE_OR_MORE_ERROR_FIELD_VALIDATION + errObjList.toString()); } else { if (schemeName) errObjList.remove(Constants.SCHEME_NAME); @@ -490,7 +494,7 @@ private void validateUpdateBudgetInfo(BudgetInfo budgetInfo) throws Exception { } if (!CollectionUtils.isEmpty(errObjList)) { - throw new Exception("One or more required fields are empty. Empty fields " + errObjList.toString()); + throw new Exception(Constants.ONE_OR_MORE_ERROR_FIELD_VALIDATION + errObjList.toString()); } } @@ -550,7 +554,7 @@ private Map getAuditMap(String userId, Map data, } private void validateAddBudgetDocInfo(BudgetDocInfo budgetInfo) throws Exception { - List errObjList = new ArrayList(); + List errObjList = new ArrayList<>(); if (StringUtils.isEmpty(budgetInfo.getOrgId())) { errObjList.add(Constants.ORG_ID); } @@ -574,7 +578,7 @@ private void validateAddBudgetDocInfo(BudgetDocInfo budgetInfo) throws Exception } if (!CollectionUtils.isEmpty(errObjList)) { - throw new Exception("One or more required fields are empty. Empty fields " + errObjList.toString()); + throw new Exception(Constants.ONE_OR_MORE_ERROR_FIELD_VALIDATION + errObjList.toString()); } } } diff --git a/src/main/java/org/sunbird/cache/DataCacheMgr.java b/src/main/java/org/sunbird/cache/DataCacheMgr.java index 79af0468..b651462d 100644 --- a/src/main/java/org/sunbird/cache/DataCacheMgr.java +++ b/src/main/java/org/sunbird/cache/DataCacheMgr.java @@ -1,5 +1,6 @@ package org.sunbird.cache; +import java.util.Collections; import java.util.HashMap; import java.util.Map; @@ -7,11 +8,11 @@ @Component public class DataCacheMgr { - private Map strCacheMap = new HashMap(); + private Map strCacheMap = new HashMap<>(); - private Map objCacheMap = new HashMap(); + private Map objCacheMap = new HashMap<>(); - private Map> contentCacheMap = new HashMap>(); + private Map> contentCacheMap = new HashMap<>(); public void putStringInCache(String key, String value) { strCacheMap.put(key, value); @@ -43,6 +44,6 @@ public Map getContentFromCache(String key) { if (contentCacheMap.containsKey(key)) { return contentCacheMap.get(key); } - return null; + return Collections.emptyMap(); } } diff --git a/src/main/java/org/sunbird/cache/RedisCacheMgr.java b/src/main/java/org/sunbird/cache/RedisCacheMgr.java index 12199105..9fe6e302 100644 --- a/src/main/java/org/sunbird/cache/RedisCacheMgr.java +++ b/src/main/java/org/sunbird/cache/RedisCacheMgr.java @@ -52,7 +52,7 @@ public void putCache(String key, Object object, int ttl) { String data = objectMapper.writeValueAsString(object); jedis.set(Constants.REDIS_COMMON_KEY + key, data); jedis.expire(Constants.REDIS_COMMON_KEY + key, ttl); - logger.debug("Cache_key_value " + Constants.REDIS_COMMON_KEY + key + " is saved in redis"); + logger.debug(Constants.CACHE_KEY_VALUE + Constants.REDIS_COMMON_KEY + key + Constants.IS_SAVED_IN_REDIS); } catch (Exception e) { logger.error(e); } @@ -65,7 +65,7 @@ public void putInQuestionCache(String key, Object object) { String data = objectMapper.writeValueAsString(object); jedis.set(Constants.REDIS_COMMON_KEY + key, data); jedis.expire(Constants.REDIS_COMMON_KEY + key, questions_cache_ttl); - logger.debug("Cache_key_value " + Constants.REDIS_COMMON_KEY + key + " is saved in redis"); + logger.debug(Constants.CACHE_KEY_VALUE + Constants.REDIS_COMMON_KEY + key + Constants.IS_SAVED_IN_REDIS); } catch (Exception e) { logger.error(e); } @@ -74,7 +74,7 @@ public void putStringInCache(String key, String value,int ttl) { try (Jedis jedis = jedisPool.getResource()) { jedis.set(Constants.REDIS_COMMON_KEY + key, value); jedis.expire(Constants.REDIS_COMMON_KEY + key, ttl); - logger.debug("Cache_key_value " + Constants.REDIS_COMMON_KEY + key + " is saved in redis"); + logger.debug(Constants.CACHE_KEY_VALUE + Constants.REDIS_COMMON_KEY + key + Constants.IS_SAVED_IN_REDIS); } catch (Exception e) { logger.error(e); } @@ -87,7 +87,7 @@ public void putStringInCache(String key, String value) { public boolean deleteKeyByName(String key) { try (Jedis jedis = jedisPool.getResource()) { jedis.del(Constants.REDIS_COMMON_KEY + key); - logger.debug("Cache_key_value " + Constants.REDIS_COMMON_KEY + key + " is deleted from redis"); + logger.debug(Constants.CACHE_KEY_VALUE + Constants.REDIS_COMMON_KEY + key + " is deleted from redis"); return true; } catch (Exception e) { logger.error(e); @@ -129,7 +129,7 @@ public List mget(List fields) { } catch (Exception e) { logger.error(e); } - return null; + return Collections.emptyList(); } public Set getAllKeyNames() { @@ -169,7 +169,7 @@ public List hget(String key, int index, String... fields) { return jedis.hmget(key, fields); } catch (Exception e) { logger.error(e); - return null; + return Collections.emptyList(); } } diff --git a/src/main/java/org/sunbird/cache/controller/RedisCacheController.java b/src/main/java/org/sunbird/cache/controller/RedisCacheController.java index 165de5f7..0711c938 100644 --- a/src/main/java/org/sunbird/cache/controller/RedisCacheController.java +++ b/src/main/java/org/sunbird/cache/controller/RedisCacheController.java @@ -14,19 +14,19 @@ public class RedisCacheController { @DeleteMapping("/redis") - public ResponseEntity deleteCache() throws Exception { + public ResponseEntity deleteCache() { SBApiResponse response = redisCacheService.deleteCache(); return new ResponseEntity<>(response, response.getResponseCode()); } @GetMapping("/redis") - public ResponseEntity getKeys() throws Exception { + public ResponseEntity getKeys() { SBApiResponse response = redisCacheService.getKeys(); return new ResponseEntity<>(response, response.getResponseCode()); } @GetMapping("/redis/values") - public ResponseEntity getKeysAndValues() throws Exception { + public ResponseEntity getKeysAndValues() { SBApiResponse response = redisCacheService.getKeysAndValues(); return new ResponseEntity<>(response, response.getResponseCode()); } diff --git a/src/main/java/org/sunbird/cache/service/RedisCacheService.java b/src/main/java/org/sunbird/cache/service/RedisCacheService.java index be065ecf..b0226fd3 100644 --- a/src/main/java/org/sunbird/cache/service/RedisCacheService.java +++ b/src/main/java/org/sunbird/cache/service/RedisCacheService.java @@ -4,10 +4,10 @@ public interface RedisCacheService { - public SBApiResponse deleteCache() throws Exception; + public SBApiResponse deleteCache(); - public SBApiResponse getKeys() throws Exception; + public SBApiResponse getKeys(); - public SBApiResponse getKeysAndValues() throws Exception; + public SBApiResponse getKeysAndValues(); } diff --git a/src/main/java/org/sunbird/cache/service/RedisCacheServiceImpl.java b/src/main/java/org/sunbird/cache/service/RedisCacheServiceImpl.java index 6046d625..fe95600a 100644 --- a/src/main/java/org/sunbird/cache/service/RedisCacheServiceImpl.java +++ b/src/main/java/org/sunbird/cache/service/RedisCacheServiceImpl.java @@ -21,14 +21,14 @@ public class RedisCacheServiceImpl implements RedisCacheService { private CbExtLogger logger = new CbExtLogger(getClass().getName()); @Override - public SBApiResponse deleteCache() throws Exception { + public SBApiResponse deleteCache() { SBApiResponse response = new SBApiResponse(Constants.API_REDIS_DELETE); boolean res = redisCache.deleteAllCBExtKey(); if (res) { response.getParams().setStatus(Constants.SUCCESSFUL); response.setResponseCode(HttpStatus.OK); } else { - String errMsg = "No Keys found, Redis cache is empty"; + String errMsg = Constants.NO_REDIS_CACHE_KEY_FOUND; logger.info(errMsg); response.getParams().setErrmsg(errMsg); response.setResponseCode(HttpStatus.NOT_FOUND); @@ -37,7 +37,7 @@ public SBApiResponse deleteCache() throws Exception { } @Override - public SBApiResponse getKeys() throws Exception { + public SBApiResponse getKeys() { SBApiResponse response = new SBApiResponse(Constants.API_REDIS_GET_KEYS); Set res = redisCache.getAllKeyNames(); if (!res.isEmpty()) { @@ -46,7 +46,7 @@ public SBApiResponse getKeys() throws Exception { response.setResponseCode(HttpStatus.OK); } else { - String errMsg = "No Keys found, Redis cache is empty"; + String errMsg = Constants.NO_REDIS_CACHE_KEY_FOUND; logger.info(errMsg); response.getParams().setErrmsg(errMsg); response.setResponseCode(HttpStatus.NOT_FOUND); @@ -55,7 +55,7 @@ public SBApiResponse getKeys() throws Exception { } @Override - public SBApiResponse getKeysAndValues() throws Exception { + public SBApiResponse getKeysAndValues() { SBApiResponse response = new SBApiResponse(Constants.API_REDIS_GET_KEYS_VALUE_SET); List> result = redisCache.getAllKeysAndValues(); @@ -65,7 +65,7 @@ public SBApiResponse getKeysAndValues() throws Exception { response.put(Constants.RESPONSE, result); response.setResponseCode(HttpStatus.OK); } else { - String errMsg = "No Keys found, Redis cache is empty"; + String errMsg = Constants.NO_REDIS_CACHE_KEY_FOUND; logger.info(errMsg); response.getParams().setErrmsg(errMsg); response.setResponseCode(HttpStatus.NOT_FOUND); diff --git a/src/main/java/org/sunbird/cassandra/utils/CassandraOperationImpl.java b/src/main/java/org/sunbird/cassandra/utils/CassandraOperationImpl.java index abed658c..b461e198 100644 --- a/src/main/java/org/sunbird/cassandra/utils/CassandraOperationImpl.java +++ b/src/main/java/org/sunbird/cassandra/utils/CassandraOperationImpl.java @@ -132,7 +132,7 @@ public List> searchByWhereClause(String keyspace, String tab selectQuery.allowFiltering(); Clause lastAccessTime = QueryBuilder.lt("last_access_time", date); selectWhere.and(lastAccessTime); - logger.debug("our query: " + selectQuery.getQueryString()); + logger.debug("our query: {}" , selectQuery.getQueryString()); ResultSet resultSet = connectionManager.getSession(keyspace).execute(selectQuery); return CassandraUtil.createResponse(resultSet); } @@ -263,7 +263,7 @@ public void getAllRecords(String keyspace, String table, List fields, St rowMap.put(entry.getKey(), (String) row.getObject(entry.getValue())); }); - objectInfo.put((String) rowMap.get(key), rowMap); + objectInfo.put(rowMap.get(key), rowMap); }); } catch (Exception e) { logger.error(Constants.EXCEPTION_MSG_FETCH + table + " : " + e.getMessage(), e); @@ -299,7 +299,7 @@ public void getAllRecordsWithPagination(String keyspace, String table, List createCbPlan( @RequestBody SunbirdApiRequest request, @RequestHeader(Constants.X_AUTH_TOKEN) String token, - @RequestHeader(Constants.X_AUTH_USER_ORG_ID) String userOrgId) throws Exception { + @RequestHeader(Constants.X_AUTH_USER_ORG_ID) String userOrgId) { SBApiResponse response = cbPlanService.createCbPlan(request, userOrgId, token); return new ResponseEntity<>(response, response.getResponseCode()); @@ -32,7 +32,7 @@ public ResponseEntity updateCbPlan( @RequestBody SunbirdApiRequest request, @RequestHeader(Constants.X_AUTH_TOKEN) String token, @RequestHeader(Constants.X_AUTH_USER_ORG_ID) String userOrgId, - @RequestHeader(Constants.X_AUTH_USER_ROLES) List userRoles) throws Exception { + @RequestHeader(Constants.X_AUTH_USER_ROLES) List userRoles) { SBApiResponse response = cbPlanService.updateCbPlan(request, userOrgId, token, userRoles); return new ResponseEntity<>(response, response.getResponseCode()); @@ -43,7 +43,7 @@ public ResponseEntity publishCbPlan( @RequestBody SunbirdApiRequest request, @RequestHeader(Constants.X_AUTH_TOKEN) String token, @RequestHeader(Constants.X_AUTH_USER_ORG_ID) String userOrgId, - @RequestHeader(Constants.X_AUTH_USER_ROLES) List userRoles) throws Exception { + @RequestHeader(Constants.X_AUTH_USER_ROLES) List userRoles) { SBApiResponse response = cbPlanService.publishCbPlan(request, userOrgId, token, userRoles); return new ResponseEntity<>(response, response.getResponseCode()); @@ -54,7 +54,7 @@ public ResponseEntity retireCbPlan( @RequestBody SunbirdApiRequest request, @RequestHeader(Constants.X_AUTH_TOKEN) String token, @RequestHeader(Constants.X_AUTH_USER_ORG_ID) String userOrgId, - @RequestHeader(Constants.X_AUTH_USER_ROLES) List userRoles) throws Exception { + @RequestHeader(Constants.X_AUTH_USER_ROLES) List userRoles) { SBApiResponse response = cbPlanService.retireCbPlan(request, userOrgId, token, userRoles); return new ResponseEntity<>(response, response.getResponseCode()); @@ -64,7 +64,7 @@ public ResponseEntity retireCbPlan( public ResponseEntity readCbPlan( @PathVariable("cbPlanId") String cbPlanId, @RequestHeader(Constants.X_AUTH_TOKEN) String token, - @RequestHeader(Constants.X_AUTH_USER_ORG_ID) String userOrgId) throws Exception { + @RequestHeader(Constants.X_AUTH_USER_ORG_ID) String userOrgId) { SBApiResponse response = cbPlanService.readCbPlan(cbPlanId, userOrgId, token); return new ResponseEntity<>(response, response.getResponseCode()); @@ -82,7 +82,7 @@ public ResponseEntity listCBPlan( @GetMapping("/v1/user/list") public ResponseEntity getCBPlanListForUser( @RequestHeader(Constants.X_AUTH_TOKEN) String token, - @RequestHeader(Constants.X_AUTH_USER_ORG_ID)String userOrgId) throws Exception { + @RequestHeader(Constants.X_AUTH_USER_ORG_ID)String userOrgId) { SBApiResponse response = cbPlanService.getCBPlanListForUser(userOrgId, token); return new ResponseEntity<>(response, response.getResponseCode()); @@ -91,7 +91,7 @@ public ResponseEntity getCBPlanListForUser( @GetMapping("/v1/private/user/list") public ResponseEntity getPrivateCBPlanListForUser( @RequestHeader(Constants.X_AUTH_USER_ID) String userId, - @RequestHeader(Constants.X_AUTH_USER_ORG_ID)String userOrgId) throws Exception { + @RequestHeader(Constants.X_AUTH_USER_ORG_ID)String userOrgId) { SBApiResponse response = cbPlanService.getCBPlanListForUser(userOrgId, userId,true); return new ResponseEntity<>(response, response.getResponseCode()); diff --git a/src/main/java/org/sunbird/cbp/service/CbPlanService.java b/src/main/java/org/sunbird/cbp/service/CbPlanService.java index a71d2efd..c5d89e95 100644 --- a/src/main/java/org/sunbird/cbp/service/CbPlanService.java +++ b/src/main/java/org/sunbird/cbp/service/CbPlanService.java @@ -1,6 +1,5 @@ package org.sunbird.cbp.service; -import org.sunbird.cbp.model.dto.CbPlanDto; import org.sunbird.common.model.SBApiResponse; import org.sunbird.common.model.SunbirdApiRequest; diff --git a/src/main/java/org/sunbird/cbp/service/CbPlanServiceImpl.java b/src/main/java/org/sunbird/cbp/service/CbPlanServiceImpl.java index fd3a81cb..e7e72c5a 100644 --- a/src/main/java/org/sunbird/cbp/service/CbPlanServiceImpl.java +++ b/src/main/java/org/sunbird/cbp/service/CbPlanServiceImpl.java @@ -102,17 +102,17 @@ public SBApiResponse createCbPlan(SunbirdApiRequest request, String userOrgId, S response.getResult().put(Constants.ID, cbPlanId); } else { response.getParams().setStatus(Constants.FAILED); - response.getParams().setErrmsg("Failed to Create CB Plan for OrgId: " + userOrgId + " message: " + resp.getParams().getErrmsg()); + response.getParams().setErrmsg(Constants.FAILED_TO_CREATE_CBLAN_FOR_ORGID + userOrgId + " message: " + resp.getParams().getErrmsg()); response.setResponseCode(HttpStatus.INTERNAL_SERVER_ERROR); } } catch (JsonProcessingException e) { - logger.error("Failed to Create CB Plan for OrgId: " + userOrgId, e); + logger.error(Constants.FAILED_TO_CREATE_CBLAN_FOR_ORGID + userOrgId, e); response.getParams().setStatus(Constants.FAILED); response.getParams().setErrmsg(e.getMessage()); response.setResponseCode(HttpStatus.INTERNAL_SERVER_ERROR); } } catch (Exception e) { - logger.error("Failed to Create CB Plan for OrgId: " + userOrgId, e); + logger.error(Constants.FAILED_TO_CREATE_CBLAN_FOR_ORGID + userOrgId, e); response.getParams().setStatus(Constants.FAILED); response.getParams().setErrmsg(e.getMessage()); response.setResponseCode(HttpStatus.INTERNAL_SERVER_ERROR); @@ -181,7 +181,7 @@ public SBApiResponse updateCbPlan(SunbirdApiRequest request, String userOrgId, S } else { response.getParams().setStatus(Constants.FAILED); response.getParams() - .setErrmsg((String) resp.get(Constants.ERROR_MESSAGE) + "for cbPlanId: " + cbPlanId); + .setErrmsg((String) resp.get(Constants.ERROR_MESSAGE) + Constants.FOR_CBPLANID + cbPlanId); response.setResponseCode(HttpStatus.BAD_REQUEST); } } else { @@ -219,7 +219,7 @@ public SBApiResponse publishCbPlan(SunbirdApiRequest request, String userOrgId, String comment = (String) requestData.get(Constants.COMMENT); if (cbPlanId == null) { response.getParams().setStatus(Constants.FAILED); - response.getParams().setErrmsg("CbPlanId is missing."); + response.getParams().setErrmsg(Constants.CB_PLANID_MISSING); response.setResponseCode(HttpStatus.BAD_REQUEST); return response; } @@ -294,12 +294,12 @@ public SBApiResponse publishCbPlan(SunbirdApiRequest request, String userOrgId, } else { response.getParams().setStatus(Constants.FAILED); response.getParams() - .setErrmsg((String) resp.get(Constants.ERROR_MESSAGE) + "for cbPlanId: " + cbPlanId); + .setErrmsg((String) resp.get(Constants.ERROR_MESSAGE) + Constants.FOR_CBPLANID + cbPlanId); response.setResponseCode(HttpStatus.BAD_REQUEST); } } else { response.getParams().setStatus(Constants.FAILED); - response.getParams().setErrmsg("CbPlan is not exist for ID: " + cbPlanId); + response.getParams().setErrmsg(Constants.CBPLAN_NOT_EXIST_FOR_ID + cbPlanId); response.setResponseCode(HttpStatus.BAD_REQUEST); } } catch (Exception e) { @@ -327,7 +327,7 @@ public SBApiResponse retireCbPlan(SunbirdApiRequest request, String userOrgId, S String comment = (String) requestData.get(Constants.COMMENT); if (cbPlanId == null) { response.getParams().setStatus(Constants.FAILED); - response.getParams().setErrmsg("CbPlanId is missing."); + response.getParams().setErrmsg(Constants.CB_PLANID_MISSING); response.setResponseCode(HttpStatus.BAD_REQUEST); return response; } @@ -371,12 +371,12 @@ public SBApiResponse retireCbPlan(SunbirdApiRequest request, String userOrgId, S } else { response.getParams().setStatus(Constants.FAILED); response.getParams() - .setErrmsg((String) resp.get(Constants.ERROR_MESSAGE) + "for cbPlanId: " + cbPlanId); + .setErrmsg((String) resp.get(Constants.ERROR_MESSAGE) + Constants.FOR_CBPLANID + cbPlanId); response.setResponseCode(HttpStatus.BAD_REQUEST); } } else { response.getParams().setStatus(Constants.FAILED); - response.getParams().setErrmsg("CbPlan is not exist for ID: " + cbPlanId); + response.getParams().setErrmsg(Constants.CBPLAN_NOT_EXIST_FOR_ID + cbPlanId); response.setResponseCode(HttpStatus.BAD_REQUEST); } } catch (Exception e) { @@ -395,7 +395,7 @@ public SBApiResponse readCbPlan(String cbPlanId, String userOrgId, String authUs UUID cbPlanUUID = UUID.fromString(cbPlanId); if (cbPlanId == null) { response.getParams().setStatus(Constants.FAILED); - response.getParams().setErrmsg("CbPlanId is missing."); + response.getParams().setErrmsg(Constants.CB_PLANID_MISSING); response.setResponseCode(HttpStatus.BAD_REQUEST); return response; } @@ -411,7 +411,7 @@ public SBApiResponse readCbPlan(String cbPlanId, String userOrgId, String authUs response.getResult().put(Constants.CONTENT, enrichData); } else { response.getParams().setStatus(Constants.FAILED); - response.getParams().setErrmsg("CbPlan is not exist for ID: " + cbPlanId); + response.getParams().setErrmsg(Constants.CBPLAN_NOT_EXIST_FOR_ID + cbPlanId); response.setResponseCode(HttpStatus.BAD_REQUEST); } } catch (Exception e) { @@ -437,7 +437,7 @@ public SBApiResponse getCBPlanListForUser(String userOrgId, String authTokenOrUs userId = authTokenOrUserId; else userId = validateAuthTokenAndFetchUserId(authTokenOrUserId); - logger.info("UserId of the User : " + userId + "User org ID : " + userOrgId); + logger.info("UserId of the User : {}, User org ID : {}", userId, userOrgId); List fields = Arrays.asList(Constants.PROFILE_DETAILS, Constants.ROOT_ORG_ID); Map propertiesMap = new HashMap<>(); propertiesMap.put(Constants.ID, userId); @@ -468,7 +468,7 @@ public SBApiResponse getCBPlanListForUser(String userOrgId, String authTokenOrUs } List assignmentTypeInfoKeyQueryList = new ArrayList<>(Arrays.asList(userId, Constants.ALL_USER)); if (StringUtils.isNotEmpty(userDesignation)) { - logger.info("User Designation : " + userDesignation); + logger.info("User Designation : {}", userDesignation); assignmentTypeInfoKeyQueryList.add(userDesignation); } propertiesMap.clear(); @@ -484,7 +484,7 @@ public SBApiResponse getCBPlanListForUser(String userOrgId, String authTokenOrUs } List> resultMap = new ArrayList<>(); Map courseDetailsMap = new HashMap<>(); - cbplanResult = cbplanResult.stream().filter(userCbPlan -> (Boolean)userCbPlan.get(Constants.CB_IS_ACTIVE) == true) + cbplanResult = cbplanResult.stream().filter(userCbPlan -> (Boolean)userCbPlan.get(Constants.CB_IS_ACTIVE) == Boolean.TRUE) .sorted(Comparator.comparing(m -> (Date) ((Map) m).get(Constants.END_DATE)).reversed()).collect(Collectors.toList()); for (Map cbPlan : cbplanResult) { Map cbPlanDetails = new HashMap<>(); @@ -499,7 +499,6 @@ public SBApiResponse getCBPlanListForUser(String userOrgId, String authTokenOrUs if (!courseDetailsMap.containsKey(courseId)) { contentDetails = contentService.readContentFromCache(courseId, null); if (MapUtils.isNotEmpty(contentDetails)) { - //if (Constants.LIVE.equalsIgnoreCase((String) contentDetails.get(Constants.STATUS))) { if (courseId.contains("_rc")) { if (isVerifiedKaramyogi != null && isVerifiedKaramyogi) { Map secureSettings = (Map) contentDetails.get(Constants.SECURE_SETTINGS); @@ -518,7 +517,7 @@ public SBApiResponse getCBPlanListForUser(String userOrgId, String authTokenOrUs } //} } else { - logger.error("Failed to read course details for Id: " + courseId); + logger.error("Failed to read course details for Id: {}", courseId); } } else { continue; @@ -530,7 +529,7 @@ public SBApiResponse getCBPlanListForUser(String userOrgId, String authTokenOrUs cbPlanDetails.put(Constants.CB_CONTENT_LIST, courseList); resultMap.add(cbPlanDetails); } - logger.info("Number of CB Plan Available for the user is " + resultMap.size()); + logger.info("Number of CB Plan Available for the user is {}", resultMap.size()); response.getResult().put(Constants.COUNT, resultMap.size()); response.getResult().put(Constants.CONTENT, resultMap); } catch (Exception e) { @@ -663,8 +662,9 @@ private Map populateReadData(Map cbPlan) throws enrichUserInfo(userInfoMap); } + String createdBy = (String) cbPlan.get(Constants.CREATED_BY); enrichData.put(Constants.CREATED_BY_NAME, - userInfoMap.get((String) cbPlan.get(Constants.CREATED_BY)).get(Constants.FIRSTNAME)); + userInfoMap.get(createdBy).get(Constants.FIRSTNAME)); enrichData.put(Constants.CREATED_BY, cbPlan.get(Constants.CREATED_BY)); List> enrichContentInfoMap = new ArrayList<>(); for (String contentId : contentTypeInfo) { @@ -733,7 +733,7 @@ private boolean updateCbPlanLookupInfo(CbPlan planDto, String orgId, UUID cbPlan boolean isUpdatedLookup = false; List> cbPlanMap = cassandraOperation.getRecordsByProperties(Constants.KEYSPACE_SUNBIRD, Constants.TABLE_CB_PLAN_LOOKUP, cbPlanInfo, null); - List cbPlanInfoInsertAssignmentKey = new ArrayList<>(); + List cbPlanInfoInsertAssignmentKey; List cbPlanInfoUpdateAssignmentKey = new ArrayList<>(); List cbPlanInfoRequestUpdateAssignmentKey = new ArrayList<>(); if (CollectionUtils.isNotEmpty(cbPlanMap)) { @@ -745,7 +745,7 @@ private boolean updateCbPlanLookupInfo(CbPlan planDto, String orgId, UUID cbPlan cbPlanInfoUpdateAssignmentKey = assignmentKeyInfoList.stream() .filter(key -> !planDto.getAssignmentTypeInfo().contains(key)).collect(Collectors.toList()); cbPlanInfoRequestUpdateAssignmentKey = cbPlanMap.stream().filter(key -> (planDto.getAssignmentTypeInfo().contains((String)key.get(Constants.CB_ASSIGNMENT_TYPE_INFO_KEY)) - && (Boolean)key.get(Constants.CB_IS_ACTIVE) == false)) + && (Boolean)key.get(Constants.CB_IS_ACTIVE) == Boolean.FALSE)) .map(key -> (String) key.get(Constants.CB_ASSIGNMENT_TYPE_INFO_KEY)) .collect(Collectors.toList()); cbPlanInfoUpdateAssignmentKey.addAll(cbPlanInfoRequestUpdateAssignmentKey); @@ -871,7 +871,7 @@ public SBApiResponse listCbPlan(SunbirdApiRequest request, String userOrgId, Str return response; } - Map cbPlanPrimaryKey = new HashMap(); + Map cbPlanPrimaryKey = new HashMap<>(); cbPlanPrimaryKey.put(Constants.ORG_ID, userOrgId); List fields = Arrays.asList(Constants.ORG_ID, Constants.ID, Constants.NAME, Constants.CB_CONTENT_TYPE, Constants.CB_CONTENT_LIST, Constants.CB_ASSIGNMENT_TYPE, @@ -966,7 +966,7 @@ public SBApiResponse listCbPlan(SunbirdApiRequest request, String userOrgId, Str cbPlan.put(Constants.USER_DETAILS, enrichUserInfoList); } else if (Constants.CB_DESIGNATION_TYPE.equalsIgnoreCase(assignmentType)) { - cbPlan.put(Constants.USER_DETAILS, (List) cbPlan.get(Constants.CB_ASSIGNMENT_TYPE_INFO)); + cbPlan.put(Constants.USER_DETAILS, Collections.singletonList((String) cbPlan.get(Constants.CB_ASSIGNMENT_TYPE_INFO))); } userUtilityService.getUserDetailsFromDB(Arrays.asList((String) cbPlan.get(Constants.CREATED_BY)), @@ -1017,7 +1017,8 @@ private String validateListAPI(String orgId, SunbirdApiRequest request, CbPlanSe return errMsg; } - String contentType, assignmentType; + String contentType; + String assignmentType; contentType = (String) searchReq.getFilters().get(Constants.CONTENT_TYPE); assignmentType = (String) searchReq.getFilters().get(Constants.CB_ASSIGNMENT_TYPE); diff --git a/src/main/java/org/sunbird/cbp/service/CbplanContentConsumer.java b/src/main/java/org/sunbird/cbp/service/CbplanContentConsumer.java index 4493f9c2..8bc8b0bc 100644 --- a/src/main/java/org/sunbird/cbp/service/CbplanContentConsumer.java +++ b/src/main/java/org/sunbird/cbp/service/CbplanContentConsumer.java @@ -83,14 +83,13 @@ private void processKafkaMessage(Map cbplanContentRequest) { mailNotificationDetails.put(Constants.DESCRIPTION , cbplanContentRequest.get(Constants.DESCRIPTION)); mailNotificationDetails.put(Constants.COPY_EMAIL, mdoAdminEmail); sendNotificationToProviders(mailNotificationDetails); - logger.info(String.format("Completed request for content. Time taken: ", (System.currentTimeMillis() - startTime))); + logger.info(String.format("Completed request for content. Time taken: %d milliseconds", (System.currentTimeMillis() - startTime))); } catch (Exception e) { logger.error("Exception occurred while sending email : " + e.getMessage(), e); } } public List getCBPAdminDetails(Set rootOrgIds){ - List> userRecords = new ArrayList<>(); Map request = getSearchObject(rootOrgIds); HashMap headersValue = new HashMap<>(); headersValue.put("Content-Type", "application/json"); diff --git a/src/main/java/org/sunbird/common/helper/cassandra/CassandraConnectionManagerImpl.java b/src/main/java/org/sunbird/common/helper/cassandra/CassandraConnectionManagerImpl.java index 15d0c007..51de8728 100644 --- a/src/main/java/org/sunbird/common/helper/cassandra/CassandraConnectionManagerImpl.java +++ b/src/main/java/org/sunbird/common/helper/cassandra/CassandraConnectionManagerImpl.java @@ -22,7 +22,7 @@ public class CassandraConnectionManagerImpl implements CassandraConnectionManager { private static Cluster cluster; private static Map cassandraSessionMap = new ConcurrentHashMap<>(2); - public static CbExtLogger logger = new CbExtLogger(CassandraConnectionManagerImpl.class.getName()); + public static final CbExtLogger logger = new CbExtLogger(CassandraConnectionManagerImpl.class.getName()); List keyspaces = Arrays.asList(Constants.KEYSPACE_SUNBIRD, Constants.KEYSPACE_SUNBIRD_COURSES); @PostConstruct diff --git a/src/main/java/org/sunbird/common/model/NotificationRequest.java b/src/main/java/org/sunbird/common/model/NotificationRequest.java index 5b2a847d..1396182c 100644 --- a/src/main/java/org/sunbird/common/model/NotificationRequest.java +++ b/src/main/java/org/sunbird/common/model/NotificationRequest.java @@ -9,7 +9,7 @@ public class NotificationRequest { private Config config; private List ids; private Template template; - private Map rawData; + private Map rawData; private List copyEmail; public String getMode() { diff --git a/src/main/java/org/sunbird/common/service/ContentServiceImpl.java b/src/main/java/org/sunbird/common/service/ContentServiceImpl.java index bd9aea18..c5596250 100644 --- a/src/main/java/org/sunbird/common/service/ContentServiceImpl.java +++ b/src/main/java/org/sunbird/common/service/ContentServiceImpl.java @@ -86,7 +86,7 @@ public List getParticipantsList(String xAuthUser, List batchIdLi Map batch = new HashMap<>(); batch.put("active", true); request.put("batch", batch); - requestBody.put("request", request); + requestBody.put(Constants.REQUEST, request); for (String batchId : batchIdList) { try { @@ -128,7 +128,7 @@ public List getParticipantsForBatch(String xAuthUser, String batchId) { Map batch = new HashMap<>(); batch.put("active", true); request.put("batch", batch); - requestBody.put("request", request); + requestBody.put(Constants.REQUEST, request); try { batch.put("batchId", batchId); SunbirdApiResp response = mapper.convertValue( @@ -172,7 +172,7 @@ public SunbirdApiResp getQuestionListDetails(List questionIdList) { Map search = new HashMap<>(); search.put(Constants.IDENTIFIER, questionIdList); request.put("search", search); - requestMap.put("request", request); + requestMap.put(Constants.REQUEST, request); Map headerValues = new HashMap<>(); headerValues.put(Constants.AUTH_TOKEN, serverConfig.getSbApiKey()); @@ -213,7 +213,7 @@ public Map searchLiveContent(String rootOrgId, String contentId, if (null != response && Constants.OK.equalsIgnoreCase((String) response.get(Constants.RESPONSE_CODE))) { return response; } - return null; + return Collections.emptyMap(); } public Map searchLiveContent(String contentId) { @@ -286,7 +286,7 @@ public Map searchLiveContentByContentIds(List contentIds if (null != response && Constants.OK.equalsIgnoreCase((String) response.get(Constants.RESPONSE_CODE))) { return response; } - return null; + return Collections.emptyMap(); } public void getLiveContentDetails(List contentIdList, List fields, @@ -322,7 +322,7 @@ public void getLiveContentDetails(List contentIdList, List field for (Map content : contentList) { String id = (String) content.get(Constants.IDENTIFIER); if (!contentInfoMap.containsKey(id)) { - Map contentInfo = new HashMap(); + Map contentInfo = new HashMap<>(); contentInfo.put(Constants.COURSE_ID, id); for (String field : fields) { if (content.containsKey(field)) { @@ -369,7 +369,7 @@ public Map readContent(String contentId, List fields) { Map contentResult = (Map) response.get(Constants.RESULT); return (Map) contentResult.get(Constants.CONTENT); } - return null; + return Collections.emptyMap(); } public List> searchContent(String tag) { @@ -430,7 +430,7 @@ public Map readContentFromCache(String contentId, List f responseData = readContent(contentId, fields); } else { try { - responseData = new HashMap(); + responseData = new HashMap<>(); Map contentData = mapper.readValue(contentString, new TypeReference>() { }); diff --git a/src/main/java/org/sunbird/common/service/OutboundRequestHandlerServiceImpl.java b/src/main/java/org/sunbird/common/service/OutboundRequestHandlerServiceImpl.java index 60ed4e12..471d1fca 100644 --- a/src/main/java/org/sunbird/common/service/OutboundRequestHandlerServiceImpl.java +++ b/src/main/java/org/sunbird/common/service/OutboundRequestHandlerServiceImpl.java @@ -85,11 +85,11 @@ public Object fetchResult(String uri) { }); } catch (Exception e1) { } - log.error("Error received: " + e.getResponseBodyAsString(), e); + log.error(Constants.ERROR_RECEIVED + e.getResponseBodyAsString(), e); } catch (Exception e) { log.error(e); try { - log.warn("Error Response: " + mapper.writeValueAsString(response)); + log.warn(Constants.ERROR_RESPONSE + mapper.writeValueAsString(response)); } catch (Exception e1) { } } @@ -151,11 +151,11 @@ public Object fetchUsingGetWithHeadersProfile(String uri, Map he }); } catch (Exception e1) { } - log.error("Error received: " + e.getResponseBodyAsString(), e); + log.error(Constants.ERROR_RECEIVED + e.getResponseBodyAsString(), e); } catch (Exception e) { log.error(e); try { - log.warn("Error Response: " + mapper.writeValueAsString(response)); + log.warn(Constants.ERROR_RESPONSE + mapper.writeValueAsString(response)); } catch (Exception e1) { } } @@ -193,11 +193,11 @@ public Map fetchResultUsingPost(String uri, Object request, Map< }); } catch (Exception e1) { } - log.error("Error received: " + hce.getResponseBodyAsString(), hce); + log.error(Constants.ERROR_RECEIVED + hce.getResponseBodyAsString(), hce); } catch(JsonProcessingException e) { log.error(e); try { - log.warn("Error Response: " + mapper.writeValueAsString(response)); + log.warn(Constants.ERROR_RESPONSE + mapper.writeValueAsString(response)); } catch (Exception e1) { } } @@ -227,7 +227,7 @@ public Map fetchResultUsingPatch(String uri, Object request, Map }); } catch (Exception e1) { } - log.error("Error received: " + e.getResponseBodyAsString(), e); + log.error(Constants.ERROR_RECEIVED + e.getResponseBodyAsString(), e); } if (response == null) { return MapUtils.EMPTY_MAP; diff --git a/src/main/java/org/sunbird/common/service/PdfGenerationService.java b/src/main/java/org/sunbird/common/service/PdfGenerationService.java index 4be965fd..95ab809e 100644 --- a/src/main/java/org/sunbird/common/service/PdfGenerationService.java +++ b/src/main/java/org/sunbird/common/service/PdfGenerationService.java @@ -1,6 +1,5 @@ package org.sunbird.common.service; -import java.io.ByteArrayInputStream; import java.io.ByteArrayOutputStream; import java.io.File; import java.text.SimpleDateFormat; @@ -13,6 +12,7 @@ import org.springframework.beans.factory.annotation.Value; import org.springframework.stereotype.Service; import org.springframework.util.ObjectUtils; +import org.sunbird.common.util.Constants; import org.sunbird.core.logger.CbExtLogger; import org.sunbird.workallocation.model.ChildNode; import org.sunbird.workallocation.model.CompetencyDetails; @@ -48,15 +48,6 @@ public byte[] getWAPdf(WorkAllocation wa, String statusSelected) { pageTable.add(getUserRoleActivities(wa, statusSelected)); ByteArrayOutputStream out = new ByteArrayOutputStream(); -// try { -// JsonPDF.writeToStream((new ByteArrayInputStream(pageTable.toJSONString().getBytes())), out, null); -// } catch (Exception e) { -// String errorMessage = "Failed to generate PDF from JSON Object. Exception: " + e.getMessage(); -// logger.warn(errorMessage); -// logger.error(e); -// return getWaErrorPdf(errorMessage); -// } -// return out.toByteArray(); } @@ -64,10 +55,10 @@ public byte[] getWaExpiredError(WorkAllocation wa, String oldWaId) { if (ObjectUtils.isEmpty(wa.getActiveWAObject())) { // There is no active WA object found. We can not create QR Code for // redirection. - // TODO - Construct Error pdf and return. + // Construct Error pdf and return. } - return null; + return new byte[0]; } public byte[] getWaErrorPdf(String errorMessage) { @@ -80,10 +71,10 @@ public byte[] getWaErrorPdf(String errorMessage) { pageTable.add(jPages); JSONObject paragraphSpacing = new JSONObject(); - paragraphSpacing.put("spacing-after", 5); + paragraphSpacing.put(Constants.SPACING_AFTER, 5); JSONArray headerArray = new JSONArray(); - headerArray.add("paragraph"); + headerArray.add(Constants.PARAGRAPH); headerArray.add(paragraphSpacing); headerArray.add(errorMessage); @@ -91,12 +82,11 @@ public byte[] getWaErrorPdf(String errorMessage) { try { ByteArrayOutputStream out = new ByteArrayOutputStream(); -// JsonPDF.writeToStream((new ByteArrayInputStream(pageTable.toJSONString().getBytes())), out, null); return out.toByteArray(); } catch (Exception e) { logger.error(e); } - return null; + return new byte[0]; } /** @@ -117,12 +107,12 @@ private JSONArray getDepartmentLogoAndQRCode(WorkAllocation wa, String statusSel } JSONArray pdfTable = new JSONArray(); - pdfTable.add("pdf-table"); + pdfTable.add(Constants.PDF_TABLE); { JSONObject pdfTableProperties = new JSONObject(); - pdfTableProperties.put("width-percent", 100); - pdfTableProperties.put("cell-border", false); - pdfTableProperties.put("spacing-after", 20); + pdfTableProperties.put(Constants.WIDTH_PERCENT, 100); + pdfTableProperties.put(Constants.CELL_BORDER, false); + pdfTableProperties.put(Constants.SPACING_AFTER, 20); pdfTable.add(pdfTableProperties); JSONArray widthColumn = new JSONArray(); @@ -135,7 +125,7 @@ private JSONArray getDepartmentLogoAndQRCode(WorkAllocation wa, String statusSel // Adding Department Details... { JSONArray deptColArray = new JSONArray(); - deptColArray.add("pdf-table"); + deptColArray.add(Constants.PDF_TABLE); widthColumn = new JSONArray(); widthColumn.add(40); widthColumn.add(60); @@ -145,9 +135,9 @@ private JSONArray getDepartmentLogoAndQRCode(WorkAllocation wa, String statusSel // Cell for Logo JSONArray deptLogoArray = new JSONArray(); - deptLogoArray.add("pdf-cell"); + deptLogoArray.add(Constants.PDF_CELL); JSONObject firstColProperties = new JSONObject(); - firstColProperties.put("align", "left"); + firstColProperties.put(Constants.ALIGN, "left"); firstColProperties.put("border", true); firstColProperties.put("border-width", 20); JSONArray borderColor = new JSONArray(); @@ -157,14 +147,14 @@ private JSONArray getDepartmentLogoAndQRCode(WorkAllocation wa, String statusSel firstColProperties.put("border-color", borderColor); JSONArray borderEnabled = new JSONArray(); borderEnabled.add("top"); - borderEnabled.add("bottom"); + borderEnabled.add(Constants.BOTTOM); borderEnabled.add("left"); borderEnabled.add("right"); firstColProperties.put("set-border", borderEnabled); deptLogoArray.add(firstColProperties); // Add image { - // TODO check the DeptRepo for Dept Image details. + // check the DeptRepo for Dept Image details. JSONArray deptLogoImage = new JSONArray(); deptLogoImage.add("image"); JSONObject imageProperties = new JSONObject(); @@ -179,14 +169,14 @@ private JSONArray getDepartmentLogoAndQRCode(WorkAllocation wa, String statusSel // Cell for DeptName JSONArray deptNameColArray = new JSONArray(); - deptNameColArray.add("pdf-cell"); + deptNameColArray.add(Constants.PDF_CELL); JSONObject secondColProperties = new JSONObject(); - secondColProperties.put("valign", "bottom"); + secondColProperties.put("valign", Constants.BOTTOM); deptNameColArray.add(secondColProperties); // Add Name { JSONArray deptName = new JSONArray(); - deptName.add("paragraph"); + deptName.add(Constants.PARAGRAPH); deptName.add(waObj.getDeptName()); deptNameColArray.add(deptName); @@ -200,7 +190,7 @@ private JSONArray getDepartmentLogoAndQRCode(WorkAllocation wa, String statusSel // Adding QR Code { JSONArray deptColArray = new JSONArray(); - deptColArray.add("pdf-table"); + deptColArray.add(Constants.PDF_TABLE); widthColumn = new JSONArray(); widthColumn.add(40); widthColumn.add(60); @@ -210,9 +200,9 @@ private JSONArray getDepartmentLogoAndQRCode(WorkAllocation wa, String statusSel // Cell for Logo JSONArray deptLogoArray = new JSONArray(); - deptLogoArray.add("pdf-cell"); + deptLogoArray.add(Constants.PDF_CELL); JSONObject firstColProperties = new JSONObject(); - firstColProperties.put("align", "left"); + firstColProperties.put(Constants.ALIGN, "left"); deptLogoArray.add(firstColProperties); // Add image { @@ -229,14 +219,14 @@ private JSONArray getDepartmentLogoAndQRCode(WorkAllocation wa, String statusSel // Cell for DeptName JSONArray deptNameColArray = new JSONArray(); - deptNameColArray.add("pdf-cell"); + deptNameColArray.add(Constants.PDF_CELL); firstColProperties = new JSONObject(); - firstColProperties.put("valign", "bottom"); + firstColProperties.put("valign", Constants.BOTTOM); deptNameColArray.add(firstColProperties); // Add Name { JSONArray deptName = new JSONArray(); - deptName.add("paragraph"); + deptName.add(Constants.PARAGRAPH); deptName.add("Scan this QR code to find the latest updated digital version of this document"); deptNameColArray.add(deptName); @@ -259,12 +249,12 @@ private JSONArray getDepartmentLogoAndQRCode(WorkAllocation wa, String statusSel */ private JSONArray getHeaderAndDate() { JSONArray pdfTable = new JSONArray(); - pdfTable.add("pdf-table"); + pdfTable.add(Constants.PDF_TABLE); { JSONObject pdfTableProperties = new JSONObject(); - pdfTableProperties.put("width-percent", 100); - pdfTableProperties.put("cell-border", false); - pdfTableProperties.put("spacing-after", 10); + pdfTableProperties.put(Constants.WIDTH_PERCENT, 100); + pdfTableProperties.put(Constants.CELL_BORDER, false); + pdfTableProperties.put(Constants.SPACING_AFTER, 10); pdfTable.add(pdfTableProperties); JSONArray widthRow = new JSONArray(); @@ -273,9 +263,9 @@ private JSONArray getHeaderAndDate() { JSONArray firstRow = new JSONArray(); JSONArray firstColArray = new JSONArray(); - firstColArray.add("pdf-cell"); + firstColArray.add(Constants.PDF_CELL); JSONObject firstColProperties = new JSONObject(); - firstColProperties.put("align", "left"); + firstColProperties.put(Constants.ALIGN, "left"); firstColProperties.put("style", "bold"); firstColProperties.put("size", 13); firstColArray.add(firstColProperties); @@ -286,9 +276,9 @@ private JSONArray getHeaderAndDate() { JSONArray secondRow = new JSONArray(); JSONArray secondColArray = new JSONArray(); - secondColArray.add("pdf-cell"); + secondColArray.add(Constants.PDF_CELL); JSONObject secondColProperties = new JSONObject(); - secondColProperties.put("align", "left"); + secondColProperties.put(Constants.ALIGN, "left"); secondColProperties.put("size", 11); secondColArray.add(secondColProperties); @@ -313,12 +303,12 @@ private JSONArray getHeaderAndDate() { */ private JSONArray getRoleActivityHeader(String statusSelected) { JSONArray pdfTable = new JSONArray(); - pdfTable.add("pdf-table"); + pdfTable.add(Constants.PDF_TABLE); { JSONObject pdfTableProperties = new JSONObject(); - pdfTableProperties.put("width-percent", 100); - pdfTableProperties.put("cell-border", false); - pdfTableProperties.put("spacing-after", 10); + pdfTableProperties.put(Constants.WIDTH_PERCENT, 100); + pdfTableProperties.put(Constants.CELL_BORDER, false); + pdfTableProperties.put(Constants.SPACING_AFTER, 10); pdfTable.add(pdfTableProperties); JSONArray widthRow = new JSONArray(); @@ -329,35 +319,35 @@ private JSONArray getRoleActivityHeader(String statusSelected) { JSONArray firstRow = new JSONArray(); JSONArray firstColArray = new JSONArray(); - firstColArray.add("pdf-cell"); + firstColArray.add(Constants.PDF_CELL); JSONObject firstColProperties = new JSONObject(); - firstColProperties.put("align", "left"); + firstColProperties.put(Constants.ALIGN, "left"); firstColProperties.put("size", 11); JSONArray bgColorArray = new JSONArray(); bgColorArray.add(225); bgColorArray.add(225); bgColorArray.add(225); - firstColProperties.put("background-color", bgColorArray); + firstColProperties.put(Constants.BACKGROUND_COLOR, bgColorArray); firstColArray.add(firstColProperties); firstColArray.add("Full name"); firstRow.add(firstColArray); JSONArray secondColArray = new JSONArray(); - secondColArray.add("pdf-cell"); + secondColArray.add(Constants.PDF_CELL); JSONObject secondColProperties = new JSONObject(); - secondColProperties.put("align", "left"); + secondColProperties.put(Constants.ALIGN, "left"); secondColProperties.put("size", 11); - secondColProperties.put("background-color", bgColorArray); + secondColProperties.put(Constants.BACKGROUND_COLOR, bgColorArray); secondColArray.add(secondColProperties); secondColArray.add("Roles"); firstRow.add(secondColArray); JSONArray thridColArray = new JSONArray(); - thridColArray.add("pdf-cell"); + thridColArray.add(Constants.PDF_CELL); JSONObject thirdColProperties = new JSONObject(); - thirdColProperties.put("align", "left"); + thirdColProperties.put(Constants.ALIGN, "left"); thirdColProperties.put("size", 11); - thirdColProperties.put("background-color", bgColorArray); + thirdColProperties.put(Constants.BACKGROUND_COLOR, bgColorArray); thridColArray.add(thirdColProperties); String header = "Activities"; if (WorkAllocationConstants.DRAFT_STATUS.equalsIgnoreCase(statusSelected)) { @@ -382,12 +372,12 @@ private JSONArray getRoleActivityHeader(String statusSelected) { private JSONArray getUserRoleActivities(WorkAllocation wa, String statusSelected) { WAObject waObj = getWaObject(wa, statusSelected); JSONArray pdfTable = new JSONArray(); - pdfTable.add("pdf-table"); + pdfTable.add(Constants.PDF_TABLE); { JSONObject pdfTableProperties = new JSONObject(); - pdfTableProperties.put("width-percent", 100); - pdfTableProperties.put("cell-border", false); - pdfTableProperties.put("spacing-after", 10); + pdfTableProperties.put(Constants.WIDTH_PERCENT, 100); + pdfTableProperties.put(Constants.CELL_BORDER, false); + pdfTableProperties.put(Constants.SPACING_AFTER, 10); pdfTable.add(pdfTableProperties); JSONArray widthRow = new JSONArray(); @@ -398,9 +388,9 @@ private JSONArray getUserRoleActivities(WorkAllocation wa, String statusSelected JSONArray firstRow = new JSONArray(); { JSONArray firstColArray = new JSONArray(); - firstColArray.add("pdf-cell"); + firstColArray.add(Constants.PDF_CELL); JSONObject firstColProperties = new JSONObject(); - firstColProperties.put("align", "left"); + firstColProperties.put(Constants.ALIGN, "left"); firstColProperties.put("size", 11); firstColArray.add(firstColProperties); firstColArray.add(wa.getUserName()); @@ -409,7 +399,7 @@ private JSONArray getUserRoleActivities(WorkAllocation wa, String statusSelected } JSONArray secondColPdfTable = new JSONArray(); - secondColPdfTable.add("pdf-table"); + secondColPdfTable.add(Constants.PDF_TABLE); widthRow = new JSONArray(); widthRow.add(40); widthRow.add(60); @@ -448,9 +438,9 @@ private JSONArray parseRoleCompetency(RoleCompetency roleCompetency, String stat JSONArray roleCompetencyRow = new JSONArray(); JSONArray firstColArray = new JSONArray(); - firstColArray.add("pdf-cell"); + firstColArray.add(Constants.PDF_CELL); JSONObject firstColProperties = new JSONObject(); - firstColProperties.put("align", "left"); + firstColProperties.put(Constants.ALIGN, "left"); firstColProperties.put("size", 11); firstColArray.add(firstColProperties); firstColArray.add(roleCompetency.getRoleDetails().getName()); @@ -458,18 +448,18 @@ private JSONArray parseRoleCompetency(RoleCompetency roleCompetency, String stat roleCompetencyRow.add(firstColArray); JSONArray secondColArray = new JSONArray(); - secondColArray.add("pdf-cell"); + secondColArray.add(Constants.PDF_CELL); JSONObject secondColProperties = new JSONObject(); - secondColProperties.put("align", "left"); + secondColProperties.put(Constants.ALIGN, "left"); secondColProperties.put("size", 11); secondColArray.add(firstColProperties); JSONObject paragraphSpacing = new JSONObject(); - paragraphSpacing.put("spacing-after", 5); + paragraphSpacing.put(Constants.SPACING_AFTER, 5); if (WorkAllocationConstants.DRAFT_STATUS.equalsIgnoreCase(statusSelected)) { JSONArray headerArray = new JSONArray(); - headerArray.add("paragraph"); + headerArray.add(Constants.PARAGRAPH); headerArray.add(paragraphSpacing); headerArray.add("Activities"); secondColArray.add(headerArray); @@ -477,7 +467,7 @@ private JSONArray parseRoleCompetency(RoleCompetency roleCompetency, String stat for (ChildNode activity : roleCompetency.getRoleDetails().getChildNodes()) { JSONArray chunkArray = new JSONArray(); - chunkArray.add("paragraph"); + chunkArray.add(Constants.PARAGRAPH); chunkArray.add(paragraphSpacing); chunkArray.add(activity.getName()); secondColArray.add(chunkArray); @@ -485,13 +475,13 @@ private JSONArray parseRoleCompetency(RoleCompetency roleCompetency, String stat if (WorkAllocationConstants.DRAFT_STATUS.equalsIgnoreCase(statusSelected)) { JSONArray headerArray = new JSONArray(); - headerArray.add("paragraph"); + headerArray.add(Constants.PARAGRAPH); headerArray.add(paragraphSpacing); headerArray.add("Competencies"); secondColArray.add(headerArray); for (CompetencyDetails competency : roleCompetency.getCompetencyDetails()) { JSONArray chunkArray = new JSONArray(); - chunkArray.add("paragraph"); + chunkArray.add(Constants.PARAGRAPH); chunkArray.add(paragraphSpacing); chunkArray.add(competency.getName()); secondColArray.add(chunkArray); diff --git a/src/main/java/org/sunbird/common/util/AccessTokenValidator.java b/src/main/java/org/sunbird/common/util/AccessTokenValidator.java index 0ad87419..c069afd1 100644 --- a/src/main/java/org/sunbird/common/util/AccessTokenValidator.java +++ b/src/main/java/org/sunbird/common/util/AccessTokenValidator.java @@ -42,14 +42,14 @@ private Map validateToken(String token) throws Exception { mapper.readValue(new String(decodeFromBase64(body)), Map.class); boolean isExp = isExpired((Integer) tokenBody.get("exp")); if (isExp) { - return Collections.EMPTY_MAP; + return Collections.emptyMap(); } return tokenBody; } } catch (IOException e) { - return Collections.EMPTY_MAP; + return Collections.emptyMap(); } - return Collections.EMPTY_MAP; + return Collections.emptyMap(); } diff --git a/src/main/java/org/sunbird/common/util/Base64Util.java b/src/main/java/org/sunbird/common/util/Base64Util.java index 31dd3713..4ea09439 100644 --- a/src/main/java/org/sunbird/common/util/Base64Util.java +++ b/src/main/java/org/sunbird/common/util/Base64Util.java @@ -3,7 +3,7 @@ /* * Copyright (C) 2010 The Android Open Source Project * - * Licensed under the Apache License, Version 2.0 (the "License"); + * Licensed under the Apache License, Version 2.0 (the "License") * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * @@ -16,6 +16,7 @@ * limitations under the License. */ import java.io.UnsupportedEncodingException; +import java.nio.charset.StandardCharsets; /** * Utilities for encoding and decoding the Base64 representation of @@ -155,12 +156,7 @@ public static byte[] decode(byte[] input, int offset, int len, int flags) { * adheres to RFC 2045. */ public static String encodeToString(byte[] input, int flags) { - try { - return new String(encode(input, flags), "US-ASCII"); - } catch (UnsupportedEncodingException e) { - // US-ASCII is guaranteed to be available. - throw new AssertionError(e); - } + return new String(encode(input, flags), StandardCharsets.US_ASCII); } // -------------------------------------------------------- @@ -180,12 +176,7 @@ public static String encodeToString(byte[] input, int flags) { * adheres to RFC 2045. */ public static String encodeToString(byte[] input, int offset, int len, int flags) { - try { - return new String(encode(input, offset, len, flags), "US-ASCII"); - } catch (UnsupportedEncodingException e) { - // US-ASCII is guaranteed to be available. - throw new AssertionError(e); - } + return new String(encode(input, offset, len, flags), StandardCharsets.US_ASCII); } /** @@ -251,7 +242,7 @@ public static byte[] encode(byte[] input, int offset, int len, int flags) { return encoder.output; } - /* package */ static abstract class Coder { + /* package */ abstract static class Coder { public byte[] output; public int op; @@ -282,7 +273,7 @@ public static byte[] encode(byte[] input, int offset, int len, int flags) { * Lookup table for turning bytes into their position in the * Base64 alphabet. */ - private static final int DECODE[] = { + private static final int[] DECODE = { -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, 62, -1, -1, -1, 63, @@ -305,7 +296,7 @@ public static byte[] encode(byte[] input, int offset, int len, int flags) { * Decode lookup table for the "web safe" variant (RFC 3548 * sec. 4) where - and _ replace + and /. */ - private static final int DECODE_WEBSAFE[] = { + private static final int[] DECODE_WEBSAFE = { -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, 62, -1, -1, @@ -329,7 +320,7 @@ public static byte[] encode(byte[] input, int offset, int len, int flags) { */ private static final int SKIP = -1; private static final int EQUALS = -2; - final private int[] alphabet; + private final int[] alphabet; /** * States 0-3 are reading through the next input tuple. * State 4 is having read one '=' and expecting exactly @@ -444,7 +435,6 @@ public boolean process(byte[] input, int offset, int len, boolean finish) { value = (value << 6) | d; ++state; } else if (d == EQUALS) { - // Emit the last (partial) output tuple; // expect exactly one more padding character. output[op++] = (byte) (value >> 4); state = 4; @@ -464,7 +454,6 @@ public boolean process(byte[] input, int offset, int len, boolean finish) { op += 3; state = 0; } else if (d == EQUALS) { - // Emit the last (partial) output tuple; // expect no further data or padding characters. output[op + 1] = (byte) (value >> 2); output[op] = (byte) (value >> 10); @@ -491,6 +480,8 @@ public boolean process(byte[] input, int offset, int len, boolean finish) { return false; } break; + default: + break; } } @@ -554,7 +545,7 @@ public boolean process(byte[] input, int offset, int len, boolean finish) { * Lookup table for turning Base64 alphabet positions (6 bits) * into output bytes. */ - private static final byte ENCODE[] = { + private static final byte[] ENCODE = { 'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z', 'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', @@ -565,17 +556,17 @@ public boolean process(byte[] input, int offset, int len, boolean finish) { * Lookup table for turning Base64 alphabet positions (6 bits) * into output bytes. */ - private static final byte ENCODE_WEBSAFE[] = { + private static final byte[] ENCODE_WEBSAFE = { 'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z', 'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z', '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', '-', '_', }; - final public boolean do_padding; - final public boolean do_newline; - final public boolean do_cr; - final private byte[] tail; - final private byte[] alphabet; + public final boolean do_padding; + public final boolean do_newline; + public final boolean do_cr; + private final byte[] tail; + private final byte[] alphabet; /* package */ int tailLen; private int count; @@ -630,7 +621,6 @@ public boolean process(byte[] input, int offset, int len, boolean finish) { (input[p++] & 0xff); tailLen = 0; } - ; break; case 2: @@ -642,6 +632,8 @@ public boolean process(byte[] input, int offset, int len, boolean finish) { tailLen = 0; } break; + default: + throw new IllegalStateException("Unexpected value: " + tailLen); } if (v != -1) { diff --git a/src/main/java/org/sunbird/common/util/CbExtServerProperties.java b/src/main/java/org/sunbird/common/util/CbExtServerProperties.java index d78adce1..4b1c5e99 100644 --- a/src/main/java/org/sunbird/common/util/CbExtServerProperties.java +++ b/src/main/java/org/sunbird/common/util/CbExtServerProperties.java @@ -8,7 +8,6 @@ import org.codehaus.plexus.util.StringUtils; import org.springframework.beans.factory.annotation.Value; import org.springframework.stereotype.Component; -import org.sunbird.common.model.SBApiResponse; @Component public class CbExtServerProperties { @@ -462,7 +461,7 @@ public void setRedisDataPort(String redisDataPort) { private String assessmentSubmitTopic; @Value("${metaData.contextTypes}") - private String[] ContextTypes; + private String[] contextTypes; @Value("${kafka.topics.user.bulk.upload}") private String userBulkUploadTopic; @@ -595,7 +594,7 @@ public void setRedisDataPort(String redisDataPort) { private String cbPlanEndDate; @Value("${karma.points.limit}") - private int KarmaPointsLimit; + private int karmaPointsLimit; @Value("${kafka.topics.claim.acbp.karma.points}") private String claimKarmaPointsTopic; @@ -1292,14 +1291,6 @@ public void setAssessmentQuestionListPath(String assessmentQuestionListPath) { this.assessmentQuestionListPath = assessmentQuestionListPath; } - public String getSunbirdCbExtVersion() { - return sunbirdCbExtVersion; - } - - public void setSunbirdCbExtVersion(String sunbirdCbExtVersion) { - this.sunbirdCbExtVersion = sunbirdCbExtVersion; - } - public List getAssessmentLevelParams() { return Arrays.asList(assessmentLevelParams.split(",", -1)); } @@ -1625,7 +1616,7 @@ public String[] getSbEsHostList() { } public void setSbEsHostList(String sbEsHost) { - this.sbEsHostList = sbEsHostList; + this.sbEsHostList = sbEsHost; } public String getSbEsUser() { @@ -1857,11 +1848,11 @@ public void setEsUserReportIncludeFields(String esUserReportIncludeFields) { } public String[] getContextTypes() { - return ContextTypes; + return contextTypes; } public void setContextTypes(String[] contextTypes) { - ContextTypes = contextTypes; + this.contextTypes = contextTypes; } public String getUserBulkUploadTopic() { @@ -2145,11 +2136,11 @@ public void setCbPlanUpdatePublishAuthorizedRoles(String cbPlanUpdatePublishAuth } public int getKarmaPointsLimit() { - return KarmaPointsLimit; + return karmaPointsLimit; } public void setKarmaPointsLimit(int karmaPointsLimit) { - KarmaPointsLimit = karmaPointsLimit; + this.karmaPointsLimit = karmaPointsLimit; } public String getClaimKarmaPointsTopic() { @@ -2244,10 +2235,6 @@ public String getEhrmsDetailUrl() { return ehrmsDetailUrl; } - public void setEhrmsDetailUrl(SBApiResponse response) { - this.ehrmsDetailUrl = ehrmsDetailUrl; - } - public void setEhrmsDetailUrl(String ehrmsDetailUrl) { this.ehrmsDetailUrl = ehrmsDetailUrl; } diff --git a/src/main/java/org/sunbird/common/util/Constants.java b/src/main/java/org/sunbird/common/util/Constants.java index 0b370f25..3fa26e02 100644 --- a/src/main/java/org/sunbird/common/util/Constants.java +++ b/src/main/java/org/sunbird/common/util/Constants.java @@ -106,8 +106,8 @@ public class Constants { public static final boolean FETCH_ON_LEVEL = false; public static final boolean SKIP_ACCESS_CHECK = true; public static final List MINIMUL_FIELDS = Collections - .unmodifiableList(Arrays.asList("identifier", "duration", "downloadUrl", "description", "mimeType", - "artifactUrl", "name", STATUS, "resourceType", "categoryType", "category")); + .unmodifiableList(Arrays.asList(Constants.IDENTIFIER, Constants.DURATION, "downloadUrl", Constants.DESCRIPTION, "mimeType", + "artifactUrl", "name", STATUS, "resourceType", "categoryType", Constants.CATEGORY)); public static final String FETCH_RESULT_CONSTANT = ".fetchResult:"; public static final String URI_CONSTANT = "URI: "; public static final String REQUEST_CONSTANT = "Request: "; @@ -557,7 +557,7 @@ public class Constants { public static final String CIPHER_ALGORITHM = "AES"; public static final byte[] CIPHER_KEY = new byte[] { 'T', 'h', 'i', 's', 'A', 's', 'I', 'S', 'e', 'r', 'c', 'e', 'K', 't', 'e', 'y' }; - public static final List DECRYPTED_FIELDS = Arrays.asList("phone", "email"); + public static final List DECRYPTED_FIELDS = Arrays.asList(Constants.PHONE, Constants.EMAIL); public static final String CREATED_FOR = "createdFor"; public static final String COURSE_ORG_ID = "courseOrgId"; public static final String COURSE_ORG_NAME = "courseOrgName"; @@ -975,8 +975,63 @@ public class Constants { public static final String EHRMS_AUTH_PASSWORD = "password"; public static final String USER_ID_LOWER = "userid"; public static final String EHRMS_USER_TOKEN = "ehrmsUserToken"; - - private Constants() { + public static final String BUDGET_YEAR_CONSTANT = ", BudgetYear: "; + public static final String FAILED_BUDGET_SCHEME_FOR_ORGID = "Failed to find BudgetScheme for OrgId: "; + public static final String ID_CONSTANT = ", Id: "; + public static final String OPEN_BATCH = "Open Batch"; + public static final String ONE_OR_MORE_ERROR_FIELD_VALIDATION = "One or more required fields are empty. Empty fields "; + public static final String CACHE_KEY_VALUE = "Cache_key_value "; + public static final String IS_SAVED_IN_REDIS = " is saved in redis"; + public static final String NO_REDIS_CACHE_KEY_FOUND = "No Keys found, Redis cache is empty"; + public static final String FAILED_TO_CREATE_CBLAN_FOR_ORGID = "Failed to Create CB Plan for OrgId: "; + public static final String FOR_CBPLANID = "for cbPlanId: "; + public static final String CB_PLANID_MISSING = "CbPlanId is missing."; + public static final String CBPLAN_NOT_EXIST_FOR_ID = "CbPlan is not exist for ID: "; + public static final String ERROR_RECEIVED = "Error received: "; + public static final String ERROR_RESPONSE = "Error Response: "; + public static final String SPACING_AFTER = "spacing-after"; + public static final String PARAGRAPH = "paragraph"; + public static final String PDF_TABLE = "pdf-table"; + public static final String WIDTH_PERCENT = "width-percent"; + public static final String CELL_BORDER = "cell-border"; + public static final String PDF_CELL = "pdf-cell"; + public static final String ALIGN = "align"; + public static final String BOTTOM = "bottom"; + public static final String BACKGROUND_COLOR = "background-color"; + public static final String TRIPLE_DES = "TripleDES"; + public static final String NULL_CONSTANT = ""; + public static final String FAILED_CREATING_ORG_IN_SUNBIRD = "Failed to create organisation in Sunbird."; + public static final String FAILED_PROFILE_UPDATE_PROCESS = "Failed to process profile update. Exception: "; + public static final String INVALID_COL_TYPE_EXPECTING_STRING = "Invalid column type. Expecting string format"; + public static final String PROGRESS_DETAILS = "progressDetails"; + public static final String RECEIVED_RESPONSE = "Received Response: "; + public static final String STAFF_SERVICE_POSITION = ", Position: "; + public static final String EMPTY_FIELDS_EXCEPTION = "One or more required fields are empty. Empty fields "; + public static final String FAILED_TO_UPLOAD_FILE_EXCEPTION = "Failed to upload file. Exception: "; + public static final String FAILED_TO_DELETE_FILE_EXCEPTION_MESSAGE = "Failed to delete file. Exception: "; + public static final String FAILED_TO_DOWNLOAD_FILE_EXCEPTION_MESSAGE ="Failed to download the file. Exception: "; + public static final String EXCEPTION = ", Exception: "; + public static final String FAILED_TO_DELETE_FILE = "Failed to delete file: "; + public static final String FAILED_TO_DOWNLOAD_FILE = "Failed to download the file: "; + public static final String FAILED_TO_READ_FILE ="Failed to read the downloaded file: "; + public static final String FAILED_USER_INFO_RETRIEVAL_MESSAGE = "Failed to get UserInfo from cassandra for userId: {}"; + public static final String UNAUTHORIZED_FILE_DOWNLOAD_FOR_OTHER_ORG = "User not authorized to download file for other org: {}, request orgId:{}"; + public static final String LASTMODIFIED ="lastModified"; + public static final String FILEMETADATA ="fileMetaData"; + public static final String FAILED_TO_READ_DOWNLOADED_FILE_FOR_URL = "Failed to read the downloaded file for URL: {}"; + public static final String EXCEPTION_MESSAGE_FORMAT = "Exception in %s : %s"; + public static final String SUNBIRD_SERVICE_ERROR = "Sunbird Service ERROR: "; + public static final String WORKORDER_ID = "workorderId"; + public static final String X_AUTHENTICATED_USER_TOKEN = "X-Authenticated-User-Token"; + public static final String X_CHANNEL_ID = "x-channel-id"; + public static final String WORK_ALLOCATION_SAVE_EXCEPTION = "Exception occurred while saving the work allocation!!"; + public static final String DEPT_ID = "deptId"; + public static final String CORRECT_COUNT = "correctCount"; + public static final String INCORRECT_COUNT = "incorrectCount"; + public static final String NOT_ANSWERED_COUNT = "notAnsweredCount"; + public static final String SOURCE_TITLE = "sourceTitle"; + + private Constants() { throw new IllegalStateException("Utility class"); } diff --git a/src/main/java/org/sunbird/common/util/CryptoUtil.java b/src/main/java/org/sunbird/common/util/CryptoUtil.java index cffd11fb..11c2d23a 100644 --- a/src/main/java/org/sunbird/common/util/CryptoUtil.java +++ b/src/main/java/org/sunbird/common/util/CryptoUtil.java @@ -1,10 +1,13 @@ package org.sunbird.common.util; import java.nio.charset.Charset; +import java.nio.charset.StandardCharsets; import java.security.*; public class CryptoUtil { - private static final Charset US_ASCII = Charset.forName("US-ASCII"); + private CryptoUtil() {} + + private static final Charset US_ASCII = StandardCharsets.US_ASCII; public static boolean verifyRSASign(String payLoad, byte[] signature, PublicKey key, String algorithm) { Signature sign; diff --git a/src/main/java/org/sunbird/common/util/IndexerService.java b/src/main/java/org/sunbird/common/util/IndexerService.java index 722fd3be..a14353b8 100644 --- a/src/main/java/org/sunbird/common/util/IndexerService.java +++ b/src/main/java/org/sunbird/common/util/IndexerService.java @@ -1,6 +1,7 @@ package org.sunbird.common.util; import java.io.IOException; +import java.util.Collections; import java.util.List; import java.util.Map; @@ -103,7 +104,7 @@ public Map readEntity(String index, String indexType, String ent logger.error("Exception in getting the record from ElasticSearch", e); } if (null == response) - return null; + return Collections.emptyMap(); return response.getSourceAsMap(); } @@ -126,7 +127,7 @@ public SearchResponse getEsResult(String indexName, String type, SearchSourceBui return getEsResult(searchRequest, isSunbirdES); } - public RestStatus BulkInsert(List indexRequestList) { + public RestStatus bulkInsert(List indexRequestList) { BulkResponse restStatus = null; if (!CollectionUtils.isEmpty(indexRequestList)) { BulkRequest bulkRequest = new BulkRequest(); diff --git a/src/main/java/org/sunbird/common/util/KeyCloakConnectionProvider.java b/src/main/java/org/sunbird/common/util/KeyCloakConnectionProvider.java index a122c3ca..50235e72 100644 --- a/src/main/java/org/sunbird/common/util/KeyCloakConnectionProvider.java +++ b/src/main/java/org/sunbird/common/util/KeyCloakConnectionProvider.java @@ -12,6 +12,7 @@ * other operations. */ public class KeyCloakConnectionProvider { + private KeyCloakConnectionProvider() {} private static Logger logger = LoggerFactory.getLogger(KeyCloakConnectionProvider.class.getName()); @@ -36,7 +37,7 @@ public class KeyCloakConnectionProvider { * * @return Keycloak connection */ - public static Keycloak initialiseConnection() throws Exception { + public static Keycloak initialiseConnection() { keycloak = initialiseEnvConnection(); if (keycloak != null) { return keycloak; @@ -71,7 +72,7 @@ public static Keycloak initialiseConnection() throws Exception { * * @return Keycloak */ - private static Keycloak initialiseEnvConnection() throws Exception { + private static Keycloak initialiseEnvConnection() { String url = System.getenv(Constants.SUNBIRD_SSO_URL); String username = System.getenv(Constants.SUNBIRD_SSO_USERNAME); String password = System.getenv(Constants.SUNBIRD_SSO_PASSWORD); @@ -136,6 +137,7 @@ public static Keycloak getConnection() { * @author Manzarul */ static class ResourceCleanUp extends Thread { + @Override public void run() { if (null != keycloak) { keycloak.close(); diff --git a/src/main/java/org/sunbird/common/util/KeyManager.java b/src/main/java/org/sunbird/common/util/KeyManager.java index ac2e6069..6ce14ba6 100644 --- a/src/main/java/org/sunbird/common/util/KeyManager.java +++ b/src/main/java/org/sunbird/common/util/KeyManager.java @@ -1,11 +1,14 @@ package org.sunbird.common.util; +import java.io.UnsupportedEncodingException; import java.nio.charset.StandardCharsets; import java.nio.file.Files; import java.nio.file.Path; import java.nio.file.Paths; import java.security.KeyFactory; +import java.security.NoSuchAlgorithmException; import java.security.PublicKey; +import java.security.spec.InvalidKeySpecException; import java.security.spec.X509EncodedKeySpec; import java.util.HashMap; import java.util.List; @@ -61,15 +64,15 @@ public KeyData getPublicKey(String keyId) { return keyMap.get(keyId); } - public static PublicKey loadPublicKey(String key) throws Exception { + public static PublicKey loadPublicKey(String key) throws NoSuchAlgorithmException, InvalidKeySpecException { String publicKey = new String(key.getBytes(), StandardCharsets.UTF_8); publicKey = publicKey.replaceAll("(-+BEGIN PUBLIC KEY-+)", ""); publicKey = publicKey.replaceAll("(-+END PUBLIC KEY-+)", ""); publicKey = publicKey.replaceAll("[\\r\\n]+", ""); - byte[] keyBytes = Base64Util.decode(publicKey.getBytes("UTF-8"), Base64Util.DEFAULT); + byte[] keyBytes = Base64Util.decode(publicKey.getBytes(StandardCharsets.UTF_8), Base64Util.DEFAULT); - X509EncodedKeySpec X509publicKey = new X509EncodedKeySpec(keyBytes); + X509EncodedKeySpec x509publicKey = new X509EncodedKeySpec(keyBytes); KeyFactory kf = KeyFactory.getInstance("RSA"); - return kf.generatePublic(X509publicKey); + return kf.generatePublic(x509publicKey); } } \ No newline at end of file diff --git a/src/main/java/org/sunbird/common/util/NotificationUtil.java b/src/main/java/org/sunbird/common/util/NotificationUtil.java index 0045ddab..920b87df 100644 --- a/src/main/java/org/sunbird/common/util/NotificationUtil.java +++ b/src/main/java/org/sunbird/common/util/NotificationUtil.java @@ -36,12 +36,10 @@ public void sendNotification(List sendTo, Map params, St List notificationTosend = new ArrayList<>(Arrays.asList( new Notification(Constants.EMAIL, Constants.MESSAGE, new EmailConfig(senderMail, emailSubject), sendTo, new Template(null, emailTemplate, params)))); - notificationRequest.put(Constants.REQUEST, new HashMap>() { - { - put(Constants.NOTIFICATIONS, notificationTosend); - } - }); - logger.debug(String.format("Notification Request : %s", notificationRequest)); + Map> notificationsMap = new HashMap<>(); + notificationsMap.put(Constants.NOTIFICATIONS, notificationTosend); + notificationRequest.put(Constants.REQUEST, notificationsMap); + logger.debug(String.format("Notification Request : %s" , notificationRequest)); HttpEntity req = new HttpEntity<>(notificationRequest, headers); restTemplate.postForEntity(notificationUrl, req, String.class); } catch (Exception e) { @@ -58,12 +56,9 @@ public void sendNotification(List> notifications) { HttpHeaders headers = new HttpHeaders(); headers.setContentType(MediaType.APPLICATION_JSON); Map notificationRequest = new HashMap<>(); - notificationRequest.put(Constants.REQUEST, new HashMap() { - { - put(Constants.NOTIFICATIONS, notifications); - } - }); - + Map notificationsMap = new HashMap<>(); + notificationsMap.put(Constants.NOTIFICATIONS, notifications); + notificationRequest.put(Constants.REQUEST, notificationsMap); HttpEntity req = new HttpEntity<>(notificationRequest, headers); logger.info(String.format("Notification Request : %s", notificationRequest)); restTemplate.postForEntity(notificationUrl, req, Object.class); diff --git a/src/main/java/org/sunbird/common/util/ProjectUtil.java b/src/main/java/org/sunbird/common/util/ProjectUtil.java index b006910b..ee15cc0a 100644 --- a/src/main/java/org/sunbird/common/util/ProjectUtil.java +++ b/src/main/java/org/sunbird/common/util/ProjectUtil.java @@ -26,9 +26,9 @@ */ public class ProjectUtil { - public static CbExtLogger logger = new CbExtLogger(ProjectUtil.class.getName()); + public static final CbExtLogger logger = new CbExtLogger(ProjectUtil.class.getName()); - public static String DEFAULT_BULK_UPLOAD_VERIFICATION_REGEX = "^[a-zA-Z\\s,]+$"; + public static String DEFAULT_BULK_UPLOAD_VERIFICATION_REGEX = "^[a-zA-Z\\s,]+$"; /** * This method will check incoming value is null or empty it will do empty check @@ -70,7 +70,7 @@ public static SBApiResponse createDefaultResponse(String api) { } public static Map getDefaultHeaders() { - Map headers = new HashMap(); + Map headers = new HashMap<>(); headers.put(Constants.CONTENT_TYPE, Constants.APPLICATION_JSON); return headers; } diff --git a/src/main/java/org/sunbird/core/cipher/BASE64Decoder.java b/src/main/java/org/sunbird/core/cipher/BASE64Decoder.java index e6012588..4de703dc 100644 --- a/src/main/java/org/sunbird/core/cipher/BASE64Decoder.java +++ b/src/main/java/org/sunbird/core/cipher/BASE64Decoder.java @@ -18,7 +18,7 @@ protected int bytesPerLine() { /** * This character array provides the character to value map based on RFC1521. */ - private static final char pem_array[] = { + private static final char[] pemArray = { // 0 1 2 3 4 5 6 7 'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', // 0 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', // 1 @@ -30,25 +30,29 @@ protected int bytesPerLine() { '4', '5', '6', '7', '8', '9', '+', '/' // 7 }; - private static final byte pem_convert_array[] = new byte[256]; + private static final byte[] pemConvertArray = new byte[256]; static { for (int i = 0; i < 255; i++) { - pem_convert_array[i] = -1; + pemConvertArray[i] = -1; } - for (int i = 0; i < pem_array.length; i++) { - pem_convert_array[pem_array[i]] = (byte) i; + for (int i = 0; i < pemArray.length; i++) { + pemConvertArray[pemArray[i]] = (byte) i; } } - byte decode_buffer[] = new byte[4]; + byte[] decodeBuffer = new byte[4]; /** Decode one BASE64 atom into 1, 2, or 3 bytes of data. */ + @Override @SuppressWarnings("fallthrough") protected void decodeAtom(PushbackInputStream inStream, OutputStream outStream, int rem) throws java.io.IOException { int i; - byte a = -1, b = -1, c = -1, d = -1; + byte a = -1; + byte b = -1; + byte c = -1; + byte d = -1; if (rem < 2) { throw new IOException("BASE64Decoder: Not enough bytes for an atom."); @@ -59,45 +63,49 @@ protected void decodeAtom(PushbackInputStream inStream, OutputStream outStream, throw new IOException(); } } while (i == '\n' || i == '\r'); - decode_buffer[0] = (byte) i; + decodeBuffer[0] = (byte) i; - i = readFully(inStream, decode_buffer, 1, rem - 1); + i = readFully(inStream, decodeBuffer, 1, rem - 1); if (i == -1) { throw new IOException(); } - if (rem > 3 && decode_buffer[3] == '=') { + if (rem > 3 && decodeBuffer[3] == '=') { rem = 3; } - if (rem > 2 && decode_buffer[2] == '=') { + if (rem > 2 && decodeBuffer[2] == '=') { rem = 2; } switch (rem) { - case 4: - d = pem_convert_array[decode_buffer[3] & 0xff]; - // NOBREAK - case 3: - c = pem_convert_array[decode_buffer[2] & 0xff]; - // NOBREAK - case 2: - b = pem_convert_array[decode_buffer[1] & 0xff]; - a = pem_convert_array[decode_buffer[0] & 0xff]; - break; + case 4: + d = pemConvertArray[decodeBuffer[3] & 0xff]; + // NOBREAK + case 3: + c = pemConvertArray[decodeBuffer[2] & 0xff]; + // NOBREAK + case 2: + b = pemConvertArray[decodeBuffer[1] & 0xff]; + a = pemConvertArray[decodeBuffer[0] & 0xff]; + break; + default: + break; } switch (rem) { - case 2: - outStream.write((byte) (((a << 2) & 0xfc) | ((b >>> 4) & 3))); - break; - case 3: - outStream.write((byte) (((a << 2) & 0xfc) | ((b >>> 4) & 3))); - outStream.write((byte) (((b << 4) & 0xf0) | ((c >>> 2) & 0xf))); - break; - case 4: - outStream.write((byte) (((a << 2) & 0xfc) | ((b >>> 4) & 3))); - outStream.write((byte) (((b << 4) & 0xf0) | ((c >>> 2) & 0xf))); - outStream.write((byte) (((c << 6) & 0xc0) | (d & 0x3f))); - break; + case 2: + outStream.write((byte) (((a << 2) & 0xfc) | ((b >>> 4) & 3))); + break; + case 3: + outStream.write((byte) (((a << 2) & 0xfc) | ((b >>> 4) & 3))); + outStream.write((byte) (((b << 4) & 0xf0) | ((c >>> 2) & 0xf))); + break; + case 4: + outStream.write((byte) (((a << 2) & 0xfc) | ((b >>> 4) & 3))); + 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/org/sunbird/core/cipher/CharacterDecoder.java b/src/main/java/org/sunbird/core/cipher/CharacterDecoder.java index b732e722..556aaf02 100644 --- a/src/main/java/org/sunbird/core/cipher/CharacterDecoder.java +++ b/src/main/java/org/sunbird/core/cipher/CharacterDecoder.java @@ -56,7 +56,7 @@ protected void decodeAtom(PushbackInputStream aStream, OutputStream bStream, int * This method works around the bizarre semantics of BufferedInputStream's read * method. */ - protected int readFully(InputStream in, byte buffer[], int offset, int len) throws java.io.IOException { + protected int readFully(InputStream in, byte[] buffer, int offset, int len) throws java.io.IOException { for (int i = 0; i < len; i++) { int q = in.read(); if (q == -1) @@ -110,7 +110,7 @@ public void decodeBuffer(InputStream aStream, OutputStream bStream) throws IOExc * @exception IOException An error has occurred while decoding */ public byte decodeBuffer(String inputString)[] throws IOException { - byte inputBuffer[] = new byte[inputString.length()]; + byte[] inputBuffer = new byte[inputString.length()]; ByteArrayInputStream inStream; ByteArrayOutputStream outStream; @@ -122,7 +122,7 @@ public byte decodeBuffer(String inputString)[] throws IOException { } /** Decode the contents of the inputstream into a buffer. */ - public byte decodeBuffer(InputStream in)[] throws IOException { + public byte[] decodeBuffer(InputStream in) throws IOException { ByteArrayOutputStream outStream = new ByteArrayOutputStream(); decodeBuffer(in, outStream); return (outStream.toByteArray()); diff --git a/src/main/java/org/sunbird/core/cipher/DecryptServiceImpl.java b/src/main/java/org/sunbird/core/cipher/DecryptServiceImpl.java index f1b56bb3..bb67d754 100644 --- a/src/main/java/org/sunbird/core/cipher/DecryptServiceImpl.java +++ b/src/main/java/org/sunbird/core/cipher/DecryptServiceImpl.java @@ -15,7 +15,7 @@ @Component public class DecryptServiceImpl { - private int ITERATIONS = 3; + private int iterations = 3; @Value("${sb.env.chiper.password}") private String sbChiperPassword; @@ -47,7 +47,7 @@ public String decryptString(String encStr) { try { String dValue = null; String valueToDecrypt = encStr.trim(); - for (int i = 0; i < ITERATIONS; i++) { + for (int i = 0; i < iterations; i++) { byte[] decodedValue = new BASE64Decoder().decodeBuffer(valueToDecrypt); byte[] decValue = decryptCipher.doFinal(decodedValue); dValue = new String(decValue, StandardCharsets.UTF_8).substring(sbChiperPassword.length()); diff --git a/src/main/java/org/sunbird/core/cipher/SecretKeySpec.java b/src/main/java/org/sunbird/core/cipher/SecretKeySpec.java index 2268de58..48692cf1 100644 --- a/src/main/java/org/sunbird/core/cipher/SecretKeySpec.java +++ b/src/main/java/org/sunbird/core/cipher/SecretKeySpec.java @@ -18,12 +18,12 @@ public class SecretKeySpec implements KeySpec, SecretKey { @PostConstruct public void postConstruct() { - this.key = (byte[]) Constants.CIPHER_KEY.clone(); + this.key = Constants.CIPHER_KEY.clone(); this.algorithm = Constants.CIPHER_ALGORITHM; } public String getAlgorithm() { - return Constants.CIPHER_ALGORITHM; + return this.algorithm; } public String getFormat() { @@ -31,7 +31,7 @@ public String getFormat() { } public byte[] getEncoded() { - return (byte[]) this.key.clone(); + return this.key.clone(); } public int hashCode() { @@ -41,7 +41,7 @@ public int hashCode() { retval += this.key[i] * i; } - return this.algorithm.equalsIgnoreCase("TripleDES") ? retval ^ "desede".hashCode() + return this.algorithm.equalsIgnoreCase(Constants.TRIPLE_DES) ? retval ^ "desede".hashCode() : retval ^ this.algorithm.toLowerCase(Locale.ENGLISH).hashCode(); } @@ -53,8 +53,8 @@ public boolean equals(Object obj) { } else { String thatAlg = ((SecretKey) obj).getAlgorithm(); if (thatAlg.equalsIgnoreCase(this.algorithm) - || thatAlg.equalsIgnoreCase("DESede") && this.algorithm.equalsIgnoreCase("TripleDES") - || thatAlg.equalsIgnoreCase("TripleDES") && this.algorithm.equalsIgnoreCase("DESede")) { + || thatAlg.equalsIgnoreCase("DESede") && this.algorithm.equalsIgnoreCase(Constants.TRIPLE_DES) + || thatAlg.equalsIgnoreCase(Constants.TRIPLE_DES) && this.algorithm.equalsIgnoreCase("DESede")) { byte[] thatKey = ((SecretKey) obj).getEncoded(); return MessageDigest.isEqual(this.key, thatKey); } else { diff --git a/src/main/java/org/sunbird/core/config/EsConfig.java b/src/main/java/org/sunbird/core/config/EsConfig.java index 2d1d27ad..20c609d4 100644 --- a/src/main/java/org/sunbird/core/config/EsConfig.java +++ b/src/main/java/org/sunbird/core/config/EsConfig.java @@ -12,12 +12,8 @@ import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.sunbird.common.util.CbExtServerProperties; -import org.springframework.util.StringUtils; import org.sunbird.core.logger.CbExtLogger; -import java.util.List; - - @Configuration public class EsConfig { private CbExtLogger logger = new CbExtLogger(getClass().getName()); diff --git a/src/main/java/org/sunbird/core/config/RedisConfig.java b/src/main/java/org/sunbird/core/config/RedisConfig.java index 3a399dc1..7dbb291b 100644 --- a/src/main/java/org/sunbird/core/config/RedisConfig.java +++ b/src/main/java/org/sunbird/core/config/RedisConfig.java @@ -19,17 +19,15 @@ public class RedisConfig { @Bean public JedisPool jedisPool() { final JedisPoolConfig poolConfig = buildPoolConfig(); - JedisPool jedisPool = new JedisPool(poolConfig, cbProperties.getRedisHostName(), + return new JedisPool(poolConfig, cbProperties.getRedisHostName(), Integer.parseInt(cbProperties.getRedisPort())); - return jedisPool; } @Bean public JedisPool jedisDataPopulationPool() { final JedisPoolConfig poolConfig = buildPoolConfig(); - JedisPool jedisPool = new JedisPool(poolConfig, cbProperties.getRedisDataHostName(), + return new JedisPool(poolConfig, cbProperties.getRedisDataHostName(), Integer.parseInt(cbProperties.getRedisDataPort())); - return jedisPool; } private JedisPoolConfig buildPoolConfig() { final JedisPoolConfig poolConfig = new JedisPoolConfig(); diff --git a/src/main/java/org/sunbird/core/exception/ApplicationLogicError.java b/src/main/java/org/sunbird/core/exception/ApplicationLogicError.java index f0543798..62b749c6 100644 --- a/src/main/java/org/sunbird/core/exception/ApplicationLogicError.java +++ b/src/main/java/org/sunbird/core/exception/ApplicationLogicError.java @@ -25,6 +25,7 @@ public ApplicationLogicError(String message,Throwable e) this.message = message; } + @Override public String getMessage() { return message; } diff --git a/src/main/java/org/sunbird/course/model/Content.java b/src/main/java/org/sunbird/course/model/Content.java index a0db22a7..b74f3498 100644 --- a/src/main/java/org/sunbird/course/model/Content.java +++ b/src/main/java/org/sunbird/course/model/Content.java @@ -5,6 +5,7 @@ import com.fasterxml.jackson.annotation.JsonInclude; import com.fasterxml.jackson.annotation.JsonProperty; import com.fasterxml.jackson.annotation.JsonPropertyOrder; +import org.sunbird.common.util.Constants; @JsonInclude(JsonInclude.Include.NON_NULL) @JsonPropertyOrder({ "trackable", "instructions", "identifier", "purpose", "channel", "organisation", "description", @@ -284,91 +285,91 @@ public String toString() { .append('['); sb.append("trackable"); sb.append('='); - sb.append(((this.trackable == null) ? "" : this.trackable)); + sb.append(((this.trackable == null) ? Constants.NULL_CONSTANT : this.trackable)); sb.append(','); sb.append("instructions"); sb.append('='); - sb.append(((this.instructions == null) ? "" : this.instructions)); + sb.append(((this.instructions == null) ? Constants.NULL_CONSTANT : this.instructions)); sb.append(','); sb.append("identifier"); sb.append('='); - sb.append(((this.identifier == null) ? "" : this.identifier)); + sb.append(((this.identifier == null) ? Constants.NULL_CONSTANT : this.identifier)); sb.append(','); sb.append("purpose"); sb.append('='); - sb.append(((this.purpose == null) ? "" : this.purpose)); + sb.append(((this.purpose == null) ? Constants.NULL_CONSTANT : this.purpose)); sb.append(','); sb.append("channel"); sb.append('='); - sb.append(((this.channel == null) ? "" : this.channel)); + sb.append(((this.channel == null) ? Constants.NULL_CONSTANT : this.channel)); sb.append(','); sb.append("organisation"); sb.append('='); - sb.append(((this.organisation == null) ? "" : this.organisation)); + sb.append(((this.organisation == null) ? Constants.NULL_CONSTANT : this.organisation)); sb.append(','); sb.append("description"); sb.append('='); - sb.append(((this.description == null) ? "" : this.description)); + sb.append(((this.description == null) ? Constants.NULL_CONSTANT : this.description)); sb.append(','); sb.append("creatorLogo"); sb.append('='); - sb.append(((this.creatorLogo == null) ? "" : this.creatorLogo)); + sb.append(((this.creatorLogo == null) ? Constants.NULL_CONSTANT : this.creatorLogo)); sb.append(','); sb.append("mimeType"); sb.append('='); - sb.append(((this.mimeType == null) ? "" : this.mimeType)); + sb.append(((this.mimeType == null) ? Constants.NULL_CONSTANT : this.mimeType)); sb.append(','); sb.append("posterImage"); sb.append('='); - sb.append(((this.posterImage == null) ? "" : this.posterImage)); + sb.append(((this.posterImage == null) ? Constants.NULL_CONSTANT : this.posterImage)); sb.append(','); sb.append("idealScreenSize"); sb.append('='); - sb.append(((this.idealScreenSize == null) ? "" : this.idealScreenSize)); + sb.append(((this.idealScreenSize == null) ? Constants.NULL_CONSTANT : this.idealScreenSize)); sb.append(','); sb.append("version"); sb.append('='); - sb.append(((this.version == null) ? "" : this.version)); + sb.append(((this.version == null) ? Constants.NULL_CONSTANT : this.version)); sb.append(','); sb.append("pkgVersion"); sb.append('='); - sb.append(((this.pkgVersion == null) ? "" : this.pkgVersion)); + sb.append(((this.pkgVersion == null) ? Constants.NULL_CONSTANT : this.pkgVersion)); sb.append(','); sb.append("objectType"); sb.append('='); - sb.append(((this.objectType == null) ? "" : this.objectType)); + sb.append(((this.objectType == null) ? Constants.NULL_CONSTANT : this.objectType)); sb.append(','); sb.append("learningMode"); sb.append('='); - sb.append(((this.learningMode == null) ? "" : this.learningMode)); + sb.append(((this.learningMode == null) ? Constants.NULL_CONSTANT : this.learningMode)); sb.append(','); sb.append("duration"); sb.append('='); - sb.append(((this.duration == null) ? "" : this.duration)); + sb.append(((this.duration == null) ? Constants.NULL_CONSTANT : this.duration)); sb.append(','); sb.append("license"); sb.append('='); - sb.append(((this.license == null) ? "" : this.license)); + sb.append(((this.license == null) ? Constants.NULL_CONSTANT : this.license)); sb.append(','); sb.append("appIcon"); sb.append('='); - sb.append(((this.appIcon == null) ? "" : this.appIcon)); + sb.append(((this.appIcon == null) ? Constants.NULL_CONSTANT : this.appIcon)); sb.append(','); sb.append("primaryCategory"); sb.append('='); - sb.append(((this.primaryCategory == null) ? "" : this.primaryCategory)); + sb.append(((this.primaryCategory == null) ? Constants.NULL_CONSTANT : this.primaryCategory)); sb.append(','); sb.append("name"); sb.append('='); - sb.append(((this.name == null) ? "" : this.name)); + sb.append(((this.name == null) ? Constants.NULL_CONSTANT : this.name)); sb.append(','); sb.append("lastUpdatedOn"); sb.append('='); - sb.append(((this.lastUpdatedOn == null) ? "" : this.lastUpdatedOn)); + sb.append(((this.lastUpdatedOn == null) ? Constants.NULL_CONSTANT : this.lastUpdatedOn)); sb.append(','); sb.append("contentType"); sb.append('='); - sb.append(((this.contentType == null) ? "" : this.contentType)); + sb.append(((this.contentType == null) ? Constants.NULL_CONSTANT : this.contentType)); sb.append(','); if (sb.charAt((sb.length() - 1)) == ',') { sb.setCharAt((sb.length() - 1), ']'); diff --git a/src/main/java/org/sunbird/course/model/NewCourseData.java b/src/main/java/org/sunbird/course/model/NewCourseData.java index 38280b85..ad6ac5e2 100644 --- a/src/main/java/org/sunbird/course/model/NewCourseData.java +++ b/src/main/java/org/sunbird/course/model/NewCourseData.java @@ -3,6 +3,7 @@ import com.fasterxml.jackson.annotation.JsonInclude; import com.fasterxml.jackson.annotation.JsonProperty; import com.fasterxml.jackson.annotation.JsonPropertyOrder; +import org.sunbird.common.util.Constants; @JsonInclude(JsonInclude.Include.NON_NULL) @JsonPropertyOrder({ "id", "ver", "ts", "params", "responseCode", "result" }) @@ -88,27 +89,27 @@ public String toString() { .append('['); sb.append("id"); sb.append('='); - sb.append(((this.id == null) ? "" : this.id)); + sb.append(((this.id == null) ? Constants.NULL_CONSTANT : this.id)); sb.append(','); sb.append("ver"); sb.append('='); - sb.append(((this.ver == null) ? "" : this.ver)); + sb.append(((this.ver == null) ? Constants.NULL_CONSTANT : this.ver)); sb.append(','); sb.append("ts"); sb.append('='); - sb.append(((this.ts == null) ? "" : this.ts)); + sb.append(((this.ts == null) ? Constants.NULL_CONSTANT : this.ts)); sb.append(','); sb.append("params"); sb.append('='); - sb.append(((this.params == null) ? "" : this.params)); + sb.append(((this.params == null) ? Constants.NULL_CONSTANT : this.params)); sb.append(','); sb.append("responseCode"); sb.append('='); - sb.append(((this.responseCode == null) ? "" : this.responseCode)); + sb.append(((this.responseCode == null) ? Constants.NULL_CONSTANT : this.responseCode)); sb.append(','); sb.append("result"); sb.append('='); - sb.append(((this.result == null) ? "" : this.result)); + sb.append(((this.result == null) ? Constants.NULL_CONSTANT : this.result)); sb.append(','); if (sb.charAt((sb.length() - 1)) == ',') { sb.setCharAt((sb.length() - 1), ']'); diff --git a/src/main/java/org/sunbird/course/model/Params.java b/src/main/java/org/sunbird/course/model/Params.java index 534c3414..d464d53c 100644 --- a/src/main/java/org/sunbird/course/model/Params.java +++ b/src/main/java/org/sunbird/course/model/Params.java @@ -1,10 +1,10 @@ package org.sunbird.course.model; -import javax.annotation.Generated; import com.fasterxml.jackson.annotation.JsonInclude; import com.fasterxml.jackson.annotation.JsonProperty; import com.fasterxml.jackson.annotation.JsonPropertyOrder; +import org.sunbird.common.util.Constants; @JsonInclude(JsonInclude.Include.NON_NULL) @JsonPropertyOrder({ "resmsgid", "msgid", "status", "err", "errmsg" }) @@ -78,23 +78,23 @@ public String toString() { .append('['); sb.append("resmsgid"); sb.append('='); - sb.append(((this.resmsgid == null) ? "" : this.resmsgid)); + sb.append(((this.resmsgid == null) ? Constants.NULL_CONSTANT : this.resmsgid)); sb.append(','); sb.append("msgid"); sb.append('='); - sb.append(((this.msgid == null) ? "" : this.msgid)); + sb.append(((this.msgid == null) ? Constants.NULL_CONSTANT : this.msgid)); sb.append(','); sb.append("status"); sb.append('='); - sb.append(((this.status == null) ? "" : this.status)); + sb.append(((this.status == null) ? Constants.NULL_CONSTANT : this.status)); sb.append(','); sb.append("err"); sb.append('='); - sb.append(((this.err == null) ? "" : this.err)); + sb.append(((this.err == null) ? Constants.NULL_CONSTANT : this.err)); sb.append(','); sb.append("errmsg"); sb.append('='); - sb.append(((this.errmsg == null) ? "" : this.errmsg)); + sb.append(((this.errmsg == null) ? Constants.NULL_CONSTANT : this.errmsg)); sb.append(','); if (sb.charAt((sb.length() - 1)) == ',') { sb.setCharAt((sb.length() - 1), ']'); diff --git a/src/main/java/org/sunbird/course/service/CourseReminderNotificationService.java b/src/main/java/org/sunbird/course/service/CourseReminderNotificationService.java index 8b8fadfe..22f0d04d 100644 --- a/src/main/java/org/sunbird/course/service/CourseReminderNotificationService.java +++ b/src/main/java/org/sunbird/course/service/CourseReminderNotificationService.java @@ -73,7 +73,7 @@ private void sendIncompleteCourseEmail( Map.Entry userCourseProgressDetailsEntry) { try { if (!StringUtils.isEmpty(userCourseProgressDetailsEntry.getValue().getEmail()) - && userCourseProgressDetailsEntry.getValue().getIncompleteCourses().size() > 0) { + && !userCourseProgressDetailsEntry.getValue().getIncompleteCourses().isEmpty()) { Map params = new HashMap<>(); for (int i = 0; i < userCourseProgressDetailsEntry.getValue().getIncompleteCourses().size(); i++) { String courseId = Constants.COURSE_KEYWORD + (i + 1); @@ -103,9 +103,8 @@ private void sendIncompleteCourseEmail( private void fetchCourseIdsAndSetCourseNameAndThumbnail(List> userCoursesList) throws IOException { - Set courseIds = new HashSet<>(); List desiredKeys = Collections.singletonList(Constants.COURSE_ID); - courseIds = userCoursesList.stream() + Set courseIds = userCoursesList.stream() .flatMap(x -> desiredKeys.stream().filter(x::containsKey).distinct().map(x::get)) .collect(Collectors.toSet()); getAndSetCourseName(courseIds); diff --git a/src/main/java/org/sunbird/course/service/ExploreCourseServiceImpl.java b/src/main/java/org/sunbird/course/service/ExploreCourseServiceImpl.java index ce66c031..7ec9c8b8 100644 --- a/src/main/java/org/sunbird/course/service/ExploreCourseServiceImpl.java +++ b/src/main/java/org/sunbird/course/service/ExploreCourseServiceImpl.java @@ -55,7 +55,7 @@ public SBApiResponse getExploreCourseList() { List> courseList = cassandraOperation.getRecordsByProperties( Constants.SUNBIRD_KEY_SPACE_NAME, Constants.TABLE_EXPLORE_COURSE_LIST, MapUtils.EMPTY_MAP, ListUtils.EMPTY_LIST); - List identifierList = new ArrayList(); + List identifierList = new ArrayList<>(); for (Map course : courseList) { identifierList.add((String) course.get(Constants.IDENTIFIER)); } @@ -71,7 +71,7 @@ public SBApiResponse getExploreCourseList() { logger.error(errMsg, e); } if (StringUtils.isNotEmpty(errMsg)) { - logger.error("Failed to initialize the Open Course Details to Cache. ErrMsg: " + errMsg); + logger.error("Failed to initialize the Open Course Details to Cache. ErrMsg: {}" , errMsg); response.getParams().setErrmsg(errMsg); response.getParams().setStatus(Constants.FAILED); response.setResponseCode(HttpStatus.INTERNAL_SERVER_ERROR); @@ -91,7 +91,7 @@ private Map searchContent(List identifierList) { try { StringBuilder sbUrl = new StringBuilder(serverProperties.getKmBaseHost()); sbUrl.append(serverProperties.getKmBaseContentSearch()); - Map headers = new HashMap(); + Map headers = new HashMap<>(); headers.put(Constants.CONTENT_TYPE, Constants.APPLICATION_JSON); return outboundRequestHandlerService.fetchResultUsingPost(sbUrl.toString(), getContentSearchRequest(identifierList), headers); @@ -103,12 +103,12 @@ private Map searchContent(List identifierList) { private Map getContentSearchRequest(List identifierList) { Map request = new HashMap<>(); - Map requestBody = new HashMap(); - Map filters = new HashMap(); + Map requestBody = new HashMap<>(); + Map filters = new HashMap<>(); filters.put(Constants.IDENTIFIER, identifierList); filters.put(Constants.PRIMARY_CATEGORY, serverProperties.getKmCompositeSearchPrimaryCategoryFilters()); requestBody.put(Constants.FILTERS, filters); - Map sortBy = new HashMap(); + Map sortBy = new HashMap<>(); sortBy.put(Constants.LAST_UPDATED_ON, Constants.DESCENDING_ORDER); requestBody.put(Constants.SORT_BY, sortBy); requestBody.put(Constants.FIELDS, serverProperties.getKmCompositeSearchFields()); diff --git a/src/main/java/org/sunbird/halloffame/controller/HallOfFameController.java b/src/main/java/org/sunbird/halloffame/controller/HallOfFameController.java index 17e9541e..1cdd682f 100644 --- a/src/main/java/org/sunbird/halloffame/controller/HallOfFameController.java +++ b/src/main/java/org/sunbird/halloffame/controller/HallOfFameController.java @@ -4,7 +4,6 @@ import org.springframework.http.HttpStatus; import org.springframework.http.ResponseEntity; import org.springframework.web.bind.annotation.PostMapping; -import org.springframework.web.bind.annotation.RequestHeader; import org.springframework.web.bind.annotation.RestController; import org.sunbird.halloffame.service.HallOfFameService; diff --git a/src/main/java/org/sunbird/halloffame/service/HallOfFameServiceImpl.java b/src/main/java/org/sunbird/halloffame/service/HallOfFameServiceImpl.java index 4ff0f5cd..85ce01fa 100644 --- a/src/main/java/org/sunbird/halloffame/service/HallOfFameServiceImpl.java +++ b/src/main/java/org/sunbird/halloffame/service/HallOfFameServiceImpl.java @@ -20,8 +20,6 @@ public class HallOfFameServiceImpl implements HallOfFameService { @Autowired private CassandraOperation cassandraOperation; - private Logger logger = LoggerFactory.getLogger(getClass().getName()); - @Override public Map fetchHallOfFameData() { Map resultMap = new HashMap<>(); @@ -43,15 +41,13 @@ public Map fetchHallOfFameData() { List> dptList = cassandraOperation.getRecordsByPropertiesWithoutFiltering( Constants.KEYSPACE_SUNBIRD, Constants.MDO_KARMA_POINTS, propertymap, null); - List> lastToPreviousMonthList = new ArrayList<>(); - List> lastMonthList = new ArrayList<>(); - lastToPreviousMonthList = dptList.stream() + List> lastToPreviousMonthList = dptList.stream() .filter(record -> (int) record.get(Constants.MONTH) == previousToLastMonth && (int) record.get(Constants.YEAR) == previousToLastMonthsYearValue) .collect(Collectors.toList()); - lastMonthList = dptList.stream() + List> lastMonthList = dptList.stream() .filter(record -> (int) record.get(Constants.MONTH) == lastMonthValue && (int) record.get(Constants.YEAR) == lastMonthYearValue) .collect(Collectors.toList()); @@ -121,9 +117,7 @@ public Map fetchHallOfFameData() { return trialmap; }) .collect(Collectors.toList()); - if (!resultMap.containsKey(Constants.TITLE)) { - resultMap.put(Constants.TITLE, formattedDateLastMonth); - } + resultMap.computeIfAbsent(Constants.TITLE, k -> formattedDateLastMonth); resultMap.put(Constants.MDO_LIST, trialmapList); return resultMap; } diff --git a/src/main/java/org/sunbird/health/controller/HealthController.java b/src/main/java/org/sunbird/health/controller/HealthController.java index 4115d6a5..4ce3dd17 100644 --- a/src/main/java/org/sunbird/health/controller/HealthController.java +++ b/src/main/java/org/sunbird/health/controller/HealthController.java @@ -14,7 +14,7 @@ public class HealthController { private HealthService healthService; @GetMapping("/health") - public ResponseEntity healthCheck() throws Exception { + public ResponseEntity healthCheck() throws Exception { SBApiResponse response = healthService.checkHealthStatus(); return new ResponseEntity<>(response, response.getResponseCode()); } diff --git a/src/main/java/org/sunbird/insights/controller/InsightsController.java b/src/main/java/org/sunbird/insights/controller/InsightsController.java index a88de547..440c9754 100644 --- a/src/main/java/org/sunbird/insights/controller/InsightsController.java +++ b/src/main/java/org/sunbird/insights/controller/InsightsController.java @@ -14,7 +14,7 @@ public class InsightsController { private InsightsService insightsService; @PostMapping("/user/v2/insights") - public ResponseEntity insights( + public ResponseEntity insights( @RequestBody Map requestBody,@RequestHeader("x-authenticated-userid") String userId) throws Exception { SBApiResponse response = insightsService.insights(requestBody,userId); return new ResponseEntity<>(response, response.getResponseCode()); diff --git a/src/main/java/org/sunbird/insights/controller/service/InsightsServiceImpl.java b/src/main/java/org/sunbird/insights/controller/service/InsightsServiceImpl.java index 913a7900..4fd87c3e 100644 --- a/src/main/java/org/sunbird/insights/controller/service/InsightsServiceImpl.java +++ b/src/main/java/org/sunbird/insights/controller/service/InsightsServiceImpl.java @@ -42,17 +42,17 @@ public SBApiResponse insights(Map requestBody,String userId) thr String[] fieldsArray = keys.toArray(new String[keys.size()]); ArrayList certificateOrgs= new ArrayList<>(); certificateOrgs.add("across"); - ArrayList certificate_keys = nudgeKeys(certificateOrgs); - String[] fieldsArray_certificates = certificate_keys.toArray(new String[certificate_keys.size()]); + ArrayList certificateKeys = nudgeKeys(certificateOrgs); + String[] fieldsArrayCertificates = certificateKeys.toArray(new String[certificateKeys.size()]); ArrayList nudges = new ArrayList<>(); List lhpLearningHours = redisCacheMgr.hget(INSIGHTS_LEARNING_HOURS_REDIS_KEY, serverProperties.getRedisInsightIndex(),fieldsArray); - List lhpCertifications = redisCacheMgr.hget(INSIGHTS_CERTIFICATIONS_REDIS_KEY, serverProperties.getRedisInsightIndex(),fieldsArray_certificates); + List lhpCertifications = redisCacheMgr.hget(INSIGHTS_CERTIFICATIONS_REDIS_KEY, serverProperties.getRedisInsightIndex(),fieldsArrayCertificates); if(lhpLearningHours == null) lhpLearningHours = new ArrayList<>(); if(lhpCertifications ==null) lhpCertifications = new ArrayList<>(); populateIfNudgeExist(lhpLearningHours, nudges, INSIGHTS_TYPE_LEARNING_HOURS,organizations,labelsLearningHours); - populateIfNudgeExist(lhpCertifications, nudges, INSIGHTS_TYPE_CERTIFICATE,Arrays.asList(fieldsArray_certificates),labelsCertificates); + populateIfNudgeExist(lhpCertifications, nudges, INSIGHTS_TYPE_CERTIFICATE,Arrays.asList(fieldsArrayCertificates),labelsCertificates); HashMap responseMap = new HashMap<>(); responseMap.put(WEEKLY_CLAPS, populateIfClapsExist(userId) ); responseMap.put(NUDGES, nudges); @@ -82,7 +82,7 @@ private Map populateIfClapsExist(String userId) { List> result= cassandraOperation.getRecordsByProperties(KEYSPACE_SUNBIRD, LEARNER_STATS, userRequest, fields); LocalDate[] dates = populateDate(); - if (result ==null || result.size() < 1) { + if (result ==null || result.isEmpty()) { result = new ArrayList<>(); HashMap m = new HashMap(); result.add(m); @@ -94,9 +94,8 @@ private Map populateIfClapsExist(String userId) { } - public void populateIfNudgeExist(List data, ArrayList nudges, String type, List organizations,String labels[]) { + public void populateIfNudgeExist(List data, List nudges, String type, List organizations, String[] labels) { for (int i = 0, j = 0; i < data.size(); i += 2, j++) { - // String label = data.get(i); double yesterday = StringUtils.isNotBlank(data.get(i)) ? Double.parseDouble(data.get(i)) : 0.0; double today = StringUtils.isNotBlank(data.get(i+1)) ? Double.parseDouble(data.get(i+1)) : 0.0; double change; @@ -138,7 +137,7 @@ public LocalDate[] populateDate(){ return local; } public static double roundToTwoDecimals(double value) { - BigDecimal bd = new BigDecimal(value); + BigDecimal bd = BigDecimal.valueOf(value); bd = bd.setScale(2, RoundingMode.HALF_UP); return bd.doubleValue(); } diff --git a/src/main/java/org/sunbird/karmapoints/controller/KarmaPointsController.java b/src/main/java/org/sunbird/karmapoints/controller/KarmaPointsController.java index e1336dc7..327f3310 100644 --- a/src/main/java/org/sunbird/karmapoints/controller/KarmaPointsController.java +++ b/src/main/java/org/sunbird/karmapoints/controller/KarmaPointsController.java @@ -21,20 +21,20 @@ public class KarmaPointsController { @PostMapping("/v1/karmapoints/read") public ResponseEntity> fetchKarmaPointsData(@RequestBody KarmaPointsRequest request, @RequestHeader("x-authenticated-user-orgid") String userOrgId, - @RequestHeader("x-authenticated-userid") String userId) throws Exception { + @RequestHeader("x-authenticated-userid") String userId) { Map karmaPointsDataMap = karmaPointsService.fetchKarmaPointsData(userId, request); return new ResponseEntity<>(karmaPointsDataMap, HttpStatus.OK); } @PostMapping("/v1/user/course/karmapoints/read") public ResponseEntity> readCourseKp(@RequestBody Map requestBody, - @RequestHeader("x-authenticated-userid") String userId) throws Exception { + @RequestHeader("x-authenticated-userid") String userId) { Map karmaPointsDataMap = karmaPointsService.fetchKarmaPointsUserCourse(userId, requestBody); return new ResponseEntity<>(karmaPointsDataMap, HttpStatus.OK); } @PostMapping("/v1/claimkarmapoints") - public ResponseEntity> claimACBPKarmaPoints(@RequestBody ClaimKarmaPointsRequest request) throws Exception { + public ResponseEntity> claimACBPKarmaPoints(@RequestBody ClaimKarmaPointsRequest request) { karmaPointsService.claimKarmaPoints(request); return new ResponseEntity<>(HttpStatus.OK); } diff --git a/src/main/java/org/sunbird/karmapoints/service/KarmaPointsServiceImpl.java b/src/main/java/org/sunbird/karmapoints/service/KarmaPointsServiceImpl.java index bcd17ca9..72d87cf0 100644 --- a/src/main/java/org/sunbird/karmapoints/service/KarmaPointsServiceImpl.java +++ b/src/main/java/org/sunbird/karmapoints/service/KarmaPointsServiceImpl.java @@ -75,10 +75,10 @@ public Map fetchKarmaPointsUserCourse(String userId, Map)userCourseKpList.get(key)).get(Constants.DB_COLUMN_CREDIT_DATE)).getTime(); + long creditDate = ((Date)((Map)userCourseKpList.get(key)).get(Constants.DB_COLUMN_CREDIT_DATE)).getTime(); Map whereMap = new HashMap<>(); whereMap.put(Constants.KARMA_POINTS_USER_ID, userId); - whereMap.put(Constants.DB_COLUMN_CREDIT_DATE, credit_date); + whereMap.put(Constants.DB_COLUMN_CREDIT_DATE, creditDate); whereMap.put(Constants.DB_CLOUMN_CONTEXT_TYPE, cntxType); whereMap.put(Constants.DB_COLUMN_CONTEXT_ID, cntxtId); whereMap.put(Constants.DB_COLUMN_OPERATION_TYPE, Constants.COURSE_COMPLETION); @@ -97,7 +97,7 @@ public void claimKarmaPoints(ClaimKarmaPointsRequest request) { edata.put(Constants.COURSE_ID, request.getCourseId()); karmaPointsDataMap.put("edata",edata); kafkaProducer.push(serverProperties.getClaimKarmaPointsTopic(), karmaPointsDataMap); - logger.info("UserID and CourseId successfully Published to : " + serverProperties.getClaimKarmaPointsTopic()); + logger.info("UserID and CourseId successfully Published to : {}", serverProperties.getClaimKarmaPointsTopic()); } public Map userTotalKarmaPoints(String userId){ diff --git a/src/main/java/org/sunbird/org/controller/ExtendedOrgController.java b/src/main/java/org/sunbird/org/controller/ExtendedOrgController.java index 5ecf4443..f0b95bb9 100644 --- a/src/main/java/org/sunbird/org/controller/ExtendedOrgController.java +++ b/src/main/java/org/sunbird/org/controller/ExtendedOrgController.java @@ -41,13 +41,13 @@ public ResponseEntity listOrg(@PathVariable("parentMapId") String } @PostMapping("/org/v1/ext/search") - public ResponseEntity orgExtSearch(@RequestBody Map request) throws Exception { + public ResponseEntity orgExtSearch(@RequestBody Map request) throws Exception { SBApiResponse response = orgService.orgExtSearch(request); return new ResponseEntity<>(response, response.getResponseCode()); } @PostMapping("/org/v2/ext/signup/search") - public ResponseEntity orgExtSearchV2(@RequestBody Map request) { + public ResponseEntity orgExtSearchV2(@RequestBody Map request) { SBApiResponse response = orgService.orgExtSearchV2(request); return new ResponseEntity<>(response, response.getResponseCode()); } diff --git a/src/main/java/org/sunbird/org/service/ExtendedOrgService.java b/src/main/java/org/sunbird/org/service/ExtendedOrgService.java index d315f522..f0a6b884 100644 --- a/src/main/java/org/sunbird/org/service/ExtendedOrgService.java +++ b/src/main/java/org/sunbird/org/service/ExtendedOrgService.java @@ -10,7 +10,7 @@ public interface ExtendedOrgService { public SBApiResponse createOrg(Map requestData, String userToken); - public SBApiResponse orgExtSearch(Map request) throws Exception; + public SBApiResponse orgExtSearch(Map request); public void getOrgDetailsFromDB(List orgIds, Map orgInfoMap); diff --git a/src/main/java/org/sunbird/org/service/ExtendedOrgServiceImpl.java b/src/main/java/org/sunbird/org/service/ExtendedOrgServiceImpl.java index e131a4a1..0bb8fb49 100644 --- a/src/main/java/org/sunbird/org/service/ExtendedOrgServiceImpl.java +++ b/src/main/java/org/sunbird/org/service/ExtendedOrgServiceImpl.java @@ -26,7 +26,6 @@ import org.sunbird.common.util.CbExtServerProperties; import org.sunbird.common.util.Constants; import org.sunbird.common.util.ProjectUtil; -import org.sunbird.core.logger.CbExtLogger; import org.sunbird.org.model.OrgHierarchy; import org.sunbird.org.model.OrgHierarchyInfo; import org.sunbird.org.repository.OrgHierarchyRepository; @@ -70,7 +69,7 @@ public SBApiResponse createOrg(Map request, String userToken) { // system. orgId = createOrgInSunbird(request, (String) requestData.get(Constants.CHANNEL), userToken); if (StringUtils.isBlank(orgId)) { - response.getParams().setErrmsg("Failed to create organisation in Sunbird."); + response.getParams().setErrmsg(Constants.FAILED_CREATING_ORG_IN_SUNBIRD); response.setResponseCode(HttpStatus.INTERNAL_SERVER_ERROR); return response; } @@ -94,7 +93,7 @@ public SBApiResponse createOrg(Map request, String userToken) { requestData.put(Constants.CHANNEL, channelName); orgId = createOrgInSunbird(request, (String) requestData.get(Constants.CHANNEL), userToken); if (StringUtils.isBlank(orgId)) { - response.getParams().setErrmsg("Failed to create organisation in Sunbird."); + response.getParams().setErrmsg(Constants.FAILED_CREATING_ORG_IN_SUNBIRD); response.setResponseCode(HttpStatus.INTERNAL_SERVER_ERROR); return response; } @@ -136,16 +135,16 @@ public SBApiResponse createOrg(Map request, String userToken) { } if (orgCreatedWithNewChannel) { - Map updateRequest = new HashMap(); + Map updateRequest = new HashMap<>(); String orgName = (String) requestData.get(Constants.ORG_NAME); - updateRequest.put(Constants.CHANNEL, (String) requestData.get(Constants.CHANNEL)); + updateRequest.put(Constants.CHANNEL, requestData.get(Constants.CHANNEL)); updateRequest.put(Constants.SB_ORG_ID, orgId); updateRequest.put(Constants.ORG_NAME, orgName); updateRequest.put(Constants.SB_ORG_TYPE, orgType); - updateRequest.put(Constants.L1_MAP_ID, (String) requestData.get(Constants.L1_MAP_ID)); - updateRequest.put(Constants.L2_MAP_ID, (String) requestData.get(Constants.L2_MAP_ID)); - updateRequest.put(Constants.L1_ORG_NAME, (String) requestData.get(Constants.L1_ORG_NAME)); - updateRequest.put(Constants.L2_ORG_NAME, (String) requestData.get(Constants.L2_ORG_NAME)); + updateRequest.put(Constants.L1_MAP_ID, requestData.get(Constants.L1_MAP_ID)); + updateRequest.put(Constants.L2_MAP_ID, requestData.get(Constants.L2_MAP_ID)); + updateRequest.put(Constants.L1_ORG_NAME, requestData.get(Constants.L1_ORG_NAME)); + updateRequest.put(Constants.L2_ORG_NAME, requestData.get(Constants.L2_ORG_NAME)); String mapId = (String) requestData.get(Constants.MAP_ID); if (StringUtils.isEmpty(mapId)) { @@ -180,7 +179,7 @@ public SBApiResponse createOrg(Map request, String userToken) { } if (!StringUtils.isEmpty((String) requestData.get(Constants.MAP_ID))) { ObjectMapper om = new ObjectMapper(); - logger.info("Need to update the record here... " + om.writeValueAsString(updateRequest)); + logger.info("Need to update the record here... {}", om.writeValueAsString(updateRequest)); if (ObjectUtils.isEmpty(updateRequest.get(Constants.SB_ROOT_ORG_ID))) { orgRepository.updateOrgIdForChannel(channelName, (String) updateRequest.get(Constants.SB_ORG_ID)); @@ -221,7 +220,7 @@ public SBApiResponse listOrg(String parentMapId) { orgHierarchyList = orgRepository.findAllByParentMapId(parentMapId); } if (CollectionUtils.isNotEmpty(orgHierarchyList)) { - Map responseMap = new HashMap(); + Map responseMap = new HashMap<>(); responseMap.put(Constants.CONTENT, orgHierarchyList); responseMap.put(Constants.COUNT, orgHierarchyList.size()); response.put(Constants.RESPONSE, responseMap); @@ -237,7 +236,7 @@ public SBApiResponse listOrg(String parentMapId) { } @Override - public SBApiResponse orgExtSearch(Map request) throws Exception { + public SBApiResponse orgExtSearch(Map request) { SBApiResponse response = ProjectUtil.createDefaultResponse(Constants.API_ORG_EXT_SEARCH); try { String errMsg = validateOrgSearchReq(request); @@ -271,11 +270,11 @@ public SBApiResponse orgExtSearch(Map request) throws Exception put(Constants.REQUEST, orgSearchRequest); } }; - Map headers = new HashMap(); + Map headers = new HashMap<>(); headers.put(Constants.CONTENT_TYPE, Constants.APPLICATION_JSON); String url = configProperties.getSbUrl() + configProperties.getSbOrgSearchPath(); - Map apiResponse = (Map) outboundService.fetchResultUsingPost(url, + Map apiResponse = outboundService.fetchResultUsingPost(url, orgSearchRequestBody, headers); if (Constants.OK.equalsIgnoreCase((String) apiResponse.get(Constants.RESPONSE_CODE))) { Map apiResponseResult = (Map) apiResponse.get(Constants.RESULT); @@ -285,9 +284,9 @@ public SBApiResponse orgExtSearch(Map request) throws Exception response.setResponseCode(HttpStatus.INTERNAL_SERVER_ERROR); } } else { - Map responseMap = new HashMap(); + Map responseMap = new HashMap<>(); responseMap.put(Constants.COUNT, 0); - responseMap.put(Constants.CONTENT, Collections.EMPTY_LIST); + responseMap.put(Constants.CONTENT, Collections.emptyList()); response.put(Constants.RESPONSE, responseMap); } } catch (Exception e) { @@ -299,7 +298,7 @@ public SBApiResponse orgExtSearch(Map request) throws Exception } private String validateOrgRequest(Map request) { - List params = new ArrayList(); + List params = new ArrayList<>(); StringBuilder strBuilder = new StringBuilder(); Map requestData = (Map) request.get(Constants.REQUEST); if (ObjectUtils.isEmpty(requestData)) { @@ -312,7 +311,7 @@ private String validateOrgRequest(Map request) { } String orgType = (String) requestData.get(Constants.ORGANIZATION_TYPE); - if (StringUtils.isEmpty(((String) orgType))) { + if (StringUtils.isEmpty(orgType)) { params.add(Constants.ORGANIZATION_TYPE); } else if (!Constants.STATE.equalsIgnoreCase(orgType) && !Constants.MINISTRY.equalsIgnoreCase(orgType)) { if (StringUtils.isEmpty((String) requestData.get(Constants.PARENT_MAP_ID))) { @@ -340,7 +339,7 @@ private String validateOrgRequest(Map request) { } private String validateOrgSearchReq(Map requestData) { - List params = new ArrayList(); + List params = new ArrayList<>(); StringBuilder strBuilder = new StringBuilder(); Map request = (Map) requestData.get(Constants.REQUEST); @@ -362,7 +361,7 @@ private String validateOrgSearchReq(Map requestData) { } private String checkOrgExist(String channel, String userToken) { - Map headers = new HashMap(); + Map headers = new HashMap<>(); headers.put(Constants.CONTENT_TYPE, Constants.APPLICATION_JSON); if (StringUtils.isNotEmpty(userToken)) { headers.put(Constants.X_AUTH_TOKEN, userToken); @@ -387,7 +386,7 @@ private String checkOrgExist(String channel, String userToken) { } }; String url = configProperties.getSbUrl() + configProperties.getSbOrgSearchPath(); - Map apiResponse = (Map) outboundService.fetchResultUsingPost(url, + Map apiResponse = outboundService.fetchResultUsingPost(url, searchRequestBody, headers); if (Constants.OK.equalsIgnoreCase((String) apiResponse.get(Constants.RESPONSE_CODE))) { Map result = (Map) apiResponse.get(Constants.RESULT); @@ -406,13 +405,13 @@ private String checkOrgExist(String channel, String userToken) { private String createOrgInSunbird(Map request, String channel, String userToken) { String url = configProperties.getSbUrl() + configProperties.getLmsOrgCreatePath(); - Map headers = new HashMap(); + Map headers = new HashMap<>(); headers.put(Constants.CONTENT_TYPE, Constants.APPLICATION_JSON); if (StringUtils.isNotEmpty(userToken)) { headers.put(Constants.X_AUTH_TOKEN, userToken); } - Map apiResponse = (Map) outboundService.fetchResultUsingPost(url, request, + Map apiResponse = outboundService.fetchResultUsingPost(url, request, headers); if (Constants.OK.equalsIgnoreCase((String) apiResponse.get(Constants.RESPONSE_CODE))) { Map result = (Map) apiResponse.get(Constants.RESULT); @@ -433,7 +432,7 @@ public Map getOrgDetails(List orgIds, List field request.put(Constants.REQUEST, requestBody); Map headers = new HashMap<>(); headers.put(Constants.CONTENT_TYPE, Constants.APPLICATION_JSON); - Map apiResponse = (Map) outboundService.fetchResultUsingPost( + Map apiResponse = outboundService.fetchResultUsingPost( configProperties.getSbUrl() + configProperties.getSbOrgSearchPath(), request, headers); Map orgMap = new HashMap<>(); if (Constants.OK.equalsIgnoreCase((String) apiResponse.get(Constants.RESPONSE_CODE))) { @@ -494,7 +493,7 @@ public SBApiResponse createOrgForUserRegistration(Map request) { response.getResult().put(Constants.ORGANIZATION_ID, orgId); response.getResult().put(Constants.RESPONSE, Constants.SUCCESS); } else { - response.getParams().setErrmsg("Failed to create organisation in Sunbird."); + response.getParams().setErrmsg(Constants.FAILED_CREATING_ORG_IN_SUNBIRD); response.setResponseCode(HttpStatus.INTERNAL_SERVER_ERROR); } } catch (Exception e) { @@ -509,7 +508,7 @@ public SBApiResponse createOrgForUserRegistration(Map request) { private String createMapId(Map requestData) { List existingOrgList = null; String prefix = StringUtils.EMPTY; - String mapIdNew = StringUtils.EMPTY; + String mapIdNew; String orgType = (String) requestData.get(Constants.ORGANIZATION_TYPE); if (!Constants.STATE.equalsIgnoreCase(orgType) && !Constants.MINISTRY.equalsIgnoreCase(orgType)) { String orgSubType = (String) requestData.get(Constants.ORGANIZATION_SUB_TYPE); @@ -582,7 +581,7 @@ private void fetchMapIdFromDB(Map requestData) { } private String validateOrgRequestForRegistration(Map request) { - List params = new ArrayList(); + List params = new ArrayList<>(); StringBuilder strBuilder = new StringBuilder(); Map requestData = (Map) request.get(Constants.REQUEST); if (ObjectUtils.isEmpty(requestData)) { @@ -620,7 +619,7 @@ private String validateOrgRequestForRegistration(Map request) { public SBApiResponse orgExtSearchV2(Map request) { SBApiResponse response = ProjectUtil.createDefaultResponse(Constants.API_ORG_HIERACHY_SEARCH); try { - Map searchFilters = new HashMap(); + Map searchFilters = new HashMap<>(); String errMsg = validateSearchRequest(request, searchFilters); if (StringUtils.isNotBlank(errMsg)) { response.setResponseCode(HttpStatus.BAD_REQUEST); @@ -628,7 +627,7 @@ public SBApiResponse orgExtSearchV2(Map request) { return response; } List orgInfoList = new ArrayList(); - List orgList = Collections.emptyList(); + List orgList; if (searchFilters.containsKey(Constants.IDENTIFIER)) { orgList = orgRepository.findAllBySbOrgId((List) searchFilters.get(Constants.IDENTIFIER)); } else { @@ -735,7 +734,7 @@ private String prepareChannelName(String parentMapId, Map reques return channelName; } List parentList = orgRepository.findAllByMapId(parentMapId); - if (!ObjectUtils.isEmpty(parentList) && parentList.size() > 0) { + if (!ObjectUtils.isEmpty(parentList) && !parentList.isEmpty()) { OrgHierarchy parent = parentList.get(0); if (!Constants.SPV.equalsIgnoreCase(parent.getParentMapId())) { prepareChannelName(parent.getParentMapId(), requestData); @@ -770,8 +769,8 @@ public SBApiResponse createParentOrg(OrgHierarchy parentOrg) { String orgId = checkOrgExist(parentOrg.getChannel(), StringUtils.EMPTY); if (StringUtils.isEmpty(orgId)) { - Map request = new HashMap(); - Map requestBody = new HashMap(); + Map request = new HashMap<>(); + Map requestBody = new HashMap<>(); requestBody.put(Constants.ORG_NAME, parentOrg.getOrgName()); requestBody.put(Constants.CHANNEL, parentOrg.getChannel()); @@ -784,7 +783,6 @@ public SBApiResponse createParentOrg(OrgHierarchy parentOrg) { if (!StringUtils.isEmpty(orgId)) { String sbRootOrgId = orgRepository.getSbOrgIdFromMapId(parentOrg.getParentMapId()); - ; if (StringUtils.isBlank(parentOrg.getSbRootOrgId())) { sbRootOrgId = orgRepository.getSbOrgIdFromMapId(parentOrg.getParentMapId()); } diff --git a/src/main/java/org/sunbird/portal/department/controller/PortalController.java b/src/main/java/org/sunbird/portal/department/controller/PortalController.java index abeeb219..503a7700 100644 --- a/src/main/java/org/sunbird/portal/department/controller/PortalController.java +++ b/src/main/java/org/sunbird/portal/department/controller/PortalController.java @@ -25,13 +25,13 @@ public ResponseEntity> getDeptNameList() { } @GetMapping("/portal/getAllDept") - public ResponseEntity> getAllDepartment() throws Exception { + public ResponseEntity> getAllDepartment() { return new ResponseEntity<>(portalService.getAllDept(), HttpStatus.OK); } @GetMapping("/portal/deptSearch") public ResponseEntity searchDepartment( - @RequestParam(name = "friendlyName", required = true) String deptName) throws Exception { + @RequestParam(name = "friendlyName", required = true) String deptName) { return new ResponseEntity<>(portalService.searchDept(deptName), HttpStatus.OK); } // ----------------- END of Public APIs -------------------- diff --git a/src/main/java/org/sunbird/portal/department/service/PortalService.java b/src/main/java/org/sunbird/portal/department/service/PortalService.java index 0f5e665b..c0901777 100644 --- a/src/main/java/org/sunbird/portal/department/service/PortalService.java +++ b/src/main/java/org/sunbird/portal/department/service/PortalService.java @@ -9,9 +9,9 @@ public interface PortalService { List getDeptNameList(); - List getAllDept() throws Exception; + List getAllDept() throws UnsupportedOperationException; - DeptPublicInfo searchDept(String deptName) throws Exception; + DeptPublicInfo searchDept(String deptName) throws UnsupportedOperationException; List> getDeptNameListByAdmin(); } diff --git a/src/main/java/org/sunbird/portal/department/service/PortalServiceImpl.java b/src/main/java/org/sunbird/portal/department/service/PortalServiceImpl.java index e3afc63c..ae769bec 100644 --- a/src/main/java/org/sunbird/portal/department/service/PortalServiceImpl.java +++ b/src/main/java/org/sunbird/portal/department/service/PortalServiceImpl.java @@ -10,7 +10,6 @@ import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import org.springframework.util.ObjectUtils; -import org.sunbird.cassandra.utils.CassandraOperation; import org.sunbird.common.model.SunbirdApiResp; import org.sunbird.common.model.SunbirdApiRespContent; import org.sunbird.common.model.SunbirdApiResultResponse; @@ -31,9 +30,6 @@ public class PortalServiceImpl implements PortalService { @Autowired CbExtServerProperties serverConfig; - @Autowired - CassandraOperation cassandraOperation; - @Autowired OutboundRequestHandlerServiceImpl outboundRequestHandlerService; @@ -50,21 +46,16 @@ public List getDeptNameList() { requestMap.put(Constants.LIMIT, 100); requestMap.put(Constants.FIELDS, new ArrayList<>(Arrays.asList(Constants.CHANNEL, Constants.IS_MDO, Constants.IS_CBP))); - requestMap.put(Constants.FILTERS, new HashMap() { - { - put(Constants.IS_TENANT, Boolean.TRUE); - put(Constants.STATUS, 1); - } - }); + Map deptFilterMap = new HashMap<>(); + deptFilterMap.put(Constants.IS_TENANT, Boolean.TRUE); + deptFilterMap.put(Constants.STATUS, 1); + requestMap.put(Constants.FILTERS,deptFilterMap); String serviceURL = serverConfig.getSbUrl() + serverConfig.getSbOrgSearchPath(); + Map requestBody = new HashMap<>(); + requestBody.put(Constants.REQUEST, requestMap); SunbirdApiResp orgResponse = mapper.convertValue( - outboundRequestHandlerService.fetchResultUsingPost(serviceURL, new HashMap() { - { - put(Constants.REQUEST, requestMap); - } - }), SunbirdApiResp.class); - + outboundRequestHandlerService.fetchResultUsingPost(serviceURL, requestBody), SunbirdApiResp.class); SunbirdApiResultResponse resultResp = orgResponse.getResult().getResponse(); count = resultResp.getCount(); iterateCount = iterateCount + resultResp.getContent().size(); @@ -85,7 +76,7 @@ public List getDeptNameList() { } @Override - public List getAllDept() throws Exception { + public List getAllDept() throws UnsupportedOperationException { UnsupportedOperationException ex = new UnsupportedOperationException( "/portal/getAllDept API is not implemented."); logger.error(ex); @@ -93,7 +84,7 @@ public List getAllDept() throws Exception { } @Override - public DeptPublicInfo searchDept(String deptName) throws Exception { + public DeptPublicInfo searchDept(String deptName) throws UnsupportedOperationException { UnsupportedOperationException ex = new UnsupportedOperationException( "/portal/getAllDept API is not implemented."); logger.error(ex); @@ -113,21 +104,15 @@ public List> getDeptNameListByAdmin() { requestMap.put(Constants.LIMIT, 100); requestMap.put(Constants.FIELDS, new ArrayList<>(Arrays.asList(Constants.CHANNEL, Constants.IS_MDO, Constants.IS_CBP, Constants.ID))); - requestMap.put(Constants.FILTERS, new HashMap() { - { - put(Constants.IS_TENANT, Boolean.TRUE); - put(Constants.STATUS, 1); - } - }); - + Map filtersMap = new HashMap<>(); + filtersMap.put(Constants.IS_TENANT, Boolean.TRUE); + filtersMap.put(Constants.STATUS, 1); + requestMap.put(Constants.FILTERS, filtersMap); String serviceURL = serverConfig.getSbUrl() + serverConfig.getSbOrgSearchPath(); + Map request = new HashMap<>(); + requestMap.put(Constants.REQUEST, request); SunbirdApiResp orgResponse = mapper.convertValue( - outboundRequestHandlerService.fetchResultUsingPost(serviceURL, new HashMap() { - { - put(Constants.REQUEST, requestMap); - } - }), SunbirdApiResp.class); - + outboundRequestHandlerService.fetchResultUsingPost(serviceURL, request), SunbirdApiResp.class); SunbirdApiResultResponse resultResp = orgResponse.getResult().getResponse(); count = resultResp.getCount(); iterateCount = iterateCount + resultResp.getContent().size(); @@ -135,7 +120,7 @@ public List> getDeptNameListByAdmin() { // return orgname only if cbp or mdo if ((!ObjectUtils.isEmpty(content.getIsMdo()) && content.getIsMdo()) || (!ObjectUtils.isEmpty(content.getIsCbp()) && content.getIsCbp())) { - Map orgMap = new HashMap(); + Map orgMap = new HashMap<>(); orgMap.put(Constants.CHANNEL, content.getChannel()); orgMap.put(Constants.ORG_ID, content.getId()); orgDetailsList.add(orgMap); diff --git a/src/main/java/org/sunbird/profile/controller/ProfileController.java b/src/main/java/org/sunbird/profile/controller/ProfileController.java index d419a0dc..41953dc5 100644 --- a/src/main/java/org/sunbird/profile/controller/ProfileController.java +++ b/src/main/java/org/sunbird/profile/controller/ProfileController.java @@ -7,6 +7,7 @@ import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.core.io.Resource; import org.springframework.http.ResponseEntity; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.PatchMapping; @@ -30,67 +31,67 @@ public class ProfileController { private Logger log = LoggerFactory.getLogger(getClass().getName()); @PostMapping("/user/patch") - public ResponseEntity profileUpdate( + public ResponseEntity profileUpdate( @RequestHeader(value = Constants.X_AUTH_TOKEN, required = true) String userToken, @RequestHeader(value = Constants.AUTH_TOKEN, required = false) String authToken, @RequestHeader(value = Constants.X_AUTH_USER_ORG_ID, required = false) String rootOrgId, - @RequestBody Map request) throws Exception { + @RequestBody Map request) { SBApiResponse response = profileService.profileUpdate(request, userToken, authToken, rootOrgId); return new ResponseEntity<>(response, response.getResponseCode()); } @PatchMapping("/org/v1/profile/patch") - public ResponseEntity orgProfileUpdate(@RequestBody Map request) throws Exception { + public ResponseEntity orgProfileUpdate(@RequestBody Map request) { SBApiResponse response = profileService.orgProfileUpdate(request); return new ResponseEntity<>(response, response.getResponseCode()); } @GetMapping("/org/v1/profile/read") - public ResponseEntity orgProfileRead(@RequestParam String orgId) throws Exception { + public ResponseEntity orgProfileRead(@RequestParam String orgId) { SBApiResponse response = profileService.orgProfileRead(orgId); return new ResponseEntity<>(response, response.getResponseCode()); } @GetMapping("/user/v1/basicInfo") - public ResponseEntity userBasicInfo(@RequestHeader(Constants.X_AUTH_USER_ID) String userId) { + public ResponseEntity userBasicInfo(@RequestHeader(Constants.X_AUTH_USER_ID) String userId) { SBApiResponse response = profileService.userBasicInfo(userId); return new ResponseEntity<>(response, response.getResponseCode()); } @PostMapping("/user/v1/basicProfileUpdate") - public ResponseEntity parichayProfileUpdate(@RequestBody Map request) { + public ResponseEntity parichayProfileUpdate(@RequestBody Map request) { SBApiResponse response = profileService.userBasicProfileUpdate(request); return new ResponseEntity<>(response, response.getResponseCode()); } @GetMapping("/user/v1/autocomplete/{searchTerm}") - public ResponseEntity userAutoComplete(@PathVariable("searchTerm") String searchTerm) { + public ResponseEntity userAutoComplete(@PathVariable("searchTerm") String searchTerm) { SBApiResponse response = profileService.userAutoComplete(searchTerm); return new ResponseEntity<>(response, response.getResponseCode()); } @GetMapping("/user/v1/admin/autocomplete/{searchTerm}") - public ResponseEntity userMdoAutoComplete(@PathVariable("searchTerm") String searchTerm, + public ResponseEntity userMdoAutoComplete(@PathVariable("searchTerm") String searchTerm, @RequestHeader(Constants.X_AUTH_USER_ORG_ID) String rootOrgId) { SBApiResponse response = profileService.userAdminAutoComplete(searchTerm, rootOrgId); return new ResponseEntity<>(response, response.getResponseCode()); } @PatchMapping("/user/v1/migrate") - private ResponseEntity adminMigrateUser(@RequestHeader(Constants.X_AUTH_TOKEN) String userToken, + private ResponseEntity adminMigrateUser(@RequestHeader(Constants.X_AUTH_TOKEN) String userToken, @RequestHeader(Constants.AUTH_TOKEN) String authToken, @RequestBody Map request) { SBApiResponse response = profileService.migrateUser(request, userToken, authToken); return new ResponseEntity<>(response, response.getResponseCode()); } @PostMapping("/user/v1/ext/signup") - public ResponseEntity userSignup(@RequestBody Map request) { + public ResponseEntity userSignup(@RequestBody Map request) { SBApiResponse response = profileService.userSignup(request); return new ResponseEntity<>(response, response.getResponseCode()); } @PostMapping("/user/v1/bulkupload") - public ResponseEntity bulkUpload(@RequestParam(value = "file", required = true) MultipartFile multipartFile, + public ResponseEntity bulkUpload(@RequestParam(value = "file", required = true) MultipartFile multipartFile, @RequestHeader(Constants.X_AUTH_USER_ORG_ID) String rootOrgId, @RequestHeader(Constants.X_AUTH_USER_CHANNEL) String channel, @RequestHeader(Constants.X_AUTH_USER_ID) String userId) throws UnsupportedEncodingException { @@ -101,35 +102,35 @@ public ResponseEntity bulkUpload(@RequestParam(value = "file", required = tru } @GetMapping("/user/v1/bulkupload/{orgId}") - public ResponseEntity getBulkUploadDetails(@PathVariable("orgId") String orgId) { + public ResponseEntity getBulkUploadDetails(@PathVariable("orgId") String orgId) { SBApiResponse response = profileService.getBulkUploadDetails(orgId); return new ResponseEntity<>(response, response.getResponseCode()); } @GetMapping("/user/v1/enrollement/report") - public ResponseEntity getUserEnrollmentReport() { + public ResponseEntity getUserEnrollmentReport() { SBApiResponse response = profileService.getUserEnrollmentReport(); return new ResponseEntity<>(response, response.getResponseCode()); } @GetMapping("/user/v1/report") - public ResponseEntity generateUserReport() { + public ResponseEntity generateUserReport() { SBApiResponse response = profileService.getUserReport(); return new ResponseEntity<>(response, response.getResponseCode()); } @GetMapping("/user/v1/bulkuser/download/{fileName}") - public ResponseEntity downloadFile(@PathVariable("fileName") String fileName) { + public ResponseEntity downloadFile(@PathVariable("fileName") String fileName) { return profileService.downloadFile(fileName); } @GetMapping("/user/v1/groups") - public ResponseEntity getGroupList() throws Exception { + public ResponseEntity getGroupList() throws Exception { SBApiResponse response = profileService.getGroupList(); return new ResponseEntity<>(response, response.getResponseCode()); } @PostMapping("/user/admin/patch") - public ResponseEntity profileMDOAdminUpdate( + public ResponseEntity profileMDOAdminUpdate( @RequestHeader(value = Constants.X_AUTH_TOKEN, required = false) String userToken, @RequestHeader(value = Constants.AUTH_TOKEN, required = false) String authToken, @RequestHeader(value = Constants.X_AUTH_USER_ORG_ID, required = false) String rootOrgId, @@ -139,7 +140,7 @@ public ResponseEntity profileMDOAdminUpdate( } @PostMapping("/user/v1/profile/externalsystem/update") - public ResponseEntity profileExternalSystemUpdate( + public ResponseEntity profileExternalSystemUpdate( @RequestHeader(value = Constants.X_AUTH_TOKEN, required = false) String userToken, @RequestBody Map request) { SBApiResponse response = profileService.profileExternalSystemUpdate(request, userToken); diff --git a/src/main/java/org/sunbird/profile/service/ProfileService.java b/src/main/java/org/sunbird/profile/service/ProfileService.java index ff5d5658..b102e485 100644 --- a/src/main/java/org/sunbird/profile/service/ProfileService.java +++ b/src/main/java/org/sunbird/profile/service/ProfileService.java @@ -8,11 +8,11 @@ import org.sunbird.common.model.SBApiResponse; public interface ProfileService { - SBApiResponse profileUpdate(Map request, String XAuthToken, String AuthToken, String rootOrgId) throws Exception; + SBApiResponse profileUpdate(Map request, String xAuthToken, String authToken, String rootOrgId); - SBApiResponse orgProfileUpdate(Map request) throws Exception; + SBApiResponse orgProfileUpdate(Map request); - SBApiResponse orgProfileRead(String orgId) throws Exception; + SBApiResponse orgProfileRead(String orgId); SBApiResponse userBasicInfo(String userId); diff --git a/src/main/java/org/sunbird/profile/service/ProfileServiceImpl.java b/src/main/java/org/sunbird/profile/service/ProfileServiceImpl.java index 445d2ff3..49af06ec 100644 --- a/src/main/java/org/sunbird/profile/service/ProfileServiceImpl.java +++ b/src/main/java/org/sunbird/profile/service/ProfileServiceImpl.java @@ -108,8 +108,7 @@ public class ProfileServiceImpl implements ProfileService { private Logger log = LoggerFactory.getLogger(getClass().getName()); @Override - public SBApiResponse profileUpdate(Map request, String userToken, String authToken, String rootOrgId) - throws Exception { + public SBApiResponse profileUpdate(Map request, String xAuthToken, String authToken, String rootOrgId) { SBApiResponse response = new SBApiResponse(Constants.API_PROFILE_UPDATE); try { Map requestData = (Map) request.get(Constants.REQUEST); @@ -120,7 +119,7 @@ public SBApiResponse profileUpdate(Map request, String userToken } String userId = (String) requestData.get(Constants.USER_ID); - String userIdFromToken = accessTokenValidator.fetchUserIdFromAccessToken(userToken); + String userIdFromToken = accessTokenValidator.fetchUserIdFromAccessToken(xAuthToken); if (!userId.equalsIgnoreCase(userIdFromToken)) { response.setResponseCode(HttpStatus.BAD_REQUEST); response.getParams().setStatus(Constants.FAILED); @@ -145,7 +144,7 @@ public SBApiResponse profileUpdate(Map request, String userToken HashMap headerValues = new HashMap<>(); headerValues.put(Constants.AUTH_TOKEN, authToken); headerValues.put(Constants.CONTENT_TYPE, Constants.APPLICATION_JSON); - headerValues.put(Constants.X_AUTH_TOKEN, userToken); + headerValues.put(Constants.X_AUTH_TOKEN, xAuthToken); Map workflowResponse = new HashMap<>(); Map updateResponse = new HashMap<>(); if (!profileDetailsMap.isEmpty()) { @@ -180,11 +179,6 @@ public SBApiResponse profileUpdate(Map request, String userToken } } //This field is updated via approval - /*if (validateJsonAgainstSchema(existingProfileDetails)) { - existingProfileDetails.put(Constants.VERIFIED_KARMAYOGI, true); - } else { - existingProfileDetails.put(Constants.VERIFIED_KARMAYOGI, false); - }*/ Map updateRequestValue = requestData; updateRequestValue.put(Constants.PROFILE_DETAILS, existingProfileDetails); Map updateRequest = new HashMap<>(); @@ -319,7 +313,7 @@ public SBApiResponse profileUpdate(Map request, String userToken } } } catch (Exception e) { - log.error("Failed to process profile update. Exception: ", e); + log.error(Constants.FAILED_PROFILE_UPDATE_PROCESS, e); response.getParams().setStatus(Constants.FAILED); response.getParams().setErr(e.getMessage()); response.setResponseCode(HttpStatus.INTERNAL_SERVER_ERROR); @@ -346,7 +340,7 @@ public boolean validateJsonAgainstSchema(Map existingProfileDeta } @Override - public SBApiResponse orgProfileUpdate(Map request) throws Exception { + public SBApiResponse orgProfileUpdate(Map request) { SBApiResponse response = new SBApiResponse(Constants.ORG_PROFILE_UPDATE); Map requestData = (Map) request.get(Constants.REQUEST); String errMsg = validateOrgProfilePayload(requestData); @@ -375,7 +369,7 @@ public SBApiResponse orgProfileUpdate(Map request) throws Except } if (status.equals(RestStatus.CREATED) || status.equals(RestStatus.OK)) { response.setResponseCode(HttpStatus.ACCEPTED); - Map resultMap = new HashMap(); + Map resultMap = new HashMap<>(); resultMap.put(Constants.ORG_ID, orgId); resultMap.put(Constants.PROFILE_DETAILS, esOrgProfileMap); response.getResult().put(Constants.RESULT, resultMap); @@ -448,7 +442,7 @@ public SBApiResponse migrateUser(Map request, String userToken, if (profileDetails.containsKey(Constants.EMPLOYMENT_DETAILS)) { Map empDetails = (Map) profileDetails.get(Constants.EMPLOYMENT_DETAILS); empDetails.put(Constants.DEPARTMENTNAME, orgName); - empDetails.put(Constants.DEPARTMENT_ID, (String) userData.get(Constants.ROOT_ORG_ID_LOWER)); + empDetails.put(Constants.DEPARTMENT_ID, userData.get(Constants.ROOT_ORG_ID_LOWER)); profileDetails.put(Constants.EMPLOYMENT_DETAILS, empDetails); } @@ -463,7 +457,7 @@ public SBApiResponse migrateUser(Map request, String userToken, } professionalDetail.put(Constants.NAME, orgName); - professionalDetail.put(Constants.ID, (String) userData.get(Constants.ROOT_ORG_ID_LOWER)); + professionalDetail.put(Constants.ID, userData.get(Constants.ROOT_ORG_ID_LOWER)); profileDetails.put(Constants.PROFESSIONAL_DETAILS, Arrays.asList(professionalDetail)); updateDBRequest.put(Constants.PROFILE_DETAILS_LOWER, mapper.writeValueAsString(profileDetails)); @@ -536,11 +530,11 @@ public SBApiResponse migrateUser(Map request, String userToken, } @Override - public SBApiResponse orgProfileRead(String orgId) throws Exception { + public SBApiResponse orgProfileRead(String orgId) { SBApiResponse response = createDefaultResponse(Constants.ORG_ONBOARDING_PROFILE_RETRIEVE_API); Map orgProfile = getOrgProfileForOrgId(orgId); if (!ObjectUtils.isEmpty(orgProfile)) { - Map resultMap = new HashMap(); + Map resultMap = new HashMap<>(); resultMap.put(Constants.ORG_ID, orgId); resultMap.put(Constants.PROFILE_DETAILS, orgProfile); response.getResult().put(Constants.RESULT, resultMap); @@ -574,7 +568,7 @@ public SBApiResponse userBasicInfo(String userId) { return response; } - Map responseMap = new HashMap(); + Map responseMap = new HashMap<>(); responseMap.put(Constants.IS_UPDATE_REQUIRED, false); if (custodianOrgChannel.equalsIgnoreCase((String) userData.get(Constants.CHANNEL)) @@ -701,7 +695,7 @@ public SBApiResponse userSignup(Map request) { try { Map requestBody = (Map) request.get(Constants.REQUEST); requestBody.put(Constants.EMAIL_VERIFIED, true); - Map readData = (Map) outboundRequestHandlerService.fetchResultUsingPost( + Map readData = outboundRequestHandlerService.fetchResultUsingPost( serverConfig.getSbUrl() + serverConfig.getLmsUserSignUpPath(), request, ProjectUtil.getDefaultHeaders()); if (Constants.OK.equalsIgnoreCase((String) readData.get(Constants.RESPONSE_CODE))) { @@ -744,7 +738,7 @@ public SBApiResponse bulkUpload(MultipartFile mFile, String orgId, String channe SBApiResponse uploadResponse = storageService.uploadFile(mFile, serverConfig.getBulkUploadContainerName()); if (!HttpStatus.OK.equals(uploadResponse.getResponseCode())) { setErrorData(response, String.format("Failed to upload file. Error: %s", - (String) uploadResponse.getParams().getErrmsg())); + uploadResponse.getParams().getErrmsg())); return response; } @@ -774,7 +768,7 @@ public SBApiResponse bulkUpload(MultipartFile mFile, String orgId, String channe sendBulkUploadNotification(orgId, channel, (String) uploadResponse.getResult().get(Constants.URL)); } catch (Exception e) { setErrorData(response, - String.format("Failed to process user bulk upload request. Error: ", e.getMessage())); + String.format("Failed to process user bulk upload request. Error: %s", e.getMessage())); } return response; } @@ -795,7 +789,7 @@ public SBApiResponse getBulkUploadDetails(String orgId) { response.getResult().put(Constants.COUNT, bulkUploadList != null ? bulkUploadList.size() : 0); } catch (Exception e) { setErrorData(response, - String.format("Failed to get user bulk upload request status. Error: ", e.getMessage())); + String.format("Failed to get user bulk upload request status. Error: %s", e.getMessage())); } return response; } @@ -804,7 +798,7 @@ public List approvalFields() { List approvalFields = (List) dataCacheMgr .getObjectFromCache(Constants.PROFILE_APPROVAL_FIELDS_KEY); if (CollectionUtils.isEmpty(approvalFields)) { - Map searchRequest = new HashMap(); + Map searchRequest = new HashMap<>(); searchRequest.put(Constants.ID, Constants.PROFILE_APPROVAL_FIELDS_KEY); List> existingDataList = cassandraOperation.getRecordsByPropertiesWithoutFiltering( @@ -814,7 +808,7 @@ public List approvalFields() { String strApprovalFields = (String) data.get(Constants.VALUE); if (StringUtils.isNotBlank(strApprovalFields)) { - String strArray[] = strApprovalFields.split(",", -1); + String[] strArray = strApprovalFields.split(",", -1); approvalFields = Arrays.asList(strArray); dataCacheMgr.putObjectInCache(Constants.PROFILE_APPROVAL_FIELDS_KEY, approvalFields); return approvalFields; @@ -829,7 +823,7 @@ public List approvalFields() { public String getVerifiedProfileSchema() { String strSchema = dataCacheMgr.getStringFromCache(Constants.VERIFIED_PROFILE_FIELDS_KEY); if (StringUtils.isEmpty(strSchema)) { - Map searchRequest = new HashMap(); + Map searchRequest = new HashMap<>(); searchRequest.put(Constants.ID, Constants.VERIFIED_PROFILE_FIELDS_KEY); List> existingDataList = cassandraOperation.getRecordsByPropertiesWithoutFiltering( @@ -870,7 +864,7 @@ private void getModifiedPersonalDetails(Object personalDetailsObj, Map getOrgProfileForOrgId(String registrationCode) { try { - Map esObject = indexerService.readEntity(serverConfig.getOrgOnboardingIndex(), + return indexerService.readEntity(serverConfig.getOrgOnboardingIndex(), serverConfig.getEsProfileIndexType(), registrationCode); - return esObject; } catch (Exception e) { log.error("Failed to get Org Profile. Exception: ", e); log.warn(String.format("Exception in %s : %s", "getUserRegistrationDetails", e.getMessage())); } - return null; + return Collections.emptyMap(); } private String validateOrgProfilePayload(Map orgProfileInfo) { StringBuffer str = new StringBuffer(); - List errList = new ArrayList(); + List errList = new ArrayList<>(); if (StringUtils.isBlank((String) orgProfileInfo.get(Constants.ORG_ID))) { errList.add(Constants.ORG_ID); } @@ -922,7 +915,7 @@ private SBApiResponse createDefaultResponse(String api) { public String getCustodianOrgId() { String custodianOrgId = dataCacheMgr.getStringFromCache(Constants.CUSTODIAN_ORG_ID); if (StringUtils.isEmpty(custodianOrgId)) { - Map searchRequest = new HashMap(); + Map searchRequest = new HashMap<>(); searchRequest.put(Constants.ID, Constants.CUSTODIAN_ORG_ID); List> existingDataList = cassandraOperation.getRecordsByPropertiesWithoutFiltering( @@ -939,7 +932,7 @@ public String getCustodianOrgId() { public String getCustodianOrgChannel() { String custodianOrgChannel = dataCacheMgr.getStringFromCache(Constants.CUSTODIAN_ORG_CHANNEL); if (StringUtils.isEmpty(custodianOrgChannel)) { - Map searchRequest = new HashMap(); + Map searchRequest = new HashMap<>(); searchRequest.put(Constants.ID, Constants.CUSTODIAN_ORG_CHANNEL); List> existingDataList = cassandraOperation.getRecordsByPropertiesWithoutFiltering( @@ -955,7 +948,7 @@ public String getCustodianOrgChannel() { private String validateBasicProfilePayload(Map requestObj) { StringBuffer str = new StringBuffer(); - List errList = new ArrayList(); + List errList = new ArrayList<>(); if (ObjectUtils.isEmpty(requestObj.get(Constants.REQUEST))) { errList.add(Constants.REQUEST); @@ -977,7 +970,7 @@ private String validateBasicProfilePayload(Map requestObj) { } private Map getOrgCreateRequest(Map request) { - Map requestBody = new HashMap(); + Map requestBody = new HashMap<>(); requestBody.put(Constants.ORG_NAME, request.get(Constants.ORG_NAME)); requestBody.put(Constants.CHANNEL, request.get(Constants.CHANNEL)); requestBody.put(Constants.SB_ROOT_ORG_ID, request.get(Constants.SB_ROOT_ORG_ID)); @@ -985,28 +978,22 @@ private Map getOrgCreateRequest(Map request) { requestBody.put(Constants.ORGANIZATION_SUB_TYPE, request.get(Constants.ORGANIZATION_SUB_TYPE)); requestBody.put(Constants.MAP_ID, request.get(Constants.MAP_ID)); requestBody.put(Constants.IS_TENANT, true); - Map newRequest = new HashMap(); + Map newRequest = new HashMap<>(); newRequest.put(Constants.REQUEST, requestBody); return newRequest; } private Map getUserMigrateRequest(String userId, String channel, boolean isSelfMigrate) { - Map requestBody = new HashMap() { - { - put(Constants.USER_ID, userId); - put(Constants.CHANNEL, channel); - put(Constants.SOFT_DELETE_OLD_ORG, true); - put(Constants.NOTIFY_MIGRATION, false); - if (!isSelfMigrate) { - put(Constants.FORCE_MIGRATION, true); - } - } - }; - Map request = new HashMap() { - { - put(Constants.REQUEST, requestBody); - } - }; + Map requestBody = new HashMap<>(); + requestBody.put(Constants.USER_ID, userId); + requestBody.put(Constants.CHANNEL, channel); + requestBody.put(Constants.SOFT_DELETE_OLD_ORG, true); + requestBody.put(Constants.NOTIFY_MIGRATION, false); + if (!isSelfMigrate) { + requestBody.put(Constants.FORCE_MIGRATION, true); + } + Map request = new HashMap<>(); + request.put(Constants.REQUEST, requestBody); return request; } @@ -1023,7 +1010,8 @@ private String createOrgIfRequired(Map requestBody) { // We got the orgId successfully... let's migrate the user to this org. try { Thread.sleep(1000); - } catch (Exception e) { + } catch (InterruptedException e) { + Thread.currentThread().interrupt(); } errMsg = executeSelfMigrateUser(requestBody); } else { @@ -1041,14 +1029,14 @@ private String createOrgIfRequired(Map requestBody) { private String executeSelfMigrateUser(Map requestBody) { String errMsg = StringUtils.EMPTY; - Map migrateResponse = (Map) outboundRequestHandlerService.fetchResultUsingPatch( + Map migrateResponse = outboundRequestHandlerService.fetchResultUsingPatch( serverConfig.getSbUrl() + serverConfig.getLmsUserMigratePath(), getUserMigrateRequest((String) requestBody.get(Constants.USER_ID), (String) requestBody.get(Constants.CHANNEL), true), MapUtils.EMPTY_MAP); if (Constants.OK.equalsIgnoreCase((String) migrateResponse.get(Constants.RESPONSE_CODE))) { - log.info(String.format("Successfully self migrated user. UserId: %s, Channel: %s", - (String) requestBody.get(Constants.USER_ID), (String) requestBody.get(Constants.CHANNEL))); + log.info("Successfully self migrated user. UserId: {}, Channel: {}", + requestBody.get(Constants.USER_ID), requestBody.get(Constants.CHANNEL)); errMsg = updateUserProfile(requestBody); } else { try { @@ -1070,7 +1058,7 @@ private String updateUserProfile(Map request) { if (userReadResponse.containsKey(Constants.ROLES)) { existingRoles = (List) userReadResponse.get(Constants.ROLES); } else { - existingRoles = new ArrayList(); + existingRoles = new ArrayList<>(); } Map existingProfile = (Map) userReadResponse.get(Constants.PROFILE_DETAILS); @@ -1083,28 +1071,24 @@ private String updateUserProfile(Map request) { if (existingProfile.containsKey(Constants.PROFESSIONAL_DETAILS)) { professionalDetails = (List>) existingProfile.get(Constants.PROFESSIONAL_DETAILS); } else { - professionalDetails = new ArrayList>() { - { - Map profDetail = new HashMap(); + professionalDetails = new ArrayList<>(); + Map profDetail = new HashMap<>(); profDetail.put(Constants.OSID, UUID.randomUUID().toString()); - add(profDetail); - } - }; - existingProfile.put(Constants.PROFESSIONAL_DETAILS, professionalDetails); + professionalDetails.add(profDetail); + existingProfile.put(Constants.PROFESSIONAL_DETAILS, professionalDetails); } professionalDetails.get(0).put(Constants.GROUP, request.get(Constants.GROUP)); professionalDetails.get(0).put(Constants.ORGANIZATION_TYPE, Constants.GOVERNMENT); - Map empDetails; if (existingProfile.containsKey(Constants.EMPLOYMENTDETAILS)) { empDetails = (Map) existingProfile.get(Constants.EMPLOYMENTDETAILS); } else { - empDetails = new HashMap(); + empDetails = new HashMap<>(); existingProfile.put(Constants.EMPLOYMENTDETAILS, empDetails); } empDetails.put(Constants.DEPARTMENTNAME, request.get(Constants.CHANNEL)); - Map updateReqBody = new HashMap(); + Map updateReqBody = new HashMap<>(); Map existingPersonalDetail = (Map) existingProfile .get(Constants.PERSONAL_DETAILS); @@ -1133,19 +1117,19 @@ private String updateUserProfile(Map request) { private String assignUserRole(Map requestBody, List existingRoles) { String errMsg = StringUtils.EMPTY; Map assignRoleReq = new HashMap<>(); - Map assignRoleReqBody = new HashMap(); + Map assignRoleReqBody = new HashMap<>(); assignRoleReqBody.put(Constants.ORGANIZATION_ID, requestBody.get(Constants.SB_ORG_ID)); assignRoleReqBody.put(Constants.USER_ID, requestBody.get(Constants.USER_ID)); if (existingRoles == null) { - existingRoles = new ArrayList(); + existingRoles = new ArrayList<>(); } - if (existingRoles.size() == 0) { + if (existingRoles.isEmpty()) { existingRoles.add(Constants.PUBLIC); } assignRoleReqBody.put(Constants.ROLES, existingRoles); assignRoleReq.put(Constants.REQUEST, assignRoleReqBody); - Map assignRoleResponse = (Map) outboundRequestHandlerService + Map assignRoleResponse = outboundRequestHandlerService .fetchResultUsingPost(serverConfig.getSbUrl() + serverConfig.getSbAssignRolePath(), assignRoleReq, MapUtils.EMPTY_MAP); if (!Constants.OK.equalsIgnoreCase((String) assignRoleResponse.get(Constants.RESPONSE_CODE))) { @@ -1157,7 +1141,7 @@ private String assignUserRole(Map requestBody, List exis private String validateMigrateRequest(Map requestBody) { StringBuffer str = new StringBuffer(); - List errObjList = new ArrayList(); + List errObjList = new ArrayList<>(); Map request = (Map) requestBody.get(Constants.REQUEST); if (ObjectUtils.isEmpty(request)) { @@ -1185,7 +1169,7 @@ private void setErrorData(SBApiResponse response, String errMsg) { private String executeMigrateUser(Map request, Map headers) { String errMsg = StringUtils.EMPTY; - Map migrateResponse = (Map) outboundRequestHandlerService.fetchResultUsingPatch( + Map migrateResponse = outboundRequestHandlerService.fetchResultUsingPatch( serverConfig.getSbUrl() + serverConfig.getLmsUserMigratePath(), request, headers); if (migrateResponse == null || !Constants.OK.equalsIgnoreCase((String) migrateResponse.get(Constants.RESPONSE_CODE))) { @@ -1210,14 +1194,14 @@ private Map getUserDetailsForId(String userId) { private String syncUserData(String userId) { String errMsg = null; - Map requestBody = new HashMap(); - Map request = new HashMap(); + Map requestBody = new HashMap<>(); + Map request = new HashMap<>(); request.put(Constants.OPERATION_TYPE, Constants.SYNC); request.put(Constants.OBJECT_IDS, Arrays.asList(userId)); request.put(Constants.OBJECT_TYPE, Constants.USER); requestBody.put(Constants.REQUEST, request); - Map syncDataResp = (Map) outboundRequestHandlerService.fetchResultUsingPost( + Map syncDataResp = outboundRequestHandlerService.fetchResultUsingPost( serverConfig.getSbUrl() + serverConfig.getLmsDataSyncPath(), requestBody, MapUtils.EMPTY_MAP); if (syncDataResp == null || !Constants.OK.equalsIgnoreCase((String) syncDataResp.get(Constants.RESPONSE_CODE))) { @@ -1274,14 +1258,14 @@ public List> getAdminUserSearchData(String searchTerm, Strin private boolean updateUser(Map requestObject) { boolean retValue = false; Map updateRequest = new HashMap<>(); - Map updateRequestBody = new HashMap(); + Map updateRequestBody = new HashMap<>(); updateRequestBody.put(Constants.USER_ID, requestObject.get(Constants.USER_ID)); - Map profileDetails = new HashMap(); + Map profileDetails = new HashMap<>(); profileDetails.put(Constants.MANDATORY_FIELDS_EXISTS, false); - Map employementDetails = new HashMap(); + Map employementDetails = new HashMap<>(); employementDetails.put(Constants.DEPARTMENTNAME, requestObject.get(Constants.ORG_NAME)); profileDetails.put(Constants.EMPLOYMENTDETAILS, employementDetails); - Map personalDetails = new HashMap(); + Map personalDetails = new HashMap<>(); Map requestBody = (Map) requestObject.get(Constants.REQUEST); personalDetails.put(Constants.FIRSTNAME.toLowerCase(), requestBody.get(Constants.FIRSTNAME)); personalDetails.put(Constants.PRIMARY_EMAIL, requestBody.get(Constants.EMAIL)); @@ -1298,7 +1282,7 @@ private boolean updateUser(Map requestObject) { } profileDetails.put(Constants.PERSONAL_DETAILS, personalDetails); - Map professionDetailObj = new HashMap(); + Map professionDetailObj = new HashMap<>(); professionDetailObj.put(Constants.ORGANIZATION_TYPE, Constants.GOVERNMENT); if (StringUtils.isNotEmpty((String) requestObject.get(Constants.POSITION))) { professionDetailObj.put(Constants.DESIGNATION, requestObject.get(Constants.POSITION)); @@ -1309,7 +1293,7 @@ private boolean updateUser(Map requestObject) { updateRequestBody.put(Constants.PROFILE_DETAILS, profileDetails); updateRequest.put(Constants.REQUEST, updateRequestBody); - Map updateReadData = (Map) outboundRequestHandlerService.fetchResultUsingPatch( + Map updateReadData = outboundRequestHandlerService.fetchResultUsingPatch( serverConfig.getSbUrl() + serverConfig.getLmsUserUpdatePrivatePath(), updateRequest, ProjectUtil.getDefaultHeaders()); if (Constants.OK.equalsIgnoreCase((String) updateReadData.get(Constants.RESPONSE_CODE))) { @@ -1324,15 +1308,15 @@ private boolean updateUser(Map requestObject) { private boolean assignRole(Map request) { boolean retValue = false; Map requestObj = new HashMap<>(); - Map requestBody = new HashMap(); + Map requestBody = new HashMap<>(); requestBody.put(Constants.ORGANIZATION_ID, request.get(Constants.ORGANIZATION_ID)); requestBody.put(Constants.USER_ID, request.get(Constants.USER_ID)); requestBody.put(Constants.ROLES, Arrays.asList(Constants.PUBLIC)); requestObj.put(Constants.REQUEST, requestBody); - Map readData = (Map) outboundRequestHandlerService.fetchResultUsingPost( + Map readData = outboundRequestHandlerService.fetchResultUsingPost( serverConfig.getSbUrl() + serverConfig.getSbAssignRolePath(), requestObj, ProjectUtil.getDefaultHeaders()); - if (readData.isEmpty() == Boolean.FALSE) { + if (!readData.isEmpty()) { if (Constants.OK.equalsIgnoreCase((String) readData.get(Constants.RESPONSE_CODE))) retValue = Boolean.TRUE; } @@ -1340,7 +1324,7 @@ private boolean assignRole(Map request) { } private String validateSignupRequest(Map requestData) { - List params = new ArrayList(); + List params = new ArrayList<>(); StringBuilder strBuilder = new StringBuilder(); Map request = (Map) requestData.get(Constants.REQUEST); if (ObjectUtils.isEmpty(request)) { @@ -1368,7 +1352,7 @@ private void sendBulkUploadNotification(String orgId, String orgName, String fil } } Map request = new HashMap<>(); - Map requestBody = new HashMap(); + Map requestBody = new HashMap<>(); requestBody.put(Constants.BODY, Constants.HELLO); requestBody.put(Constants.EMAIL_TEMPLATE_TYPE, serverConfig.getBulkUploadEmailTemplate()); requestBody.put(Constants.LINK, fileUrl); @@ -1394,9 +1378,9 @@ public SBApiResponse getUserEnrollmentReport() { propertyMap.put(Constants.ACTIVE, Boolean.TRUE); // Use the following map to construct the excel report - Map> userInfoMap = new HashMap>(); - Map> courseInfoMap = new HashMap>(); - Map orgInfoMap = new HashMap(); + Map> userInfoMap = new HashMap<>(); + Map> courseInfoMap = new HashMap<>(); + Map orgInfoMap = new HashMap<>(); try { List> userEnrolmentList = cassandraOperation.getRecordsByProperties( @@ -1429,7 +1413,7 @@ public SBApiResponse getUserEnrollmentReport() { Map> userEnrolmentMap = new HashMap>(); // Construct the userEnrolment Map; for (Map enrolment : userEnrolmentList) { - Map enrolmentReport = new HashMap(); + Map enrolmentReport = new HashMap<>(); // Get user details String userId = (String) enrolment.get(Constants.USER_ID); String courseId = (String) enrolment.get(Constants.COURSE_ID); @@ -1501,7 +1485,7 @@ public SBApiResponse getUserEnrollmentReport() { } } - List reportFields = new ArrayList(); + List reportFields = new ArrayList<>(); reportFields.addAll(Constants.USER_ENROLMENT_REPORT_FIELDS); reportFields.addAll(Constants.COURSE_ENROLMENT_REPORT_FIELDS); reportFields.addAll(Constants.USER_ENROLMENT_COMMON_FIELDS); @@ -1520,7 +1504,7 @@ public SBApiResponse getUserReport() { long startTime = System.currentTimeMillis(); SBApiResponse response = ProjectUtil.createDefaultResponse(Constants.API_USER_REPORT); try { - List fields = new ArrayList(); + List fields = new ArrayList<>(); fields.addAll(Constants.USER_ENROLMENT_REPORT_FIELDS); fields.add(Constants.ROLES); int index = 0; @@ -1556,7 +1540,7 @@ public SBApiResponse getUserReport() { resultArray.clear(); userInfoMap.clear(); - index = (int) Math.min(userCount, index + size); + index = (int) Math.min(userCount, (long) index + size); if (index == userCount) { isCompleted = true; @@ -1579,7 +1563,7 @@ public SBApiResponse getUserReport() { private void processUserDetails(List> userMapList, Map> userInfoMap) { for (Map user : userMapList) { - Map userInfo = new HashMap(); + Map userInfo = new HashMap<>(); userInfo.put(Constants.USER_ID, (String) user.get(Constants.USER_ID)); userInfo.put(Constants.FIRSTNAME, (String) user.get(Constants.FIRSTNAME)); userInfo.put(Constants.ROOT_ORG_ID, (String) user.get(Constants.ROOT_ORG_ID)); @@ -1617,9 +1601,7 @@ private void enrichUserDetails(List userIdList, Map> item = it.next(); String orgId = item.getValue().get(Constants.ROOT_ORG_ID); - if (!orgInfoMap.containsKey(orgId)) { - orgInfoMap.put(orgId, item.getValue().get(Constants.CHANNEL)); - } + orgInfoMap.computeIfAbsent(orgId, k -> item.getValue().get(Constants.CHANNEL)); } log.info(String.format("Org enrichment took %s seconds", (System.currentTimeMillis() - startTime) / 1000)); } @@ -1633,7 +1615,7 @@ private void enrichCourseDetails(List courseIdList, Map>> it = courseInfoMap.entrySet().iterator(); - List orgIdList = new ArrayList(); + List orgIdList = new ArrayList<>(); while (it.hasNext()) { Entry> item = it.next(); String orgId = item.getValue().get(Constants.COURSE_ORG_ID); @@ -1644,7 +1626,7 @@ private void enrichCourseDetails(List courseIdList, Map 0) { + if (!orgIdList.isEmpty()) { extOrgService.getOrgDetailsFromDB(orgIdList, orgInfoMap); it = courseInfoMap.entrySet().iterator(); while (it.hasNext()) { @@ -1721,7 +1703,7 @@ public SBApiResponse getGroupList() { } @Override - public SBApiResponse profileMDOAdminUpdate(Map request, String userToken, String authToken, String rootOrgId) throws Exception { + public SBApiResponse profileMDOAdminUpdate(Map request, String userToken, String authToken, String rootOrgId) { SBApiResponse response = new SBApiResponse(Constants.API_PROFILE_UPDATE); try { Map requestData = (Map) request.get(Constants.REQUEST); @@ -1809,7 +1791,7 @@ public SBApiResponse profileMDOAdminUpdate(Map request, String u } } } catch (Exception e) { - log.error("Failed to process profile update. Exception: ", e); + log.error(Constants.FAILED_PROFILE_UPDATE_PROCESS, e); response.getParams().setStatus(Constants.FAILED); response.getParams().setErr(e.getMessage()); response.setResponseCode(HttpStatus.INTERNAL_SERVER_ERROR); @@ -1843,7 +1825,7 @@ public SBApiResponse profileExternalSystemUpdate(Map request, St userUtilityService.getUserDetailsFromDB(Arrays.asList(userId), Arrays.asList(Constants.PROFILE_DETAILS_LOWER, Constants.USER_ID), userInfoMap); if (!(ObjectUtils.isEmpty(userInfoMap))) { Map userInfo = userInfoMap.get(userId); - String profileDetails = (String) userInfo.get(Constants.PROFILE_DETAILS_LOWER); + String profileDetails = userInfo.get(Constants.PROFILE_DETAILS_LOWER); Map profileDetailsMap = new HashMap<>(); if (StringUtils.isNotEmpty(profileDetails)) { profileDetailsMap = mapper.readValue(profileDetails, new TypeReference>() { @@ -1885,7 +1867,7 @@ public SBApiResponse profileExternalSystemUpdate(Map request, St } } } catch (Exception e) { - log.error("Failed to process profile update. Exception: ", e); + log.error(Constants.FAILED_PROFILE_UPDATE_PROCESS, e); response.getParams().setStatus(Constants.FAILED); response.getParams().setErr(e.getMessage()); response.setResponseCode(HttpStatus.INTERNAL_SERVER_ERROR); @@ -1906,7 +1888,7 @@ public List adminApprovalFields() { List adminApprovalFields = (List) dataCacheMgr .getObjectFromCache(serverConfig.getMdoAdminUpdateUsers()); if (CollectionUtils.isEmpty(adminApprovalFields)) { - Map searchRequest = new HashMap(); + Map searchRequest = new HashMap<>(); searchRequest.put(Constants.ID, serverConfig.getMdoAdminUpdateUsers()); List> existingDataList = cassandraOperation.getRecordsByPropertiesWithoutFiltering( @@ -1916,7 +1898,7 @@ public List adminApprovalFields() { String strAdminApprovalFields = (String) data.get(Constants.VALUE); if (StringUtils.isNotBlank(strAdminApprovalFields)) { - String strArray[] = strAdminApprovalFields.split(",", -1); + String[] strArray = strAdminApprovalFields.split(",", -1); adminApprovalFields = Arrays.asList(strArray); dataCacheMgr.putObjectInCache(serverConfig.getMdoAdminUpdateUsers(), adminApprovalFields); return adminApprovalFields; diff --git a/src/main/java/org/sunbird/profile/service/UserBulkUploadConsumer.java b/src/main/java/org/sunbird/profile/service/UserBulkUploadConsumer.java index 5fdc53b1..781aa6ec 100644 --- a/src/main/java/org/sunbird/profile/service/UserBulkUploadConsumer.java +++ b/src/main/java/org/sunbird/profile/service/UserBulkUploadConsumer.java @@ -21,7 +21,7 @@ public class UserBulkUploadConsumer { public void processUserBulkUploadMessage(ConsumerRecord data) { logger.info( "UserBulkUploadConsumer::processMessage: Received event to initiate User Bulk Upload Process..."); - logger.info("Received message:: " + data.value()); + logger.info("Received message:: {}" , data.value()); try { if (StringUtils.isNoneBlank(data.value())) { CompletableFuture.runAsync(() -> { diff --git a/src/main/java/org/sunbird/profile/service/UserBulkUploadService.java b/src/main/java/org/sunbird/profile/service/UserBulkUploadService.java index 722c6590..c3d48e8c 100644 --- a/src/main/java/org/sunbird/profile/service/UserBulkUploadService.java +++ b/src/main/java/org/sunbird/profile/service/UserBulkUploadService.java @@ -67,8 +67,7 @@ public void initiateUserBulkUploadProcess(String inputData) { e); } duration = System.currentTimeMillis() - startTime; - logger.info("UserBulkUploadService:: initiateUserBulkUploadProcess: Completed. Time taken: " - + duration + " milli-seconds"); + logger.info("UserBulkUploadService:: initiateUserBulkUploadProcess: Completed. Time taken: {} milli-seconds", duration ); } public void updateUserBulkUploadStatus(String rootOrgId, String identifier, String status, int totalRecordsCount, @@ -130,7 +129,7 @@ private void processBulkUpload(HashMap inputDataMap) throws IOEx } int count = 0; while (rowIterator.hasNext()) { - logger.info("UserBulkUploadService:: Record " + count++); + logger.info("UserBulkUploadService:: Record {}" , count++); long duration = 0; long startTime = System.currentTimeMillis(); StringBuffer str = new StringBuffer(); @@ -143,11 +142,11 @@ private void processBulkUpload(HashMap inputDataMap) throws IOEx } else { if (nextRow.getCell(0).getCellType() == CellType.STRING) { userRegistration.setFirstName(nextRow.getCell(0).getStringCellValue().trim()); - if (!ProjectUtil.validateFullName(userRegistration.getFirstName())) { + if (Boolean.FALSE.equals(ProjectUtil.validateFullName(userRegistration.getFirstName()))) { invalidErrList.add("Invalid Full Name"); } } else { - invalidErrList.add("Invalid column type. Expecting string format"); + invalidErrList.add(Constants.INVALID_COL_TYPE_EXPECTING_STRING); } } if (nextRow.getCell(1) == null || nextRow.getCell(1).getCellType() == CellType.BLANK) { @@ -156,7 +155,7 @@ private void processBulkUpload(HashMap inputDataMap) throws IOEx if (nextRow.getCell(1).getCellType() == CellType.STRING) { userRegistration.setEmail(nextRow.getCell(1).getStringCellValue().trim()); } else { - invalidErrList.add("Invalid column type. Expecting string format"); + invalidErrList.add(Constants.INVALID_COL_TYPE_EXPECTING_STRING); } } if (nextRow.getCell(2) == null || nextRow.getCell(2).getCellType() == CellType.BLANK) { @@ -180,13 +179,13 @@ private void processBulkUpload(HashMap inputDataMap) throws IOEx invalidErrList.add("Invalid Group : Group can be only among one of these " + serverProperties.getBulkUploadGroupValue()); } } else { - invalidErrList.add("Invalid column type. Expecting string format"); + invalidErrList.add(Constants.INVALID_COL_TYPE_EXPECTING_STRING); } } if (nextRow.getCell(4) != null && nextRow.getCell(4).getCellType() != CellType.BLANK) { if (nextRow.getCell(4).getCellType() == CellType.STRING) { String tagStr = nextRow.getCell(4).getStringCellValue().trim(); - List tagList = new ArrayList(); + List tagList = new ArrayList<>(); if (!StringUtils.isEmpty(tagStr)) { String[] tagStrList = tagStr.split(",", -1); for(String tag : tagStrList) { @@ -194,22 +193,22 @@ private void processBulkUpload(HashMap inputDataMap) throws IOEx } } userRegistration.setTag(tagList); - if (!ProjectUtil.validateTag(userRegistration.getTag())) { + if (Boolean.FALSE.equals(ProjectUtil.validateTag(userRegistration.getTag()))) { invalidErrList.add("Invalid Tag : Tags are comma seperated string values. A Tag can contain only alphabets with spaces. eg: Bihar Circle, Patna Division"); } } else { - invalidErrList.add("Invalid column type. Expecting string format"); + invalidErrList.add(Constants.INVALID_COL_TYPE_EXPECTING_STRING); } } if (nextRow.getCell(5) != null && nextRow.getCell(5).getCellType() != CellType.BLANK) { if (nextRow.getCell(5).getCellType() == CellType.NUMERIC) { userRegistration.setExternalSystemId(NumberToTextConverter.toText(nextRow.getCell(5).getNumericCellValue()).trim()); - if (!ProjectUtil.validateExternalSystemId(userRegistration.getExternalSystemId())) { + if (Boolean.FALSE.equals(ProjectUtil.validateExternalSystemId(userRegistration.getExternalSystemId()))) { invalidErrList.add("Invalid External System ID : External System Id can contain alphanumeric characters and have a max length of 30"); } } else if (nextRow.getCell(5).getCellType() == CellType.STRING) { userRegistration.setExternalSystemId(nextRow.getCell(5).getStringCellValue().trim()); - if (!ProjectUtil.validateExternalSystemId(userRegistration.getExternalSystemId())) { + if (Boolean.FALSE.equals(ProjectUtil.validateExternalSystemId(userRegistration.getExternalSystemId()))) { invalidErrList.add("Invalid External System ID : External System Id can contain alphanumeric characters and have a max length of 30"); } } else { @@ -219,11 +218,11 @@ private void processBulkUpload(HashMap inputDataMap) throws IOEx if (nextRow.getCell(6) != null && !StringUtils.isBlank(nextRow.getCell(6).toString())) { if (nextRow.getCell(6).getCellType() == CellType.STRING) { userRegistration.setExternalSystem(nextRow.getCell(6).getStringCellValue().trim()); - if (!ProjectUtil.validateExternalSystem(userRegistration.getExternalSystem())) { + if (Boolean.FALSE.equals(ProjectUtil.validateExternalSystem(userRegistration.getExternalSystem()))) { invalidErrList.add("Invalid External System : External System can contain only alphabets and can have a max length of 255"); } } else { - invalidErrList.add("Invalid column type. Expecting string format"); + invalidErrList.add(Constants.INVALID_COL_TYPE_EXPECTING_STRING); } } userRegistration.setOrgName(inputDataMap.get(Constants.ORG_NAME)); @@ -268,8 +267,7 @@ private void processBulkUpload(HashMap inputDataMap) throws IOEx } } duration = System.currentTimeMillis() - startTime; - logger.info("UserBulkUploadService:: Record Completed. Time taken: " - + duration + " milli-seconds"); + logger.info("UserBulkUploadService:: Record Completed. Time taken: {} milli-seconds", duration); } if (totalRecordsCount == 0) { XSSFRow row = sheet.createRow(sheet.getLastRowNum() + 1); @@ -327,10 +325,10 @@ private String uploadTheUpdatedFile(File file, XSSFWorkbook wb) private List validateEmailContactAndDomain(UserRegistration userRegistration) { StringBuffer str = new StringBuffer(); List errList = new ArrayList<>(); - if (!ProjectUtil.validateEmailPattern(userRegistration.getEmail())) { + if (Boolean.FALSE.equals(ProjectUtil.validateEmailPattern(userRegistration.getEmail()))) { errList.add("Invalid Email Id"); } - if (!ProjectUtil.validateContactPattern(userRegistration.getPhone())) { + if (Boolean.FALSE.equals(ProjectUtil.validateContactPattern(userRegistration.getPhone()))) { errList.add("Invalid Mobile Number"); } if (!errList.isEmpty()) { diff --git a/src/main/java/org/sunbird/progress/controller/ContentProgressController.java b/src/main/java/org/sunbird/progress/controller/ContentProgressController.java index 540e4489..028e55b5 100644 --- a/src/main/java/org/sunbird/progress/controller/ContentProgressController.java +++ b/src/main/java/org/sunbird/progress/controller/ContentProgressController.java @@ -1,7 +1,6 @@ package org.sunbird.progress.controller; import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.http.HttpStatus; import org.springframework.http.ResponseEntity; import org.springframework.web.bind.annotation.*; import org.sunbird.common.model.SBApiResponse; @@ -27,7 +26,7 @@ public class ContentProgressController { * @return - Return the response of success/failure after processing the request. */ @PostMapping("/v1/ext/update") - public ResponseEntity updateContentProgress(@RequestBody SunbirdApiRequest requestBody, + public ResponseEntity updateContentProgress(@RequestBody SunbirdApiRequest requestBody, @RequestHeader(Constants.USER_TOKEN) String authUserToken) { SBApiResponse response = service.updateContentProgress(authUserToken, requestBody); @@ -40,7 +39,7 @@ public ResponseEntity updateContentProgress(@RequestBody SunbirdApiRequest re * @return - Return the response of success/failure after processing the request. */ @PostMapping("/v1/read/getUserDetails") - public ResponseEntity getUserSessionDetailsAndCourseProgress(@RequestBody SunbirdApiRequest requestBody, + public ResponseEntity getUserSessionDetailsAndCourseProgress(@RequestBody SunbirdApiRequest requestBody, @RequestHeader(Constants.USER_TOKEN) String authUserToken) throws IOException { SBApiResponse response = service.getUserSessionDetailsAndCourseProgress(authUserToken, requestBody); diff --git a/src/main/java/org/sunbird/progress/model/UpdateContentProgressRequest.java b/src/main/java/org/sunbird/progress/model/UpdateContentProgressRequest.java index 0fd24814..fab5f6d2 100644 --- a/src/main/java/org/sunbird/progress/model/UpdateContentProgressRequest.java +++ b/src/main/java/org/sunbird/progress/model/UpdateContentProgressRequest.java @@ -3,6 +3,7 @@ import org.sunbird.common.model.SunbirdApiRequest; import java.util.HashMap; +import java.util.Map; public class UpdateContentProgressRequest { @@ -18,12 +19,12 @@ public void setRequestBody(SunbirdApiRequest requestBody) { this.requestBody = requestBody; } - public HashMap getHeadersValues() { + public Map getHeadersValues() { return headersValues; } - public void setHeadersValues(HashMap headerValues) { - this.headersValues = headerValues; + public void setHeadersValues(Map headerValues) { + this.headersValues = (HashMap) headerValues; } } diff --git a/src/main/java/org/sunbird/progress/service/ContentProgressService.java b/src/main/java/org/sunbird/progress/service/ContentProgressService.java index f4a4fcf0..4813aae7 100644 --- a/src/main/java/org/sunbird/progress/service/ContentProgressService.java +++ b/src/main/java/org/sunbird/progress/service/ContentProgressService.java @@ -3,8 +3,6 @@ import org.sunbird.common.model.SBApiResponse; import org.sunbird.common.model.SunbirdApiRequest; -import java.io.IOException; - public interface ContentProgressService { public SBApiResponse updateContentProgress(String authUserToken, SunbirdApiRequest requestBody); diff --git a/src/main/java/org/sunbird/progress/service/ContentProgressServiceImpl.java b/src/main/java/org/sunbird/progress/service/ContentProgressServiceImpl.java index d42165b9..86a097f4 100644 --- a/src/main/java/org/sunbird/progress/service/ContentProgressServiceImpl.java +++ b/src/main/java/org/sunbird/progress/service/ContentProgressServiceImpl.java @@ -91,7 +91,7 @@ public SBApiResponse getUserSessionDetailsAndCourseProgress(String authUserToken contentProgressInfo = mapper.convertValue(requestBody.getRequest(), ContentProgressInfo.class); validateContentProgressInfo(contentProgressInfo); } - if (contentProgressInfo.getUserId() != null && contentProgressInfo.getUserId().size() > 0) { + if (contentProgressInfo.getUserId() != null && !contentProgressInfo.getUserId().isEmpty()) { usersList.addAll(contentProgressInfo.getUserId()); } else { List> enrollmentBatchLookupList = getEnrollmentBatchLookupDetails(contentProgressInfo); @@ -101,7 +101,6 @@ public SBApiResponse getUserSessionDetailsAndCourseProgress(String authUserToken } })); } - //final Map> contentMaps = prepareProgressDetailsMap(contentProgressInfo.getContentId()); logger.info(" Troubleshoot start of the getUserContentConsumptionDetails : 1"); List> userContentConsumptionList = getUserContentConsumptionDetails(contentProgressInfo, usersList); logger.info(" Troubleshoot End of the getUserContentConsumptionDetails : 1"); @@ -109,32 +108,29 @@ public SBApiResponse getUserSessionDetailsAndCourseProgress(String authUserToken userContentConsumptionList.forEach(contentMap -> { String userId = (String) contentMap.get(Constants.USER_ID); String contentId = (String) contentMap.get("contentid"); - /* userDetailsList.get(userId).computeIfAbsent("progressDetails", key -> { - return new HashMap<>(contentMaps); - });*/ contentMap.remove(Constants.USER_ID); Map userMap = userDetailsList.get(userId); - if (userMap.containsKey("progressDetails")) { - Map> progressDetailsMap = (Map>) userMap.get("progressDetails"); + if (userMap.containsKey(Constants.PROGRESS_DETAILS)) { + Map> progressDetailsMap = (Map>) userMap.get(Constants.PROGRESS_DETAILS); progressDetailsMap.compute(contentId, (key, existingValue) -> { return contentMap; }); } else { - Map> progressDetailsMap = new HashMap>(); - Map progressMap = new HashMap(); + Map> progressDetailsMap = new HashMap<>(); + Map progressMap = new HashMap<>(); progressMap.put("contentId", contentId); progressMap.put("status", contentMap.get("status")); progressDetailsMap.put(contentId, progressMap); - userMap.put("progressDetails", progressDetailsMap); + userMap.put(Constants.PROGRESS_DETAILS, progressDetailsMap); } }); userDetailsList.forEach((userId, userInformation) -> { - if (userInformation.containsKey("progressDetails")) { - Map progressDetails = (Map) userInformation.get("progressDetails"); - userInformation.put("progressDetails", new ArrayList<>(progressDetails.values())); + if (userInformation.containsKey(Constants.PROGRESS_DETAILS)) { + Map progressDetails = (Map) userInformation.get(Constants.PROGRESS_DETAILS); + userInformation.put(Constants.PROGRESS_DETAILS, new ArrayList<>(progressDetails.values())); } else { - userInformation.put("progressDetails", new ArrayList<>()); + userInformation.put(Constants.PROGRESS_DETAILS, new ArrayList<>()); } }); response.getResult().put(Constants.COUNT, userDetailsList.size()); @@ -165,7 +161,7 @@ private List> getUserContentConsumptionDetails(ContentProgre propertyMap.put(Constants.BATCH_ID, contentProgressInfo.getBatchId()); propertyMap.put(Constants.COURSE_ID, contentProgressInfo.getCourseId()); propertyMap.put(Constants.USER_ID, usersList); - if (contentProgressInfo.getContentId() != null && contentProgressInfo.getContentId().size() > 0) { + if (contentProgressInfo.getContentId() != null && !contentProgressInfo.getContentId().isEmpty()) { propertyMap.put(Constants.CONTENT_ID_KEY, contentProgressInfo.getContentId()); } return cassandraOperation.getRecordsByProperties(Constants.KEYSPACE_SUNBIRD_COURSES, @@ -188,22 +184,11 @@ private List> getEnrollmentBatchLookupDetails(ContentProgres // Stream to filter and collect only non-null "endDate" maps return list.stream() .filter(item -> { - return item != null && item.containsKey("active") && (boolean) item.get("active") == true; + return item != null && item.containsKey("active") && (boolean) item.get("active") == Boolean.TRUE; }) .collect(Collectors.toList()); } - /*private Map> prepareProgressDetailsMap(List contentIdList) { - Map> progressDetailsMap = new HashMap>(); - for (String contentId : contentIdList) { - Map progressMap = new HashMap(); - progressMap.put("contentId", contentId); - progressMap.put("status", 0); - progressDetailsMap.put(contentId, progressMap); - } - return progressDetailsMap; - }*/ - private void validateContentProgressInfo(ContentProgressInfo contentProgressInfo) { if (StringUtils.isEmpty(contentProgressInfo.getBatchId())) { throw new InvalidDataInputException(Constants.CONTENT_PROGRESS_BATCH_ID_ERROR_MSG); diff --git a/src/main/java/org/sunbird/progress/service/MandatoryContentServiceImpl.java b/src/main/java/org/sunbird/progress/service/MandatoryContentServiceImpl.java index e26c23b0..475fdad8 100644 --- a/src/main/java/org/sunbird/progress/service/MandatoryContentServiceImpl.java +++ b/src/main/java/org/sunbird/progress/service/MandatoryContentServiceImpl.java @@ -17,7 +17,6 @@ import org.sunbird.cassandra.utils.CassandraOperation; import org.sunbird.common.model.SearchUserApiContent; import org.sunbird.common.model.SunbirdApiRequest; -import org.sunbird.common.model.SunbirdApiResp; import org.sunbird.common.model.SunbirdUserProfileDetail; import org.sunbird.common.service.ContentServiceImpl; import org.sunbird.common.service.OutboundRequestHandlerServiceImpl; diff --git a/src/main/java/org/sunbird/progress/service/UpdateContentProgressConsumer.java b/src/main/java/org/sunbird/progress/service/UpdateContentProgressConsumer.java index eef3456c..640bcf2a 100644 --- a/src/main/java/org/sunbird/progress/service/UpdateContentProgressConsumer.java +++ b/src/main/java/org/sunbird/progress/service/UpdateContentProgressConsumer.java @@ -84,7 +84,7 @@ public void updateContentProgressConsumer(ConsumerRecord data) { String userId = (String) learnerInfo.get(Constants.USER_ID); mailNotificationDetails.put(Constants.USER_ID, userId); req = new HashMap<>(); - req.put("request", request); + req.put(Constants.REQUEST, request); Map response = outboundReqService.fetchResultUsingPatch( cbExtServerProperties.getCourseServiceHost() + cbExtServerProperties.getProgressUpdateEndPoint(), req, contentProgressRequest.getHeadersValues()); @@ -204,12 +204,11 @@ private void sendNotificationToLearner( Map mailNotificationDeta notificationRequest.setConfig(config); Map> notificationMap = new HashMap<>(); notificationMap.put("notifications", Arrays.asList(notificationRequest)); - req.put("request", notificationMap); + req.put(Constants.REQUEST, notificationMap); sendNotification(req); } public Map getUserDetails(Set userIds){ - HashMap userResult = new HashMap<>(); Map request = getSearchObject(userIds); HashMap headersValue = new HashMap<>(); headersValue.put("Content-Type", "application/json"); @@ -250,7 +249,7 @@ private Map getSearchObject(Set userIds) { request.put("limit", userIds.size()); request.put("offset", 0); request.put("filters", filters); - requestObject.put("request", request); + requestObject.put(Constants.REQUEST, request); return requestObject; } diff --git a/src/main/java/org/sunbird/ratings/controller/RatingsController.java b/src/main/java/org/sunbird/ratings/controller/RatingsController.java index 57e91167..0884cb1c 100644 --- a/src/main/java/org/sunbird/ratings/controller/RatingsController.java +++ b/src/main/java/org/sunbird/ratings/controller/RatingsController.java @@ -21,13 +21,13 @@ public class RatingsController { // ----------------- Public APIs -------------------- @PostMapping("/ratings/v1/upsert") - public ResponseEntity upsertRating(@Valid @RequestBody RequestRating requestRatingBody) { + public ResponseEntity upsertRating(@Valid @RequestBody RequestRating requestRatingBody) { SBApiResponse response = ratingService.upsertRating(requestRatingBody); return new ResponseEntity<>(response, response.getResponseCode()); } @GetMapping("/ratings/v1/read/{activityId}/{activityType}/{userId}") - public ResponseEntity getRating(@PathVariable("activityId") String activityId, + public ResponseEntity getRating(@PathVariable("activityId") String activityId, @PathVariable("activityType") String activityType, @PathVariable("userId") String userId) { SBApiResponse response = ratingService.getRatings(activityId, activityType, userId); @@ -35,32 +35,32 @@ public ResponseEntity getRating(@PathVariable("activityId") String activityId } @GetMapping("/ratings/v1/summary/{activityId}/{activityType}") - public ResponseEntity getRatingSummary(@PathVariable("activityId") String activityId, + public ResponseEntity getRatingSummary(@PathVariable("activityId") String activityId, @PathVariable("activityType") String activityType) { SBApiResponse response = ratingService.getRatingSummary(activityId, activityType); return new ResponseEntity<>(response, response.getResponseCode()); } @PostMapping("/ratings/v1/ratingLookUp") - public ResponseEntity ratingLookUp(@RequestBody LookupRequest request) { + public ResponseEntity ratingLookUp(@RequestBody LookupRequest request) { SBApiResponse response = ratingService.ratingLookUp(request); return new ResponseEntity<>(response, response.getResponseCode()); } @PostMapping("/ratings/v2/read") - public ResponseEntity readRating(@RequestBody Map request) { + public ResponseEntity readRating(@RequestBody Map request) { SBApiResponse response = ratingService.readRatings(request); return new ResponseEntity<>(response, response.getResponseCode()); } @PostMapping("/ratings/meta/update") - public ResponseEntity updateRatingsMetaData() { + public ResponseEntity updateRatingsMetaData() { SBApiResponse response = ratingService.updateRatingsMetaData(); return new ResponseEntity<>(response, response.getResponseCode()); } @PostMapping("/update/v1/content/additionaltag") - public ResponseEntity updateAdditionalTag(@RequestParam("tag") String tag) { + public ResponseEntity updateAdditionalTag(@RequestParam("tag") String tag) { SBApiResponse response = ratingService.updateAdditionalTag(tag); return new ResponseEntity<>(response, response.getResponseCode()); } diff --git a/src/main/java/org/sunbird/ratings/exception/ValidationException.java b/src/main/java/org/sunbird/ratings/exception/ValidationException.java index a0f31c7f..ef6fa810 100644 --- a/src/main/java/org/sunbird/ratings/exception/ValidationException.java +++ b/src/main/java/org/sunbird/ratings/exception/ValidationException.java @@ -42,6 +42,7 @@ public void setResponseCode(int responseCode) { this.responseCode = responseCode; } + @Override public String getMessage() { return message.toString(); } diff --git a/src/main/java/org/sunbird/ratings/model/LookupResponse.java b/src/main/java/org/sunbird/ratings/model/LookupResponse.java index 1fb13c06..49482bd5 100644 --- a/src/main/java/org/sunbird/ratings/model/LookupResponse.java +++ b/src/main/java/org/sunbird/ratings/model/LookupResponse.java @@ -1,7 +1,5 @@ package org.sunbird.ratings.model; -import java.sql.Timestamp; - public class LookupResponse { private String activityId; private String review; diff --git a/src/main/java/org/sunbird/ratings/model/RatingMessage.java b/src/main/java/org/sunbird/ratings/model/RatingMessage.java index 3f5f7320..2f1f066c 100644 --- a/src/main/java/org/sunbird/ratings/model/RatingMessage.java +++ b/src/main/java/org/sunbird/ratings/model/RatingMessage.java @@ -1,30 +1,29 @@ package org.sunbird.ratings.model; public class RatingMessage { - public Integer version = 1; private String action = "ratingUpdate"; - private String activity_id; - private String activity_Type; - private String user_id; - private String created_Date; + private String activityId; + private String activityType; + private String userId; + private String createdDate; private UpdatedValues prevValues; private UpdatedValues updatedValues; - public RatingMessage(String action, String activity_id, String activity_Type, String user_id, String created_Date) { + public RatingMessage(String action, String activityId, String activityType, String userId, String createdDate) { this.action = action; - this.activity_id = activity_id; - this.activity_Type = activity_Type; - this.user_id = user_id; - this.created_Date = created_Date; + this.activityId = activityId; + this.activityType = activityType; + this.userId = userId; + this.createdDate = createdDate; } - public String getActivity_id() { - return activity_id; + public String getActivityId() { + return activityId; } - public void setActivity_id(String activity_id) { - this.activity_id = activity_id; + public void setActivityId(String activityId) { + this.activityId = activityId; } public String getAction() { @@ -35,28 +34,28 @@ public void setAction(String action) { this.action = action; } - public String getActivity_Type() { - return activity_Type; + public String getActivityType() { + return activityType; } - public void setActivity_Type(String activity_Type) { - this.activity_Type = activity_Type; + public void setActivityType(String activityType) { + this.activityType = activityType; } - public String getUser_id() { - return user_id; + public String getUserId() { + return userId; } - public void setUser_id(String user_id) { - this.user_id = user_id; + public void setUserId(String userId) { + this.userId = userId; } - public String getCreated_Date() { - return created_Date; + public String getCreatedDate() { + return createdDate; } - public void setCreated_Date(String created_Date) { - this.created_Date = created_Date; + public void setCreatedDate(String createdDate) { + this.createdDate = createdDate; } public UpdatedValues getPrevValues() { @@ -76,9 +75,9 @@ public void setUpdatedValues(UpdatedValues updatedValues) { } public static class UpdatedValues { - public String updatedOn; - public Float rating; - public String review; + private String updatedOn; + private Float rating; + private String review; public String getUpdatedOn() { return updatedOn; diff --git a/src/main/java/org/sunbird/ratings/model/SummaryModel.java b/src/main/java/org/sunbird/ratings/model/SummaryModel.java index 462a1b12..da5e919f 100644 --- a/src/main/java/org/sunbird/ratings/model/SummaryModel.java +++ b/src/main/java/org/sunbird/ratings/model/SummaryModel.java @@ -5,25 +5,27 @@ public class SummaryModel { private String activityId; private String activityType; - private Float totalcount1stars; - private Float totalcount2stars; - private Float totalcount3stars; - private Float totalcount4stars; - private Float totalcount5stars; - private Float total_number_of_ratings; - private Float sum_of_total_ratings; + private Float totalCount1Stars; + private Float totalCount2Stars; + private Float totalCount3Stars; + private Float totalCount4Stars; + private Float totalCount5Stars; + private Float totalNumberOfRatings; + private Float sumOfTotalRatings; private String latest50Reviews; - public SummaryModel(String activityId, String activityType, Float totalcount1stars, Float totalcount2stars, Float totalcount3stars, Float totalcount4stars, Float totalcount5stars, Float total_number_of_ratings, Float sum_of_total_ratings, String latest50Reviews) { + + + public SummaryModel(String activityId, String activityType, Float totalCount1Stars, Float totalCount2Stars, Float totalCount3Stars, Float totalCount4Stars, Float totalCount5Stars, Float totalNumberOfRatings, Float sumOfTotalRatings, String latest50Reviews) { this.activityId = activityId; this.activityType = activityType; - this.totalcount1stars = totalcount1stars; - this.totalcount2stars = totalcount2stars; - this.totalcount3stars = totalcount3stars; - this.totalcount4stars = totalcount4stars; - this.totalcount5stars = totalcount5stars; - this.total_number_of_ratings = total_number_of_ratings; - this.sum_of_total_ratings = sum_of_total_ratings; + this.totalCount1Stars = totalCount1Stars; + this.totalCount2Stars = totalCount2Stars; + this.totalCount3Stars = totalCount3Stars; + this.totalCount4Stars = totalCount4Stars; + this.totalCount5Stars = totalCount5Stars; + this.totalNumberOfRatings = totalNumberOfRatings; + this.sumOfTotalRatings = sumOfTotalRatings; this.latest50Reviews = latest50Reviews; } @@ -39,60 +41,60 @@ public void setActivityId(String activityId) { this.activityId = activityId; } - public Float getTotalcount3stars() { - return totalcount3stars; + public Float getTotalCount3Stars() { + return totalCount3Stars; } - public void setTotalcount3stars(Float totalcount3stars) { - this.totalcount3stars = totalcount3stars; + public void setTotalCount3Stars(Float totalCount3Stars) { + this.totalCount3Stars = totalCount3Stars; } - public Float getTotalcount1stars() { - return totalcount1stars; + public Float getTotalCount1Stars() { + return totalCount1Stars; } - public void setTotalcount1stars(Float totalcount1stars) { - this.totalcount1stars = totalcount1stars; + public void setTotalCount1Stars(Float totalCount1Stars) { + this.totalCount1Stars = totalCount1Stars; } - public Float getTotalcount4stars() { - return totalcount4stars; + public Float getTotalCount4Stars() { + return totalCount4Stars; } - public void setTotalcount4stars(Float totalcount4stars) { - this.totalcount4stars = totalcount4stars; + public void setTotalCount4Stars(Float totalCount4Stars) { + this.totalCount4Stars = totalCount4Stars; } - public Float getTotalcount5stars() { - return totalcount5stars; + public Float getTotalCount5Stars() { + return totalCount5Stars; } - public void setTotalcount5stars(Float totalcount5stars) { - this.totalcount5stars = totalcount5stars; + public void setTotalCount5Stars(Float totalCount5Stars) { + this.totalCount5Stars = totalCount5Stars; } - public Float getTotal_number_of_ratings() { - return total_number_of_ratings; + public Float getTotalNumberOfRatings() { + return totalNumberOfRatings; } - public void setTotal_number_of_ratings(Float total_number_of_ratings) { - this.total_number_of_ratings = total_number_of_ratings; + public void setTotalNumberOfRatings(Float totalNumberOfRatings) { + this.totalNumberOfRatings = totalNumberOfRatings; } - public Float getTotalcount2stars() { - return totalcount2stars; + public Float getTotalCount2Stars() { + return totalCount2Stars; } - public void setTotalcount2stars(Float totalcount2stars) { - this.totalcount2stars = totalcount2stars; + public void setTotalCount2Stars(Float totalCount2Stars) { + this.totalCount2Stars = totalCount2Stars; } - public Float getSum_of_total_ratings() { - return sum_of_total_ratings; + public Float getSumOfTotalRatings() { + return sumOfTotalRatings; } - public void setSum_of_total_ratings(Float sum_of_total_ratings) { - this.sum_of_total_ratings = sum_of_total_ratings; + public void setSumOfTotalRatings(Float sumOfTotalRatings) { + this.sumOfTotalRatings = sumOfTotalRatings; } public String getActivityType() { @@ -111,17 +113,17 @@ public void setLatest50Reviews(String latest50Reviews) { this.latest50Reviews = latest50Reviews; } - static public class latestReviews { + public static class latestReviews { private String objectType; - private String user_id; + private String userId; private Timestamp date; private Float rating; private String review; private String firstName; - public latestReviews(String objectType, String user_id, Timestamp date, Float rating, String review, String firstName) { + public latestReviews(String objectType, String userId, Timestamp date, Float rating, String review, String firstName) { this.objectType = objectType; - this.user_id = user_id; + this.userId = userId; this.date = date; this.rating = rating; this.review = review; @@ -136,12 +138,12 @@ public void setObjectType(String objectType) { this.objectType = objectType; } - public String getUser_id() { - return user_id; + public String getUserId() { + return userId; } - public void setUser_id(String user_id) { - this.user_id = user_id; + public void setUserId(String userId) { + this.userId = userId; } public Timestamp getDate() { diff --git a/src/main/java/org/sunbird/ratings/model/SummaryNodeModel.java b/src/main/java/org/sunbird/ratings/model/SummaryNodeModel.java index 36c5b2e8..09b1ad2f 100644 --- a/src/main/java/org/sunbird/ratings/model/SummaryNodeModel.java +++ b/src/main/java/org/sunbird/ratings/model/SummaryNodeModel.java @@ -1,10 +1,8 @@ package org.sunbird.ratings.model; -import java.util.UUID; - public class SummaryNodeModel { private String objectType; - private String user_id; + private String userId; private String date; private Double rating; private String review; @@ -12,9 +10,9 @@ public class SummaryNodeModel { public SummaryNodeModel() { } - public SummaryNodeModel(String objectType, String user_id, String date, Double rating, String review) { + public SummaryNodeModel(String objectType, String userId, String date, Double rating, String review) { this.objectType = objectType; - this.user_id = user_id; + this.userId = userId; this.date = date; this.rating = rating; this.review = review; @@ -28,12 +26,12 @@ public void setObjectType(String objectType) { this.objectType = objectType; } - public String getUser_id() { - return user_id; + public String getUserId() { + return userId; } - public void setUser_id(String user_id) { - this.user_id = user_id; + public void setUserId(String userId) { + this.userId = userId; } public String getDate() { diff --git a/src/main/java/org/sunbird/ratings/responsecode/ResponseCode.java b/src/main/java/org/sunbird/ratings/responsecode/ResponseCode.java index 2ff48468..faaa9da7 100644 --- a/src/main/java/org/sunbird/ratings/responsecode/ResponseCode.java +++ b/src/main/java/org/sunbird/ratings/responsecode/ResponseCode.java @@ -89,7 +89,7 @@ public static String getResponseMessage(String code) { if (StringUtils.isBlank(code)) { return ""; } - ResponseCode responseCodes[] = ResponseCode.values(); + ResponseCode[] responseCodes = ResponseCode.values(); for (ResponseCode actionState : responseCodes) { if (actionState.getErrorCode().equals(code)) { return actionState.getErrorMessage(); @@ -121,8 +121,7 @@ public static ResponseCode getResponse(String errorCode) { if (StringUtils.isBlank(errorCode)) { return null; } else { - // ResponseCode value = null; - ResponseCode responseCodes[] = ResponseCode.values(); + ResponseCode[] responseCodes = ResponseCode.values(); for (ResponseCode response : responseCodes) { if (response.getErrorCode().equals(errorCode)) { return response; diff --git a/src/main/java/org/sunbird/ratings/service/RatingServiceImpl.java b/src/main/java/org/sunbird/ratings/service/RatingServiceImpl.java index 1887231a..d928c375 100644 --- a/src/main/java/org/sunbird/ratings/service/RatingServiceImpl.java +++ b/src/main/java/org/sunbird/ratings/service/RatingServiceImpl.java @@ -103,8 +103,8 @@ public SBApiResponse getRatings(String activityId, String activityType, String u ratingModelInfo.setRecommended(ratingData.get(Constants.RECOMMENDED)!=null ?(String)ratingData.get(Constants.RECOMMENDED): null); if(ratingData.get(Constants.COMMENT_UPDATED_ON)!=null){ UUID commentupdatedOn = (UUID) ratingData.get(Constants.COMMENT_UPDATED_ON); - Long CommentUpdatedTime = (commentupdatedOn.timestamp() - 0x01b21dd213814000L) / 10000L; - ratingModelInfo.setCommentUpdatedOn(new Timestamp(CommentUpdatedTime)); + Long commentUpdatedTime = (commentupdatedOn.timestamp() - 0x01b21dd213814000L) / 10000L; + ratingModelInfo.setCommentUpdatedOn(new Timestamp(commentUpdatedTime)); } timeBasedUuid = (UUID) ratingData.get(Constants.UPDATED_ON); @@ -159,7 +159,7 @@ public SBApiResponse getRatingSummary(String activityId, String activityType) { for (JsonNode jsonNode : actualObj) { final SummaryNodeModel summaryModel = mapper.convertValue(jsonNode, SummaryNodeModel.class); - reviewMap.put(summaryModel.getUser_id(), summaryModel); + reviewMap.put(summaryModel.getUserId(), summaryModel); userList.add(jsonNode.get("user_id").asText()); } @@ -281,7 +281,7 @@ public SBApiResponse upsertRating(RequestRating requestRating) { response.setResponseCode(HttpStatus.OK); response.getParams().setStatus(Constants.SUCCESSFUL); if(requestRating.getComment()==null && requestRating.getCommentBy()==null) { - System.out.println("Message "+mapper.writeValueAsString(ratingMessage)); + logger.info("Message "+mapper.writeValueAsString(ratingMessage)); kafkaProducer.push(updateRatingTopicName, ratingMessage); } } catch (ValidationException ex) { @@ -360,7 +360,7 @@ public SBApiResponse ratingLookUp(LookupRequest lookupRequest) { } Collections.sort(listOfLookupResponse, (l1, l2) -> { - if(l1.getUpdatedon() == l2.getUpdatedon()) + if(l1.getUpdatedon().equals(l2.getUpdatedon())) return 0; return l2.getUpdatedon() < l1.getUpdatedon() ? -1 : 1; }); @@ -392,11 +392,11 @@ public RatingMessage.UpdatedValues processEventMessage(String date, Float rating return values; } - private void validateRatingsInfo(ValidationBody validationBody, String flag) throws Exception { + private void validateRatingsInfo(ValidationBody validationBody, String flag) throws ValidationException { List errObjList = new ArrayList<>(); - if (flag == Constants.RATING_UPSERT_OPERATION) { + if (Constants.RATING_UPSERT_OPERATION.equalsIgnoreCase(flag)) { if (StringUtils.isEmpty(validationBody.getRequestRating().getActivityId())) { errObjList.add(ResponseMessage.Message.INVALID_INPUT); } @@ -416,7 +416,7 @@ private void validateRatingsInfo(ValidationBody validationBody, String flag) thr if (StringUtils.isEmpty(validationBody.getRequestRating().getUserId())) { errObjList.add(ResponseMessage.Message.INVALID_USER); } - } else if (flag == Constants.RATING_LOOKUP_RATING_OPERATION) { + } else if (Constants.RATING_LOOKUP_RATING_OPERATION.equalsIgnoreCase(flag)) { if (StringUtils.isEmpty(validationBody.getLookupRequest().getActivityId())) { errObjList.add(ResponseMessage.Message.INVALID_INPUT); @@ -431,7 +431,7 @@ private void validateRatingsInfo(ValidationBody validationBody, String flag) thr if (validationBody.getLookupRequest().getLimit() < 1) { errObjList.add(ResponseMessage.Message.INVALID_LIMIT); } - } else if (flag == Constants.RATING_GET_OPERATION || flag == Constants.RATING_SUMMARY_OPERATION) { + } else if (Constants.RATING_GET_OPERATION.equalsIgnoreCase(flag) || Constants.RATING_SUMMARY_OPERATION.equalsIgnoreCase(flag)) { if (StringUtils.isEmpty(validationBody.getActivityId())) { errObjList.add(ResponseMessage.Message.INVALID_INPUT); } @@ -439,7 +439,7 @@ private void validateRatingsInfo(ValidationBody validationBody, String flag) thr errObjList.add(ResponseMessage.Message.INVALID_INPUT); } - if (flag == Constants.RATING_GET_OPERATION && StringUtils.isEmpty(validationBody.getUserId())) { + if (Constants.RATING_GET_OPERATION.equalsIgnoreCase(flag) && StringUtils.isEmpty(validationBody.getUserId())) { errObjList.add(ResponseMessage.Message.INVALID_INPUT); } } @@ -469,12 +469,12 @@ public SBApiResponse readRatings(Map request) { } Map requestBody = (Map) request.get(Constants.REQUEST); - Map compositeKey = new HashMap(); + Map compositeKey = new HashMap<>(); activityId = (String) requestBody.get(Constants.ACTIVITY_ID); compositeKey.put(Constants.ACTIVITY_ID, activityId); - compositeKey.put(Constants.ACTIVITY_TYPE, (String) requestBody.get(Constants.ACTIVITY_TYPE)); - compositeKey.put(Constants.RATINGS_USER_ID, (List) requestBody.get(Constants.USER_ID)); + compositeKey.put(Constants.ACTIVITY_TYPE, requestBody.get(Constants.ACTIVITY_TYPE)); + compositeKey.put(Constants.RATINGS_USER_ID, requestBody.get(Constants.USER_ID)); List> existingDataList = cassandraOperation.getRecordsByPropertiesWithoutFiltering( Constants.KEYSPACE_SUNBIRD, Constants.TABLE_RATINGS, compositeKey, null); @@ -497,7 +497,7 @@ private String validateRequest(Map request) { return strBuilder.toString(); } - List missingAttrib = new ArrayList(); + List missingAttrib = new ArrayList<>(); if (!requestBody.containsKey(Constants.ACTIVITY_ID)) { missingAttrib.add(Constants.ACTIVITY_ID); } @@ -509,7 +509,7 @@ private String validateRequest(Map request) { missingAttrib.add(Constants.USER_ID); } - if (missingAttrib.size() > 0) { + if (!missingAttrib.isEmpty()) { strBuilder.append("The following parameter(s) are missing. Missing params - [") .append(missingAttrib.toString()).append("]"); } @@ -560,7 +560,7 @@ public SBApiResponse updateRatingsMetaData() { contentRequest.put(Constants.CONTENT, updateRatingValues); Map updateContent = new HashMap<>(); updateContent.put(Constants.REQUEST, contentRequest); - Map updateReadData = (Map) outboundRequestHandlerService.fetchResultUsingPatch( + Map updateReadData = outboundRequestHandlerService.fetchResultUsingPatch( serverConfig.getLearningServiceBaseUrl() + serverConfig.getSystemUpdateAPI() + contentId, updateContent, ProjectUtil.getDefaultHeaders()); if (Constants.OK.equalsIgnoreCase((String) updateReadData.get(Constants.RESPONSE_CODE))) { @@ -660,7 +660,7 @@ private boolean updateAdditionalTag(Map contentResponse, String } if (isRemove) { - if (additionalTags.size() == 0) + if (additionalTags.isEmpty()) return false; additionalTags.remove(tag); } else { @@ -675,7 +675,7 @@ private boolean updateAdditionalTag(Map contentResponse, String contentRequest.put(Constants.CONTENT, updatedValues); Map updateContent = new HashMap<>(); updateContent.put(Constants.REQUEST, contentRequest); - Map updateReadData = (Map) outboundRequestHandlerService.fetchResultUsingPatch(serverConfig.getLearningServiceBaseUrl() + Map updateReadData = outboundRequestHandlerService.fetchResultUsingPatch(serverConfig.getLearningServiceBaseUrl() + serverConfig.getSystemUpdateAPI() + contentId, updateContent, ProjectUtil.getDefaultHeaders()); if (Constants.OK.equalsIgnoreCase((String) updateReadData.get(Constants.RESPONSE_CODE))) { return true; diff --git a/src/main/java/org/sunbird/searchby/controller/MasterDataController.java b/src/main/java/org/sunbird/searchby/controller/MasterDataController.java index 41d3d712..32e98758 100644 --- a/src/main/java/org/sunbird/searchby/controller/MasterDataController.java +++ b/src/main/java/org/sunbird/searchby/controller/MasterDataController.java @@ -19,73 +19,73 @@ public class MasterDataController { private MasterDataServiceImpl masterDataService; @GetMapping("/positions") - public ResponseEntity getPositionsList() { + public ResponseEntity getPositionsList() { FracApiResponse response = masterDataService.getListPositions(); return new ResponseEntity<>(response, HttpStatus.valueOf(response.getStatusInfo().getStatusCode())); } @GetMapping("/getLanguages") - public ResponseEntity getLanguagesList() { + public ResponseEntity> getLanguagesList() { return new ResponseEntity<>(masterDataService.getMasterDataByType(Constants.LANGUAGES), HttpStatus.OK); } @GetMapping("/getNationalities") - public ResponseEntity getNationalitiesList() { + public ResponseEntity> getNationalitiesList() { return new ResponseEntity<>(masterDataService.getMasterDataByType(Constants.NATIONALITY), HttpStatus.OK); } @GetMapping("/getCountries") - public ResponseEntity getCountriesList() { + public ResponseEntity> getCountriesList() { return new ResponseEntity<>(masterDataService.getMasterDataByType(Constants.COUNTRIES), HttpStatus.OK); } @GetMapping("/getIndustries") - public ResponseEntity getIndustriesList() { + public ResponseEntity> getIndustriesList() { return new ResponseEntity<>(masterDataService.getMasterDataByType(Constants.INDUSTRIES), HttpStatus.OK); } @GetMapping("/getGraduations") - public ResponseEntity getGraduationsList() { + public ResponseEntity> getGraduationsList() { return new ResponseEntity<>(masterDataService.getMasterDataByType(Constants.GRADUATIONS), HttpStatus.OK); } @GetMapping("/getPostGraduations") - public ResponseEntity getPostGraduationsList() { + public ResponseEntity> getPostGraduationsList() { return new ResponseEntity<>(masterDataService.getMasterDataByType(Constants.POST_GRADUATIONS), HttpStatus.OK); } @GetMapping("/getProfilePageMetaData") - public ResponseEntity getProfilePageMetaData() { + public ResponseEntity> getProfilePageMetaData() { return new ResponseEntity<>(masterDataService.getProfilePageMetaData(), HttpStatus.OK); } @GetMapping("/getMinistries") - public ResponseEntity getMinistriesList() { + public ResponseEntity> getMinistriesList() { return new ResponseEntity<>(masterDataService.getMasterDataByType(Constants.MINISTRIES), HttpStatus.OK); } @GetMapping("/getCadre") - public ResponseEntity getCadreList() { + public ResponseEntity> getCadreList() { return new ResponseEntity<>(masterDataService.getMasterDataByType(Constants.CADRE), HttpStatus.OK); } @GetMapping("/getService") - public ResponseEntity getServiceList() { + public ResponseEntity> getServiceList() { return new ResponseEntity<>(masterDataService.getMasterDataByType(Constants.SERVICE), HttpStatus.OK); } @GetMapping("/getDesignation") - public ResponseEntity getDesignationList() { + public ResponseEntity> getDesignationList() { return new ResponseEntity<>(masterDataService.getMasterDataByType(Constants.DESIGNATIONS), HttpStatus.OK); } @GetMapping("/getGradePay") - public ResponseEntity getGradePayList() { + public ResponseEntity> getGradePayList() { return new ResponseEntity<>(masterDataService.getMasterDataByType(Constants.GRADE_PAY), HttpStatus.OK); } @PostMapping("/upsert") - public ResponseEntity upsertMasterData(@RequestBody Map request) { + public ResponseEntity upsertMasterData(@RequestBody Map request) { SBApiResponse response = masterDataService.upsertMasterData(request); return new ResponseEntity<>(response, response.getResponseCode()); } diff --git a/src/main/java/org/sunbird/searchby/controller/MasterDataControllerV2.java b/src/main/java/org/sunbird/searchby/controller/MasterDataControllerV2.java index 1f20e965..18433638 100644 --- a/src/main/java/org/sunbird/searchby/controller/MasterDataControllerV2.java +++ b/src/main/java/org/sunbird/searchby/controller/MasterDataControllerV2.java @@ -22,13 +22,13 @@ public class MasterDataControllerV2 { private MasterDataServiceImpl masterDataService; @GetMapping("/deptPosition") - public ResponseEntity getDeptPositionsList(@RequestHeader(Constants.X_AUTH_USER_ORG_ID) String userOrgId) { + public ResponseEntity getDeptPositionsList(@RequestHeader(Constants.X_AUTH_USER_ORG_ID) String userOrgId) { SBApiResponse response = masterDataService.getDeptPositions(userOrgId); return new ResponseEntity<>(response, response.getResponseCode()); } @PostMapping("/admin/deptPosition") - public ResponseEntity retrieveDeptPositionByAdmin(@RequestBody Map request) { + public ResponseEntity retrieveDeptPositionByAdmin(@RequestBody Map request) { SBApiResponse response = masterDataService.retrieveDeptPositionByAdmin(request); return new ResponseEntity<>(response, response.getResponseCode()); } diff --git a/src/main/java/org/sunbird/searchby/controller/SearchByController.java b/src/main/java/org/sunbird/searchby/controller/SearchByController.java index 38546cad..39c7daa1 100644 --- a/src/main/java/org/sunbird/searchby/controller/SearchByController.java +++ b/src/main/java/org/sunbird/searchby/controller/SearchByController.java @@ -8,8 +8,12 @@ import org.springframework.web.bind.annotation.RestController; import org.sunbird.common.model.FracApiResponse; import org.sunbird.common.util.Constants; +import org.sunbird.searchby.model.CompetencyInfo; +import org.sunbird.searchby.model.ProviderInfo; import org.sunbird.searchby.service.SearchByService; +import java.util.Collection; + @RestController public class SearchByController { @@ -17,19 +21,19 @@ public class SearchByController { private SearchByService searchByService; @GetMapping("/v1/browseByCompetency") - public ResponseEntity browseByCompetency(@RequestHeader(Constants.X_AUTH_TOKEN) String authUserToken) + public ResponseEntity> browseByCompetency(@RequestHeader(Constants.X_AUTH_TOKEN) String authUserToken) throws Exception { return new ResponseEntity<>(searchByService.getCompetencyDetails(authUserToken), HttpStatus.OK); } @GetMapping("/v1/browseByProvider") - public ResponseEntity browseByProvider(@RequestHeader(Constants.X_AUTH_TOKEN) String authUserToken) + public ResponseEntity> browseByProvider(@RequestHeader(Constants.X_AUTH_TOKEN) String authUserToken) throws Exception { return new ResponseEntity<>(searchByService.getProviderDetails(authUserToken), HttpStatus.OK); } @GetMapping("/v1/listPositions") - public ResponseEntity listPositions(@RequestHeader(Constants.X_AUTH_TOKEN) String userToken) { + public ResponseEntity listPositions(@RequestHeader(Constants.X_AUTH_TOKEN) String userToken) { FracApiResponse response = searchByService.listPositions(userToken); return new ResponseEntity<>(response, HttpStatus.valueOf(response.getStatusInfo().getStatusCode())); } diff --git a/src/main/java/org/sunbird/searchby/service/MasterDataServiceImpl.java b/src/main/java/org/sunbird/searchby/service/MasterDataServiceImpl.java index f7ab1454..5764f3af 100644 --- a/src/main/java/org/sunbird/searchby/service/MasterDataServiceImpl.java +++ b/src/main/java/org/sunbird/searchby/service/MasterDataServiceImpl.java @@ -133,7 +133,7 @@ public SBApiResponse upsertMasterData(Map requestObj) { Map updateResponse = cassandraOperation.updateRecord(Constants.KEYSPACE_SUNBIRD, Constants.TABLE_MASTER_DATA, updateRequest, request); if (updateResponse != null && !Constants.SUCCESS.equalsIgnoreCase((String) updateResponse.get(Constants.RESPONSE))) { - errMsg = String.format("Failed to update details"); + errMsg = "Failed to update details"; response.getParams().setErrmsg(errMsg); return response; } @@ -141,11 +141,11 @@ public SBApiResponse upsertMasterData(Map requestObj) { Map propertyMap = new HashMap<>(); propertyMap.put(Constants.CONTEXT_TYPE.toLowerCase(), masterData.get(Constants.CONTEXT_TYPE)); List> totalMasterData = cassandraOperation.getRecordsByProperties(Constants.KEYSPACE_SUNBIRD, Constants.TABLE_MASTER_DATA, propertyMap, new ArrayList<>()); - request.put(Constants.ID, Long.toString(totalMasterData.size() + 1)); + request.put(Constants.ID, Long.toString((long)totalMasterData.size() + 1)); request.put(Constants.CONTEXT_DATA, masterData.get(Constants.CONTEXT_DATA)); response = cassandraOperation.insertRecord(Constants.KEYSPACE_SUNBIRD, Constants.TABLE_MASTER_DATA, request); if (!Constants.SUCCESS.equalsIgnoreCase((String) response.get(Constants.RESPONSE))) { - errMsg = String.format("Failed to Create position"); + errMsg = "Failed to Create position"; response.setResponseCode(HttpStatus.BAD_REQUEST); response.getParams().setErrmsg(errMsg); return response; @@ -168,7 +168,7 @@ public SBApiResponse upsertMasterData(Map requestObj) { } private String validateUpsertRequest(Map masterData) { - List params = new ArrayList(); + List params = new ArrayList<>(); StringBuilder strBuilder = new StringBuilder(); if (ObjectUtils.isEmpty(masterData)) { strBuilder.append("Model object is empty."); @@ -221,15 +221,15 @@ public Map getProfilePageMetaData() { private Map createDesiredResponse(List> contexts) { Map transformed = new HashMap<>(); Map>> degrees = new HashMap<>(); - degrees.put("graduations", new ArrayList<>()); - degrees.put("postGraduations", new ArrayList<>()); + degrees.put(Constants.GRADUATIONS, new ArrayList<>()); + degrees.put(Constants.POST_GRADUATIONS, new ArrayList<>()); Map>> designations = new HashMap<>(); - designations.put("designations", new ArrayList<>()); - designations.put("gradePay", new ArrayList<>()); + designations.put(Constants.DESIGNATIONS, new ArrayList<>()); + designations.put(Constants.GRADE_PAY, new ArrayList<>()); Map>> govtOrg = new HashMap<>(); - govtOrg.put("cadre", new ArrayList<>()); - govtOrg.put("ministries", new ArrayList<>()); - govtOrg.put("service", new ArrayList<>()); + govtOrg.put(Constants.CADRE, new ArrayList<>()); + govtOrg.put(Constants.MINISTRIES, new ArrayList<>()); + govtOrg.put(Constants.SERVICE, new ArrayList<>()); List> industries = new ArrayList<>(); for (Map context : contexts) { @@ -239,26 +239,26 @@ private Map createDesiredResponse(List> cont contextMap.put("name", contextName); switch (contextType) { - case "graduations": - degrees.get("graduations").add(contextMap); + case Constants.GRADUATIONS: + degrees.get(Constants.GRADUATIONS).add(contextMap); break; - case "postGraduations": - degrees.get("postGraduations").add(contextMap); + case Constants.POST_GRADUATIONS: + degrees.get(Constants.POST_GRADUATIONS).add(contextMap); break; - case "designations": - designations.get("designations").add(contextMap); + case Constants.DESIGNATIONS: + designations.get(Constants.DESIGNATIONS).add(contextMap); break; - case "gradePay": - designations.get("gradePay").add(contextMap); + case Constants.GRADE_PAY: + designations.get(Constants.GRADE_PAY).add(contextMap); break; - case "cadre": - govtOrg.get("cadre").add(contextMap); + case Constants.CADRE: + govtOrg.get(Constants.CADRE).add(contextMap); break; - case "ministries": - govtOrg.get("ministries").add(contextMap); + case Constants.MINISTRIES: + govtOrg.get(Constants.MINISTRIES).add(contextMap); break; - case "service": - govtOrg.get("service").add(contextMap); + case Constants.SERVICE: + govtOrg.get(Constants.SERVICE).add(contextMap); break; case "industries": industries.add(contextMap); @@ -268,7 +268,7 @@ private Map createDesiredResponse(List> cont } } transformed.put("degrees", degrees); - transformed.put("designations", designations); + transformed.put(Constants.DESIGNATIONS, designations); transformed.put("govtOrg", govtOrg); transformed.put("industries", industries); return transformed; @@ -277,17 +277,15 @@ private Map createDesiredResponse(List> cont private void enrichFracPositions(List positionList, String userToken) { Map headers = new HashMap<>(); HashMap reqBody = new HashMap<>(); - headers = new HashMap<>(); - headers.put(Constants.AUTHORIZATION, Constants.BEARER + userToken); - reqBody = new HashMap<>(); - List> searchList = new ArrayList<>(); + headers.put(Constants.AUTHORIZATION, Constants.BEARER + userToken); + List> searchList = new ArrayList<>(); Map compSearchObj = new HashMap<>(); compSearchObj.put(Constants.TYPE, Constants.POSITION.toUpperCase()); compSearchObj.put(Constants.FIELD, Constants.NAME); compSearchObj.put(Constants.KEYWORD, StringUtils.EMPTY); searchList.add(compSearchObj); - compSearchObj = new HashMap(); + compSearchObj = new HashMap<>(); compSearchObj.put(Constants.TYPE, Constants.POSITION.toUpperCase()); compSearchObj.put(Constants.KEYWORD, Constants.VERIFIED); compSearchObj.put(Constants.FIELD, Constants.STATUS); @@ -295,14 +293,15 @@ private void enrichFracPositions(List positionList, String userToken reqBody.put(Constants.SEARCHES, searchList); - List positionNameList = new ArrayList(); + List positionNameList = new ArrayList<>(); Map fracSearchRes = outboundRequestHandlerService.fetchResultUsingPost( cbExtServerProperties.getFracHost() + cbExtServerProperties.getFracSearchPath(), reqBody, headers); List> fracResponseList = (List>) fracSearchRes .get(Constants.RESPONSE_DATA); if (!CollectionUtils.isEmpty(fracResponseList)) { for (Map respObj : fracResponseList) { - if (!positionNameList.contains((String) respObj.get(Constants.CONTEXT_NAME.toLowerCase()))) { + String contextName= (String) respObj.get(Constants.CONTEXT_NAME.toLowerCase()); + if (!positionNameList.contains(contextName)) { positionList.add(new MasterData((String) respObj.get(Constants.ID), Constants.POSITION, (String) respObj.get(Constants.NAME), (String) respObj.get(Constants.DESCRIPTION))); positionNameList.add((String) respObj.get(Constants.NAME)); @@ -393,7 +392,7 @@ public SBApiResponse retrieveDeptPositionByAdmin(Map request) { responseData.put(Constants.CONTENT, resultList); response.getResult().put(Constants.RESPONSE, responseData); } catch (Exception e) { - errMsg = String.format("Failed to get positions for orgIdList. Exception: ", e.getMessage()); + errMsg = String.format("Failed to get positions for orgIdList. Exception: %s", e.getMessage()); logger.error(errMsg); response.getParams().setStatus(Constants.FAILED); response.getParams().setErrmsg(errMsg); diff --git a/src/main/java/org/sunbird/searchby/service/SearchByService.java b/src/main/java/org/sunbird/searchby/service/SearchByService.java index 0eb19604..09c5fb2f 100644 --- a/src/main/java/org/sunbird/searchby/service/SearchByService.java +++ b/src/main/java/org/sunbird/searchby/service/SearchByService.java @@ -146,7 +146,7 @@ private Map updateCompetencyDetails(String authUserToken if (!CollectionUtils.isEmpty(facetValueList)) { for (Map facetValueObj : facetValueList) { CompetencyInfo compInfo = new CompetencyInfo(); - // TODO - Make sure which competency field is unique + // Make sure which competency field is unique compInfo.setName((String) facetValueObj.get(Constants.NAME)); compInfo.setContentCount((int) facetValueObj.get(Constants.COUNT)); competencyMap.put((String) facetValueObj.get(Constants.NAME), compInfo); @@ -158,7 +158,7 @@ private Map updateCompetencyDetails(String authUserToken Exception err = new Exception("Failed to get facets value from Composite Search API."); logger.error(err); try { - logger.info("Received Response: " + (new ObjectMapper()).writeValueAsString(compositeSearchResult)); + logger.info(Constants.RECEIVED_RESPONSE + (new ObjectMapper()).writeValueAsString(compositeSearchResult)); } catch (Exception e) { } throw err; @@ -234,7 +234,7 @@ private Map updateCompetencyDetails(String authUserToken Exception err = new Exception("Failed to get competency info from FRAC API."); logger.error(err); try { - logger.info("Received Response: " + (new ObjectMapper()).writeValueAsString(fracSearchRes)); + logger.info(Constants.RECEIVED_RESPONSE + (new ObjectMapper()).writeValueAsString(fracSearchRes)); } catch (Exception e) { } throw err; @@ -272,7 +272,7 @@ private Map updateProviderDetails(String authUserToken) th Map compositeSearchResult = (Map) compositeSearchRes.get(Constants.RESULT); List> facetsList = (List>) compositeSearchResult.get(Constants.FACETS); if (!CollectionUtils.isEmpty(facetsList)) { - providerMap = new HashMap(); + providerMap = new HashMap<>(); for (Map facetObj : facetsList) { String name = (String) facetObj.get(Constants.NAME); if (Constants.SOURCE.equalsIgnoreCase(name)) { @@ -292,7 +292,7 @@ private Map updateProviderDetails(String authUserToken) th Exception err = new Exception("Failed to get facets value from Composite Search API."); logger.error(err); try { - logger.info("Received Response: " + (new ObjectMapper()).writeValueAsString(compositeSearchResult)); + logger.info(Constants.RECEIVED_RESPONSE + (new ObjectMapper()).writeValueAsString(compositeSearchResult)); } catch (Exception e) { } throw err; @@ -332,7 +332,7 @@ private Map updateProviderDetails(String authUserToken) th Exception err = new Exception("Failed to get competency info from FRAC API."); logger.error(err); try { - logger.info("Received Response: " + (new ObjectMapper()).writeValueAsString(orgSearchRes)); + logger.info(Constants.RECEIVED_RESPONSE + (new ObjectMapper()).writeValueAsString(orgSearchRes)); } catch (Exception e) { } throw err; @@ -345,9 +345,7 @@ private Map updateProviderDetails(String authUserToken) th private Map> updateDesignationDetails(String authUserToken) throws Exception { Map headers = new HashMap<>(); HashMap reqBody = new HashMap<>(); - headers = new HashMap<>(); headers.put(Constants.AUTHORIZATION, Constants.BEARER + authUserToken); - reqBody = new HashMap<>(); List> searchList = new ArrayList<>(); Map compSearchObj = new HashMap<>(); compSearchObj.put(Constants.TYPE, Constants.POSITION.toUpperCase()); @@ -355,7 +353,7 @@ private Map> updateDesignationDetails(String authUs compSearchObj.put(Constants.KEYWORD, StringUtils.EMPTY); searchList.add(compSearchObj); - compSearchObj = new HashMap(); + compSearchObj = new HashMap<>(); compSearchObj.put(Constants.TYPE, Constants.POSITION.toUpperCase()); compSearchObj.put(Constants.KEYWORD, Constants.VERIFIED); compSearchObj.put(Constants.FIELD, Constants.STATUS); @@ -363,7 +361,7 @@ private Map> updateDesignationDetails(String authUs reqBody.put(Constants.SEARCHES, searchList); - List positionNameList = new ArrayList(); + List positionNameList = new ArrayList<>(); List positionList = getMasterPositionList(positionNameList); Map fracSearchRes = outboundRequestHandlerService.fetchResultUsingPost( @@ -372,7 +370,8 @@ private Map> updateDesignationDetails(String authUs .get(Constants.RESPONSE_DATA); if (!CollectionUtils.isEmpty(fracResponseList)) { for (Map respObj : fracResponseList) { - if (!positionNameList.contains((String) respObj.get(Constants.NAME))) { + String name = (String) respObj.get(Constants.NAME); + if (!positionNameList.contains(name)) { positionList.add(new FracCommonInfo((String) respObj.get(Constants.ID), (String) respObj.get(Constants.NAME), (String) respObj.get(Constants.DESCRIPTION))); positionNameList.add((String) respObj.get(Constants.NAME)); @@ -382,12 +381,12 @@ private Map> updateDesignationDetails(String authUs Exception err = new Exception("Failed to get position info from FRAC API."); logger.error(err); try { - logger.info("Received Response: " + (new ObjectMapper()).writeValueAsString(fracSearchRes)); + logger.info(Constants.RECEIVED_RESPONSE + (new ObjectMapper()).writeValueAsString(fracSearchRes)); } catch (Exception e) { } throw err; } - Map> positionMap = new HashMap>(); + Map> positionMap = new HashMap<>(); positionMap.put(Constants.POSITIONS_CACHE_NAME, positionList); redisCacheMgr.putCache(Constants.POSITIONS_CACHE_NAME, positionMap); return positionMap; diff --git a/src/main/java/org/sunbird/staff/controller/StaffController.java b/src/main/java/org/sunbird/staff/controller/StaffController.java index 5f915107..5d24b8ac 100644 --- a/src/main/java/org/sunbird/staff/controller/StaffController.java +++ b/src/main/java/org/sunbird/staff/controller/StaffController.java @@ -24,34 +24,34 @@ public class StaffController { StaffService staffService; @PostMapping("/staff/position") - public ResponseEntity createStaffDetails(@RequestHeader("x-authenticated-userid") String userId, - @Valid @RequestBody StaffInfo requestBody) throws Exception { + public ResponseEntity createStaffDetails(@RequestHeader("x-authenticated-userid") String userId, + @Valid @RequestBody StaffInfo requestBody) { SBApiResponse response = staffService.submitStaffDetails(requestBody, userId); return new ResponseEntity<>(response, response.getResponseCode()); } @GetMapping("/staff/position/{orgId}") - public ResponseEntity getStaffDetails(@PathVariable("orgId") String orgId) throws Exception { + public ResponseEntity getStaffDetails(@PathVariable("orgId") String orgId) { SBApiResponse response = staffService.getStaffDetails(orgId); return new ResponseEntity<>(response, response.getResponseCode()); } @PatchMapping("/staff/position") - public ResponseEntity updateStaffDetails(@RequestHeader("x-authenticated-userid") String userId, - @Valid @RequestBody StaffInfo requestBody) throws Exception { + public ResponseEntity updateStaffDetails(@RequestHeader("x-authenticated-userid") String userId, + @Valid @RequestBody StaffInfo requestBody) { SBApiResponse response = staffService.updateStaffDetails(requestBody, userId); return new ResponseEntity<>(response, response.getResponseCode()); } @DeleteMapping("/staff/position") - public ResponseEntity deleteStaffDetails(@RequestParam String orgId, + public ResponseEntity deleteStaffDetails(@RequestParam String orgId, @RequestParam(name = "id", required = true) String staffDetailsId) throws Exception { SBApiResponse response = staffService.deleteStaffDetails(orgId, staffDetailsId); return new ResponseEntity<>(response, response.getResponseCode()); } @GetMapping("/orghistory/{orgId}/staff") - public ResponseEntity getStaffHistoryDetails(@PathVariable("orgId") String orgId) throws Exception { + public ResponseEntity getStaffHistoryDetails(@PathVariable("orgId") String orgId) throws Exception { SBApiResponse response = staffService.getStaffAudit(orgId); return new ResponseEntity<>(response, response.getResponseCode()); } diff --git a/src/main/java/org/sunbird/staff/service/StaffService.java b/src/main/java/org/sunbird/staff/service/StaffService.java index c61b6051..8caff797 100644 --- a/src/main/java/org/sunbird/staff/service/StaffService.java +++ b/src/main/java/org/sunbird/staff/service/StaffService.java @@ -5,13 +5,13 @@ public interface StaffService { - public SBApiResponse submitStaffDetails(StaffInfo data, String userId) throws Exception; + public SBApiResponse submitStaffDetails(StaffInfo data, String userId); - public SBApiResponse getStaffDetails(String orgId) throws Exception; + public SBApiResponse getStaffDetails(String orgId); - public SBApiResponse updateStaffDetails(StaffInfo data, String userId) throws Exception; + public SBApiResponse updateStaffDetails(StaffInfo data, String userId); - public SBApiResponse deleteStaffDetails(String orgId, String staffDetailsId) throws Exception; + public SBApiResponse deleteStaffDetails(String orgId, String staffDetailsId); public SBApiResponse getStaffAudit(String orgId)throws Exception; diff --git a/src/main/java/org/sunbird/staff/service/StaffServiceImpl.java b/src/main/java/org/sunbird/staff/service/StaffServiceImpl.java index 7087ae13..dee22545 100644 --- a/src/main/java/org/sunbird/staff/service/StaffServiceImpl.java +++ b/src/main/java/org/sunbird/staff/service/StaffServiceImpl.java @@ -8,6 +8,7 @@ import java.util.Map; import java.util.UUID; +import com.fasterxml.jackson.core.JsonProcessingException; import org.apache.commons.lang.StringUtils; import org.slf4j.Logger; import org.slf4j.LoggerFactory; @@ -33,7 +34,7 @@ public class StaffServiceImpl implements StaffService { private CassandraOperation cassandraOperation; @Override - public SBApiResponse submitStaffDetails(StaffInfo data, String userId) throws Exception { + public SBApiResponse submitStaffDetails(StaffInfo data, String userId) { SBApiResponse response = new SBApiResponse(Constants.API_STAFF_POSITION_ADD); try { validateAddStaffInfo(data); @@ -42,7 +43,7 @@ public SBApiResponse submitStaffDetails(StaffInfo data, String userId) throws Ex data.getPosition()); if (!CollectionUtils.isEmpty(existingList)) { String errMsg = "Position exist for given name. Failed to create StaffInfo for OrgId: " - + data.getOrgId() + ", Position: " + data.getPosition(); + + data.getOrgId() + Constants.STAFF_SERVICE_POSITION + data.getPosition(); logger.error(errMsg); response.getParams().setErrmsg(errMsg); response.setResponseCode(HttpStatus.BAD_REQUEST); @@ -76,7 +77,7 @@ public SBApiResponse submitStaffDetails(StaffInfo data, String userId) throws Ex } @Override - public SBApiResponse updateStaffDetails(StaffInfo data, String userId) throws Exception { + public SBApiResponse updateStaffDetails(StaffInfo data, String userId) { SBApiResponse response = new SBApiResponse(Constants.API_STAFF_POSITION_UPDATE); try { validateUpdateStaffInfo(data); @@ -84,7 +85,7 @@ public SBApiResponse updateStaffDetails(StaffInfo data, String userId) throws Ex List existingStaffList = getStaffListByProperty(data.getOrgId(), data.getId(), StringUtils.EMPTY); - StaffInfo existingStaffInfo = new StaffInfo(); + StaffInfo existingStaffInfo; if (!existingStaffList.isEmpty()) { existingStaffInfo = existingStaffList.get(0); } else { @@ -111,7 +112,7 @@ public SBApiResponse updateStaffDetails(StaffInfo data, String userId) throws Ex if (isAnyOtherRecordExist) { // Return error String errMsg = "Position exist for given name. Failed to update StaffInfo for OrgId: " - + data.getOrgId() + ", Position: " + data.getPosition(); + + data.getOrgId() + Constants.STAFF_SERVICE_POSITION + data.getPosition(); logger.error(errMsg); response.getParams().setErrmsg(errMsg); response.setResponseCode(HttpStatus.BAD_REQUEST); @@ -186,7 +187,7 @@ private List getStaffListByProperty(String orgId, String id, String p * String * @throws Exception */ - private void saveAuditDetails(StaffInfo data, String userId) throws Exception { + private void saveAuditDetails(StaffInfo data, String userId) throws JsonProcessingException { Map auditMap = new HashMap<>(); auditMap.put(Constants.ORG_ID, data.getOrgId()); auditMap.put(Constants.AUDIT_TYPE, Constants.STAFF); @@ -199,7 +200,7 @@ private void saveAuditDetails(StaffInfo data, String userId) throws Exception { } @Override - public SBApiResponse getStaffDetails(String orgId) throws Exception { + public SBApiResponse getStaffDetails(String orgId) { SBApiResponse response = new SBApiResponse(Constants.API_STAFF_POSITION_READ); List staffDetails = getStaffListByProperty(orgId, StringUtils.EMPTY, StringUtils.EMPTY); @@ -218,7 +219,7 @@ public SBApiResponse getStaffDetails(String orgId) throws Exception { } @Override - public SBApiResponse deleteStaffDetails(String orgId, String staffInfoId) throws Exception { + public SBApiResponse deleteStaffDetails(String orgId, String staffInfoId) { SBApiResponse response = new SBApiResponse(Constants.API_STAFF_POSITION_DELETE); try { List existingStaffList = getStaffListByProperty(orgId, staffInfoId, StringUtils.EMPTY); @@ -231,7 +232,7 @@ public SBApiResponse deleteStaffDetails(String orgId, String staffInfoId) throws response.getParams().setStatus(Constants.SUCCESSFUL); response.setResponseCode(HttpStatus.OK); } else { - String errMsg = "Staff Position doesn't exist for OrgId: " + orgId + ", Position: " + staffInfoId; + String errMsg = "Staff Position doesn't exist for OrgId: " + orgId + Constants.STAFF_SERVICE_POSITION + staffInfoId; logger.error(errMsg); response.getParams().setErrmsg(errMsg); response.setResponseCode(HttpStatus.BAD_REQUEST); @@ -280,7 +281,7 @@ public SBApiResponse getStaffAudit(String orgId) throws Exception { } private void validateAddStaffInfo(StaffInfo staffInfo) throws Exception { - List errObjList = new ArrayList(); + List errObjList = new ArrayList<>(); if (StringUtils.isEmpty(staffInfo.getOrgId())) { errObjList.add(Constants.ORG_ID); } @@ -295,19 +296,21 @@ private void validateAddStaffInfo(StaffInfo staffInfo) throws Exception { } if (!CollectionUtils.isEmpty(errObjList)) { - throw new Exception("One or more required fields are empty. Empty fields " + errObjList.toString()); + throw new Exception(Constants.EMPTY_FIELDS_EXCEPTION + errObjList.toString()); } } private void validateUpdateStaffInfo(StaffInfo staffInfo) throws Exception { - List errObjList = new ArrayList(); + List errObjList = new ArrayList<>(); if (StringUtils.isEmpty(staffInfo.getOrgId())) { errObjList.add(Constants.ORG_ID); } if (StringUtils.isEmpty(staffInfo.getId())) { errObjList.add(Constants.ID); } - boolean position = false, filled = false, vacant = false; + boolean position = false; + boolean filled = false; + boolean vacant = false; if (staffInfo.getPosition() != null) { if (StringUtils.isEmpty(staffInfo.getPosition())) { errObjList.add(Constants.POSITION); @@ -335,7 +338,7 @@ private void validateUpdateStaffInfo(StaffInfo staffInfo) throws Exception { } if (position && filled && vacant) { - throw new Exception("One or more required fields are empty. Empty fields " + errObjList.toString()); + throw new Exception(Constants.EMPTY_FIELDS_EXCEPTION + errObjList.toString()); } else { if (position) errObjList.remove(Constants.POSITION); @@ -346,7 +349,7 @@ private void validateUpdateStaffInfo(StaffInfo staffInfo) throws Exception { } if (!CollectionUtils.isEmpty(errObjList)) { - throw new Exception("One or more required fields are empty. Empty fields " + errObjList.toString()); + throw new Exception(Constants.EMPTY_FIELDS_EXCEPTION + errObjList.toString()); } } } diff --git a/src/main/java/org/sunbird/storage/controller/StorageController.java b/src/main/java/org/sunbird/storage/controller/StorageController.java index 1801ecb2..d63fb158 100644 --- a/src/main/java/org/sunbird/storage/controller/StorageController.java +++ b/src/main/java/org/sunbird/storage/controller/StorageController.java @@ -1,8 +1,10 @@ package org.sunbird.storage.controller; import java.io.IOException; +import java.util.Map; import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.core.io.Resource; import org.springframework.http.ResponseEntity; import org.springframework.web.bind.annotation.*; import org.springframework.web.multipart.MultipartFile; @@ -24,35 +26,35 @@ public class StorageController { CbExtServerProperties serverConfig; @PostMapping("/upload") - public ResponseEntity upload(@RequestParam(value = "file", required = true) MultipartFile multipartFile) + public ResponseEntity upload(@RequestParam(value = "file", required = true) MultipartFile multipartFile) throws IOException { SBApiResponse uploadResponse = storageService.uploadFile(multipartFile, serverConfig.getCloudContainerName()); return new ResponseEntity<>(uploadResponse, uploadResponse.getResponseCode()); } @DeleteMapping("/delete") - public ResponseEntity deleteCloudFile(@RequestParam(value = "fileName", required = true) String fileName) + public ResponseEntity deleteCloudFile(@RequestParam(value = "fileName", required = true) String fileName) throws JsonProcessingException { SBApiResponse deleteResponse = storageService.deleteFile(fileName, serverConfig.getCloudContainerName()); return new ResponseEntity<>(deleteResponse, deleteResponse.getResponseCode()); } @GetMapping("/v1/report/{reportType}/{date}/{orgId}/{fileName}") - public ResponseEntity downloadFile(@PathVariable("reportType") String reportType, - @PathVariable("date") String date, - @PathVariable("orgId") String orgId, - @RequestHeader(Constants.X_AUTH_TOKEN) String userToken, - @PathVariable("fileName") String fileName) { + public ResponseEntity downloadFile(@PathVariable("reportType") String reportType, + @PathVariable("date") String date, + @PathVariable("orgId") String orgId, + @RequestHeader(Constants.X_AUTH_TOKEN) String userToken, + @PathVariable("fileName") String fileName) { return storageService.downloadFile(reportType, date, orgId, fileName, userToken); } @GetMapping("/v1/reportInfo/{orgId}") - public ResponseEntity getFileInfo(@PathVariable("orgId") String orgId) { + public ResponseEntity>> getFileInfo(@PathVariable("orgId") String orgId) { return storageService.getFileInfo(orgId); } @PostMapping("/profilePhotoUpload/{cloudFolderName}") - public ResponseEntity profileUpload(@PathVariable("cloudFolderName") String cloudFolderName,@RequestParam(value = "file", required = true) MultipartFile multipartFile) + public ResponseEntity profileUpload(@PathVariable("cloudFolderName") String cloudFolderName,@RequestParam(value = "file", required = true) MultipartFile multipartFile) throws IOException { SBApiResponse uploadResponse = storageService.uploadFile(multipartFile, cloudFolderName, serverConfig.getCloudProfileImageContainerName()); return new ResponseEntity<>(uploadResponse, uploadResponse.getResponseCode()); diff --git a/src/main/java/org/sunbird/storage/service/StorageServiceImpl.java b/src/main/java/org/sunbird/storage/service/StorageServiceImpl.java index bb70968a..c7edd320 100644 --- a/src/main/java/org/sunbird/storage/service/StorageServiceImpl.java +++ b/src/main/java/org/sunbird/storage/service/StorageServiceImpl.java @@ -83,9 +83,9 @@ public SBApiResponse uploadFile(MultipartFile mFile, String cloudFolderName, Str fos.close(); return uploadFile(file, cloudFolderName,containerName); } catch (Exception e) { - logger.error("Failed to upload file. Exception: ", e); + logger.error(Constants.FAILED_TO_UPLOAD_FILE_EXCEPTION, e); response.getParams().setStatus(Constants.FAILED); - response.getParams().setErrmsg("Failed to upload file. Exception: " + e.getMessage()); + response.getParams().setErrmsg(Constants.FAILED_TO_UPLOAD_FILE_EXCEPTION + e.getMessage()); response.setResponseCode(HttpStatus.INTERNAL_SERVER_ERROR); return response; } finally { @@ -108,9 +108,9 @@ public SBApiResponse uploadFile(File file, String cloudFolderName, String contai response.getResult().putAll(uploadedFile); return response; } catch (Exception e) { - logger.error("Failed to upload file. Exception: ", e); + logger.error(Constants.FAILED_TO_UPLOAD_FILE_EXCEPTION, e); response.getParams().setStatus(Constants.FAILED); - response.getParams().setErrmsg("Failed to upload file. Exception: " + e.getMessage()); + response.getParams().setErrmsg(Constants.FAILED_TO_UPLOAD_FILE_EXCEPTION + e.getMessage()); response.setResponseCode(HttpStatus.INTERNAL_SERVER_ERROR); return response; } finally { @@ -132,9 +132,9 @@ public SBApiResponse deleteFile(String fileName, String containerName) { response.setResponseCode(HttpStatus.OK); return response; } catch (Exception e) { - logger.error("Failed to delete file: " + fileName + ", Exception: ", e); + logger.error(Constants.FAILED_TO_DELETE_FILE + fileName + Constants.EXCEPTION, e); response.getParams().setStatus(Constants.FAILED); - response.getParams().setErrmsg("Failed to delete file. Exception: " + e.getMessage()); + response.getParams().setErrmsg(Constants.FAILED_TO_DELETE_FILE_EXCEPTION_MESSAGE + e.getMessage()); response.setResponseCode(HttpStatus.INTERNAL_SERVER_ERROR); return response; } @@ -148,9 +148,9 @@ public SBApiResponse downloadFile(String fileName) { Option.apply(Boolean.FALSE)); return response; } catch (Exception e) { - logger.error("Failed to download the file: " + fileName + ", Exception: ", e); + logger.error(Constants.FAILED_TO_DOWNLOAD_FILE + fileName + Constants.EXCEPTION, e); response.getParams().setStatus(Constants.FAILED); - response.getParams().setErrmsg("Failed to download the file. Exception: " + e.getMessage()); + response.getParams().setErrmsg(Constants.FAILED_TO_DOWNLOAD_FILE_EXCEPTION_MESSAGE + e.getMessage()); response.setResponseCode(HttpStatus.INTERNAL_SERVER_ERROR); return response; } @@ -161,13 +161,13 @@ public ResponseEntity downloadFile(String reportType, String date, Str try { String userId = accessTokenValidator.fetchUserIdFromAccessToken(userToken); if (StringUtils.isEmpty(userId)) { - logger.error("Failed to get UserId for orgId: " + orgId); + logger.error("Failed to get UserId for orgId: {}", orgId); return ResponseEntity.status(HttpStatus.UNAUTHORIZED).build(); } Map> userInfoMap = new HashMap<>(); userUtilityService.getUserDetailsFromDB(Arrays.asList(userId), Arrays.asList(Constants.USER_ID, Constants.ROOT_ORG_ID), userInfoMap); if (MapUtils.isEmpty(userInfoMap)) { - logger.error("Failed to get UserInfo from cassandra for userId: " + userId); + logger.error(Constants.FAILED_USER_INFO_RETRIEVAL_MESSAGE, userId); return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).build(); } String rootOrgId = userInfoMap.get(userId).get(Constants.ROOT_ORG_ID); @@ -177,7 +177,7 @@ public ResponseEntity downloadFile(String reportType, String date, Str } } if (!rootOrgId.equalsIgnoreCase(orgId)) { - logger.error("User is not authorized to download the file for other org: " + rootOrgId + ", request orgId " + orgId); + logger.error(Constants.UNAUTHORIZED_FILE_DOWNLOAD_FOR_OTHER_ORG, rootOrgId, orgId); return ResponseEntity.status(HttpStatus.UNAUTHORIZED).build(); } String objectKey = serverProperties.getReportDownloadFolderName() + "/" + reportType + "/" + date + "/" + orgId + "/" + fileName; @@ -226,38 +226,30 @@ public ResponseEntity>> getFileInfo(String orgId DateTimeFormatter dateFormat = DateTimeFormatter.ofPattern("yyyy-MM-dd"); String todayFormattedDate = now.format(dateFormat); String mdoId = "mdoid=" + orgId; - /*if (orgId != null && !orgId.isEmpty()) { - if (orgId.contains("=")) { - String[] array = orgId.split("="); - mdoId = array[1]; - } else { - mdoId = orgId; - } - }*/ String fileName = reportFileNameMap.get(reportType); String objectKey = serverProperties.getReportDownloadFolderName() + "/" + reportType + "/" + todayFormattedDate + "/" + mdoId + "/" + fileName; try { Model.Blob blob = storageService.getObject(serverProperties.getReportDownloadContainerName(), objectKey, Option.apply(Boolean.FALSE)); if (blob != null) { - resourceMap.put("lastModified", blob.lastModified()); - resourceMap.put("fileMetaData", blob.metadata()); + resourceMap.put(Constants.LASTMODIFIED, blob.lastModified()); + resourceMap.put(Constants.FILEMETADATA, blob.metadata()); } } catch (Exception e) { - logger.error("Failed to read the downloaded file for url: " + objectKey); + logger.error(Constants.FAILED_TO_READ_DOWNLOADED_FILE_FOR_URL, objectKey); LocalDateTime yesterday = now.minusDays(1); String yesterdayFormattedDate = yesterday.format(dateFormat); objectKey = serverProperties.getReportDownloadFolderName() + "/" + reportType + "/" + yesterdayFormattedDate + "/" + mdoId + "/" + fileName; try { Model.Blob blob = storageService.getObject(serverProperties.getReportDownloadContainerName(), objectKey, Option.apply(Boolean.FALSE)); if (blob != null) { - resourceMap.put("lastModified", blob.lastModified()); - resourceMap.put("fileMetaData", blob.metadata()); + resourceMap.put(Constants.LASTMODIFIED, blob.lastModified()); + resourceMap.put(Constants.FILEMETADATA, blob.metadata()); } else { resourceMap.put("msg", "No Report Available"); logger.info("Unable to fetch fileInfo"); } } catch (Exception ex) { - logger.error("Failed to read the downloaded file for url: " + objectKey); + logger.error(Constants.FAILED_TO_READ_DOWNLOADED_FILE_FOR_URL, objectKey); } } reportTypeInfo.put(fileName, resourceMap); @@ -279,13 +271,13 @@ public ResponseEntity downloadFile(String reportType, String date, String fil Map> userInfoMap = new HashMap<>(); userUtilityService.getUserDetailsFromDB(Arrays.asList(userId), Arrays.asList(Constants.USER_ID, Constants.CHANNEL), userInfoMap); if (MapUtils.isEmpty(userInfoMap)) { - logger.error("Failed to get UserInfo from cassandra for userId: " + userId); + logger.error(Constants.FAILED_USER_INFO_RETRIEVAL_MESSAGE, userId); return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).build(); } String channel = userInfoMap.get(userId).get(Constants.CHANNEL); if (!serverProperties.getSpvChannelName().equalsIgnoreCase(channel)) { - logger.error("User is not authorized to download the file for other org: "); + logger.error(Constants.UNAUTHORIZED_FILE_DOWNLOAD_FOR_OTHER_ORG); return ResponseEntity.status(HttpStatus.UNAUTHORIZED).build(); } Map spvReportSubFolderTypeMap = serverProperties.getSpvReportSubFolderTypeMap(); @@ -302,13 +294,14 @@ public ResponseEntity downloadFile(String reportType, String date, String fil .contentType(MediaType.parseMediaType(MediaType.MULTIPART_FORM_DATA_VALUE)) .body(resource); } catch (Exception e) { - logger.error("Failed to read the downloaded file: " + fileName + ", Exception: ", e); + logger.error(Constants.FAILED_TO_READ_FILE + fileName + Constants.EXCEPTION, e); return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).build(); } finally { try { File file = new File(Constants.LOCAL_BASE_PATH + fileName); if (file.exists()) { - file.delete(); + boolean isFileDeleted = file.delete(); + logger.debug("Status of file deleted is {}", isFileDeleted); } } catch (Exception e1) { } @@ -326,13 +319,13 @@ public ResponseEntity getFileInfoSpv(String userToken, String date) { Map> userInfoMap = new HashMap<>(); userUtilityService.getUserDetailsFromDB(Arrays.asList(userId), Arrays.asList(Constants.USER_ID, Constants.CHANNEL), userInfoMap); if (MapUtils.isEmpty(userInfoMap)) { - logger.error("Failed to get UserInfo from cassandra for userId: " + userId); + logger.error(Constants.FAILED_USER_INFO_RETRIEVAL_MESSAGE, userId); return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).build(); } String channel = userInfoMap.get(userId).get(Constants.CHANNEL); if (!serverProperties.getSpvChannelName().equalsIgnoreCase(channel)) { - logger.error("User is not authorized to download the file for other org: "); + logger.error(Constants.UNAUTHORIZED_FILE_DOWNLOAD_FOR_OTHER_ORG); return ResponseEntity.status(HttpStatus.UNAUTHORIZED).build(); } Map reportFileNameMap = serverProperties.getSpvReportMap(); @@ -346,11 +339,11 @@ public ResponseEntity getFileInfoSpv(String userToken, String date) { try { Model.Blob blob = storageService.getObject(serverProperties.getReportDownloadContainerName(), objectKey, Option.apply(Boolean.FALSE)); if (blob != null) { - resourceMap.put("lastModified", blob.lastModified()); - resourceMap.put("fileMetaData", blob.metadata()); + resourceMap.put(Constants.LASTMODIFIED, blob.lastModified()); + resourceMap.put(Constants.FILEMETADATA, blob.metadata()); } } catch (Exception e) { - logger.error("Failed to read the downloaded file for url: " + objectKey); + logger.error(Constants.FAILED_TO_READ_DOWNLOADED_FILE_FOR_URL, objectKey); } reportTypeInfo.put(fileName, resourceMap); } diff --git a/src/main/java/org/sunbird/telemetry/model/Edata.java b/src/main/java/org/sunbird/telemetry/model/Edata.java index 0a7bac7e..70d5a893 100644 --- a/src/main/java/org/sunbird/telemetry/model/Edata.java +++ b/src/main/java/org/sunbird/telemetry/model/Edata.java @@ -1,7 +1,6 @@ package org.sunbird.telemetry.model; import java.util.List; -import javax.annotation.Generated; import com.fasterxml.jackson.annotation.JsonInclude; import com.fasterxml.jackson.annotation.JsonProperty; import com.fasterxml.jackson.annotation.JsonPropertyOrder; diff --git a/src/main/java/org/sunbird/telemetry/model/ObjectData.java b/src/main/java/org/sunbird/telemetry/model/ObjectData.java index 73e80551..605c7733 100644 --- a/src/main/java/org/sunbird/telemetry/model/ObjectData.java +++ b/src/main/java/org/sunbird/telemetry/model/ObjectData.java @@ -1,6 +1,5 @@ package org.sunbird.telemetry.model; -import javax.annotation.Generated; import com.fasterxml.jackson.annotation.JsonInclude; import com.fasterxml.jackson.annotation.JsonProperty; import com.fasterxml.jackson.annotation.JsonPropertyOrder; diff --git a/src/main/java/org/sunbird/telemetry/model/Pdata.java b/src/main/java/org/sunbird/telemetry/model/Pdata.java index 3921fa56..861ff6c6 100644 --- a/src/main/java/org/sunbird/telemetry/model/Pdata.java +++ b/src/main/java/org/sunbird/telemetry/model/Pdata.java @@ -1,6 +1,5 @@ package org.sunbird.telemetry.model; -import javax.annotation.Generated; import com.fasterxml.jackson.annotation.JsonInclude; import com.fasterxml.jackson.annotation.JsonProperty; import com.fasterxml.jackson.annotation.JsonPropertyOrder; diff --git a/src/main/java/org/sunbird/trending/controller/TrendingServiceImpl.java b/src/main/java/org/sunbird/trending/controller/TrendingServiceImpl.java index d5951209..809d59b5 100644 --- a/src/main/java/org/sunbird/trending/controller/TrendingServiceImpl.java +++ b/src/main/java/org/sunbird/trending/controller/TrendingServiceImpl.java @@ -43,7 +43,7 @@ public Map trendingSearch(Map requestBody, Strin String org = ((String) (filter).get(Constants.ORGANISATION)) == null ? "" : ((String) (filter).get(Constants.ORGANISATION)) ; String designation = ((String) filter.get(Constants.DESIGNATION)); String redisKey = TRENDING_COURSES_REDIS_KEY; - Map redisKeyNameMap = new HashMap(); + Map redisKeyNameMap = new HashMap<>(); if (StringUtils.isBlank(designation)) { designation = ""; } else { @@ -51,7 +51,7 @@ public Map trendingSearch(Map requestBody, Strin } boolean isAcbpEnabled = false; - List updatedContextTypeList = new ArrayList(); + List updatedContextTypeList = new ArrayList<>(); for (String contextType : contextTypeList) { if (Constants.ACBP_KEY.equalsIgnoreCase(contextType)) { isAcbpEnabled = true; @@ -65,14 +65,7 @@ public Map trendingSearch(Map requestBody, Strin redisKeyNameMap.put(org + COLON + contextType, contextType); } } - int limit = Optional.ofNullable(request.get(Constants.LIMIT)).map(l -> (Integer) l).orElse(0); - /*List fieldList = updatedContextTypeList.stream() - .map(type -> org + COLON + type) - .collect(Collectors.toList()); - - String[] fieldsArray = fieldList.toArray(new String[fieldList.size()]); - */ String[] newFieldsArray = redisKeyNameMap.keySet().toArray(new String[0]); // Fetch trending Ids for requested type of courses List trendingCoursesAndPrograms = redisCacheMgr.hget(redisKey, serverProperties.getRedisInsightIndex(),newFieldsArray); @@ -89,19 +82,11 @@ public Map trendingSearch(Map requestBody, Strin } } } - - /* if(trendingCoursesAndPrograms == null) - trendingCoursesAndPrograms = new ArrayList<>(); - - for(int i=0;i i && trendingCoursesAndPrograms.size() > 0 ) - typeList.put(updatedContextTypeList.get(i),fetchIds(trendingCoursesAndPrograms.get(i), limit, fieldList.get(i))); - } */ List searchIds = typeList.values().stream().flatMap(List::stream).collect(Collectors.toList()); Map compositeSearchRes ; List> contentList = new ArrayList<>(); Map resultMap = new HashMap<>(); - if(searchIds != null && searchIds.size() > 0) { + if(searchIds != null && !searchIds.isEmpty()) { compositeSearchRes = compositeSearch(searchIds, token); if(null == compositeSearchRes) compositeSearchRes = new HashMap<>(); diff --git a/src/main/java/org/sunbird/user/registration/controller/UserRegistrationController.java b/src/main/java/org/sunbird/user/registration/controller/UserRegistrationController.java index 5a9d6bfa..3f57fae6 100644 --- a/src/main/java/org/sunbird/user/registration/controller/UserRegistrationController.java +++ b/src/main/java/org/sunbird/user/registration/controller/UserRegistrationController.java @@ -4,7 +4,6 @@ import org.springframework.http.ResponseEntity; import org.springframework.web.bind.annotation.*; import org.sunbird.common.model.SBApiResponse; -import org.sunbird.common.util.Constants; import org.sunbird.user.registration.model.UserRegistrationInfo; import org.sunbird.user.registration.service.UserRegistrationService; import java.util.Map; @@ -22,25 +21,25 @@ public class UserRegistrationController { UserRegistrationService userRegService; @PostMapping("/user/registration/v1/register") - public ResponseEntity registerUser(@RequestBody UserRegistrationInfo userRegIno) throws Exception { + public ResponseEntity registerUser(@RequestBody UserRegistrationInfo userRegIno) { SBApiResponse response = userRegService.registerUser(userRegIno); return new ResponseEntity<>(response, response.getResponseCode()); } @GetMapping("/user/registration/v1/getUserRegistrationDetails") - public ResponseEntity getUserRegistrationDetails(@RequestParam String regCode) throws Exception { + public ResponseEntity getUserRegistrationDetails(@RequestParam String regCode) { SBApiResponse response = userRegService.getUserRegistrationDetails(regCode); return new ResponseEntity<>(response, response.getResponseCode()); } @GetMapping("/user/registration/v1/getDeptDetails") - public ResponseEntity getDeptDetails() throws Exception { + public ResponseEntity getDeptDetails() { SBApiResponse response = userRegService.getDeptDetails(); return new ResponseEntity<>(response, response.getResponseCode()); } @PostMapping("/user/otp/v1/generate") - public ResponseEntity generateOTP(@RequestBody Map otpRequests) throws Exception { + public ResponseEntity generateOTP(@RequestBody Map otpRequests) { SBApiResponse response = userRegService.generateOTP(otpRequests); return new ResponseEntity<>(response, response.getResponseCode()); } diff --git a/src/main/java/org/sunbird/user/registration/model/UserRegistrationInfo.java b/src/main/java/org/sunbird/user/registration/model/UserRegistrationInfo.java index fa13f042..c1030ea7 100644 --- a/src/main/java/org/sunbird/user/registration/model/UserRegistrationInfo.java +++ b/src/main/java/org/sunbird/user/registration/model/UserRegistrationInfo.java @@ -1,11 +1,6 @@ package org.sunbird.user.registration.model; -import com.fasterxml.jackson.annotation.JsonIgnore; import com.fasterxml.jackson.annotation.JsonIgnoreProperties; -import org.apache.commons.lang.StringUtils; - -import java.util.ArrayList; -import java.util.Arrays; import java.util.List; /** diff --git a/src/main/java/org/sunbird/user/registration/service/UserRegistrationConsumer.java b/src/main/java/org/sunbird/user/registration/service/UserRegistrationConsumer.java index 78c859c1..4951b8a8 100644 --- a/src/main/java/org/sunbird/user/registration/service/UserRegistrationConsumer.java +++ b/src/main/java/org/sunbird/user/registration/service/UserRegistrationConsumer.java @@ -1,6 +1,7 @@ package org.sunbird.user.registration.service; import java.util.Arrays; +import java.util.Collections; import java.util.HashMap; import java.util.List; import java.util.Map; @@ -71,7 +72,7 @@ public void processMessage(ConsumerRecord data) { * notification to user mentioning the registration request failed and try again * later. And also update in the ES doc status value. * - * 4. TODO - In case of transition request created but failed to send email + * 4. In case of transition request created but failed to send email * notification. */ if (wfTransitionData != null) { @@ -85,11 +86,10 @@ public void processMessage(ConsumerRecord data) { serverProperties.getEsProfileIndexType(), userRegistration.getRegistrationCode(), mapper.convertValue(userRegistration, Map.class)); - LOGGER.info("Successfully called ES update request. REST Status ? " + (status != null ? status.name() : null)); + LOGGER.info("Successfully called ES update request. REST Status ? {}", (status != null ? status.name() : null)); if (!RestStatus.OK.equals(status)) { - LOGGER.info("Failed to update registration status for the document id : " - + userRegistration.getRegistrationCode() + "and status : " + userRegistration.getStatus()); + LOGGER.info("Failed to update registration status for the document id :{} and status : {}", userRegistration.getRegistrationCode(), userRegistration.getStatus()); } // send notification userRegNotificationService.sendNotification(userRegistration); @@ -99,8 +99,8 @@ public void processMessage(ConsumerRecord data) { public void processCreateUserMessage(ConsumerRecord data) { try { WfRequest wfRequest = gson.fromJson(data.value(), WfRequest.class); - LOGGER.info("Consumed Request in Topic to create user in registration:: " - + mapper.writeValueAsString(wfRequest)); + String wfRequestData = mapper.writeValueAsString(wfRequest); + LOGGER.info("Consumed Request in Topic to create user in registration:: {}", wfRequestData); userRegService.initiateCreateUserFlow(wfRequest.getApplicationId()); } catch (Exception e) { LOGGER.error("Failed to process message in Topic to create user in registration.", e); @@ -111,8 +111,8 @@ public void processCreateUserMessage(ConsumerRecord data) { public void processAutoCreateUserEvent(ConsumerRecord data) { try { UserRegistration userRegistration = gson.fromJson(data.value(), UserRegistration.class); - LOGGER.info("Consumed Request in Topic to auto create user in registration:: " - + mapper.writeValueAsString(userRegistration)); + String userRegistrationRequest =mapper.writeValueAsString(userRegistration); + LOGGER.info("Consumed Request in Topic to auto create user in registration:: {}", userRegistrationRequest); userRegService.initiateCreateUserFlow(userRegistration.getRegistrationCode()); } catch (Exception e) { LOGGER.error("Failed to process message in Topic to auto create user in registration.", e); @@ -150,6 +150,6 @@ private Map workflowTransition(WfRequest wfRequest) { } catch (Exception e) { LOGGER.error(String.format("Exception in %s : %s", "workflowTransition", e.getMessage())); } - return null; + return Collections.emptyMap(); } } diff --git a/src/main/java/org/sunbird/user/registration/service/UserRegistrationNotificationServiceImpl.java b/src/main/java/org/sunbird/user/registration/service/UserRegistrationNotificationServiceImpl.java index 9c9d72d8..d9940169 100644 --- a/src/main/java/org/sunbird/user/registration/service/UserRegistrationNotificationServiceImpl.java +++ b/src/main/java/org/sunbird/user/registration/service/UserRegistrationNotificationServiceImpl.java @@ -31,15 +31,13 @@ public void sendNotification(UserRegistration userRegistration) { add(userRegistration.getEmail()); } }; + Map notificationConfig = new HashMap<>(); + notificationConfig.put(Constants.SUBJECT, serverProperties.getUserRegistrationSubject()); Map notificationObj = new HashMap<>(); notificationObj.put(Constants.MODE, Constants.EMAIL); notificationObj.put(Constants.DELIVERY_TYPE, Constants.MESSAGE); - notificationObj.put(Constants.CONFIG, new HashMap() { - { - put(Constants.SUBJECT, serverProperties.getUserRegistrationSubject()); - } - }); + notificationObj.put(Constants.CONFIG, notificationConfig); notificationObj.put(Constants.IDS, sendTo); notificationObj.put(Constants.TEMPLATE, notificationMessage(userRegistration.getStatus(), userRegistration.getRegistrationCode())); diff --git a/src/main/java/org/sunbird/user/registration/service/UserRegistrationServiceImpl.java b/src/main/java/org/sunbird/user/registration/service/UserRegistrationServiceImpl.java index 1d28b0ae..2dbc6f6c 100644 --- a/src/main/java/org/sunbird/user/registration/service/UserRegistrationServiceImpl.java +++ b/src/main/java/org/sunbird/user/registration/service/UserRegistrationServiceImpl.java @@ -49,7 +49,7 @@ @Service public class UserRegistrationServiceImpl implements UserRegistrationService { - private Logger LOGGER = LoggerFactory.getLogger(UserRegistrationServiceImpl.class); + private Logger logger = LoggerFactory.getLogger(UserRegistrationServiceImpl.class); ObjectMapper mapper = new ObjectMapper(); @@ -118,7 +118,7 @@ public SBApiResponse registerUser(UserRegistrationInfo userRegInfo) { } if (status.equals(RestStatus.CREATED) || status.equals(RestStatus.OK)) { - if (isPreApprovedDomain(regDocument.getEmail())) { + if (Boolean.TRUE.equals(isPreApprovedDomain(regDocument.getEmail()))) { // Fire createUser event kafkaProducer.push(serverProperties.getUserRegistrationAutoCreateUserTopic(), regDocument); @@ -137,7 +137,7 @@ public SBApiResponse registerUser(UserRegistrationInfo userRegInfo) { } } } catch (Exception e) { - LOGGER.error(String.format("Exception in %s : %s", "registerUser", e.getMessage()), e); + logger.error(String.format(Constants.EXCEPTION_MESSAGE_FORMAT, "registerUser", e.getMessage()), e); errMsg = "Failed to process message. Exception: " + e.getMessage(); } } @@ -186,7 +186,7 @@ public SBApiResponse getDeptDetails() { response.getResult().put(Constants.COUNT, orgList.size()); response.getResult().put(Constants.CONTENT, orgList); } catch (Exception e) { - LOGGER.error("Exception occurred in getDeptDetails", e); + logger.error("Exception occurred in getDeptDetails", e); response.setResponseCode(HttpStatus.INTERNAL_SERVER_ERROR); response.getParams().setErrmsg("Exception occurred in getDeptDetails. Exception: " + e.getMessage()); } @@ -215,7 +215,7 @@ public SBApiResponse generateOTP(Map otpRequests) { errMsg = (String) ((Map)apiResponse.get(Constants.PARAMS)).get(Constants.ERROR_MESSAGE); } } catch (Exception e) { - LOGGER.error(String.format("Exception in %s : %s", "generateOTP", e.getMessage()), e); + logger.error(String.format(Constants.EXCEPTION_MESSAGE_FORMAT, "generateOTP", e.getMessage()), e); errMsg = "Failed to process message. Exception: " + e.getMessage(); } } @@ -233,7 +233,7 @@ public void initiateCreateUserFlow(String registrationCode) { * 1. Create User 2. Read created User 3. Update User 4. Create NodeBB user Id * 5. Assign Role 6. Reset Password and get activation link */ - LOGGER.info("Initiated User Creation flow for Reg. Code :: " + registrationCode); + logger.info("Initiated User Creation flow for Reg. Code :: {}", registrationCode); UserRegistration userReg = getUserRegistrationForRegCode(registrationCode); // Create the org if it's not already onboarded. @@ -242,16 +242,16 @@ public void initiateCreateUserFlow(String registrationCode) { if (orgResponse.getResponseCode() == HttpStatus.OK) { String orgId = (String) orgResponse.getResult().get(Constants.ORGANIZATION_ID); userReg.setSbOrgId(orgId); - LOGGER.info(String.format("Auto on-boarded organisation with Name: %s, MapId: %s, OrgId: %s", + logger.info(String.format("Auto on-boarded organisation with Name: %s, MapId: %s, OrgId: %s", userReg.getOrgName(), userReg.getMapId(), userReg.getSbOrgId())); - // TODO - Need to find a best way to give time for org creation takes effect. try { Thread.sleep(1000); - } catch (Exception e) { + } catch (InterruptedException e) { + Thread.currentThread().interrupt(); } } else { try { - LOGGER.error("Failed to auto onboard organisation. Error: " + logger.error("Failed to auto onboard organisation. Error: " + (new ObjectMapper()).writeValueAsString(orgResponse)); } catch (Exception e) { } @@ -261,9 +261,9 @@ public void initiateCreateUserFlow(String registrationCode) { UserRegistrationStatus regStatus = UserRegistrationStatus.WF_APPROVED; if (userUtilityService.createUser(userReg)) { - LOGGER.info("Successfully completed user creation flow."); + logger.info("Successfully completed user creation flow."); } else { - LOGGER.error("Failed to create user for Reg.Code :: " + registrationCode); + logger.error("Failed to create user for Reg.Code :: {}", registrationCode); regStatus = UserRegistrationStatus.FAILED; } @@ -279,9 +279,9 @@ public void initiateCreateUserFlow(String registrationCode) { strBuilder.append(". ES object update operation is ") .append(status == RestStatus.OK ? " successful." : " failed."); - LOGGER.info(strBuilder.toString()); + logger.info(strBuilder.toString()); } catch (Exception e) { - LOGGER.error("Failed to process user create flow.", e); + logger.error("Failed to process user create flow.", e); } } @@ -298,7 +298,7 @@ private SBApiResponse createDefaultResponse(String api) { private String validateRegisterationPayload(UserRegistrationInfo userRegInfo) { StringBuffer str = new StringBuffer(); - List errList = new ArrayList(); + List errList = new ArrayList<>(); if (StringUtils.isBlank(userRegInfo.getFirstName())) { errList.add("FirstName"); } @@ -331,7 +331,7 @@ private String validateRegisterationPayload(UserRegistrationInfo userRegInfo) { str.append(validateErr); } } - if(StringUtils.isNotBlank(userRegInfo.getPhone()) && !ProjectUtil.validateContactPattern(userRegInfo.getPhone())) { + if(StringUtils.isNotBlank(userRegInfo.getPhone()) && Boolean.TRUE.equals(!ProjectUtil.validateContactPattern(userRegInfo.getPhone()))) { str.setLength(0); str.append("Invalid phone number"); } @@ -346,7 +346,7 @@ private String validateRegisterationPayload(UserRegistrationInfo userRegInfo) { private String validateOTPPayload(Map otpRequest) { StringBuffer str = new StringBuffer(); Map request = (Map) otpRequest.get("request"); - List errList = new ArrayList(); + List errList = new ArrayList<>(); if (ObjectUtils.isEmpty(request.get(Constants.KEY))) { errList.add(Constants.KEY); } @@ -438,7 +438,7 @@ public String emailValidation(String email) { String emailDomain = email.split("@")[1]; Boolean retValue = isApprovedDomains(emailDomain, Constants.USER_REGISTRATION_DOMAIN) || isApprovedDomains(emailDomain, Constants.USER_REGISTRATION_PRE_APPROVED_DOMAIN); - if (!retValue) { + if (Boolean.FALSE.equals(retValue)) { str.append("Email domain of this email address is not approved. Please use Request for help."); } } else { @@ -457,13 +457,13 @@ private UserRegistration getUserRegistrationForRegCode(String registrationCode) serverProperties.getEsProfileIndexType(), registrationCode); return mapper.convertValue(esObject, UserRegistration.class); } catch (Exception e) { - LOGGER.error(String.format("Exception in %s : %s", "getUserRegistrationDetails", e.getMessage())); + logger.error(String.format(Constants.EXCEPTION_MESSAGE_FORMAT, "getUserRegistrationDetails", e.getMessage())); } return null; } private List getMasterOrgList() { - List orgList = new ArrayList(); + List orgList = new ArrayList<>(); // read file into stream, try-with-resources InputStream in = this.getClass().getClassLoader() @@ -474,7 +474,7 @@ private List getMasterOrgList() { orgList.add(line.trim()); } } catch (Exception e) { - LOGGER.error("Failed to read the master org list. Exception: ", e); + logger.error("Failed to read the master org list. Exception: ", e); } return orgList; @@ -491,23 +491,17 @@ private List getDepartmentDetails() throws Exception { requestMap.put(Constants.OFFSET, iterateCount); requestMap.put(Constants.LIMIT, 1000); requestMap.put(Constants.FIELDS, new ArrayList<>(Arrays.asList(Constants.CHANNEL, Constants.IDENTIFIER))); - Map sortByMap = new HashMap(); + Map sortByMap = new HashMap<>(); sortByMap.put(Constants.CHANNEL, Constants.ASC_ORDER); requestMap.put(Constants.SORT_BY, sortByMap); - requestMap.put(Constants.FILTERS, new HashMap() { - { - put(Constants.IS_TENANT, Boolean.TRUE); - } - }); - + Map filtersMap = new HashMap<>(); + filtersMap.put(Constants.IS_TENANT, Boolean.TRUE); + requestMap.put(Constants.FILTERS, filtersMap); String serviceURL = serverProperties.getSbUrl() + serverProperties.getSbOrgSearchPath(); + Map requestBody = new HashMap<>(); + requestBody.put(Constants.REQUEST, requestMap); SunbirdApiResp orgResponse = mapper.convertValue( - outboundRequestHandlerService.fetchResultUsingPost(serviceURL, new HashMap() { - { - put(Constants.REQUEST, requestMap); - } - }), SunbirdApiResp.class); - + outboundRequestHandlerService.fetchResultUsingPost(serviceURL, requestBody), SunbirdApiResp.class); SunbirdApiResultResponse resultResp = orgResponse.getResult().getResponse(); count = resultResp.getCount(); iterateCount = iterateCount + resultResp.getContent().size(); @@ -518,7 +512,6 @@ private List getDepartmentDetails() throws Exception { orgNameList.add(content.getChannel()); } } - List masterOrgList = getMasterOrgList(); for (String orgName : masterOrgList) { if (!orgNameList.contains(orgName)) { @@ -526,11 +519,9 @@ private List getDepartmentDetails() throws Exception { } } } while (count != iterateCount); - if (CollectionUtils.isEmpty(orgList)) { throw new Exception("Failed to retrieve organisation details."); } - Map> deptListMap = new HashMap>(); deptListMap.put(Constants.DEPARTMENT_LIST_CACHE_NAME, orgList); redisCacheMgr.putCache(Constants.DEPARTMENT_LIST_CACHE_NAME, deptListMap); @@ -538,8 +529,8 @@ private List getDepartmentDetails() throws Exception { } private Map getOrgCreateRequest(UserRegistration userReg) { - Map orgRequestBody = new HashMap(); - Map orgRequest = new HashMap(); + Map orgRequestBody = new HashMap<>(); + Map orgRequest = new HashMap<>(); orgRequest.put(Constants.ORG_NAME, userReg.getOrgName()); orgRequest.put(Constants.CHANNEL, userReg.getChannel()); orgRequest.put(Constants.ORGANIZATION_TYPE, userReg.getOrganisationType()); diff --git a/src/main/java/org/sunbird/user/report/UserReportServiceImpl.java b/src/main/java/org/sunbird/user/report/UserReportServiceImpl.java index 9d0a8203..cfb8a35c 100644 --- a/src/main/java/org/sunbird/user/report/UserReportServiceImpl.java +++ b/src/main/java/org/sunbird/user/report/UserReportServiceImpl.java @@ -62,7 +62,7 @@ public void generateUserEnrolmentReport(Map> userEnr String fileName = userStorePath + "/userEnrolmentReport-" + java.time.LocalDate.now() + System.currentTimeMillis() + ".xlsx"; - log.info("Constructed File Name -> " + fileName); + log.info("Constructed File Name -> {}" , fileName); try { File file = new File(fileName); @@ -130,7 +130,7 @@ public void completeReportWorkbook(Workbook wb, SBApiResponse response) { try { String fileName = userStorePath + "/userReport-" + java.time.LocalDate.now() + System.currentTimeMillis() + ".xlsx"; - log.info("Constructed File Name -> " + fileName); + log.info("Constructed File Name -> {}" , fileName); File file = new File(fileName); file.createNewFile(); OutputStream fileOut = new FileOutputStream(file, false); diff --git a/src/main/java/org/sunbird/user/service/UserUtilityService.java b/src/main/java/org/sunbird/user/service/UserUtilityService.java index 3e122949..69f53c39 100644 --- a/src/main/java/org/sunbird/user/service/UserUtilityService.java +++ b/src/main/java/org/sunbird/user/service/UserUtilityService.java @@ -20,7 +20,7 @@ public interface UserUtilityService { Map updateLogin(LastLoginInfo userLoginInfo); - Map getUsersReadData(String userId, String authToken, String X_authToken); + Map getUsersReadData(String userId, String authToken, String xauthToken); boolean createUser(UserRegistration userRegistration); diff --git a/src/main/java/org/sunbird/user/service/UserUtilityServiceImpl.java b/src/main/java/org/sunbird/user/service/UserUtilityServiceImpl.java index 54d64152..16dc1ce3 100644 --- a/src/main/java/org/sunbird/user/service/UserUtilityServiceImpl.java +++ b/src/main/java/org/sunbird/user/service/UserUtilityServiceImpl.java @@ -7,7 +7,6 @@ import java.util.Map.Entry; import com.fasterxml.jackson.databind.JsonNode; -import com.jcraft.jsch.UserInfo; import org.apache.commons.collections.MapUtils; import org.apache.commons.lang.StringUtils; import org.apache.velocity.VelocityContext; @@ -103,12 +102,11 @@ public boolean validateUser(String rootOrg, String userId) { SunbirdApiResp sunbirdApiResp = restTemplate.postForObject(serverUrl, requestEnty, SunbirdApiResp.class); - boolean expression = (sunbirdApiResp != null && "OK".equalsIgnoreCase(sunbirdApiResp.getResponseCode()) + return (sunbirdApiResp != null && "OK".equalsIgnoreCase(sunbirdApiResp.getResponseCode()) && sunbirdApiResp.getResult().getResponse().getCount() >= 1); - return expression; } catch (Exception e) { - throw new ApplicationLogicError("Sunbird Service ERROR: ", e); + throw new ApplicationLogicError(Constants.SUNBIRD_SERVICE_ERROR, e); } } @@ -137,7 +135,7 @@ public Map getUsersDataFromUserIds(String rootOrg, List } } } catch (Exception e) { - throw new ApplicationLogicError("Sunbird Service ERROR: ", e); + throw new ApplicationLogicError(Constants.SUNBIRD_SERVICE_ERROR, e); } return result; @@ -149,16 +147,13 @@ public Map getUsersDataFromUserIds(List userIds, List filtersMap = new HashMap<>(); + filtersMap.put(Constants.USER_ID, userIds); SunbirdApiRequest requestObj = new SunbirdApiRequest(); Map reqMap = new HashMap<>(); - reqMap.put(Constants.FILTERS, new HashMap() { - { - put(Constants.USER_ID, userIds); - } - }); + reqMap.put(Constants.FILTERS, filtersMap); reqMap.put(Constants.FIELDS_CONSTANT, fields); requestObj.setRequest(reqMap); - try { String url = props.getSbUrl() + props.getUserSearchEndPoint(); HttpEntity requestEnty = new HttpEntity<>(requestObj, headers); @@ -174,7 +169,7 @@ public Map getUsersDataFromUserIds(List userIds, List updateLogin(LastLoginInfo userLoginInfo) { serverConfig.getUserUtilityTopic()); } } catch (Exception e) { - throw new ApplicationLogicError("Sunbird Service ERROR: ", e); + throw new ApplicationLogicError(Constants.SUNBIRD_SERVICE_ERROR, e); } response.put(userLoginInfo.getUserId(), Boolean.TRUE); return response; } @Override - public Map getUsersReadData(String userId, String authToken, String userAuthToken) { + public Map getUsersReadData(String userId, String authToken, String xauthToken) { Map header = new HashMap<>(); if (StringUtils.isNotEmpty(authToken)) { header.put(Constants.AUTH_TOKEN, authToken); } - if (StringUtils.isNotEmpty(userAuthToken)) { - header.put(Constants.X_AUTH_TOKEN, userAuthToken); + if (StringUtils.isNotEmpty(xauthToken)) { + header.put(Constants.X_AUTH_TOKEN, xauthToken); } Map readData = (Map) outboundRequestHandlerService .fetchUsingGetWithHeadersProfile(serverConfig.getSbUrl() + serverConfig.getLmsUserReadPath() + userId, @@ -227,7 +222,7 @@ public Map getUsersReadData(String userId, String authToken, Str public boolean createUser(UserRegistration userRegistration) { boolean retValue = false; Map request = new HashMap<>(); - Map requestBody = new HashMap(); + Map requestBody = new HashMap<>(); requestBody.put(Constants.EMAIL, userRegistration.getEmail()); requestBody.put(Constants.CHANNEL, userRegistration.getChannel()); requestBody.put(Constants.FIRSTNAME, userRegistration.getFirstName()); @@ -236,7 +231,7 @@ public boolean createUser(UserRegistration userRegistration) { requestBody.put(Constants.PHONE_VERIFIED, true); request.put(Constants.REQUEST, requestBody); try { - Map readData = (Map) outboundRequestHandlerService.fetchResultUsingPost( + Map readData = outboundRequestHandlerService.fetchResultUsingPost( props.getSbUrl() + props.getLmsUserCreatePath(), request, ProjectUtil.getDefaultHeaders()); if (Constants.OK.equalsIgnoreCase((String) readData.get(Constants.RESPONSE_CODE))) { Map result = (Map) readData.get(Constants.RESULT); @@ -261,20 +256,20 @@ public boolean createUser(UserRegistration userRegistration) { public boolean updateUser(UserRegistration userRegistration) { boolean retValue = false; Map request = new HashMap<>(); - Map requestBody = new HashMap(); + Map requestBody = new HashMap<>(); requestBody.put(Constants.USER_ID, userRegistration.getUserId()); - Map profileDetails = new HashMap(); + Map profileDetails = new HashMap<>(); profileDetails.put(Constants.MANDATORY_FIELDS_EXISTS, false); - Map employementDetails = new HashMap(); + Map employementDetails = new HashMap<>(); employementDetails.put(Constants.DEPARTMENTNAME, userRegistration.getOrgName()); profileDetails.put(Constants.EMPLOYMENTDETAILS, employementDetails); - Map personalDetails = new HashMap(); + Map personalDetails = new HashMap<>(); personalDetails.put(Constants.FIRSTNAME.toLowerCase(), userRegistration.getFirstName()); personalDetails.put(Constants.PRIMARY_EMAIL, userRegistration.getEmail()); personalDetails.put(Constants.MOBILE, userRegistration.getPhone()); personalDetails.put(Constants.PHONE_VERIFIED, true); profileDetails.put(Constants.PERSONAL_DETAILS, personalDetails); - Map professionDetailObj = new HashMap(); + Map professionDetailObj = new HashMap<>(); professionDetailObj.put(Constants.ORGANIZATION_TYPE, Constants.GOVERNMENT); if (StringUtils.isNotEmpty(userRegistration.getPosition())) { professionDetailObj.put(Constants.DESIGNATION, userRegistration.getPosition()); @@ -285,7 +280,7 @@ public boolean updateUser(UserRegistration userRegistration) { List> professionalDetailsList = new ArrayList>(); professionalDetailsList.add(professionDetailObj); profileDetails.put(Constants.PROFESSIONAL_DETAILS, professionalDetailsList); - Map additionalProperties = new HashMap(); + Map additionalProperties = new HashMap<>(); if (!StringUtils.isEmpty(userRegistration.getGroup())) { additionalProperties.put(Constants.GROUP, userRegistration.getGroup()); } @@ -301,7 +296,7 @@ public boolean updateUser(UserRegistration userRegistration) { profileDetails.put(Constants.ADDITIONAL_PROPERTIES, additionalProperties); requestBody.put(Constants.PROFILE_DETAILS, profileDetails); request.put(Constants.REQUEST, requestBody); - Map readData = (Map) outboundRequestHandlerService.fetchResultUsingPatch( + Map readData = outboundRequestHandlerService.fetchResultUsingPatch( props.getSbUrl() + props.getLmsUserUpdatePrivatePath(), request, ProjectUtil.getDefaultHeaders()); if (Constants.OK.equalsIgnoreCase((String) readData.get(Constants.RESPONSE_CODE))) { retValue = assignRole(userRegistration.getSbOrgId(), userRegistration.getUserId(), @@ -317,12 +312,12 @@ public boolean updateUser(UserRegistration userRegistration) { public boolean assignRole(String sbOrgId, String userId, String objectDetails) { boolean retValue = false; Map request = new HashMap<>(); - Map requestBody = new HashMap(); + Map requestBody = new HashMap<>(); requestBody.put(Constants.ORGANIZATION_ID, sbOrgId); requestBody.put(Constants.USER_ID, userId); requestBody.put(Constants.ROLES, Arrays.asList(Constants.PUBLIC)); request.put(Constants.REQUEST, requestBody); - Map readData = (Map) outboundRequestHandlerService.fetchResultUsingPost( + Map readData = outboundRequestHandlerService.fetchResultUsingPost( props.getSbUrl() + props.getSbAssignRolePath(), request, ProjectUtil.getDefaultHeaders()); if (Constants.OK.equalsIgnoreCase((String) readData.get(Constants.RESPONSE_CODE))) { retValue = true; @@ -335,7 +330,7 @@ public boolean assignRole(String sbOrgId, String userId, String objectDetails) { public boolean createNodeBBUser(UserRegistration userRegistration) { boolean retValue = false; Map request = new HashMap<>(); - Map requestBody = new HashMap(); + Map requestBody = new HashMap<>(); requestBody.put(Constants.USER_NAME.toLowerCase(), userRegistration.getUserName()); requestBody.put(Constants.IDENTIFIER, userRegistration.getUserId()); requestBody.put(Constants.USER_FULL_NAME.toLowerCase(), @@ -343,12 +338,6 @@ public boolean createNodeBBUser(UserRegistration userRegistration) { request.put(Constants.REQUEST, requestBody); retValue = getActivationLink(userRegistration); - /*Map readData = (Map) outboundRequestHandlerService.fetchResultUsingPost( - props.getDiscussionHubHost() + props.getDiscussionHubCreateUserPath(), request, - ProjectUtil.getDefaultHeaders()); - if (Constants.OK.equalsIgnoreCase((String) readData.get(Constants.RESPONSE_CODE))) { - retValue = getActivationLink(userRegistration); - }*/ printMethodExecutionResult("Create NodeBB User", userRegistration.toMininumString(), retValue); return retValue; } @@ -356,13 +345,13 @@ public boolean createNodeBBUser(UserRegistration userRegistration) { @Override public boolean getActivationLink(UserRegistration userRegistration) { boolean retValue = false; - Map request = new HashMap(); - Map requestBody = new HashMap(); + Map request = new HashMap<>(); + Map requestBody = new HashMap<>(); requestBody.put(Constants.USER_ID, userRegistration.getUserId()); requestBody.put(Constants.KEY, Constants.EMAIL); requestBody.put(Constants.TYPE, Constants.EMAIL); request.put(Constants.REQUEST, requestBody); - Map readData = (Map) outboundRequestHandlerService.fetchResultUsingPost( + Map readData = outboundRequestHandlerService.fetchResultUsingPost( props.getSbUrl() + props.getSbResetPasswordPath(), request, ProjectUtil.getDefaultHeaders()); if (Constants.OK.equalsIgnoreCase((String) readData.get(Constants.RESPONSE_CODE))) { Map result = (Map) readData.get(Constants.RESULT); @@ -377,7 +366,7 @@ public boolean getActivationLink(UserRegistration userRegistration) { public boolean sendWelcomeEmail(String activationLink, UserRegistration userRegistration) { boolean retValue = false; Map request = new HashMap<>(); - Map requestBody = new HashMap(); + Map requestBody = new HashMap<>(); requestBody.put(Constants.ALLOWED_LOGGING, "You can use your email to Login"); requestBody.put(Constants.BODY, Constants.HELLO); requestBody.put(Constants.EMAIL_TEMPLATE_TYPE, props.getWelcomeEmailTemplate()); @@ -396,7 +385,7 @@ public boolean sendWelcomeEmail(String activationLink, UserRegistration userRegi request.put(Constants.REQUEST, requestBody); - Map readData = (Map) outboundRequestHandlerService.fetchResultUsingPost( + Map readData = outboundRequestHandlerService.fetchResultUsingPost( props.getSbUrl() + props.getSbSendNotificationEmailPath(), request, ProjectUtil.getDefaultHeaders()); if (Constants.OK.equalsIgnoreCase((String) readData.get(Constants.RESPONSE_CODE))) { retValue = true; @@ -421,16 +410,13 @@ private void printMethodExecutionResult(String methodAction, String objectDetail @Override public Map> getUserDetails(List userIds, List fields) { // request body + Map filtersMap = new HashMap<>(); + filtersMap.put(Constants.USER_ID, userIds); SunbirdApiRequest requestObj = new SunbirdApiRequest(); Map reqMap = new HashMap<>(); - reqMap.put(Constants.FILTERS, new HashMap() { - { - put(Constants.USER_ID, userIds); - } - }); + reqMap.put(Constants.FILTERS, filtersMap); reqMap.put(Constants.FIELDS_CONSTANT, fields); requestObj.setRequest(reqMap); - try { String url = props.getSbUrl() + props.getUserSearchEndPoint(); Map apiResponse = outboundRequestHandlerService.fetchResultUsingPost(url, requestObj, null); @@ -485,7 +471,7 @@ public void getUserDetailsFromDB(List userIds, List fields, List> userInfoList = cassandraOperation .getRecordsByPropertiesWithoutFiltering(Constants.KEYSPACE_SUNBIRD, Constants.TABLE_USER, propertyMap, fields); for (Map user : userInfoList) { - Map userMap = new HashMap(); + Map userMap = new HashMap<>(); String userId = (String) user.get(Constants.USER_ID); if (userInfoMap.containsKey(userId)) { @@ -537,22 +523,17 @@ public void enrichUserInfo(List fields, Map> @Override public boolean isUserExist(String key, String value) { // request body + Map filtersMap = new HashMap<>(); + filtersMap.put(key, value); SunbirdApiRequest requestObj = new SunbirdApiRequest(); Map reqMap = new HashMap<>(); - reqMap.put(Constants.FILTERS, new HashMap() { - { - put(key, value); - } - }); + reqMap.put(Constants.FILTERS, filtersMap); requestObj.setRequest(reqMap); - HashMap headersValue = new HashMap<>(); headersValue.put(Constants.CONTENT_TYPE, "application/json"); headersValue.put(Constants.AUTHORIZATION, props.getSbApiKey()); - try { String url = props.getSbUrl() + props.getUserSearchEndPoint(); - Map response = outboundRequestHandlerService.fetchResultUsingPost(url, requestObj, headersValue); if (response != null && "OK".equalsIgnoreCase((String) response.get("responseCode"))) { @@ -567,20 +548,20 @@ public boolean isUserExist(String key, String value) { } } } catch (Exception e) { - throw new ApplicationLogicError("Sunbird Service ERROR: ", e); + throw new ApplicationLogicError(Constants.SUNBIRD_SERVICE_ERROR, e); } return true; } @Override public boolean validateGroup(String group) { - return (!CollectionUtils.isEmpty(serverConfig.getBulkUploadGroupValue())) ? serverConfig.getBulkUploadGroupValue().stream().anyMatch(group::equalsIgnoreCase) : false; + return (!CollectionUtils.isEmpty(serverConfig.getBulkUploadGroupValue())) ? serverConfig.getBulkUploadGroupValue().stream().anyMatch(group::equalsIgnoreCase) : Boolean.FALSE; } @Override public String createBulkUploadUser(UserRegistration userRegistration) { Map request = new HashMap<>(); - Map requestBody = new HashMap(); + Map requestBody = new HashMap<>(); requestBody.put(Constants.EMAIL, userRegistration.getEmail()); requestBody.put(Constants.CHANNEL, userRegistration.getChannel()); requestBody.put(Constants.FIRSTNAME, userRegistration.getFirstName()); @@ -590,7 +571,7 @@ public String createBulkUploadUser(UserRegistration userRegistration) { requestBody.put(Constants.ROLES, Arrays.asList(Constants.PUBLIC)); request.put(Constants.REQUEST, requestBody); try { - Map readData = (Map) outboundRequestHandlerService.fetchResultUsingPost( + Map readData = outboundRequestHandlerService.fetchResultUsingPost( props.getSbUrl() + props.getLmsUserCreatePath(), request, ProjectUtil.getDefaultHeaders()); if (readData != null && !Constants.OK.equalsIgnoreCase((String) readData.get(Constants.RESPONSE_CODE))) { Map params = (Map) readData.get(Constants.PARAMS); @@ -612,20 +593,20 @@ public String createBulkUploadUser(UserRegistration userRegistration) { @Override public String updateBulkUploadUser(UserRegistration userRegistration) { Map request = new HashMap<>(); - Map requestBody = new HashMap(); + Map requestBody = new HashMap<>(); requestBody.put(Constants.USER_ID, userRegistration.getUserId()); - Map profileDetails = new HashMap(); + Map profileDetails = new HashMap<>(); profileDetails.put(Constants.MANDATORY_FIELDS_EXISTS, false); - Map employementDetails = new HashMap(); + Map employementDetails = new HashMap<>(); employementDetails.put(Constants.DEPARTMENTNAME, userRegistration.getOrgName()); profileDetails.put(Constants.EMPLOYMENTDETAILS, employementDetails); - Map personalDetails = new HashMap(); + Map personalDetails = new HashMap<>(); personalDetails.put(Constants.FIRSTNAME.toLowerCase(), userRegistration.getFirstName()); personalDetails.put(Constants.PRIMARY_EMAIL, userRegistration.getEmail()); personalDetails.put(Constants.MOBILE, userRegistration.getPhone()); personalDetails.put(Constants.PHONE_VERIFIED, true); profileDetails.put(Constants.PERSONAL_DETAILS, personalDetails); - Map professionDetailObj = new HashMap(); + Map professionDetailObj = new HashMap<>(); professionDetailObj.put(Constants.ORGANIZATION_TYPE, Constants.GOVERNMENT); if (StringUtils.isNotEmpty(userRegistration.getPosition())) { professionDetailObj.put(Constants.DESIGNATION, userRegistration.getPosition()); @@ -636,7 +617,7 @@ public String updateBulkUploadUser(UserRegistration userRegistration) { List> professionalDetailsList = new ArrayList>(); professionalDetailsList.add(professionDetailObj); profileDetails.put(Constants.PROFESSIONAL_DETAILS, professionalDetailsList); - Map additionalProperties = new HashMap(); + Map additionalProperties = new HashMap<>(); if (!CollectionUtils.isEmpty(userRegistration.getTag())) { additionalProperties.put(Constants.TAG, userRegistration.getTag()); } @@ -651,7 +632,7 @@ public String updateBulkUploadUser(UserRegistration userRegistration) { profileDetails.put(Constants.MANDATORY_FIELDS_EXISTS, false); requestBody.put(Constants.PROFILE_DETAILS, profileDetails); request.put(Constants.REQUEST, requestBody); - Map readData = (Map) outboundRequestHandlerService.fetchResultUsingPatch( + Map readData = outboundRequestHandlerService.fetchResultUsingPatch( props.getSbUrl() + props.getLmsUserUpdatePrivatePath(), request, ProjectUtil.getDefaultHeaders()); if (readData != null && !Constants.OK.equalsIgnoreCase((String) readData.get(Constants.RESPONSE_CODE))) { Map params = (Map) readData.get(Constants.PARAMS); @@ -659,9 +640,8 @@ public String updateBulkUploadUser(UserRegistration userRegistration) { return (String) params.get(Constants.ERROR_MESSAGE); } } else if (readData != null && Constants.OK.equalsIgnoreCase((String) readData.get(Constants.RESPONSE_CODE))) { - // if (getActivationLink(userRegistration)) { return (String) readData.get(Constants.RESPONSE_CODE); - // } + } return Constants.BULK_USER_UPDATE_API_FAILED; } @@ -701,7 +681,7 @@ public Map> getUserDetailsFromES(List userId backupUserInfoMap.putAll(userInfoMap); resultArray.clear(); - index = (int) Math.min(userCount, index + size); + index = (int) Math.min(userCount,(long) index + size); if (index == userCount) { isCompleted = true; } @@ -719,12 +699,11 @@ private void processUserDetails(List> userMapList, Map> userInfoMap) throws IOException{ for (Map user : userMapList) { Map userInfo = new HashMap<>(); - userInfo.put(Constants.USER_ID, (String) user.get(Constants.USER_ID)); - userInfo.put(Constants.FIRSTNAME, (String) user.get(Constants.USER_FIRST_NAME)); - userInfo.put(Constants.ROOT_ORG_ID, (String) user.get(Constants.ROOT_ORG_ID)); - userInfo.put(Constants.CHANNEL, (String) user.get(Constants.CHANNEL)); - userInfo.put(Constants.DESIGNATION, (String) user.get(Constants.PROFILE_DETAILS_DESIGNATION)); - //userInfo.put(Constants.DEPARTMENTNAME, (String) user.get(Constants.EMPLOYMENT_DETAILS_DEPARTMENT_NAME)); + userInfo.put(Constants.USER_ID, user.get(Constants.USER_ID)); + userInfo.put(Constants.FIRSTNAME, user.get(Constants.USER_FIRST_NAME)); + userInfo.put(Constants.ROOT_ORG_ID, user.get(Constants.ROOT_ORG_ID)); + userInfo.put(Constants.CHANNEL, user.get(Constants.CHANNEL)); + userInfo.put(Constants.DESIGNATION, user.get(Constants.PROFILE_DETAILS_DESIGNATION)); JsonNode jsonNode = objectMapper.convertValue(user, JsonNode.class); JsonNode primaryEmailNode = jsonNode.at("/profileDetails/personalDetails/primaryEmail"); String primaryEmail = primaryEmailNode.asText(); @@ -748,11 +727,11 @@ public Map getUsersDataFromLookup(String email, String authToken header.put(Constants.AUTH_TOKEN, authToken); } Map request = new HashMap<>(); - Map requestBody = new HashMap(); + Map requestBody = new HashMap<>(); requestBody.put(Constants.KEY, Constants.EMAIL); requestBody.put(Constants.VALUE, email); request.put(Constants.REQUEST, requestBody); - Map readData = (Map) outboundRequestHandlerService.fetchResultUsingPost( + Map readData = outboundRequestHandlerService.fetchResultUsingPost( props.getSbUrl() + props.getLmsUserLookupPath(), request, ProjectUtil.getDefaultHeaders()); if (readData != null && Constants.OK.equalsIgnoreCase((String) readData.get(Constants.RESPONSE_CODE))) { Map result = (Map) readData.get(Constants.RESULT); @@ -850,7 +829,7 @@ public SBApiResponse recommendContent(String authUserToken, Map private String validateRequest(Map request, String userId) { StringBuffer str = new StringBuffer(); - List errList = new ArrayList(); + List errList = new ArrayList<>(); Map requestData = (Map) request.get(Constants.REQUEST); if (StringUtils.isBlank(userId)) { str.append(Constants.USER_ID_DOESNT_EXIST); @@ -939,7 +918,7 @@ private void sendNotification(Map request) { builder.append(props.getNotifyServiceHost()).append(props.getNotifyServicePathAsync()); try { Map response = outboundRequestHandlerService.fetchResultUsingPost(builder.toString(), request, null); - logger.debug("The email notification is successfully sent, response is: " + response); + logger.debug("The email notification is successfully sent, response is: {}" , response); } catch (Exception e) { logger.error("Exception while posting the data in notification service: ", e); } diff --git a/src/main/java/org/sunbird/workallocation/controller/AllocationController.java b/src/main/java/org/sunbird/workallocation/controller/AllocationController.java index 466ecdb8..36ae31fc 100644 --- a/src/main/java/org/sunbird/workallocation/controller/AllocationController.java +++ b/src/main/java/org/sunbird/workallocation/controller/AllocationController.java @@ -66,8 +66,6 @@ public ResponseEntity getWAPdf(@PathVariable("userId") String userId, @PathVa headers.setContentType(MediaType.APPLICATION_PDF); headers.add("Content-Disposition", "inline; filename=wa_report.pdf"); - ResponseEntity response = new ResponseEntity<>(out, headers, HttpStatus.OK); - - return response; + return new ResponseEntity<>(out, headers, HttpStatus.OK); } } diff --git a/src/main/java/org/sunbird/workallocation/controller/PdfGeneratorController.java b/src/main/java/org/sunbird/workallocation/controller/PdfGeneratorController.java index 3690ebde..cbbc9cf3 100644 --- a/src/main/java/org/sunbird/workallocation/controller/PdfGeneratorController.java +++ b/src/main/java/org/sunbird/workallocation/controller/PdfGeneratorController.java @@ -38,8 +38,7 @@ public ResponseEntity getWAPdf(@PathVariable("woId") String woId) headers.setContentType(MediaType.APPLICATION_PDF); headers.add("Content-Disposition", "inline; filename=wo_report.pdf"); - ResponseEntity response = new ResponseEntity<>(out, headers, HttpStatus.OK); - return response; + return new ResponseEntity<>(out, headers, HttpStatus.OK); } @GetMapping(value = "/getWOPublishedPdf/{woId}") diff --git a/src/main/java/org/sunbird/workallocation/model/CompetencyDetails.java b/src/main/java/org/sunbird/workallocation/model/CompetencyDetails.java index d20df8d9..c1a60658 100644 --- a/src/main/java/org/sunbird/workallocation/model/CompetencyDetails.java +++ b/src/main/java/org/sunbird/workallocation/model/CompetencyDetails.java @@ -3,9 +3,6 @@ import java.util.ArrayList; import java.util.List; import java.util.Objects; -import java.util.Set; -import java.util.stream.Collectors; - import org.springframework.util.CollectionUtils; import org.springframework.util.StringUtils; @@ -130,24 +127,6 @@ public FracRequest getFracRequest(String source, Child child) { } } } - -// if (req.getChildren() != null && req.getChildren().size() < 5) { -// Set levelSet = children.stream().map(Child::getLevel).collect(Collectors.toSet()); -// // We need to add more children -// for (int i = 1; i <= 5; i++) { -// String level = "Level " + i; -// if(levelSet.contains(level)) { -// continue; -// } -// ChildNode newCN = new ChildNode(); -// newCN.setLevel(level); -// newCN.setName(level); -// newCN.setType("COMPETENCIESLEVEL"); -// newCN.setSource(source); -// childNodeList.add(newCN); -// } -// } - req.setChildren(childNodeList); return req; diff --git a/src/main/java/org/sunbird/workallocation/model/UserBasicInfo.java b/src/main/java/org/sunbird/workallocation/model/UserBasicInfo.java index 1caf602b..69d8c121 100644 --- a/src/main/java/org/sunbird/workallocation/model/UserBasicInfo.java +++ b/src/main/java/org/sunbird/workallocation/model/UserBasicInfo.java @@ -5,9 +5,9 @@ @JsonIgnoreProperties(ignoreUnknown = true) public class UserBasicInfo { private String wid; - private String department_name; - private String last_name; - private String first_name; + private String departmentName; + private String lastName; + private String firstName; private String email; private String designation; @@ -19,28 +19,28 @@ public void setWid(String wid) { this.wid = wid; } - public String getDepartment_name() { - return department_name; + public String getDepartmentName() { + return departmentName; } - public void setDepartment_name(String department_name) { - this.department_name = department_name; + public void setDepartmentName(String departmentName) { + this.departmentName = departmentName; } - public String getLast_name() { - return last_name; + public String getLastName() { + return lastName; } - public void setLast_name(String last_name) { - this.last_name = last_name; + public void setLastName(String lastName) { + this.lastName = lastName; } - public String getFirst_name() { - return first_name; + public String getFirstName() { + return firstName; } - public void setFirst_name(String first_name) { - this.first_name = first_name; + public void setFirstName(String firstName) { + this.firstName = firstName; } public String getEmail() { diff --git a/src/main/java/org/sunbird/workallocation/model/telemetryEvent/Event.java b/src/main/java/org/sunbird/workallocation/model/telemetryEvent/Event.java index 496be4bf..6754ed2d 100644 --- a/src/main/java/org/sunbird/workallocation/model/telemetryEvent/Event.java +++ b/src/main/java/org/sunbird/workallocation/model/telemetryEvent/Event.java @@ -1,6 +1,5 @@ package org.sunbird.workallocation.model.telemetryEvent; -import com.fasterxml.jackson.annotation.JsonProperty; import java.util.Map; diff --git a/src/main/java/org/sunbird/workallocation/model/telemetryEvent/Flags.java b/src/main/java/org/sunbird/workallocation/model/telemetryEvent/Flags.java index ee428a73..a16010e5 100644 --- a/src/main/java/org/sunbird/workallocation/model/telemetryEvent/Flags.java +++ b/src/main/java/org/sunbird/workallocation/model/telemetryEvent/Flags.java @@ -1,22 +1,22 @@ package org.sunbird.workallocation.model.telemetryEvent; public class Flags { - private boolean pp_duplicate_skipped; - private boolean pp_validation_processed; + private boolean ppDuplicateSkipped; + private boolean ppValidationProcessed; - public boolean isPp_duplicate_skipped() { - return pp_duplicate_skipped; + public boolean isPpDuplicateSkipped() { + return ppDuplicateSkipped; } - public void setPp_duplicate_skipped(boolean pp_duplicate_skipped) { - this.pp_duplicate_skipped = pp_duplicate_skipped; + public void setPpDuplicateSkipped(boolean ppDuplicateSkipped) { + this.ppDuplicateSkipped = ppDuplicateSkipped; } - public boolean isPp_validation_processed() { - return pp_validation_processed; + public boolean isPpValidationProcessed() { + return ppValidationProcessed; } - public void setPp_validation_processed(boolean pp_validation_processed) { - this.pp_validation_processed = pp_validation_processed; + public void setPpValidationProcessed(boolean ppValidationProcessed) { + this.ppValidationProcessed = ppValidationProcessed; } } diff --git a/src/main/java/org/sunbird/workallocation/service/AllocationServiceV2.java b/src/main/java/org/sunbird/workallocation/service/AllocationServiceV2.java index 8508d72a..e6553607 100644 --- a/src/main/java/org/sunbird/workallocation/service/AllocationServiceV2.java +++ b/src/main/java/org/sunbird/workallocation/service/AllocationServiceV2.java @@ -146,10 +146,10 @@ public Response addWorkOrder(String userId, WorkOrderDTO workOrder) { response.put(Constants.MESSAGE, Constants.FAILED); } HashMap watEventData = new HashMap<>(); - watEventData.put("workorderId", workOrder.getId()); + watEventData.put(Constants.WORKORDER_ID, workOrder.getId()); producer.push(cbExtServerProperties.getKafkaTopicWatEvent(), watEventData); HashMap data = new HashMap<>(); - data.put("id", workOrder.getId()); + data.put(Constants.ID, workOrder.getId()); response.put(Constants.DATA, data); response.put(Constants.STATUS, HttpStatus.OK); return response; @@ -190,7 +190,7 @@ public Response updateWorkOrder(String userId, WorkOrderDTO workOrder, String xA throw new ApplicationLogicError("Exception occurred while updating the work order", ex); } HashMap watEventData = new HashMap<>(); - watEventData.put("workorderId", workOrder.getId()); + watEventData.put(Constants.WORKORDER_ID, workOrder.getId()); producer.push(cbExtServerProperties.getKafkaTopicWatEvent(), watEventData); Response response = new Response(); if (!ObjectUtils.isEmpty(restStatus)) { @@ -254,11 +254,11 @@ public Response addWorkAllocation(String authUserToken, String userId, WorkAlloc indexerService.updateEntity(workOrderIndex, workOrderIndexType, workOrder.getId(), mapper.convertValue(workOrder, Map.class)); } catch (Exception ex) { - logger.error("Exception occurred while saving the work allocation!!", ex); - throw new ApplicationLogicError("Exception occurred while saving the work allocation!!", ex); + logger.error(Constants.WORK_ALLOCATION_SAVE_EXCEPTION, ex); + throw new ApplicationLogicError(Constants.WORK_ALLOCATION_SAVE_EXCEPTION, ex); } HashMap watEventData = new HashMap<>(); - watEventData.put("workorderId", workAllocationDTO.getWorkOrderId()); + watEventData.put(Constants.WORKORDER_ID, workAllocationDTO.getWorkOrderId()); producer.push(cbExtServerProperties.getKafkaTopicWatEvent(), watEventData); Response response = new Response(); if (!ObjectUtils.isEmpty(restStatus)) { @@ -319,11 +319,11 @@ public Response updateWorkAllocation(String authUserToken, String userId, WorkAl indexerService.updateEntity(workOrderIndex, workOrderIndexType, workOrder.getId(), mapper.convertValue(workOrder, Map.class)); } catch (Exception ex) { - logger.error("Exception occurred while saving the work allocation!!", ex); - throw new ApplicationLogicError("Exception occurred while saving the work allocation!!", ex); + logger.error(Constants.WORK_ALLOCATION_SAVE_EXCEPTION, ex); + throw new ApplicationLogicError(Constants.WORK_ALLOCATION_SAVE_EXCEPTION, ex); } HashMap watEventData = new HashMap<>(); - watEventData.put("workorderId", workAllocationDTO.getWorkOrderId()); + watEventData.put(Constants.WORKORDER_ID, workAllocationDTO.getWorkOrderId()); producer.push(cbExtServerProperties.getKafkaTopicWatEvent(), watEventData); Response response = new Response(); if (!ObjectUtils.isEmpty(restStatus)) { @@ -528,7 +528,7 @@ public Response copyWorkOrder(String userId, WorkOrderDTO workOrderDTO) { RestStatus restStatus = null; if (!CollectionUtils.isEmpty(indexRequestList)) { cassandraOperation.insertBulkRecord(Constants.KEYSPACE_SUNBIRD, Constants.TABLE_WORK_ALLOCATION, cassandraModelList); - indexerService.BulkInsert(indexRequestList); + indexerService.bulkInsert(indexRequestList); } workOrder.setUserIds(workAllocationIds); try { @@ -550,10 +550,10 @@ public Response copyWorkOrder(String userId, WorkOrderDTO workOrderDTO) { response.put(Constants.MESSAGE, Constants.FAILED); } HashMap watEventData = new HashMap<>(); - watEventData.put("workorderId", workOrder.getId()); + watEventData.put(Constants.WORKORDER_ID, workOrder.getId()); producer.push(cbExtServerProperties.getKafkaTopicWatEvent(), watEventData); HashMap data = new HashMap<>(); - data.put("id", workOrder.getId()); + data.put(Constants.ID, workOrder.getId()); response.put(Constants.DATA, data); response.put(Constants.STATUS, HttpStatus.OK); return response; @@ -662,13 +662,13 @@ private String createContentAndGetIdentifier(WorkOrderDTO workOrderDTO, String x Arrays.asList(cbExtServerProperties.getContentDefaultChannelId())); HashMap request = new HashMap<>(); HashMap contentReq = new HashMap<>(); - contentReq.put("content", contentCreateRequest); - request.put("request", contentReq); + contentReq.put(Constants.CONTENT, contentCreateRequest); + request.put(Constants.REQUEST, contentReq); HashMap headers = new HashMap<>(); - headers.put("x-channel-id", cbExtServerProperties.getContentDefaultChannelId()); - headers.put("X-Authenticated-User-Token", xAuthUser); - headers.put("Authorization", cbExtServerProperties.getSbApiKey()); - headers.put("Content-Type", "application/json"); + headers.put(Constants.X_CHANNEL_ID, cbExtServerProperties.getContentDefaultChannelId()); + headers.put(Constants.X_AUTHENTICATED_USER_TOKEN, xAuthUser); + headers.put(Constants.AUTH_TOKEN, cbExtServerProperties.getSbApiKey()); + headers.put(Constants.CONTENT_TYPE, Constants.APPLICATION_JSON); Map response = outboundRequestHandlerService.fetchResultUsingPost( cbExtServerProperties.getContentHost().concat(cbExtServerProperties.getContentCreateEndPoint()), request, headers); @@ -680,12 +680,12 @@ private String createContentAndGetIdentifier(WorkOrderDTO workOrderDTO, String x private String uploadPdfAndgetArtifactURL(String identifier, String xAuthUser, String filePath) { String downloadableLink = null; HttpHeaders headers = new HttpHeaders(); - headers.set("X-Authenticated-User-Token", xAuthUser); - headers.set("Authorization", cbExtServerProperties.getSbApiKey()); + headers.set(Constants.X_AUTHENTICATED_USER_TOKEN, xAuthUser); + headers.set(Constants.AUTH_TOKEN, cbExtServerProperties.getSbApiKey()); headers.setContentType(MediaType.MULTIPART_FORM_DATA); MultiValueMap body = new LinkedMultiValueMap<>(); FileSystemResource resource = new FileSystemResource(filePath); - body.add("data", resource); + body.add(Constants.DATA, resource); HttpEntity> requestEntity = new HttpEntity<>(body, headers); String uploadURL = cbExtServerProperties.getContentUploadEndPoint().replace("{identifier}", identifier); ResponseEntity response = restTemplate @@ -696,19 +696,19 @@ private String uploadPdfAndgetArtifactURL(String identifier, String xAuthUser, S return downloadableLink; } - public HashMap getUsersResult(Set userIds) { + public Map getUsersResult(Set userIds) { HashMap userResult = new HashMap<>(); Map request = getSearchObject(userIds); Map record; HashMap headersValue = new HashMap<>(); - headersValue.put("Content-Type", "application/json"); + headersValue.put(Constants.CONTENT_TYPE, Constants.APPLICATION_JSON); try { StringBuilder builder = new StringBuilder(); builder.append(cbExtServerProperties.getSbUrl()).append(cbExtServerProperties.getUserSearchEndPoint()); Map profileResponse = outboundRequestHandlerService.fetchResultUsingPost(builder.toString(), request, headersValue); if (profileResponse != null && "OK".equalsIgnoreCase((String) profileResponse.get("responseCode"))) { - Map map = (Map) profileResponse.get("result"); + Map map = (Map) profileResponse.get(Constants.RESULT); if (map.get("response") != null) { Map profiles = (Map) map.get("response"); List> userProfiles = (List>) profiles.get("content"); diff --git a/src/main/java/org/sunbird/workallocation/service/EnrichmentService.java b/src/main/java/org/sunbird/workallocation/service/EnrichmentService.java index f1eb045f..b68e5e35 100644 --- a/src/main/java/org/sunbird/workallocation/service/EnrichmentService.java +++ b/src/main/java/org/sunbird/workallocation/service/EnrichmentService.java @@ -78,12 +78,12 @@ private void enrichUserNamesToWorkOrder(WorkOrderDTO workOrderDTO) { logger.info("user Map : {}", mapper.writeValueAsString(usersMap)); if (StringUtils.isEmpty(workOrderDTO.getCreatedByName()) && !ObjectUtils.isEmpty(usersMap.get(workOrderDTO.getCreatedBy()))) { UserBasicInfo userBasicInfo = mapper.convertValue(usersMap.get(workOrderDTO.getCreatedBy()), UserBasicInfo.class); - String firstName = userBasicInfo.getFirst_name() == null ? "" : userBasicInfo.getFirst_name(); + String firstName = userBasicInfo.getFirstName() == null ? "" : userBasicInfo.getFirstName(); workOrderDTO.setCreatedByName(firstName); } if (!ObjectUtils.isEmpty(usersMap.get(workOrderDTO.getUpdatedBy()))) { UserBasicInfo userBasicInfo = mapper.convertValue(usersMap.get(workOrderDTO.getUpdatedBy()), UserBasicInfo.class); - String firstName = userBasicInfo.getFirst_name() == null ? "" : userBasicInfo.getFirst_name(); + String firstName = userBasicInfo.getFirstName() == null ? "" : userBasicInfo.getFirstName(); workOrderDTO.setUpdatedByName(firstName); } } catch (IOException e) { @@ -101,12 +101,12 @@ private void enrichUserNamesToWorkAllocation(WorkAllocationDTOV2 workAllocationD Map usersMap = allocationServiceV2.getUsersResult(userIds); if (StringUtils.isEmpty(workAllocationDTOV2.getCreatedByName()) && !ObjectUtils.isEmpty(usersMap.get(workAllocationDTOV2.getCreatedBy()))) { UserBasicInfo userBasicInfo = mapper.convertValue(usersMap.get(workAllocationDTOV2.getCreatedBy()), UserBasicInfo.class); - String firstName = userBasicInfo.getFirst_name() == null ? "" : userBasicInfo.getFirst_name(); + String firstName = userBasicInfo.getFirstName() == null ? "" : userBasicInfo.getFirstName(); workAllocationDTOV2.setCreatedByName(firstName); } if (!ObjectUtils.isEmpty(usersMap.get(workAllocationDTOV2.getUpdatedBy()))) { UserBasicInfo userBasicInfo = mapper.convertValue(usersMap.get(workAllocationDTOV2.getUpdatedBy()), UserBasicInfo.class); - String firstName = userBasicInfo.getFirst_name() == null ? "" : userBasicInfo.getFirst_name(); + String firstName = userBasicInfo.getFirstName() == null ? "" : userBasicInfo.getFirstName(); workAllocationDTOV2.setUpdatedByName(firstName); } } catch (Exception e) { diff --git a/src/main/java/org/sunbird/workallocation/service/PdfGeneratorServiceImpl.java b/src/main/java/org/sunbird/workallocation/service/PdfGeneratorServiceImpl.java index 547d0169..6b30abc2 100644 --- a/src/main/java/org/sunbird/workallocation/service/PdfGeneratorServiceImpl.java +++ b/src/main/java/org/sunbird/workallocation/service/PdfGeneratorServiceImpl.java @@ -29,6 +29,7 @@ import java.io.*; import java.text.SimpleDateFormat; import java.util.*; +import java.util.regex.Pattern; @Service public class PdfGeneratorServiceImpl implements PdfGeneratorService { @@ -83,7 +84,7 @@ public byte[] generatePdf(PdfGeneratorRequest request) throws Exception { } String footerTemplateName = "templates/pdf-draft-footer.html"; Map headerDetails = new HashMap<>(); - String deptId = (String) request.getTagValuePair().get("deptId"); + String deptId = (String) request.getTagValuePair().get(Constants.DEPT_ID); headerDetails.put(DEPT_NAME, request.getTagValuePair().get(DEPT_NAME)); headerDetails.put(DEPT_IMG_URL, request.getTagValuePair().get(DEPT_IMG_URL)); String headerMessage = readVm("pdf-header.vm", headerDetails); @@ -163,12 +164,12 @@ private String getPDFFilePath(String woId) throws Exception { workOrder.put("printedTime", printedTime); String status = (String) workOrder.get("status"); String deptId = ""; - if(workOrder.get("deptId") instanceof Integer){ - deptId = String.valueOf(workOrder.get("deptId")); + if(workOrder.get(Constants.DEPT_ID) instanceof Integer){ + deptId = String.valueOf(workOrder.get(Constants.DEPT_ID)); } - else if(workOrder.get("deptId") instanceof String) + else if(workOrder.get(Constants.DEPT_ID) instanceof String) { - deptId = (String)workOrder.get("deptId"); + deptId = (String)workOrder.get(Constants.DEPT_ID); } String templateName = null; String footerTemplateName = null; @@ -205,7 +206,6 @@ else if(workOrder.get("deptId") instanceof String) log.error("Exception occurred while loading the default department logo"); } headerDetails.put(DEPT_NAME, workOrder.get(DEPT_NAME)); -// headerDetails.put("deptImgUrl", (String) workOrder.get("deptImgUrl")); String headerMessage = readVm("pdf-header.vm", headerDetails); String headerHtmlFilePath = createHTMLFile("pdf-header", headerMessage); @@ -254,10 +254,10 @@ public String createHTMLFile(String fName, String htmlContent) throws IOExceptio theDir.mkdirs(); } if (htmlContent.contains("‘")) { - htmlContent = htmlContent.replaceAll("‘", "'"); + htmlContent = Pattern.compile("‘", Pattern.CANON_EQ).matcher(htmlContent).replaceAll("'"); } if (htmlContent.contains("’")) { - htmlContent = htmlContent.replaceAll("’", "'"); + htmlContent = Pattern.compile("’", Pattern.CANON_EQ).matcher(htmlContent).replaceAll("'"); } BufferedWriter out = null; try (FileWriter fstream = new FileWriter(htmlFilePath)){ @@ -362,7 +362,8 @@ public String makePdf(Map paramMap) throws IOException { log.info("Writing the pdf file {}", line); } } catch (IOException e) { - log.error("Exception occurred while writing the pdf file {}", e); + log.error("Exception occurred while writing the pdf file", e); + } finally { if (brCleanUp != null) { brCleanUp.close(); @@ -445,7 +446,7 @@ public String generateBatchSessionQRCode(String courseId,String batchId,String s File qrCodeFile = QRCode.from(qrCodeBody).to(ImageType.PNG).file(sessionId); return qrCodeFile.getAbsolutePath(); } - public byte[] generatePdf(HashMap> pdfDetails ,HashMap params ) throws IOException { + public byte[] generatePdf(Map> pdfDetails , Map params ) throws IOException { Map pdfData = new HashMap<>(); for (Map.Entry> pdf : pdfDetails.entrySet()) { String key = pdf.getKey(); @@ -463,16 +464,16 @@ public byte[] generatePdf(HashMap> pdfDetails ,Has pdfData.put(UD_HTML_HEADER_FILE_PATH,file); break; default: - String body =""; + StringBuilder body = new StringBuilder(); for (Map.Entry entry1 : params.entrySet()) { String key1 = entry1.getKey(); if (key1.startsWith(Constants.SESSION)) { - body= body+readVm(value.get(Constants.BUDGET_DOC_FILE_NAME)+ Constants.DOT_SEPARATOR+Constants.VM, params.get(key1)) ; + body.append(readVm(value.get(Constants.BUDGET_DOC_FILE_NAME) + Constants.DOT_SEPARATOR + Constants.VM, params.get(key1))); } } - body= createHTMLFile(key, body); - pdfData.put(UD_HTML_FILE_PATH, body); - pdfData.put(UD_FILE_NAME, body.replace(HTML, Constants.DOT_SEPARATOR+Constants.PDF)); + body = new StringBuilder(createHTMLFile(key, body.toString())); + pdfData.put(UD_HTML_FILE_PATH, body.toString()); + pdfData.put(UD_FILE_NAME, body.toString().replace(HTML, Constants.DOT_SEPARATOR+Constants.PDF)); break; } } @@ -489,7 +490,7 @@ public byte[] generatePdf(HashMap> pdfDetails ,Has } return bytes; } - public String generateHTMLfrmVM(String vmFName,HashMap params ) throws IOException { + public String generateHTMLfrmVM(String vmFName, Map params) throws IOException { String message = readVm(vmFName+ Constants.DOT_SEPARATOR+Constants.VM, params); return createHTMLFile(vmFName, message); } @@ -532,9 +533,8 @@ private Map fetchCourseName(String authUserToken,String courseId filters.put(Constants.IDENTIFIER, courseId); req.put(Constants.FILTERS, filters); reqBody.put(Constants.REQUEST, req); - Map compositeSearchRes = outboundRequestHandlerService.fetchResultUsingPost( + return outboundRequestHandlerService.fetchResultUsingPost( serverProperties.getKmBaseHost() + serverProperties.getKmCompositeSearchPath(), reqBody, headers); - return compositeSearchRes; } } diff --git a/src/main/java/org/sunbird/workallocation/service/WATConsumer.java b/src/main/java/org/sunbird/workallocation/service/WATConsumer.java index 9853456e..c8865f62 100644 --- a/src/main/java/org/sunbird/workallocation/service/WATConsumer.java +++ b/src/main/java/org/sunbird/workallocation/service/WATConsumer.java @@ -13,7 +13,6 @@ import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Value; import org.springframework.kafka.annotation.KafkaListener; -import org.springframework.kafka.annotation.TopicPartition; import org.springframework.stereotype.Service; import org.springframework.util.CollectionUtils; import org.springframework.util.StringUtils; @@ -70,7 +69,7 @@ public void processMessage(ConsumerRecord data) { Map workAllocationObj = mapper.readValue(String.valueOf(data.value()), Map.class); Map workOrderMap = new HashMap<>(); - workOrderMap.put(Constants.ID, (String) workAllocationObj.get("workorderId")); + workOrderMap.put(Constants.ID, workAllocationObj.get("workorderId")); List> workOrderCassandraModelOptional = cassandraOperation .getRecordsByProperties(Constants.KEYSPACE_SUNBIRD, Constants.TABLE_WORK_ORDER, workOrderMap, new ArrayList<>()); diff --git a/src/main/java/org/sunbird/workallocation/util/Validator.java b/src/main/java/org/sunbird/workallocation/util/Validator.java index 00c838c2..e08e4e27 100644 --- a/src/main/java/org/sunbird/workallocation/util/Validator.java +++ b/src/main/java/org/sunbird/workallocation/util/Validator.java @@ -12,8 +12,6 @@ import org.sunbird.workallocation.model.WorkAllocationDTOV2; import org.sunbird.workallocation.model.WorkOrderDTO; -import java.util.Arrays; -import java.util.List; import java.util.Map; @Component diff --git a/src/main/java/org/sunbird/workallocation/util/WorkAllocationConstants.java b/src/main/java/org/sunbird/workallocation/util/WorkAllocationConstants.java index 86d7131a..845385f0 100644 --- a/src/main/java/org/sunbird/workallocation/util/WorkAllocationConstants.java +++ b/src/main/java/org/sunbird/workallocation/util/WorkAllocationConstants.java @@ -1,11 +1,11 @@ package org.sunbird.workallocation.util; -import java.util.ArrayList; import java.util.Arrays; import java.util.Collections; import java.util.List; public class WorkAllocationConstants { + private WorkAllocationConstants() {} public static final String ALLOCATION_DETAILS = "allocationDetails"; public static final String USER_DETAILS = "userDetails"; @@ -39,10 +39,9 @@ public class WorkAllocationConstants { public static final String CB_NAME = "CB"; - public static final String TYPE = "WorkOrder"; - public static List PROPS = Collections.unmodifiableList(Arrays.asList("WAT")); + public static final List PROPS = Collections.unmodifiableList(Arrays.asList("WAT")); }