diff --git a/src/main/java/org/sunbird/calendar/service/CalendarBulkUploadServiceImpl.java b/src/main/java/org/sunbird/calendar/service/CalendarBulkUploadServiceImpl.java index e7cabbd99..ab21a230d 100644 --- a/src/main/java/org/sunbird/calendar/service/CalendarBulkUploadServiceImpl.java +++ b/src/main/java/org/sunbird/calendar/service/CalendarBulkUploadServiceImpl.java @@ -452,8 +452,7 @@ private void processBulkUpload(HashMap inputDataMap) throws IOEx wb.close(); if (fis != null) fis.close(); - if (file != null) - file.delete(); + ProjectUtil.deleteFileSafely(file); } } diff --git a/src/main/java/org/sunbird/common/util/Constants.java b/src/main/java/org/sunbird/common/util/Constants.java index d93ca60e0..ad33d0158 100644 --- a/src/main/java/org/sunbird/common/util/Constants.java +++ b/src/main/java/org/sunbird/common/util/Constants.java @@ -1315,8 +1315,11 @@ public class Constants { public static final String QR_LOGO_PATH = "qrCodeLogoPath"; public static final String ENABLED = "enabled"; public static final String INVALID_GROUP_MESSAGE = "Invalid Group : Group can be only among one of these "; - public static final String API_COURSE_RECOMMENDATIONS ="api.insights.get.courses.recommendations.designation"; + public static final String API_COURSE_RECOMMENDATIONS ="api.insights.get.courses.recommendations.designation"; public static final String COURSE_LIST ="courseList"; + public static final String REGEX_NAME_VALIDATION = "^(?!.*\\n)[a-zA-Z]+(?:['\\s][a-zA-Z]+)*(? 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); - } - }); + + Map> requestMap = new HashMap<>(); + requestMap.put(Constants.NOTIFICATIONS, notificationTosend); + notificationRequest.put(Constants.REQUEST, requestMap); logger.debug(String.format("Notification Request : %s", notificationRequest)); HttpEntity req = new HttpEntity<>(notificationRequest, headers); restTemplate.postForEntity(notificationUrl, req, String.class); @@ -58,11 +57,11 @@ 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 requestMap = new HashMap<>(); + requestMap.put(Constants.NOTIFICATIONS, notifications); + notificationRequest.put(Constants.REQUEST, requestMap); + HttpEntity req = new HttpEntity<>(notificationRequest, headers); logger.info(String.format("Notification Request : %s", notificationRequest)); diff --git a/src/main/java/org/sunbird/common/util/ProjectUtil.java b/src/main/java/org/sunbird/common/util/ProjectUtil.java index bb5c964e6..32c10e4c3 100644 --- a/src/main/java/org/sunbird/common/util/ProjectUtil.java +++ b/src/main/java/org/sunbird/common/util/ProjectUtil.java @@ -1,7 +1,12 @@ package org.sunbird.common.util; +import java.io.File; +import java.io.IOException; import java.io.UnsupportedEncodingException; import java.net.URLDecoder; +import java.nio.file.Files; +import java.nio.file.Path; +import java.nio.file.Paths; import java.text.ParseException; import java.text.SimpleDateFormat; import java.util.*; @@ -134,7 +139,7 @@ public static Boolean validateContactPattern(String contactNumber) { } public static Boolean validateFullName(String firstName) { - return firstName.matches("^(?!.*\\n)[a-zA-Z]+(?:['\\s][a-zA-Z]+)*(? tags) { @@ -214,4 +219,20 @@ public static Boolean validatePinCode(String regex) { public static Boolean validatesNewLine(String value) { return value.matches(".*\\n.*"); } + + /** + * Safely deletes a file. + * + * @param file The file to be deleted. + */ + public static void deleteFileSafely(File file) { + if (file != null && file.exists()) { + Path path = Paths.get(file.getAbsolutePath()); + try { + Files.delete(path); + } catch (IOException e) { + logger.warn("Failed to delete file: {}", path, e); + } + } + } } \ No newline at end of file diff --git a/src/main/java/org/sunbird/consumer/KafkaConsumer.java b/src/main/java/org/sunbird/consumer/KafkaConsumer.java index cc9223b4c..c8f2e366d 100644 --- a/src/main/java/org/sunbird/consumer/KafkaConsumer.java +++ b/src/main/java/org/sunbird/consumer/KafkaConsumer.java @@ -20,6 +20,7 @@ import org.sunbird.common.model.SBApiResponse; import org.sunbird.common.util.CbExtServerProperties; import org.sunbird.common.util.Constants; +import org.sunbird.common.util.ProjectUtil; import org.sunbird.consumer.security.EncryptionService; import org.sunbird.storage.service.StorageService; @@ -143,7 +144,7 @@ private String publicUserCertificateDownload(String certificateid) { throw new RuntimeException(e); } finally { if (mFile != null) - mFile.delete(); + ProjectUtil.deleteFileSafely(mFile); } } @@ -183,12 +184,15 @@ private String callCertRegistryApi(String certificateid) { entity, JsonNode.class ); - if (response.getStatusCode().is2xxSuccessful()) { - String printUri = response.getBody().path("result").get("printUri").asText(); - return printUri; - } else { - throw new RuntimeException("Failed to retrieve externalId. Status code: " + response.getStatusCodeValue()); + JsonNode responseBody = response.getBody(); + if (response.getStatusCode().is2xxSuccessful() && responseBody != null) { + JsonNode resultNode = responseBody.path("result"); + if (resultNode != null && resultNode.has(Constants.PRINT_URI)) { + return resultNode.get(Constants.PRINT_URI).asText(); + } } + throw new RuntimeException("Failed to retrieve externalId. Status code: " + response.getStatusCodeValue()); + } catch (Exception e) { throw new RuntimeException(e); } diff --git a/src/main/java/org/sunbird/core/logger/CbExtLogger.java b/src/main/java/org/sunbird/core/logger/CbExtLogger.java index c091aa8a9..4a09af9c1 100644 --- a/src/main/java/org/sunbird/core/logger/CbExtLogger.java +++ b/src/main/java/org/sunbird/core/logger/CbExtLogger.java @@ -93,4 +93,12 @@ public boolean isInfoEnabled() { public boolean isTraceEnabled() { return isTraceEnabled; } + + public void warn(String message, Object... params) { + if (params != null && params.length > 0) { + logger.log(Level.WARN, message, params); + } else { + logger.log(Level.WARN, message); + } + } } \ No newline at end of file diff --git a/src/main/java/org/sunbird/migrate/service/impl/UserMigrationServiceImpl.java b/src/main/java/org/sunbird/migrate/service/impl/UserMigrationServiceImpl.java index 02efbf1b7..e3254e85e 100644 --- a/src/main/java/org/sunbird/migrate/service/impl/UserMigrationServiceImpl.java +++ b/src/main/java/org/sunbird/migrate/service/impl/UserMigrationServiceImpl.java @@ -87,14 +87,15 @@ public SBApiResponse migrateUsers() { log.info("userPatchResponse for user ID '{}'.", userPatchResponse); if (userPatchResponse.getResponseCode().is2xxSuccessful()) { log.info("Successfully patched user ID '{}'. Response: {}", userId, userPatchResponse); - Map requestBody = new HashMap() {{ - put(Constants.ORGANIZATION_ID, custodianOrgId); - put(Constants.USER_ID, userId); - put(Constants.ROLES, Arrays.asList(Constants.PUBLIC)); - }}; - Map roleRequest = new HashMap() {{ - put("request", requestBody); - }}; + + Map requestBody = new HashMap<>(); + requestBody.put(Constants.ORGANIZATION_ID, custodianOrgId); + requestBody.put(Constants.USER_ID, userId); + requestBody.put(Constants.ROLES, Arrays.asList(Constants.PUBLIC)); + + Map roleRequest = new HashMap<>(); + roleRequest.put("request", requestBody); + StringBuilder assignRoleUrl = new StringBuilder(serverConfig.getSbUrl()).append(serverConfig.getSbAssignRolePath()); log.info("printing assignRoleUrl: {}", assignRoleUrl); Map assignRole = outboundRequestHandlerService.fetchResultUsingPost(assignRoleUrl.toString(), roleRequest, null); @@ -207,22 +208,16 @@ private Map userSearchRequestBody(int offset, int limit) { } 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; } @@ -250,9 +245,8 @@ private Map getUserExtPatchRequest(String userId, String default requestBody.put("userId", userId); requestBody.put("profileDetails", newProfileDetails); - return new HashMap() {{ - put("request", requestBody); - }}; - + Map request = new HashMap<>(); + request.put("request", requestBody); + return request; } } diff --git a/src/main/java/org/sunbird/org/service/OrgDesignationCompetencyMappingServiceImpl.java b/src/main/java/org/sunbird/org/service/OrgDesignationCompetencyMappingServiceImpl.java index 7acc13b03..b24ee9477 100644 --- a/src/main/java/org/sunbird/org/service/OrgDesignationCompetencyMappingServiceImpl.java +++ b/src/main/java/org/sunbird/org/service/OrgDesignationCompetencyMappingServiceImpl.java @@ -78,8 +78,7 @@ public class OrgDesignationCompetencyMappingServiceImpl implements OrgDesignatio @Override public ResponseEntity bulkUploadOrganisationCompetencyMapping(String rootOrgId, String userAuthToken, String frameworkId) { - try { - Workbook workbook = new XSSFWorkbook(); + try (Workbook workbook = new XSSFWorkbook()){ // Create sheets with safe names Sheet yourWorkspaceSheet = workbook.createSheet(WorkbookUtil.createSafeSheetName(serverProperties.getBulkUploadCompetencyYourWorkSpaceName())); @@ -588,13 +587,8 @@ public ResponseEntity downloadFile(String fileName, String rootOrgId, logger.error("Failed to read the downloaded file: " + fileName + ", 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(); - } - } catch (Exception e1) { - } + ProjectUtil.deleteFileSafely(file); } } @@ -929,8 +923,7 @@ private void processBulkUpload(HashMap inputDataMap) throws Exce wb.close(); if (fis != null) fis.close(); - if (file != null) - file.delete(); + ProjectUtil.deleteFileSafely(file); } } diff --git a/src/main/java/org/sunbird/org/service/OrgDesignationMappingServiceImpl.java b/src/main/java/org/sunbird/org/service/OrgDesignationMappingServiceImpl.java index 56b041bf0..85e627984 100644 --- a/src/main/java/org/sunbird/org/service/OrgDesignationMappingServiceImpl.java +++ b/src/main/java/org/sunbird/org/service/OrgDesignationMappingServiceImpl.java @@ -90,8 +90,7 @@ public class OrgDesignationMappingServiceImpl implements OrgDesignationMappingSe */ @Override public ResponseEntity getSampleFileForOrgDesignationMapping(String rootOrgId, String userAuthToken, String frameworkId) { - try { - Workbook workbook = new XSSFWorkbook(); + try(Workbook workbook = new XSSFWorkbook()) { // Create sheets with safe names Sheet yourWorkspaceSheet = workbook.createSheet(WorkbookUtil.createSafeSheetName(serverProperties.getBulkUploadCompetencyYourWorkSpaceName())); @@ -483,13 +482,8 @@ public ResponseEntity downloadFile(String fileName, String rootOrgId, logger.error("Failed to read the downloaded file: " + fileName + ", 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(); - } - } catch (Exception e1) { - } + ProjectUtil.deleteFileSafely(file); } } @@ -809,7 +803,8 @@ private void processBulkUpload(HashMap inputDataMap) throws IOEx } updateOrgCompetencyDesignationMappingBulkUploadStatus(inputDataMap.get(Constants.ROOT_ORG_ID), inputDataMap.get(Constants.IDENTIFIER), status, totalNumberOfRecordInSheet, noOfSuccessfulRecords, failedRecordsCount); - } catch (Exception e) { + } catch (InterruptedException e) { + Thread.currentThread().interrupt(); logger.error(String.format("Error in Process Bulk Upload %s", e.getMessage()), e); updateOrgCompetencyDesignationMappingBulkUploadStatus(inputDataMap.get(Constants.ROOT_ORG_ID), inputDataMap.get(Constants.IDENTIFIER), Constants.FAILED_UPPERCASE, 0, 0, 0); @@ -818,8 +813,7 @@ private void processBulkUpload(HashMap inputDataMap) throws IOEx wb.close(); if (fis != null) fis.close(); - if (file != null) - file.delete(); + ProjectUtil.deleteFileSafely(file); } } 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 e3afc63c4..5bb4f47e9 100644 --- a/src/main/java/org/sunbird/portal/department/service/PortalServiceImpl.java +++ b/src/main/java/org/sunbird/portal/department/service/PortalServiceImpl.java @@ -44,26 +44,23 @@ public List getDeptNameList() { int count = 0; int iterateCount = 0; do { + Map filtersMap = new HashMap<>(); + filtersMap.put(Constants.IS_TENANT, Boolean.TRUE); + filtersMap.put(Constants.STATUS, 1); + // request body Map requestMap = new HashMap<>(); requestMap.put(Constants.OFFSET, iterateCount); 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); - } - }); + requestMap.put(Constants.FILTERS, filtersMap); String serviceURL = serverConfig.getSbUrl() + serverConfig.getSbOrgSearchPath(); + Map outboundRequestMap = new HashMap<>(); + outboundRequestMap.put(Constants.REQUEST, requestMap); SunbirdApiResp orgResponse = mapper.convertValue( - outboundRequestHandlerService.fetchResultUsingPost(serviceURL, new HashMap() { - { - put(Constants.REQUEST, requestMap); - } - }), SunbirdApiResp.class); + outboundRequestHandlerService.fetchResultUsingPost(serviceURL, outboundRequestMap), SunbirdApiResp.class); SunbirdApiResultResponse resultResp = orgResponse.getResult().getResponse(); count = resultResp.getCount(); @@ -107,26 +104,25 @@ public List> getDeptNameListByAdmin() { int count = 0; int iterateCount = 0; do { + + Map filtersMap = new HashMap<>(); + filtersMap.put(Constants.IS_TENANT, Boolean.TRUE); + filtersMap.put(Constants.STATUS, 1); + // request body Map requestMap = new HashMap<>(); requestMap.put(Constants.OFFSET, iterateCount); 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); - } - }); + requestMap.put(Constants.FILTERS, filtersMap); String serviceURL = serverConfig.getSbUrl() + serverConfig.getSbOrgSearchPath(); + Map outboundRequestMap = new HashMap<>(); + outboundRequestMap.put(Constants.REQUEST, requestMap); + SunbirdApiResp orgResponse = mapper.convertValue( - outboundRequestHandlerService.fetchResultUsingPost(serviceURL, new HashMap() { - { - put(Constants.REQUEST, requestMap); - } - }), SunbirdApiResp.class); + outboundRequestHandlerService.fetchResultUsingPost(serviceURL, outboundRequestMap), SunbirdApiResp.class); SunbirdApiResultResponse resultResp = orgResponse.getResult().getResponse(); count = resultResp.getCount(); diff --git a/src/main/java/org/sunbird/profile/service/ProfileServiceImpl.java b/src/main/java/org/sunbird/profile/service/ProfileServiceImpl.java index d7c40a2a3..6c808b5fb 100644 --- a/src/main/java/org/sunbird/profile/service/ProfileServiceImpl.java +++ b/src/main/java/org/sunbird/profile/service/ProfileServiceImpl.java @@ -1189,22 +1189,16 @@ private Map getOrgCreateRequest(Map request) { } 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); + 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) { - put(Constants.FORCE_MIGRATION, true); + requestBody.put(Constants.FORCE_MIGRATION, true); } - } - }; - Map request = new HashMap() { - { - put(Constants.REQUEST, requestBody); - } - }; + Map request = new HashMap<>(); + request.put(Constants.REQUEST, requestBody); return request; } @@ -1284,13 +1278,10 @@ 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(); - profDetail.put(Constants.OSID, UUID.randomUUID().toString()); - add(profDetail); - } - }; + professionalDetails = new ArrayList<>(); + Map profDetail = new HashMap(); + profDetail.put(Constants.OSID, UUID.randomUUID().toString()); + professionalDetails.add(profDetail); existingProfile.put(Constants.PROFESSIONAL_DETAILS, professionalDetails); } professionalDetails.get(0).put(Constants.GROUP, request.get(Constants.GROUP)); @@ -1758,7 +1749,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; @@ -1906,13 +1897,8 @@ public ResponseEntity downloadFile(String fileName) { log.error("Failed to read the downloaded file: " + fileName + ", 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(); - } - } catch(Exception e1) { - } + ProjectUtil.deleteFileSafely(file); } } diff --git a/src/main/java/org/sunbird/profile/service/UserBulkUploadService.java b/src/main/java/org/sunbird/profile/service/UserBulkUploadService.java index 3236dc41b..6f092f015 100644 --- a/src/main/java/org/sunbird/profile/service/UserBulkUploadService.java +++ b/src/main/java/org/sunbird/profile/service/UserBulkUploadService.java @@ -466,8 +466,7 @@ private void processBulkUpload(HashMap inputDataMap) throws IOEx wb.close(); if (fis != null) fis.close(); - if (file != null) - file.delete(); + ProjectUtil.deleteFileSafely(file); } } public void processCSVBulkUploadV2(HashMap inputDataMap) throws IOException { @@ -492,7 +491,7 @@ public void processCSVBulkUploadV2(HashMap inputDataMap) throws List csvRecords = csvParser.getRecords(); List> updatedRecords = new ArrayList<>(); List headers = new ArrayList<>(csvParser.getHeaderNames()); - headers.replaceAll(header -> header.replaceAll("^\"|\"$", "")); + headers.replaceAll(header -> header.replaceAll(Constants.HEADER_QUOTES_REGEX, "")); if (!headers.contains("Status")) { headers.add("Status"); @@ -746,8 +745,7 @@ public void processCSVBulkUploadV2(HashMap inputDataMap) throws bufferedWriter.close(); if (fileWriter != null) fileWriter.close(); - if (file != null) - file.delete(); + ProjectUtil.deleteFileSafely(file); } } diff --git a/src/main/java/org/sunbird/storage/service/StorageServiceImpl.java b/src/main/java/org/sunbird/storage/service/StorageServiceImpl.java index 63944f883..2520cc286 100644 --- a/src/main/java/org/sunbird/storage/service/StorageServiceImpl.java +++ b/src/main/java/org/sunbird/storage/service/StorageServiceImpl.java @@ -1,20 +1,5 @@ package org.sunbird.storage.service; -import java.io.File; -import java.io.FileInputStream; -import java.io.FileOutputStream; -import java.io.IOException; -import java.nio.file.Files; -import java.nio.file.Path; -import java.nio.file.Paths; -import java.time.LocalDateTime; -import java.time.format.DateTimeFormatter; -import java.util.Arrays; -import java.util.HashMap; -import java.util.Map; - -import javax.annotation.PostConstruct; - import org.apache.commons.collections4.MapUtils; import org.apache.commons.lang3.StringUtils; import org.slf4j.Logger; @@ -43,6 +28,20 @@ import org.sunbird.user.service.UserUtilityService; import scala.Option; +import javax.annotation.PostConstruct; +import java.io.File; +import java.io.FileInputStream; +import java.io.FileOutputStream; +import java.io.IOException; +import java.nio.file.Files; +import java.nio.file.Path; +import java.nio.file.Paths; +import java.time.LocalDateTime; +import java.time.format.DateTimeFormatter; +import java.util.Arrays; +import java.util.HashMap; +import java.util.Map; + @Service public class StorageServiceImpl implements StorageService { @@ -80,7 +79,11 @@ public SBApiResponse uploadFile(MultipartFile mFile, String cloudFolderName, Str File file = null; try { file = new File(System.currentTimeMillis() + "_" + mFile.getOriginalFilename()); - file.createNewFile(); + if (file.createNewFile()) { + logger.info("File created successfully: {}", file.getAbsolutePath()); + } else { + logger.warn("File already exists: {}", file.getAbsolutePath()); + } // Use try-with-resources to ensure FileOutputStream is closed try (FileOutputStream fos = new FileOutputStream(file)) { fos.write(mFile.getBytes()); @@ -93,9 +96,7 @@ public SBApiResponse uploadFile(MultipartFile mFile, String cloudFolderName, Str response.setResponseCode(HttpStatus.INTERNAL_SERVER_ERROR); return response; } finally { - if (file != null && file.exists()) { - file.delete(); - } + ProjectUtil.deleteFileSafely(file); } } @@ -118,9 +119,7 @@ public SBApiResponse uploadFile(File file, String cloudFolderName, String contai response.setResponseCode(HttpStatus.INTERNAL_SERVER_ERROR); return response; } finally { - if (file != null) { - file.delete(); - } + ProjectUtil.deleteFileSafely(file); } } @@ -207,13 +206,8 @@ public ResponseEntity downloadFile(String reportType, String date, Str logger.error("Failed to read the downloaded file: " + fileName + ", 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(); - } - } catch(Exception e1) { - } + ProjectUtil.deleteFileSafely(file); } } @@ -327,15 +321,9 @@ public ResponseEntity downloadFile(String reportType, String date, String fil logger.error("Failed to read the downloaded file: " + fileName + ", 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(); - } - } catch (Exception e1) { - } + ProjectUtil.deleteFileSafely(file); } - } @Override @@ -441,10 +429,11 @@ public SBApiResponse ciosContentIconUpload(MultipartFile mFile, String container File file = null; try { file = new File(System.currentTimeMillis() + "_" + mFile.getOriginalFilename()); - file.createNewFile(); - FileOutputStream fos = new FileOutputStream(file); - fos.write(mFile.getBytes()); - fos.close(); + if (file.createNewFile()) { + try (FileOutputStream fos = new FileOutputStream(file)) { + fos.write(mFile.getBytes()); + } + } return uploadFile(file, cloudFolderName, containerName); } catch (Exception e) { logger.error("Failed to upload file. Exception: ", e); @@ -453,9 +442,7 @@ public SBApiResponse ciosContentIconUpload(MultipartFile mFile, String container response.setResponseCode(HttpStatus.INTERNAL_SERVER_ERROR); return response; } finally { - if (file != null) { - file.delete(); - } + ProjectUtil.deleteFileSafely(file); } } @@ -465,10 +452,11 @@ public SBApiResponse ciosContentContractUpload(MultipartFile mFile, String conta File file = null; try { file = new File(System.currentTimeMillis() + "_" + mFile.getOriginalFilename()); - file.createNewFile(); - FileOutputStream fos = new FileOutputStream(file); - fos.write(mFile.getBytes()); - fos.close(); + if (file.createNewFile()) { + try (FileOutputStream fos = new FileOutputStream(file)) { + fos.write(mFile.getBytes()); + } + } return uploadFile(file, cloudFolderName, containerName); } catch (Exception e) { logger.error("Failed to upload file. Exception: ", e); @@ -477,9 +465,7 @@ public SBApiResponse ciosContentContractUpload(MultipartFile mFile, String conta response.setResponseCode(HttpStatus.INTERNAL_SERVER_ERROR); return response; } finally { - if (file != null) { - file.delete(); - } + ProjectUtil.deleteFileSafely(file); } } @@ -502,13 +488,8 @@ public ResponseEntity downloadCiosContractFile(String fileName) { logger.error("Failed to read the downloaded file: " + fileName + ", 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(); - } - } catch (Exception e1) { - } + ProjectUtil.deleteFileSafely(file); } } @@ -528,7 +509,11 @@ public SBApiResponse uploadCiosLogsFile(String logFilePath, String fileName, Str return response; } tempFile = new File(System.currentTimeMillis() + "_" + fileName); - tempFile.createNewFile(); + if (tempFile.createNewFile()) { + logger.info("File created: {}", tempFile.getAbsolutePath()); + } else { + logger.info("File already exists: {}", tempFile.getAbsolutePath()); + } try (FileInputStream fis = new FileInputStream(file); FileOutputStream fos = new FileOutputStream(tempFile)) { byte[] buffer = new byte[1024]; @@ -548,12 +533,8 @@ public SBApiResponse uploadCiosLogsFile(String logFilePath, String fileName, Str response.getParams().setErrmsg("Failed to upload log file. Exception: " + e.getMessage()); response.setResponseCode(HttpStatus.INTERNAL_SERVER_ERROR); } finally { - if (file != null && file.exists()) { - file.delete(); - } - if (tempFile != null && tempFile.exists()) { - tempFile.delete(); - } + ProjectUtil.deleteFileSafely(file); + ProjectUtil.deleteFileSafely(tempFile); } return response; 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 9c9d72d81..2ce5644ad 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 configMap = new HashMap<>(); + configMap.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, configMap); 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 4e555407e..37e189d30 100644 --- a/src/main/java/org/sunbird/user/registration/service/UserRegistrationServiceImpl.java +++ b/src/main/java/org/sunbird/user/registration/service/UserRegistrationServiceImpl.java @@ -556,26 +556,26 @@ private List getDepartmentDetails() throws Exception { int iterateCount = 0; do { // request body + Map filtersMap = new HashMap<>(); + filtersMap.put(Constants.IS_TENANT, Boolean.TRUE); + + Map sortByMap = new HashMap<>(); + sortByMap.put(Constants.CHANNEL, Constants.ASC_ORDER); + + Map requestMap = new HashMap<>(); 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(); - 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); - } - }); + requestMap.put(Constants.FILTERS, filtersMap); + + Map requestPayload = new HashMap<>(); + requestPayload.put(Constants.REQUEST, requestMap); String serviceURL = serverProperties.getSbUrl() + serverProperties.getSbOrgSearchPath(); SunbirdApiResp orgResponse = mapper.convertValue( - outboundRequestHandlerService.fetchResultUsingPost(serviceURL, new HashMap() { - { - put(Constants.REQUEST, requestMap); - } - }), SunbirdApiResp.class); + outboundRequestHandlerService.fetchResultUsingPost(serviceURL, requestPayload), SunbirdApiResp.class); SunbirdApiResultResponse resultResp = orgResponse.getResult().getResponse(); count = resultResp.getCount(); diff --git a/src/main/java/org/sunbird/user/service/UserUtilityServiceImpl.java b/src/main/java/org/sunbird/user/service/UserUtilityServiceImpl.java index 9ae078ede..35344a393 100644 --- a/src/main/java/org/sunbird/user/service/UserUtilityServiceImpl.java +++ b/src/main/java/org/sunbird/user/service/UserUtilityServiceImpl.java @@ -148,12 +148,12 @@ public Map getUsersDataFromUserIds(List userIds, List result = new HashMap<>(); // request body SunbirdApiRequest requestObj = new SunbirdApiRequest(); + + Map filtersMap = new HashMap<>(); + filtersMap.put(Constants.USER_ID, userIds); + 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); @@ -429,15 +429,13 @@ private void printMethodExecutionResult(String methodAction, String objectDetail public Map> getUserDetails(List userIds, List fields) { // request body SunbirdApiRequest requestObj = new SunbirdApiRequest(); + Map filtersMap = new HashMap<>(); + filtersMap.put(Constants.USER_ID, userIds); + 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); @@ -545,12 +543,10 @@ public void enrichUserInfo(List fields, Map> public boolean isUserExist(String key, String value) { // request body SunbirdApiRequest requestObj = new SunbirdApiRequest(); + Map filtersMap = new HashMap<>(); + filtersMap.put(key, value); 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<>(); @@ -749,7 +745,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; } @@ -1032,12 +1028,10 @@ private String constructEmailTemplate(String templateName, Map p public Map getUserDetails(String key, String value) { // request body SunbirdApiRequest requestObj = new SunbirdApiRequest(); + Map filtersMap = new HashMap<>(); + filtersMap.put(key, value); 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<>();