Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

SonarQube bug fixing. #281

Open
wants to merge 1 commit into
base: cbrelease-4.8.21-sonar-fix
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -452,8 +452,7 @@ private void processBulkUpload(HashMap<String, String> inputDataMap) throws IOEx
wb.close();
if (fis != null)
fis.close();
if (file != null)
file.delete();
ProjectUtil.deleteFileSafely(file);
}
}

Expand Down
5 changes: 4 additions & 1 deletion src/main/java/org/sunbird/common/util/Constants.java
Original file line number Diff line number Diff line change
Expand Up @@ -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]+)*(?<!\\.|\\s)$";
public static final String PRINT_URI ="printUri";
public static final String HEADER_QUOTES_REGEX = "^\"|\"$";

private Constants() {
throw new IllegalStateException("Utility class");
Expand Down
19 changes: 9 additions & 10 deletions src/main/java/org/sunbird/common/util/NotificationUtil.java
Original file line number Diff line number Diff line change
Expand Up @@ -36,11 +36,10 @@ public void sendNotification(List<String> sendTo, Map<String, Object> params, St
List<Object> 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<String, List<Object>>() {
{
put(Constants.NOTIFICATIONS, notificationTosend);
}
});

Map<String, List<Object>> requestMap = new HashMap<>();
requestMap.put(Constants.NOTIFICATIONS, notificationTosend);
notificationRequest.put(Constants.REQUEST, requestMap);
logger.debug(String.format("Notification Request : %s", notificationRequest));
HttpEntity<Object> req = new HttpEntity<>(notificationRequest, headers);
restTemplate.postForEntity(notificationUrl, req, String.class);
Expand All @@ -58,11 +57,11 @@ public void sendNotification(List<Map<String, Object>> notifications) {
HttpHeaders headers = new HttpHeaders();
headers.setContentType(MediaType.APPLICATION_JSON);
Map<String, Object> notificationRequest = new HashMap<>();
notificationRequest.put(Constants.REQUEST, new HashMap<String, Object>() {
{
put(Constants.NOTIFICATIONS, notifications);
}
});

Map<String, Object> requestMap = new HashMap<>();
requestMap.put(Constants.NOTIFICATIONS, notifications);
notificationRequest.put(Constants.REQUEST, requestMap);


HttpEntity<Object> req = new HttpEntity<>(notificationRequest, headers);
logger.info(String.format("Notification Request : %s", notificationRequest));
Expand Down
23 changes: 22 additions & 1 deletion src/main/java/org/sunbird/common/util/ProjectUtil.java
Original file line number Diff line number Diff line change
@@ -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.*;
Expand Down Expand Up @@ -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]+)*(?<!\\.|\\s)$");
return firstName.matches(Constants.REGEX_NAME_VALIDATION);
}

public static Boolean validateTag(List<String> tags) {
Expand Down Expand Up @@ -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);
}
}
}
}
16 changes: 10 additions & 6 deletions src/main/java/org/sunbird/consumer/KafkaConsumer.java
Original file line number Diff line number Diff line change
Expand Up @@ -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;

Expand Down Expand Up @@ -143,7 +144,7 @@ private String publicUserCertificateDownload(String certificateid) {
throw new RuntimeException(e);
} finally {
if (mFile != null)
mFile.delete();
ProjectUtil.deleteFileSafely(mFile);
}
}

Expand Down Expand Up @@ -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);
}
Expand Down
8 changes: 8 additions & 0 deletions src/main/java/org/sunbird/core/logger/CbExtLogger.java
Original file line number Diff line number Diff line change
Expand Up @@ -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);
}
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -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<String, Object> requestBody = new HashMap<String, Object>() {{
put(Constants.ORGANIZATION_ID, custodianOrgId);
put(Constants.USER_ID, userId);
put(Constants.ROLES, Arrays.asList(Constants.PUBLIC));
}};
Map<String, Object> roleRequest = new HashMap<String, Object>() {{
put("request", requestBody);
}};

Map<String, Object> requestBody = new HashMap<>();
requestBody.put(Constants.ORGANIZATION_ID, custodianOrgId);
requestBody.put(Constants.USER_ID, userId);
requestBody.put(Constants.ROLES, Arrays.asList(Constants.PUBLIC));

Map<String, Object> roleRequest = new HashMap<>();
roleRequest.put("request", requestBody);

StringBuilder assignRoleUrl = new StringBuilder(serverConfig.getSbUrl()).append(serverConfig.getSbAssignRolePath());
log.info("printing assignRoleUrl: {}", assignRoleUrl);
Map<String, Object> assignRole = outboundRequestHandlerService.fetchResultUsingPost(assignRoleUrl.toString(), roleRequest, null);
Expand Down Expand Up @@ -207,22 +208,16 @@ private Map<String, Object> userSearchRequestBody(int offset, int limit) {
}

private Map<String, Object> getUserMigrateRequest(String userId, String channel, boolean isSelfMigrate) {
Map<String, Object> requestBody = new HashMap<String, Object>() {
{
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<String, Object> request = new HashMap<String, Object>() {
{
put(Constants.REQUEST, requestBody);
}
};
Map<String, Object> 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<String, Object> request = new HashMap<>();
request.put(Constants.REQUEST, requestBody);
return request;
}

Expand Down Expand Up @@ -250,9 +245,8 @@ private Map<String, Object> getUserExtPatchRequest(String userId, String default
requestBody.put("userId", userId);
requestBody.put("profileDetails", newProfileDetails);

return new HashMap<String, Object>() {{
put("request", requestBody);
}};

Map<String, Object> request = new HashMap<>();
request.put("request", requestBody);
return request;
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -78,8 +78,7 @@ public class OrgDesignationCompetencyMappingServiceImpl implements OrgDesignatio

@Override
public ResponseEntity<ByteArrayResource> 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()));
Expand Down Expand Up @@ -588,13 +587,8 @@ public ResponseEntity<Resource> 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);
}
}

Expand Down Expand Up @@ -929,8 +923,7 @@ private void processBulkUpload(HashMap<String, String> inputDataMap) throws Exce
wb.close();
if (fis != null)
fis.close();
if (file != null)
file.delete();
ProjectUtil.deleteFileSafely(file);
}
}

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -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()));
Expand Down Expand Up @@ -483,13 +482,8 @@ public ResponseEntity<Resource> 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);
}
}

Expand Down Expand Up @@ -809,7 +803,8 @@ private void processBulkUpload(HashMap<String, String> 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);
Expand All @@ -818,8 +813,7 @@ private void processBulkUpload(HashMap<String, String> inputDataMap) throws IOEx
wb.close();
if (fis != null)
fis.close();
if (file != null)
file.delete();
ProjectUtil.deleteFileSafely(file);
}
}

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -44,26 +44,23 @@ public List<String> getDeptNameList() {
int count = 0;
int iterateCount = 0;
do {
Map<String, Object> filtersMap = new HashMap<>();
filtersMap.put(Constants.IS_TENANT, Boolean.TRUE);
filtersMap.put(Constants.STATUS, 1);

// request body
Map<String, Object> 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<String, Object>() {
{
put(Constants.IS_TENANT, Boolean.TRUE);
put(Constants.STATUS, 1);
}
});
requestMap.put(Constants.FILTERS, filtersMap);

String serviceURL = serverConfig.getSbUrl() + serverConfig.getSbOrgSearchPath();
Map<String, Object> outboundRequestMap = new HashMap<>();
outboundRequestMap.put(Constants.REQUEST, requestMap);
SunbirdApiResp orgResponse = mapper.convertValue(
outboundRequestHandlerService.fetchResultUsingPost(serviceURL, new HashMap<String, Object>() {
{
put(Constants.REQUEST, requestMap);
}
}), SunbirdApiResp.class);
outboundRequestHandlerService.fetchResultUsingPost(serviceURL, outboundRequestMap), SunbirdApiResp.class);

SunbirdApiResultResponse resultResp = orgResponse.getResult().getResponse();
count = resultResp.getCount();
Expand Down Expand Up @@ -107,26 +104,25 @@ public List<Map<String,String>> getDeptNameListByAdmin() {
int count = 0;
int iterateCount = 0;
do {

Map<String, Object> filtersMap = new HashMap<>();
filtersMap.put(Constants.IS_TENANT, Boolean.TRUE);
filtersMap.put(Constants.STATUS, 1);

// request body
Map<String, Object> 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<String, Object>() {
{
put(Constants.IS_TENANT, Boolean.TRUE);
put(Constants.STATUS, 1);
}
});
requestMap.put(Constants.FILTERS, filtersMap);

String serviceURL = serverConfig.getSbUrl() + serverConfig.getSbOrgSearchPath();
Map<String, Object> outboundRequestMap = new HashMap<>();
outboundRequestMap.put(Constants.REQUEST, requestMap);

SunbirdApiResp orgResponse = mapper.convertValue(
outboundRequestHandlerService.fetchResultUsingPost(serviceURL, new HashMap<String, Object>() {
{
put(Constants.REQUEST, requestMap);
}
}), SunbirdApiResp.class);
outboundRequestHandlerService.fetchResultUsingPost(serviceURL, outboundRequestMap), SunbirdApiResp.class);

SunbirdApiResultResponse resultResp = orgResponse.getResult().getResponse();
count = resultResp.getCount();
Expand Down
Loading