Skip to content

Commit

Permalink
code review
Browse files Browse the repository at this point in the history
  • Loading branch information
devdatta-egov committed Jun 26, 2024
1 parent e850c55 commit c0710cb
Show file tree
Hide file tree
Showing 14 changed files with 84 additions and 46 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -5,8 +5,6 @@
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

// NOTE: If tracer is disabled change CustomKafkaTemplate to KafkaTemplate in autowiring

@Service
@Slf4j
public class Producer {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -40,10 +40,10 @@ public Object fetchResult(StringBuilder uri, Object request) {
try {
response = restTemplate.postForObject(uri.toString(), request, Map.class);
}catch(HttpClientErrorException e) {
log.error(EXTERNAL_SERVICE_EXCEPTION,e);
log.error(SEARCHER_SERVICE_EXCEPTION, "Error occurred while fetching data: {}", e.getMessage());
throw new ServiceCallException(e.getResponseBodyAsString());
}catch(Exception e) {
log.error(SEARCHER_SERVICE_EXCEPTION,e);
log.error(SEARCHER_SERVICE_EXCEPTION, "Error occurred while fetching data: {}", e.getMessage());
throw new ServiceCallException(e.getMessage());
}

Expand All @@ -55,10 +55,10 @@ public Object fetchResultWithGET(StringBuilder uri) {
try {
response = restTemplate.getForObject(uri.toString(), byte[].class);
} catch (HttpClientErrorException e) {
log.error(EXTERNAL_SERVICE_EXCEPTION, e);
log.error(SEARCHER_SERVICE_EXCEPTION, "Error occurred while fetching data: {}", e.getMessage());
throw new ServiceCallException(e.getResponseBodyAsString());
} catch (Exception e) {
log.error(SEARCHER_SERVICE_EXCEPTION, e);
log.error(SEARCHER_SERVICE_EXCEPTION, "Error occurred while fetching data: {}", e.getMessage());
throw new ServiceCallException(e.getMessage());
}
return response;
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -129,24 +129,22 @@ private String processExcelFile(PlanConfigurationRequest planConfigurationReques
List<CampaignResources> campaignResourcesList = new ArrayList<>();
DataFormatter dataFormatter = new DataFormatter();

for (int sheetNumber = 0; sheetNumber < workbook.getNumberOfSheets(); sheetNumber++) {
Sheet sheet = workbook.getSheetAt(sheetNumber);
workbook.forEach(sheet -> {
Map<String, Integer> mapOfColumnNameAndIndex = parsingUtil.getAttributeNameIndexFromExcel(sheet);
List<String> columnNamesList = mapOfColumnNameAndIndex.keySet().stream().toList();

parsingUtil.validateColumnNames(columnNamesList, planConfig, fileStoreId);

// Assuming processRows handles processing for each sheet
processRows(planConfigurationRequest, sheet, dataFormatter, fileStoreId, campaignResponse,
campaignBoundaryList, campaignResourcesList);
}

});
File fileToUpload = convertWorkbookToXls(workbook);
String uploadedFileStoreId = uploadConvertedFile(fileToUpload, planConfig.getTenantId());

if (config.isIntegrateWithAdminConsole()) {
campaignIntegrationUtil.updateCampaignResources(uploadedFileStoreId, campaignResourcesList,
fileToUpload.getName());
if (fileToUpload != null && !fileToUpload.delete()) {
log.warn("Failed to delete temporary file: " + fileToUpload.getPath());
}
campaignIntegrationUtil.updateCampaignDetails(planConfigurationRequest, campaignResponse,
campaignBoundaryList, campaignResourcesList);
}
Expand Down Expand Up @@ -179,7 +177,7 @@ private String processExcelFile(PlanConfigurationRequest planConfigurationReques
*/
private void processRows(PlanConfigurationRequest planConfigurationRequest, Sheet sheet,
DataFormatter dataFormatter, String fileStoreId, Object campaignResponse,
List<Boundary> campaignBoundaryList, List<CampaignResources> campaignResourcesList) throws IOException {
List<Boundary> campaignBoundaryList, List<CampaignResources> campaignResourcesList) {
CampaignResponse campaign = null;
campaign = objectMapper.convertValue(campaignResponse, CampaignResponse.class);
PlanConfiguration planConfig = planConfigurationRequest.getPlanConfiguration();
Expand All @@ -202,7 +200,7 @@ private void processRows(PlanConfigurationRequest planConfigurationRequest, Shee
private void performRowLevelCalculations(PlanConfigurationRequest planConfigurationRequest, Sheet sheet,
DataFormatter dataFormatter, String fileStoreId, List<Boundary> campaignBoundaryList,
PlanConfiguration planConfig, Map<String, Object> attributeNameVsDataTypeMap, List<String> boundaryCodeList,
Row firstRow) throws IOException {
Row firstRow) {
for (Row row : sheet) {
if (row.getRowNum() == 0) {
firstRow = row;
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -47,26 +47,51 @@ public void estimateResources(PlanConfigurationRequest planConfigurationRequest)
PlanConfiguration planConfiguration = planConfigurationRequest.getPlanConfiguration();

Map<File.InputFileTypeEnum, FileParser> parserMap = getInputFileTypeMap();
CampaignSearchRequest campaignRequest = campaignIntegrationUtil.buildCampaignRequestForSearch(planConfigurationRequest);
Object campaignSearchResponse = serviceRequestRepository.fetchResult(new StringBuilder(config.getProjectFactoryHostEndPoint()+config.getCampaignIntegrationSearchEndPoint()),
campaignRequest);
Object campaignSearchResponse = performCampaignSearch(planConfigurationRequest);
processFiles(planConfigurationRequest, planConfiguration, parserMap, campaignSearchResponse);
}

/**
* Performs a campaign search based on the provided plan configuration request.
* This method builds a campaign search request using the integration utility,
* fetches the search result from the service request repository, and returns it.
*
* @param planConfigurationRequest The request object containing configuration details for the campaign search.
* @return The response object containing the result of the campaign search.
*/
private Object performCampaignSearch(PlanConfigurationRequest planConfigurationRequest) {
CampaignSearchRequest campaignRequest = campaignIntegrationUtil.buildCampaignRequestForSearch(planConfigurationRequest);
Object campaignSearchResponse = serviceRequestRepository.fetchResult(new StringBuilder(config.getProjectFactoryHostEndPoint()+config.getCampaignIntegrationSearchEndPoint()),
campaignRequest);
return campaignSearchResponse;
}

/**
* Processes files in the plan configuration by parsing active files and skipping inactive ones.
* Uses the provided parser map to parse supported file types. If a file type is not supported,
* throws an IllegalArgumentException. Skips files with a specific template identifier defined
* in ServiceConstants.
*
* @param planConfigurationRequest The request object containing configuration details.
* @param planConfiguration The plan configuration object containing files to process.
* @param parserMap A map of supported file types to their respective parsers.
* @param campaignSearchResponse The response object from a campaign search operation.
*/
private void processFiles(PlanConfigurationRequest planConfigurationRequest, PlanConfiguration planConfiguration,
Map<File.InputFileTypeEnum, FileParser> parserMap, Object campaignSearchResponse) {
for(File file:planConfiguration.getFiles())
{
if(file.getActive())
{
File.InputFileTypeEnum fileType = file.getInputFileType();
FileParser parser = parserMap.computeIfAbsent(fileType, ft -> {
throw new IllegalArgumentException("Unsupported file type: " + ft);
});
if(!file.getTemplateIdentifier().equalsIgnoreCase(ServiceConstants.FILE_TEMPLATE))
parser.parseFileData(planConfigurationRequest, file.getFilestoreId(), campaignSearchResponse);
}
}
for (File file : planConfiguration.getFiles()) {
if (!file.getActive()) {
continue;
}
File.InputFileTypeEnum fileType = file.getInputFileType();
FileParser parser = parserMap.computeIfAbsent(fileType, ft -> {
throw new IllegalArgumentException("Unsupported file type: " + ft);
});
if (!ServiceConstants.FILE_TEMPLATE.equalsIgnoreCase(file.getTemplateIdentifier())) {
parser.parseFileData(planConfigurationRequest, file.getFilestoreId(), campaignSearchResponse);
}
}

}

/**
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -104,7 +104,7 @@ public File convertShapefileToGeoJson(PlanConfiguration planConfig, String fileS

writeFeaturesToGeoJson(featureSource, geojsonFile);
} catch (IOException e) {
throw new CustomException("CONVERSION_ERROR",e.getMessage());
throw new CustomException("ERROR_IN_SHAPE_FILE_PARSER_WHILE_CONVERTING_SHAPE_FILE_TO_GEOJSON_IN_METHOD_CONVERTSHAPEFILETOGEOJSON",e.getMessage());
}

return geojsonFile;
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -40,7 +40,7 @@ public BoundarySearchResponse search(String tenantId, String hierarchyType,PlanC

} catch (Exception ex) {
log.error("Boundary relationship response error!!", ex);
throw new CustomException("BOUNDARY_SEARCH_EXCEPTION", "Failed to parse boundary relationship response for tenantId: "+tenantId);
throw new CustomException("BOUNDARY_SEARCH_EXCEPTION", "Exception occurs while searhing boundary or parsing search response of boundary relationship for tenantId: "+tenantId);
}
}

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -120,6 +120,16 @@ public BigDecimal getInputValueFromJsonFeature(Map<String, BigDecimal> resultMap
}
}

/**
* Calculates a result based on the provided operation and inputs.
*
* @param operation The operation object containing details like input, operator, and assumption value.
* @param feature The JSON node representing additional features or parameters for calculation.
* @param mappedValues A map containing mappings for input keys to their corresponding values.
* @param assumptionValueMap A map containing assumption values referenced by keys.
* @param resultMap A map to store and update the calculated results.
* @return The calculated result as a BigDecimal.
*/
public BigDecimal calculateResult(Operation operation, JsonNode feature, Map<String, String> mappedValues, Map<String, BigDecimal> assumptionValueMap, Map<String, BigDecimal> resultMap)
{
String input = operation.getInput();
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -84,7 +84,7 @@ public void updateCampaignDetails(PlanConfigurationRequest planConfigurationRequ
} catch (Exception e) {
log.error(ServiceConstants.ERROR_WHILE_SEARCHING_CAMPAIGN
+ planConfigurationRequest.getPlanConfiguration().getExecutionPlanId(), e);
throw new CustomException("Failed to update campaign details", e.toString());
throw new CustomException("Failed to update campaign details in CampaignIntegration class within method updateCampaignDetails.", e.toString());
}
}

Expand Down Expand Up @@ -138,7 +138,7 @@ private CampaignRequest buildCampaignRequestForUpdate(PlanConfigurationRequest p
public void updateCampaignBoundary(PlanConfiguration planConfig, JsonNode feature,
Map<String, BigDecimal> assumptionValueMap, Map<String, String> mappedValues,
Map<String, Integer> mapOfColumnNameAndIndex, List<Boundary> boundaryList,
Map<String, BigDecimal> resultMap) throws IOException {
Map<String, BigDecimal> resultMap) {
Integer indexOfType = null;
boolean validToAdd = false;
Integer indexValue = 0;
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -121,7 +121,7 @@ private ModuleDetail getPlanModuleDetail() {
* @throws JsonProcessingException if there's an issue processing JSON.
*/
public Map<String, Object> filterMasterData(String masterDataJson, File.InputFileTypeEnum fileType,
String templateIdentifier, String campaignType) throws JsonMappingException, JsonProcessingException {
String templateIdentifier, String campaignType) {
Map<String, Object> properties = new HashMap<>();
Map<String, Object> masterData = JsonUtils.parseJson(masterDataJson, Map.class);
Map<String, Object> planModule = (Map<String, Object>) masterData.get(ServiceConstants.MDMS_PLAN_MODULE_NAME);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -54,15 +54,13 @@ public List<String> fetchAttributeNamesFromJson(JsonNode jsonNode)
{
if(jsonNode.get("features") == null)
throw new CustomException("No Features found in geojson", " ");
List<String> columnNames = new ArrayList<>();
if(jsonNode.get("features")!=null) {
List<String> columnNames = new ArrayList<>();
JsonNode propertiesNode = jsonNode.get("features").get(0).get("properties");
Iterator<String> fieldNames = propertiesNode.fieldNames();
while (fieldNames.hasNext()) {
String columnName = fieldNames.next();
columnNames.add(columnName);
}
}
}
return columnNames;
}
public void validateColumnNames(List<String> columnNamesList, PlanConfiguration planConfig, String fileStoreId ) {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -27,14 +27,14 @@
public class EnrichedBoundary {

@JsonProperty("id")
private String id = null;
private String id;

@JsonProperty("code")
@NotNull
private String code = null;
private String code;

@JsonProperty("boundaryType")
private String boundaryType = null;
private String boundaryType;

@JsonProperty("children")
@Valid
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -30,14 +30,12 @@ public class Boundary {
private String type;

@JsonProperty("isRoot")
@Valid
private boolean isRoot;

@JsonProperty("parent")
@Valid
private String parent;

@JsonProperty("includeAllChildren")
@Valid
private boolean includeAllChildren;
}
Original file line number Diff line number Diff line change
Expand Up @@ -63,11 +63,9 @@ public class Campaign {
private String projectId;

@JsonProperty("startDate")
@Valid
private long startDate;

@JsonProperty("endDate")
@Valid
private long endDate;

@JsonProperty("additionalDetails")
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -4,12 +4,25 @@

import jakarta.validation.Valid;

/**
* The cycle duration in days.
* This specifies the duration of the cycle for deliveries.
*/
public class CycleConfigureDate {

/**
* The cycle duration in days.
* This specifies the duration of the cycle for deliveries.
*/
@JsonProperty("cycle")
@Valid
private int cycle;


/**
* The number of deliveries within the cycle.
* This indicates how many deliveries occur during each cycle period.
*/
@JsonProperty("deliveries")
@Valid
private int deliveries;
Expand Down

0 comments on commit c0710cb

Please sign in to comment.