PageRenderTime 67ms CodeModel.GetById 24ms RepoModel.GetById 0ms app.codeStats 1ms

/MercerPoC/src/in/lnt/validations/FormValidator.java

https://bitbucket.org/jwala/mercer_api_local
Java | 2512 lines | 1978 code | 263 blank | 271 comment | 675 complexity | a168ad3c8668fa6947a214598daffffa MD5 | raw file

Large files files are truncated, but you can click here to view the full file

  1. package in.lnt.validations;
  2. import java.io.ByteArrayInputStream;
  3. import java.io.IOException;
  4. import java.io.UnsupportedEncodingException;
  5. import java.sql.SQLException;
  6. import java.text.SimpleDateFormat;
  7. import java.util.ArrayList;
  8. import java.util.Calendar;
  9. import java.util.Date;
  10. import java.util.HashMap;
  11. import java.util.HashSet;
  12. import java.util.Iterator;
  13. import java.util.LinkedHashMap;
  14. import java.util.List;
  15. import java.util.Map;
  16. import java.util.Map.Entry;
  17. import java.util.Set;
  18. import java.util.UUID;
  19. import java.util.regex.Matcher;
  20. import java.util.regex.Pattern;
  21. import org.apache.commons.lang3.EnumUtils;
  22. import org.apache.commons.lang3.StringUtils;
  23. import org.json.JSONArray;
  24. import org.json.JSONException;
  25. import org.json.JSONObject;
  26. import org.slf4j.Logger;
  27. import org.slf4j.LoggerFactory;
  28. import com.fasterxml.jackson.core.JsonParseException;
  29. import com.fasterxml.jackson.core.JsonProcessingException;
  30. import com.fasterxml.jackson.databind.JsonMappingException;
  31. import com.fasterxml.jackson.databind.JsonNode;
  32. import com.fasterxml.jackson.databind.ObjectMapper;
  33. import com.fasterxml.jackson.databind.node.ArrayNode;
  34. import com.fasterxml.jackson.databind.node.JsonNodeFactory;
  35. import com.fasterxml.jackson.databind.node.JsonNodeType;
  36. import com.fasterxml.jackson.databind.node.NullNode;
  37. import com.fasterxml.jackson.databind.node.ObjectNode;
  38. import com.lti.mosaic.function.def.InversionAndRangeCheckFunctions;
  39. import com.lti.mosaic.parser.driver.ExpressionEvalutionDriver;
  40. import com.lti.mosaic.parser.utils.ExpressionBuilderConstants;
  41. import in.lnt.constants.Constants;
  42. import in.lnt.enums.ValidationTypes;
  43. import in.lnt.exceptions.CustomStatusException;
  44. import in.lnt.ml.MachineLearningRestClient;
  45. import in.lnt.parser.CSVParser;
  46. import in.lnt.service.db.DBUtils;
  47. import in.lnt.utility.constants.CacheConstats;
  48. import in.lnt.utility.constants.ErrorCacheConstant;
  49. import in.lnt.utility.general.Cache;
  50. import in.lnt.utility.general.DataUtility;
  51. import in.lnt.utility.general.JsonUtils;
  52. import in.lnt.validations.evaluator.APIExpressionEvaluator;
  53. import in.lti.mosaic.api.mongo.MongoObject;
  54. import in.lti.mosaic.api.mongo.MongoThread;
  55. public class FormValidator {
  56. private static final Logger logger = LoggerFactory.getLogger(FormValidator.class);
  57. static ObjectMapper mapper = new ObjectMapper();
  58. ArrayList<String> paramValueList=null;
  59. static Pattern VALID_EMAIL_ADDRESS_REGEX =
  60. Pattern.compile("^(.+)@(.+)$", Pattern.CASE_INSENSITIVE);
  61. static Pattern VALID_PHONE_NUMBER_REGEX =
  62. Pattern.compile("^(\\(?\\+?[0-9]*\\)?)?[0-9_\\- \\(\\)]*$", Pattern.CASE_INSENSITIVE);
  63. // ^[A-Z0-9._%+-]+@[A-Z0-9.-]+\\.[A-Z]{2,6}$
  64. private static String MONGODB_ARCHIVE_FLAG = Cache
  65. .getMLProperty(in.lnt.utility.constants.CacheConstats.MONGODUMP_FLAG);
  66. public JsonNode parseAndValidate(String entitiesJson, String csvJsonString, boolean isAggregateRequest,
  67. Map<String, String> xslJsonMap, String firstSheetName, boolean isMultiPartRequest) throws Exception {
  68. JsonNode resultNode = null;
  69. //Generating UUID for a Request and Response
  70. final String uuid = UUID.randomUUID().toString().replace("-", "");
  71. JsonNode entitiesNodeResponse = preparingL1Input(entitiesJson, csvJsonString, isAggregateRequest, xslJsonMap,
  72. firstSheetName, isMultiPartRequest, null);
  73. //Adding Request into MongoDB
  74. dumpToMongo(uuid, mapper.writeValueAsString(entitiesNodeResponse), Constants.REQUEST);
  75. if (isAggregateRequest) {
  76. resultNode = performValidateAggregateRequest(entitiesNodeResponse, isAggregateRequest, isMultiPartRequest);
  77. } else
  78. resultNode = perform_L1_L2Validations(entitiesNodeResponse, isAggregateRequest, isMultiPartRequest);
  79. //Adding Response into MongoDB
  80. dumpToMongo(uuid, mapper.writeValueAsString(resultNode), Constants.RESPONSE);
  81. return resultNode;
  82. }
  83. /**
  84. * @param uuid
  85. * @param data
  86. * @throws JsonProcessingException
  87. * @author Vivek Kasadwar
  88. */
  89. public static void dumpToMongo(final String uuid, String data,String type){
  90. if (StringUtils.equals(MONGODB_ARCHIVE_FLAG,Constants.YES)) {
  91. MongoObject mongoObject = new MongoObject();
  92. mongoObject.setRequestId(uuid);
  93. mongoObject.setObjectType(type);
  94. mongoObject.setObjectJson(data);
  95. mongoObject.setTimeStamp(Calendar.getInstance().getTime());
  96. MongoThread.addToQueue(mongoObject);
  97. }
  98. }
  99. public HashMap<String, JsonNode> parseJsonObjectMap(String key, JsonNode value, HashMap<String, JsonNode> map,
  100. String datakey, JsonNode columnListJson,List<String> otherAndContextKeys) throws Exception { // PE-7056
  101. Iterator<Map.Entry<String, JsonNode>> it = value.fields();
  102. Map.Entry<String, JsonNode> entry = null;
  103. try {
  104. while (it.hasNext()) {
  105. entry = it.next();
  106. if (entry.getValue().getNodeType() != JsonNodeType.OBJECT) {
  107. if (datakey != null) {
  108. map.put((datakey + "." + key + "." + entry.getKey()).trim(), entry.getValue());
  109. if(otherAndContextKeys!=null)
  110. otherAndContextKeys.add((datakey + "." + key + "." + entry.getKey()).trim());
  111. } else {
  112. map.put((key + "." + entry.getKey()).trim(), entry.getValue());
  113. if(otherAndContextKeys!=null)
  114. otherAndContextKeys.add((key + "." + entry.getKey()).trim());
  115. }
  116. } else {
  117. parseJsonObjectMap(key + "." + entry.getKey(), entry.getValue(), map, datakey, columnListJson,otherAndContextKeys);
  118. }
  119. }
  120. } finally {
  121. it=null;
  122. if(null!=entry) entry=null;
  123. }
  124. return map;
  125. }
  126. public JsonNode validate(HashMap<String, JsonNode> dataMap, ArrayList<JsonNode> columnNodeList, JsonNode dataNode,
  127. APIExpressionEvaluator apiExpressionEvaluator, boolean isAggregateRequest,
  128. HashMap<String, String> columnMappingMap,HashMap<String, JsonNode> dimMap, List<String> metaDataColumnsOnly,
  129. boolean mlAutoCoorect) throws Exception {
  130. logger.debug("validate >> ExpressionEvaluatorDriver Cache : {}",
  131. apiExpressionEvaluator.getExpressionEvaluatorDriver().getAggregateFunctionCache());
  132. JsonNode validationNode = null;
  133. ObjectNode obj = null;
  134. ArrayList<ObjectNode> predefinedObjList = null;
  135. List<ObjectNode> rangeOrSeqObjList = null;
  136. String code = null;
  137. String mappedColumnName = null;
  138. ArrayNode arr = null;
  139. JsonNode nodeDTObject = null;
  140. JsonNode dnCodeObject = null;
  141. Boolean flag = null;
  142. String result = null;
  143. String skip = null;
  144. JsonNode validationObjNode = null;
  145. ObjectNode jobInversionObjNode = null;
  146. ArrayNode jobInversionArr = null;
  147. // PE-5643 by default true because for true type do not fire validations.
  148. boolean isOptionType = true;
  149. String countryCode = null;
  150. String __COMPENSATION = null;
  151. String jobInvParameter = null;
  152. // PE-5691
  153. boolean isEmtpyRecord = false;
  154. // PE - 7257
  155. ArrayNode datePatternArray = null;
  156. ArrayNode numberPatternArray = null;
  157. String columnName = null;
  158. JsonNode tempOriginalValue = null;
  159. // 8421 code changes.
  160. Map<String, String> incorrectDataType = new HashMap<>();
  161. JsonNode questionType = null; // Added for 8916 Remove %
  162. String dataType = null;
  163. if (columnNodeList != null && !columnNodeList.isEmpty()) {
  164. arr = mapper.createArrayNode();
  165. if (!JsonUtils.isNullOrBlankOrNullNode(dataMap.get(Constants.CONTEXTDATAKEY+Constants.CONTEXTDATA_DATEFORMAT))){
  166. datePatternArray = (ArrayNode)dataMap.get(Constants.CONTEXTDATAKEY+Constants.CONTEXTDATA_DATEFORMAT);
  167. }
  168. if (!JsonUtils.isNullOrBlankOrNullNode(dataMap.get(Constants.CONTEXTDATAKEY+Constants.CONTEXTDATA_NUMBERFORMAT))){
  169. numberPatternArray = (ArrayNode)dataMap.get(Constants.CONTEXTDATAKEY+Constants.CONTEXTDATA_NUMBERFORMAT);
  170. }
  171. // If request is AggregateRequest
  172. // L3A - Inversion/Aggregate Request Starts Here
  173. if (isAggregateRequest) {
  174. // PE - 7257
  175. for (JsonNode node : columnNodeList) {
  176. if (node.get(Constants.VALIDATIONS) != null && node.get(Constants.VALIDATIONS).size() > 0) {
  177. for (int i = 0; i < node.get(Constants.VALIDATIONS).size(); i++) {
  178. validationNode = node.get(Constants.VALIDATIONS).get(i);
  179. // For Inversion
  180. obj = apiExpressionEvaluator.expressionEvaluator(dataMap, validationNode, node,
  181. dataNode,isAggregateRequest, columnMappingMap, columnNodeList, metaDataColumnsOnly);
  182. if (obj != null) {
  183. arr.add(obj);
  184. obj = null;
  185. }
  186. }
  187. }
  188. }
  189. // PE-4843 Append JobInversion Object
  190. InversionAndRangeCheckFunctions invAndRangeChkFuncObj
  191. = new InversionAndRangeCheckFunctions(CSVParser.dataForAggregation, apiExpressionEvaluator.getExpressionEvaluatorDriver().getOtherData());
  192. Map<String, Object> requestMap = invAndRangeChkFuncObj.jobInversion(); // Changed by Nikhil
  193. if (requestMap.containsKey(ExpressionBuilderConstants.CONST_INVERSION_JSON_ARRAY)
  194. && null != requestMap.get(ExpressionBuilderConstants.CONST_INVERSION_JSON_ARRAY)) {
  195. jobInversionArr = (ArrayNode) mapper.readTree(
  196. requestMap.get(ExpressionBuilderConstants.CONST_INVERSION_JSON_ARRAY).toString());
  197. }
  198. if(requestMap.containsKey(ExpressionBuilderConstants.CONST_COUNTRYCODE)
  199. && null!=requestMap.get(ExpressionBuilderConstants.CONST_COUNTRYCODE)) {
  200. countryCode = requestMap.get(ExpressionBuilderConstants.CONST_COUNTRYCODE).toString();
  201. }
  202. logger.info("Creating JobInversion object...");
  203. jobInversionObjNode = mapper.createObjectNode();
  204. if(requestMap.containsKey(ExpressionBuilderConstants.CONST_COMPENSATION)
  205. && null!=requestMap.get(ExpressionBuilderConstants.CONST_COMPENSATION)) {
  206. __COMPENSATION = requestMap.get(ExpressionBuilderConstants.CONST_COMPENSATION).toString();
  207. if(__COMPENSATION.equals(ExpressionBuilderConstants.SALARY_TYPE_TOTAL_GUARANTEED_CASH)) {
  208. __COMPENSATION = ExpressionBuilderConstants.COL_TOTAL_GUARANTEED_CASH;
  209. jobInvParameter = ExpressionBuilderConstants.SALARY_TYPE_MSG_TOTAL_GUARANTEED_CASH;
  210. //PE-8454
  211. jobInversionObjNode.put(Constants.MESSAGE_KEY, Constants.JOB_INVERSION_ERROR_TOTAL_CASH);
  212. } else {
  213. __COMPENSATION = ExpressionBuilderConstants.COL_ANNUAL_BASE;
  214. jobInvParameter = ExpressionBuilderConstants.SALARY_TYPE_MSG_REGULAR;
  215. //PE-8454
  216. jobInversionObjNode.put(Constants.MESSAGE_KEY, Constants.JOB_INVERSION_ERROR_BASE_SALARY);
  217. }
  218. }
  219. jobInversionObjNode.put(Constants.ERROR_GROUP, Constants.PERSONAL);
  220. jobInversionObjNode.put(Constants.ERROR_TYPE, Constants.ERROR);
  221. jobInversionObjNode.put(Constants.VALIDATION_TYPE, Constants.EXPRESSION);
  222. jobInversionObjNode.put(Constants.FIELD, __COMPENSATION);
  223. jobInversionObjNode.put(Constants.CATEGORY, Constants.JOB_INVERSION);
  224. jobInversionObjNode.put(Constants.PARAMETER, jobInvParameter);
  225. jobInversionObjNode.putArray(Constants.DATA).addAll(jobInversionArr);
  226. arr.add(jobInversionObjNode);
  227. return mapper.convertValue(arr, JsonNode.class);
  228. }
  229. // L3A - Inversion/Aggregate Request Ends Here
  230. for (JsonNode node : columnNodeList) {
  231. JsonNode currentDataMapCol = null;
  232. isEmtpyRecord=false;
  233. if (node.get(Constants.CODE) != null)
  234. code = node.get(Constants.CODE).asText();
  235. if (node.get(Constants.SKIP) != null)
  236. skip = node.get(Constants.SKIP).asText();
  237. if (node.get(Constants.MAPPED_COLUMN_NAME) != null)
  238. mappedColumnName = node.get(Constants.MAPPED_COLUMN_NAME).asText();
  239. if ( dataNode != null || (dataNode!=null && dataNode.get(mappedColumnName) != null)) {
  240. //Following code written for Mercer JIRA Story PE-5691
  241. if(skip==null ) {
  242. if(code !=null && mappedColumnName!=null && JsonUtils.isNullOrBlankOrNullNode(dataNode.get(code))
  243. && JsonUtils.isNullOrBlankOrNullNode(dataNode.get(mappedColumnName)))
  244. {
  245. isEmtpyRecord = true;
  246. }
  247. if(code !=null && mappedColumnName ==null && JsonUtils.isNullOrBlankOrNullNode(dataNode.get(code)) )
  248. {
  249. isEmtpyRecord = true;
  250. }
  251. if(mappedColumnName !=null && code==null &&JsonUtils.isNullOrBlankOrNullNode(dataNode.get(mappedColumnName)))
  252. {
  253. isEmtpyRecord = true;
  254. }
  255. if(isEmtpyRecord)
  256. {
  257. ((ObjectNode)dataNode).set(code, JsonNodeFactory.instance.nullNode()) ;
  258. }
  259. }
  260. //PE-5691 End.
  261. flag = false;
  262. if ((mappedColumnName != null && dataNode.get(mappedColumnName) != null)
  263. && (null != code && mappedColumnName != null && !code.equals(mappedColumnName))) {
  264. // Changing logic
  265. ((ObjectNode) (dataNode)).set(code, dataMap.get(mappedColumnName));
  266. ((ObjectNode) (dataNode)).remove(mappedColumnName);
  267. }
  268. if (skip != null && (skip.equals("true") || Boolean.parseBoolean(skip) == true)) {
  269. if (code != null && !code.equals(""))
  270. ((ObjectNode) (dataNode)).remove(code);
  271. else
  272. ((ObjectNode) (dataNode)).remove(mappedColumnName);
  273. skip = null;
  274. continue;
  275. }
  276. // Validate the data type object block starts here.
  277. if(null != node.get(Constants.DATA_TYPE)){
  278. dataType = node.get(Constants.DATA_TYPE).asText();
  279. }
  280. if (dataType != null) {
  281. logger.info("Check if dataType is not empty");
  282. nodeDTObject = node.get(Constants.DATA_TYPE);
  283. if (dataNode.get(code) != null)
  284. dnCodeObject = dataNode.get(code);
  285. else if (dataNode.get(mappedColumnName) != null)
  286. dnCodeObject = dataNode.get(mappedColumnName);
  287. validationObjNode = node.get(Constants.VALIDATIONS);
  288. if ( StringUtils.isEmpty(mappedColumnName)) {
  289. columnName = code;
  290. }else {
  291. columnName = mappedColumnName;
  292. }
  293. if(null != dataMap && !JsonUtils.isNullOrBlankOrNullNode(dataMap.get(columnName))){
  294. currentDataMapCol = dataMap.get(columnName);
  295. }
  296. //Added for 8916 Remove %
  297. questionType = node.get(Constants.QUESTION_TYPE);
  298. if(null != currentDataMapCol && dataNode.get(columnName) != null
  299. && !JsonUtils.isNullOrBlankOrNullNode(questionType) && questionType.asText().equals(Constants.PERCENTAGE) ){
  300. String percentageValue = currentDataMapCol.asText().trim();
  301. if(!percentageValue.isEmpty() && percentageValue.endsWith("%")){
  302. percentageValue = percentageValue.substring(0, percentageValue.length()-1);
  303. dataMap.put(columnName,
  304. mapper.readValue(mapper.writeValueAsString(percentageValue),JsonNode.class));
  305. ((ObjectNode) dataNode).put(code, percentageValue);
  306. dnCodeObject = dataNode.get(columnName);
  307. }
  308. }
  309. // If data node is not empty then do data type validation
  310. if (!isAggregateRequest && !JsonUtils.isNullOrBlankOrNullNode(dnCodeObject)
  311. && !isEmtpyRecord && !StringUtils.isEmpty(dnCodeObject.asText().trim())) { //PE-9268
  312. //8421 code changes.
  313. incorrectDataType = dataTypeCheck(dataMap, dataNode, columnName, nodeDTObject, dnCodeObject, flag,
  314. datePatternArray, numberPatternArray);
  315. flag = Boolean.parseBoolean(incorrectDataType.get("dataTypeFlag"));
  316. } else {
  317. flag = true;
  318. }
  319. } else { // if data node is empty then skip data type validations.
  320. flag = true;
  321. }
  322. //PE -5216 and PE-5643 Check for drop down options exist in metadata or in database.
  323. // PE-5643 : Required this functionality at /uploadMulttipleFile also. (Mentioned by Alex)
  324. if (questionType != null
  325. && ( questionType.asText().equals(Constants.DROPDOWN) ||
  326. questionType.asText().equals(Constants.RADIO_BUTTONS) )) {
  327. // PE-8070 Clear & Prepare outputJson for dimensions
  328. if( !JsonUtils.isNullOrBlankOrNullNode(dataNode.get(code))
  329. && dataNode.get(code).getNodeType()==JsonNodeType.OBJECT) {
  330. Iterator<String> iter = dataNode.get(code).fieldNames();
  331. String dimensionKey = null;
  332. while(null!=iter && iter.hasNext() ) {
  333. dimensionKey = iter.next();
  334. isOptionType = FormValidator_CSC.checkAnswerExists(node, dataNode.get(code).get(dimensionKey));
  335. if ( ! isOptionType ) {
  336. // PE-8397
  337. // // Implementation start PE : 5643
  338. // // Clear the value anyways if checkAnswerExists==false
  339. //
  340. // // Implementation end PE : 5643
  341. // Generate error for dimension in format : Question1.Dimension1
  342. obj = APIExpressionEvaluator.prepareOutputJson(null, null, null, ValidationTypes.DROPDOWN,
  343. code+"."+dimensionKey, null, null,node.has(Constants.DISPLAYLABEL) ? node.get(Constants.DISPLAYLABEL).asText() : null);
  344. }
  345. if (obj != null) {
  346. arr.add(obj);
  347. obj = null;
  348. }
  349. }
  350. // Clear & Prepare outputJson for non-dimensional questions (i.e. simple values)
  351. } else {
  352. // PE-6524 ML Integration works start
  353. if(mlAutoCoorect )
  354. {
  355. isOptionType = FormValidator_CSC.checkAnswerExists(node, dataMap.get(code));
  356. }
  357. else
  358. {
  359. isOptionType = FormValidator_CSC.checkAnswerExists(node, dataNode.get(code));
  360. }
  361. // PE-6524 ML Integration works end
  362. if ( ! isOptionType ) {
  363. obj = APIExpressionEvaluator.prepareOutputJson(null, null, null, ValidationTypes.DROPDOWN,
  364. code, null, null,JsonUtils.isNullOrBlankOrNullNode(node.get(Constants.DISPLAYLABEL))? "":node.get(Constants.DISPLAYLABEL).asText() );
  365. }
  366. if (obj != null) {
  367. arr.add(obj);
  368. obj = null;
  369. }
  370. // PE-6254 ML Integration works end
  371. }
  372. }
  373. //PE-9490 Round off upto 2 precison places for money question type
  374. if(!JsonUtils.isNullOrBlankOrNullNode(questionType) && questionType.asText().equals(Constants.MONEY) && flag
  375. && null != dataMap && !JsonUtils.isNullOrBlankOrNullNode(currentDataMapCol) && dataNode.get(columnName) != null) {
  376. String colStringVal = currentDataMapCol.asText().trim();
  377. double colDoubleVal = currentDataMapCol.asDouble();
  378. if(colStringVal.contains(".")) {
  379. //RoundOff the value and return error object if it has more than 2 precison places
  380. obj = DataUtility.roundOffMoneyQuestionType(dataMap, dataNode, obj, code, dataType, colStringVal, colDoubleVal);
  381. }
  382. }
  383. tempOriginalValue = dataNode.get(code);
  384. if(mlAutoCoorect && !isAggregateRequest)
  385. {
  386. if(!JsonUtils.isNullOrBlankOrNullNode(dataNode.get(code+Constants.UNDERSCORE_ACFLAG)) && dataNode.get(code+Constants.UNDERSCORE_ACFLAG).asText().equalsIgnoreCase("R"))
  387. {
  388. arr.add(prepareMLAutocorrectObject(code,"validationType",tempOriginalValue));
  389. if( !JsonUtils.isNullOrBlankOrNullNode(dataMap.get(code)) ) { // Handled NullPointerExc
  390. ((ObjectNode) (dataNode)).put(code,dataMap.get(code).asText());
  391. } else {
  392. ((ObjectNode) (dataNode)).putNull(code);
  393. }
  394. }
  395. }
  396. if (node.get(Constants.VALIDATIONS) != null && node.get(Constants.VALIDATIONS).size() > 0
  397. && flag) { // Aggregate
  398. for (int i = 0; i < node.get(Constants.VALIDATIONS).size(); i++) {
  399. validationNode = node.get(Constants.VALIDATIONS).get(i);
  400. if (validationNode.get(Constants.VALIDATION_TYPE) != null
  401. && EnumUtils.isValidEnum(ValidationTypes.class,
  402. validationNode.get(Constants.VALIDATION_TYPE).asText().toUpperCase() )) {
  403. switch (ValidationTypes.valueOf(validationNode.get(Constants.VALIDATION_TYPE).asText().toUpperCase())) {
  404. case REQUIRED:
  405. // PE - 7241
  406. predefinedObjList = validatePredefinedValidation(dataNode,node,validationNode,dataMap,mappedColumnName,Constants.REQUIRED);
  407. break;
  408. case ONEOF:
  409. obj = apiExpressionEvaluator.checkValidationTypeOneOf(dataMap, code, node,
  410. validationNode, mappedColumnName);
  411. break;
  412. case RANGE:
  413. rangeOrSeqObjList = apiExpressionEvaluator.prepareRangeObject(dataMap, validationNode, node,
  414. dataNode);
  415. break;
  416. case RANGEVALIDATIONREFTABLE:
  417. rangeOrSeqObjList = apiExpressionEvaluator.prepareRefernceRangeObject(dataMap, validationNode,
  418. node, dataNode);
  419. break;
  420. case ELIGIBILITY:
  421. // Last Parameter is weather request of MDA
  422. arr.addAll(apiExpressionEvaluator.checkValidity(dataMap, validationNode, node,
  423. dataNode,false,metaDataColumnsOnly));
  424. break;
  425. case PHONE:
  426. // PE - 7241
  427. predefinedObjList = validatePredefinedValidation(dataNode,node,validationNode,null,mappedColumnName,Constants.PHONE);
  428. break;
  429. case EMAIL:
  430. // PE - 7241
  431. predefinedObjList = validatePredefinedValidation(dataNode,node,validationNode,null,mappedColumnName,Constants.EMAIL);
  432. break;
  433. case EXPRESSION:
  434. obj = apiExpressionEvaluator.expressionEvaluator(dataMap, validationNode, node, dataNode,
  435. isAggregateRequest, columnMappingMap, columnNodeList, metaDataColumnsOnly);
  436. break;
  437. /**
  438. * @author Akhileshwar
  439. * PE-7045
  440. **/
  441. case SEQUENTIALCHECK://PE-7989 metaDataColumnsOnly added in method signature
  442. rangeOrSeqObjList = apiExpressionEvaluator.performSequentialCheck(dataMap, validationNode, node,
  443. dataNode, dimMap,apiExpressionEvaluator.getColumnDataTypeMapping(), true, metaDataColumnsOnly);
  444. break;
  445. default:
  446. }
  447. }else {
  448. result = Constants.MANDATORY_VALIDATIONTYPE;
  449. obj = APIExpressionEvaluator.prepareOutputJson(null, null, result, null, null, null,
  450. null, null);
  451. }
  452. if (obj != null) {
  453. arr.add(obj);
  454. obj = null;
  455. }
  456. if(rangeOrSeqObjList!=null)
  457. {
  458. for(int j=0;j<rangeOrSeqObjList.size();j++)
  459. {
  460. arr.add(rangeOrSeqObjList.get(j));
  461. }
  462. rangeOrSeqObjList=null;
  463. }
  464. if((null != predefinedObjList) && (predefinedObjList.size() > 0)){
  465. arr.addAll(predefinedObjList);
  466. predefinedObjList = null;
  467. }
  468. }
  469. } else if (!isAggregateRequest && flag == false) {
  470. logger.info("{}","Check if flag is false");
  471. //8421 code changes.
  472. if(null != dataType && !incorrectDataType.containsKey(dataType)){
  473. if(Constants.INT.equals(dataType)){
  474. result = Cache.getPropertyFromError(ErrorCacheConstant.ERR_061);
  475. }else if(Constants.DOUBLE.equals(dataType)){
  476. result = Cache.getPropertyFromError(ErrorCacheConstant.ERR_062);
  477. }else if(Constants.DATE.equals(dataType)){
  478. result = Cache.getPropertyFromError(ErrorCacheConstant.ERR_063);
  479. }else{
  480. result = Cache.getPropertyFromError(ErrorCacheConstant.ERR_043);
  481. }
  482. }
  483. if (null != nodeDTObject && null != dnCodeObject) {
  484. obj = APIExpressionEvaluator.prepareOutputJson(validationObjNode, node, result,
  485. ValidationTypes.DATATYPEERROR, dnCodeObject.asText(), nodeDTObject.asText(),
  486. nodeDTObject.asText(), null);
  487. }
  488. if (obj != null) {
  489. arr.add(obj);
  490. obj = null;
  491. }
  492. }
  493. // PE-6874 : Fixed by shifting this code down here
  494. //Following code written for Mercer JIRA Story PE-5691
  495. // If data node code value is not present then set to Blank and Data map also.
  496. // PE-7071 : Remove CODE if there is no validation OR validation_errorType != "AUTOCORRECT"
  497. if(isEmtpyRecord &&
  498. (validationNode==null ||
  499. (null!=validationNode && !JsonUtils.isNullOrBlankOrNullNode(validationNode.get(Constants.ERROR_TYPE))
  500. && !(validationNode.get(Constants.ERROR_TYPE).asText()).equalsIgnoreCase("AUTOCORRECT")))) {
  501. ((ObjectNode)dataNode).remove(code);
  502. }
  503. //PE-5691 End.
  504. // PE : 2449 to create auto-correct object for missing EEID
  505. if ((code!=null &&code.equalsIgnoreCase(Constants.EMPLOYEE_EEID)) ||
  506. (mappedColumnName !=null && mappedColumnName.equalsIgnoreCase(Constants.EMPLOYEE_EEID)))
  507. obj = prepareEeidAutoCorrectObject(code, dataMap, dataNode,columnMappingMap);
  508. if (obj != null) {
  509. arr.add(obj);
  510. obj = null;
  511. }
  512. if (node.get("questionType") != null
  513. && node.get("questionType").asText().equals("checkboxes")) {
  514. buildCheckboxArray(dataNode,code, mappedColumnName);
  515. }
  516. }
  517. code = null;
  518. validationNode = null;
  519. }
  520. // PE-6254 ML Integration work
  521. if(mlAutoCoorect && !isAggregateRequest)
  522. {
  523. removeDataNodeACFields(dataNode);
  524. }
  525. if ((arr != null && arr.size() > 0)) {
  526. if (!isAggregateRequest) {
  527. /*
  528. * if(dataNode.get(k).get(code)!=null) ((ObjectNode)
  529. * (dataNode.get(k))).set(code, dataNode.get(k).get(code));
  530. */
  531. ((ObjectNode) (dataNode)).set(Constants.VALIDATION_ERRORS, arr);
  532. arr = null;
  533. } else { // Aggregate
  534. JsonNode objectNode = mapper.convertValue(arr, JsonNode.class);
  535. return objectNode;
  536. }
  537. }
  538. }
  539. return dataNode;
  540. }
  541. /**
  542. * @param dataNode
  543. * @param mappedColumnName
  544. * @param nodeDTObject
  545. * @param dnCodeObject
  546. * @param flag
  547. * @param datePatternArray
  548. * @param numberPatternArray
  549. * @return
  550. */
  551. protected Map<String,String> dataTypeCheck(HashMap<String, JsonNode> dataMap, JsonNode dataNode, String mappedColumnName, JsonNode nodeDTObject,
  552. JsonNode dnCodeObject, Boolean flag, ArrayNode datePatternArray, ArrayNode numberPatternArray) {
  553. String dnObjetText;
  554. Map<String,String> incorrectDataTypeMap = new HashMap<>();
  555. boolean isNullNode = NullNode.class.equals(dnCodeObject.getClass());
  556. if (!isNullNode) {
  557. dnObjetText = dnCodeObject.asText();
  558. }else {
  559. dnObjetText = null;
  560. }
  561. boolean dataTypeFlag = flag;
  562. String incorrectintegerDataType = "";
  563. boolean isDateArray = false;
  564. boolean isNumberArray = false;
  565. // 7257 For Multi-part request check following arrays
  566. if ( null != datePatternArray && datePatternArray.size() > 0 ) {
  567. isDateArray = true ;
  568. }
  569. if ( null != numberPatternArray && numberPatternArray.size() > 0 ) {
  570. isNumberArray = true;
  571. }
  572. // Check for integer,boolean,double ,date and string data type object.
  573. if ("int".equalsIgnoreCase(nodeDTObject.asText()) && (StringUtils.isEmpty(dnObjetText) || isNullNode
  574. || (isNumberArray ? DataUtility.isNumeric(dnObjetText, numberPatternArray)
  575. : (DataUtility.isNumeric(dnObjetText)||DataUtility.isDecimal(dnObjetText)) ))) {
  576. //8421 code changes.
  577. dataTypeFlag = true;
  578. incorrectintegerDataType = "integer";
  579. // PE-9689 : If the value is string integer("45"), then convert it to integer(45).
  580. // PE-9708 : If the value is string integer("45.0" or "45.7"), then convert it to integer(45).
  581. if(dnCodeObject.asText().matches(Constants.INT_PATTERN) || dnCodeObject.asText().matches(Constants.DATATYPE_DOUBLE_PATTERN)) {
  582. ((ObjectNode) dataNode).set(mappedColumnName, JsonNodeFactory.instance.numberNode(dnCodeObject.asInt()));
  583. dataMap.put(mappedColumnName,dataNode.get(mappedColumnName));
  584. // Else if Dataformat is defined, convert it to appropriate string.
  585. } else if (isNumberArray && !dnCodeObject.isNumber() && !StringUtils.isEmpty(dnObjetText)) {
  586. ((ObjectNode) dataNode).put(mappedColumnName, DataUtility.toNumber(dnObjetText, numberPatternArray));
  587. //PE-8731
  588. dataMap.put(mappedColumnName,dataNode.get(mappedColumnName));
  589. }
  590. } else if ("boolean".equalsIgnoreCase(nodeDTObject.asText()) && ("false".equalsIgnoreCase(dnObjetText)
  591. || isNullNode || StringUtils.isEmpty(dnObjetText) || "true".equalsIgnoreCase(dnObjetText))) {
  592. //8421 code changes.
  593. dataTypeFlag = true;
  594. incorrectintegerDataType = "boolean";
  595. ((ObjectNode) dataNode).put(mappedColumnName, DataUtility.toNumber(dnObjetText, numberPatternArray));
  596. } else if ("date".equalsIgnoreCase(nodeDTObject.asText()) && (StringUtils.isEmpty(dnObjetText) || isNullNode
  597. || (isDateArray ? DataUtility.isValidDate(dnObjetText, datePatternArray)
  598. : DataUtility.isValidDate(dnObjetText)))) {
  599. //8421 code changes.
  600. dataTypeFlag = true;
  601. incorrectintegerDataType = "date";
  602. // PE-9689 : If the value is string long("45454545"), then convert it to integer(45454545).
  603. if(dnCodeObject.asText().matches(Constants.LONG_PATTERN)) {
  604. ((ObjectNode) dataNode).set(mappedColumnName, JsonNodeFactory.instance.numberNode(Long.parseLong(dnCodeObject.asText())));
  605. dataMap.put(mappedColumnName,dataNode.get(mappedColumnName));
  606. // Else if Dateformat is defined, convert it to appropriate string.
  607. // Convert to ISO-8601 Format
  608. } else if (isDateArray && !StringUtils.isEmpty(dnObjetText)) {
  609. ((ObjectNode) dataNode).put(mappedColumnName, DataUtility.customDateConvertor(dnObjetText,datePatternArray));
  610. }
  611. } else if ("double".equalsIgnoreCase(nodeDTObject.asText()) && (StringUtils.isEmpty(dnObjetText) || isNullNode
  612. || (isNumberArray ? DataUtility.isDecimal(dnObjetText, numberPatternArray)
  613. : DataUtility.isDecimal(dnObjetText)))) {
  614. dataTypeFlag = true;
  615. incorrectintegerDataType = "double";
  616. // PE-9689 Note : If user passes integer(454545) while the dataype="double", it will get converted to double(454545.0)
  617. // If the value is string long("4545.45"), then convert it to integer(4545.45).
  618. if(dnCodeObject.asText().matches(Constants.DATATYPE_DOUBLE_PATTERN)) {
  619. ((ObjectNode) dataNode).set(mappedColumnName, JsonNodeFactory.instance.numberNode(Double.parseDouble(dnCodeObject.asText())));
  620. dataMap.put(mappedColumnName, dataNode.get(mappedColumnName));
  621. // Else if Dataformat is defined, convert it to appropriate string.
  622. //Convert to java decimal
  623. } else if (isNumberArray && !StringUtils.isEmpty(dnObjetText)) {
  624. ((ObjectNode) dataNode).put(mappedColumnName, DataUtility.toDecimal(dnObjetText, numberPatternArray));
  625. //PE-8731
  626. dataMap.put(mappedColumnName,dataNode.get(mappedColumnName));
  627. }
  628. } else if (StringUtils.isEmpty(dnObjetText) || isNullNode || "string".equalsIgnoreCase(nodeDTObject.asText())) {
  629. dataTypeFlag = true;
  630. }
  631. //8421 code changes.
  632. incorrectDataTypeMap.put("dataTypeFlag", Boolean.toString(dataTypeFlag));
  633. incorrectDataTypeMap.put("datatype", incorrectintegerDataType);
  634. return incorrectDataTypeMap;
  635. }
  636. public ArrayNode findAndMerge(JsonNode dataNode, ArrayNode csvNode, String uniqueIdColumnCode) {
  637. Iterator<String> it = null;
  638. String key = "";
  639. boolean isMerged = false;
  640. if (dataNode != null && dataNode.size() > 0) {
  641. for (int i = 0; i < dataNode.size(); i++) {
  642. isMerged = false;
  643. if (dataNode.get(i).get(uniqueIdColumnCode) != null)
  644. {
  645. for (int j = 0; j < csvNode.size(); j++) {
  646. if (csvNode.get(j).get(uniqueIdColumnCode) != null && csvNode.get(j).get(uniqueIdColumnCode)
  647. .equals(dataNode.get(i).get(uniqueIdColumnCode))) {
  648. it = dataNode.get(i).fieldNames();
  649. while (it != null && it.hasNext()) {
  650. key = it.next();
  651. if (JsonUtils.isNullOrBlankOrNullNode(csvNode.get(j).get(key)) || csvNode.get(j).get(key).asText().equals("")) {
  652. ((ObjectNode) csvNode.get(j)).set(key, dataNode.get(i).get(key));
  653. }
  654. }
  655. isMerged = true;
  656. }
  657. }
  658. if (!isMerged) {
  659. csvNode.add(dataNode.get(i));
  660. }
  661. }
  662. }
  663. }
  664. return csvNode;
  665. }
  666. public void buildCheckboxArray(JsonNode dataNode,String code, String mappedColumnName) {
  667. if (code == null || code.equals("")) {
  668. code = mappedColumnName;
  669. }
  670. if (dataNode.get(code) != null)
  671. {
  672. if (dataNode.get(code).getNodeType() != JsonNodeType.OBJECT
  673. && dataNode.get(code).getNodeType() != JsonNodeType.ARRAY) {
  674. ArrayNode arrNode = mapper.createArrayNode();
  675. // PE-7795 Array was giving arrayName["null"] wrong array.
  676. // Below changes will give arraName[null] requires correct array.
  677. if( !JsonUtils.isNullNode(dataNode.get(code))) {
  678. String arr1[] = dataNode.get(code).asText().split(",");
  679. if (arr1 != null && arr1.length > 0) {
  680. for (int i = 0; i < arr1.length; i++) {
  681. arrNode.add(arr1[i]);
  682. }
  683. }
  684. }
  685. ((ObjectNode) (dataNode)).set(code, arrNode);
  686. } else {
  687. Iterator<Map.Entry<String, JsonNode>> it = dataNode.get(code).fields();
  688. Map.Entry<String, JsonNode> entry = null;
  689. while (it != null && it.hasNext()) {
  690. entry = it.next();
  691. ArrayNode arrNode = mapper.createArrayNode();
  692. switch (entry.getValue().getNodeType()) {
  693. case ARRAY:
  694. for (final JsonNode objNode : entry.getValue()) {
  695. arrNode.add(objNode);
  696. }
  697. break;
  698. case STRING:
  699. String[] arr1 = entry.getValue().asText().split(",");
  700. if (arr1 != null && arr1.length > 0) {
  701. for (int i = 0; i < arr1.length; i++) {
  702. arrNode.add(arr1[i]);
  703. }
  704. }
  705. break;
  706. default:
  707. break;
  708. }
  709. ((ObjectNode) (dataNode.get(code))).set(entry.getKey(), arrNode);
  710. }
  711. }
  712. }
  713. }
  714. /**
  715. *
  716. * @param header
  717. * @param entitiesJson
  718. * @return
  719. * @throws JsonParseException
  720. * @throws JsonMappingException
  721. * @throws IOException
  722. */
  723. @SuppressWarnings("unchecked")
  724. public HashMap<String, Object> compareFields(List<HashMap<String, String>> records,List<String> header, String entitiesJson,
  725. HashMap<String, Object> xlsxMap,Object eeidColFlag) throws Exception {
  726. ArrayNode entitiesNode = mapper.readValue(entitiesJson, ArrayNode.class);
  727. JsonNode columnNode = null;
  728. ArrayNode arr = null;
  729. int columnNodeSize = 0;
  730. boolean found = false;
  731. boolean multiSheetExcel=false;
  732. ObjectNode resultNode = null;
  733. HashMap<String, Object> resultMap = new HashMap<String, Object>();
  734. String entityCode = null;
  735. JsonNode skip = null;
  736. String mappedColName = null;
  737. boolean sheetMatchingFlag = true;
  738. String sheetName = "";
  739. JsonNode dataNode = null;
  740. String currentHeaderCol = null;//PE-8247 duplicate cols validation
  741. Set<String> set = null;//PE-8247
  742. HashMap<String, List<String>> headerMap=null;
  743. if(xlsxMap!=null)
  744. {
  745. headerMap = (HashMap<String, List<String>>)xlsxMap.get(Constants.XLSXHEADERMAP);
  746. }
  747. if (entitiesNode != null && xlsxMap != null && headerMap != null) {
  748. if(headerMap.size() > 1 )
  749. multiSheetExcel=true;
  750. if (entitiesNode.size() < headerMap.size()) {
  751. sheetMatchingFlag = false;
  752. } else {
  753. for (int i = 0; i < entitiesNode.size(); i++) {
  754. sheetName = entitiesNode.get(i).get(Constants.CONTEXTDATAKEY).get(Constants.COMPANYNAME).asText() + "_"
  755. + entitiesNode.get(i).get(Constants.CONTEXTDATAKEY).get(Constants.CTRYCDOE).asText();
  756. if (headerMap.get(sheetName) == null) {
  757. sheetMatchingFlag = false;
  758. }
  759. break;
  760. }
  761. }
  762. }
  763. if(xlsxMap!=null && (records !=null || !multiSheetExcel) && entitiesNode.size()> 1)
  764. {
  765. HashMap<String, Object> map = new HashMap<>();
  766. if(records !=null)
  767. {
  768. map.put("data", records);
  769. map.put(Constants.COLUMNS,header );
  770. }
  771. else
  772. {
  773. map.put("data", ((HashMap<String, List<HashMap<String, String>>>)xlsxMap.get(Constants.XLSXDATAMAP)).get(xlsxMap.get(Constants.FIRSTSHEETNAME)));
  774. map.put(Constants.COLUMNS,headerMap.get(xlsxMap.get(Constants.FIRSTSHEETNAME)) );
  775. }
  776. dataNode = mapper.readValue(mapper.writeValueAsString(map), JsonNode.class);
  777. resultMap.put(Constants.RESULTNODE, dataNode);
  778. return resultMap;
  779. }
  780. for (int i = 0; i < entitiesNode.size(); i++) {
  781. set = new HashSet<>();
  782. dataNode = mapper.createObjectNode();
  783. columnNode = entitiesNode.get(i).get(Constants.SECTION_STRUCTURE).get(Constants.COLUMNS);
  784. if (entitiesNode.get(i).get(Constants.CONTEXTDATAKEY).get(Constants.COMPANYNAME) != null
  785. && entitiesNode.get(i).get(Constants.CONTEXTDATAKEY).get(Constants.CTRYCDOE) != null) {
  786. sheetName = entitiesNode.get(i).get(Constants.CONTEXTDATAKEY).get(Constants.COMPANYNAME).asText() + "_"
  787. + entitiesNode.get(i).get(Constants.CONTEXTDATAKEY).get(Constants.CTRYCDOE).asText();
  788. }
  789. columnNodeSize = (columnNode).size();
  790. if (xlsxMap != null && xlsxMap.get("xlsxHeaderMap") != null) {
  791. if (!sheetMatchingFlag) {
  792. header = headerMap.get(xlsxMap.get(Constants.FIRSTSHEETNAME));
  793. } else {
  794. header = headerMap.get(sheetName);
  795. }
  796. }
  797. resultNode = mapper.createObjectNode();
  798. if (header != null) {
  799. for (int j = 0; j < header.size(); j++) {
  800. //PE-8247 Duplicate Cols Validation
  801. if(!set.add(header.get(j).trim())){
  802. throw new CustomStatusException(Constants.HTTPSTATUS_400,
  803. in.lnt.utility.general.Cache.getPropertyFromError(ErrorCacheConstant.ERR_065));
  804. }
  805. }
  806. for (int j = 0; j < header.size(); j++) {
  807. currentHeaderCol = header.get(j);
  808. found = false;
  809. for (int k = 0; k < columnNodeSize; k++) {
  810. skip = columnNode.get(k).get(Constants.SKIP);
  811. if (null != columnNode.get(k).get("code")) {
  812. entityCode = columnNode.get(k).get("code").asText();
  813. }
  814. if (null != columnNode.get(k).get(Constants.MAPPED_COLUMN_NAME)) {
  815. mappedColName = columnNode.get(k).get(Constants.MAPPED_COLUMN_NAME).asText();
  816. }
  817. //Code modified to skip mapping in case of skip=true in request PE : 6858
  818. if(skip!=null && skip.asText().equals("true"))
  819. {
  820. if(currentHeaderCol.equals(entityCode) || currentHeaderCol.equals(mappedColName))
  821. {
  822. found = true;
  823. break;
  824. }
  825. else
  826. {
  827. continue;
  828. }
  829. }
  830. if ((!StringUtils.isEmpty(entityCode)|| !StringUtils.isEmpty(mappedColName)) && skip==null && (currentHeaderCol.equals(entityCode) || currentHeaderCol.equals(mappedColName))) {
  831. found = true;
  832. break;
  833. }
  834. }
  835. if (!found) {
  836. break;
  837. }
  838. }
  839. }
  840. if (!found) {
  841. break;
  842. }
  843. }
  844. if (!found || (xlsxMap!=null &&((Integer)xlsxMap.get(Constants.EEIDINHEADER)!= (headerMap.size()))) ) {
  845. if(!multiSheetExcel)
  846. {
  847. HashMap<String, Object> map = new HashMap<String, Object>();
  848. if(xlsxMap!=null)
  849. {
  850. if(!sheetMatchingFlag)
  851. {
  852. map.put("data", ((HashMap<String, List<HashMap<String, String>>>)xlsxMap.get(Constants.XLSXDATAMAP)).get(xlsxMap.get(Constants.FIRSTSHEETNAME)));
  853. }
  854. else{
  855. map.put("data", ((HashMap<String, List<HashMap<String, String>>>)xlsxMap.get(Constants.XLSXDATAMAP)).get(sheetName));
  856. }
  857. }
  858. else if(records!=null)
  859. {
  860. map.put("data", records);
  861. }
  862. if((boolean)eeidColFlag)
  863. {
  864. map.put(Constants.COLUMNS,header );
  865. }
  866. else
  867. {
  868. header.remove(header.size() - 1);
  869. map.put(Constants.COLUMNS,header);
  870. }
  871. dataNode = mapper.readValue(mapper.writeValueAsString(map), JsonNode.class);
  872. resultMap.put(Constants.RESULTNODE, dataNode);
  873. }
  874. else
  875. {
  876. resultMap.put(Constants.RESULTNODE, ErrorCacheConstant.ERR_055);
  877. }
  878. } else {
  879. resultMap.put(Constants.RESULTNODE, null);
  880. if (sheetMatchingFlag == false) {
  881. resultMap.put("sheetMatchingFlag",
  882. null != xlsxMap.get(Constants.FIRSTSHEETNAME) ? xlsxMap.get(Constants.FIRSTSHEETNAME) : "");
  883. }
  884. return resultMap;
  885. }
  886. if (sheetMatchingFlag == false) {
  887. resultMap.put("sheetMatchingFlag",
  888. null != xlsxMap.get(Constants.FIRSTSHEETNAME) ? xlsxMap.get(Constants.FIRSTSHEETNAME) : "");
  889. }
  890. return resultMap;
  891. }
  892. @SuppressWarnings("unchecked")
  893. public HashMap<String, Object> convertXlsxToMap(Map<String, Object> workBookMap,String empIdColumn) throws Exception {
  894. HashMap<String, Object> map = null;
  895. List<String> headerList = null;
  896. List<ArrayList<String>> dataList = null;
  897. HashMap<String, List<HashMap<String, String>>> xlsxDataMap = null;
  898. HashMap<String, List<String>> xlsxHeaderMap = null;
  899. HashMap<String, Object> xlsxMap = null;
  900. xlsxDataMap = new HashMap<>();
  901. xlsxHeaderMap = new HashMap<>();
  902. Set<Object> eeidSet = null;
  903. List<HashMap<String, String>> allRecords = null;
  904. HashMap<String, String> record = null;
  905. boolean eeidFlag = true;
  906. //PE-8933
  907. boolean eeidMissingFlag = false;
  908. String tempDataListRecord ;
  909. String tempHeaderListRecord;
  910. int eeIdInHeader=0;
  911. if (workBookMap != null && workBookMap.size() > 0) {
  912. xlsxMap = new HashMap<>();
  913. //Iterate through each xlsx tab.
  914. for (Entry<String, Object> entry : workBookMap.entrySet()) {
  915. eeidSet = new HashSet<>();
  916. if (entry.getKey().equals(Constants.FIRSTSHEETNAME)) {
  917. xlsxMap.put(Constants.FIRSTSHEETNAME, entry.getValue());
  918. continue;
  919. }
  920. allRecords = new ArrayList<>();
  921. map = (HashMap<String, Object>) entry.getValue();
  922. headerList = (List<String>) map.get("header");
  923. dataList = (List<ArrayList<String>>) map.get("data");
  924. //Iterate through data records from each xlsx tab.
  925. for (int i = 0; i < dataList.size(); i++) {
  926. record = new HashMap<>();
  927. //Iterate through each header from each tab.
  928. for (int j = 0; j < headerList.size(); j++) {
  929. tempDataListRecord = dataList.get(i).get(j);
  930. tempHeaderListRecord = headerList.get(j);
  931. if (tempHeaderListRecord.equalsIgnoreCase(Constants.EMPLOYEE_EEID) || (empIdColumn!=null
  932. && !empIdColumn.equals("") && tempHeaderListRecord.equals(empIdColumn))) {
  933. try {
  934. if(i==0)
  935. {
  936. eeIdInHeader++;
  937. }
  938. if (tempDataListRecord != null && !tempDataListRecord.equals(""))
  939. eeidFlag = eeidSet.add(tempDataListRecord);
  940. else {
  941. // PE-8933
  942. eeidMissingFlag = true;
  943. }
  944. } catch (IndexOutOfBoundsException e) {
  945. eeidFlag = true;
  946. }
  947. }
  948. if (eeidFlag) {
  949. try {
  950. boolean isNotBlankEEID = !StringUtils.isEmpty(tempDataListRecord);
  951. record.put(tempHeaderListRecord,
  952. (isNotBlankEEID ? tempDataListRecord : Constants.BLANK));
  953. } catch (IndexOutOfBoundsException e) {
  954. record.put(tempHeaderListRecord, Constants.BLANK);
  955. }
  956. } else {
  957. xlsxMap.put("isEeidDuplicate", "true");
  958. eeidSet=null;
  959. //PE-8933
  960. if(eeidMissingFlag)
  961. xlsxMap.put(Constants.MISSING_EEID, true);
  962. else
  963. xlsxMap.put(Constants.MISSING_EEID, false);
  964. return xlsxMap;
  965. }
  966. }
  967. allRecords.add(record);
  968. //Clean up block
  969. record = null;
  970. }
  971. xlsxDataMap.put(entry.getKey(), allRecords);
  972. xlsxHeaderMap.put(entry.getKey(), headerList);
  973. xlsxMap.put(Constants.XLSXHEADERMAP, xlsxHeaderMap);
  974. xlsxMap.put(Constants.XLSXDATAMAP, xlsxDataMap);
  975. //PE-8933
  976. if(eeidMissingFlag)
  977. xlsxMap.put(Constants.MISSING_EEID, true);
  978. else
  979. xlsxMap.put(Constants.MISSING_EEID, false);
  980. //Clean up records
  981. allRecords = null;
  982. }
  983. xlsxMap.put(Constants.EEIDINHEADER, eeIdInHeader);
  984. }
  985. eeidSet = null;
  986. //logger.info(String.format("%s %s", Constants.EXIT ,Constants.LOG_CONVERXLSXTOMAP));
  987. return xlsxMap;
  988. }
  989. @SuppressWarnings("unchecked")
  990. public LinkedHashMap<String, String> prepareJsonString(HashMap<String, Object> xslsMap) throws Exception{
  991. HashMap<String, Object> map = new HashMap<String, Object>();
  992. HashMap<String, List<HashMap<String, String>>> xlsxDataMap = null;
  993. String csvJsonString = "";
  994. LinkedHashMap<String, String> xslJsonMap = new LinkedHashMap<String, String>();
  995. HashMap<String, List<HashMap<String, String>>> xlsxDataMap_Temp = null;
  996. if (xslsMap != null && xslsMap.size() > 0) {
  997. xlsxDataMap_Temp = (HashMap<String, List<HashMap<String, String>>>) xslsMap.get(Constants.XLSXDATAMAP); //PE-9452 Empty cols removal
  998. xlsxDataMap = RemoveColsWithNoValue(xlsxDataMap_Temp); //PE-9452 Empty cols removal
  999. for (Entry<String, List<HashMap<String, String>>> entry : xlsxDataMap.entrySet()) {
  1000. map.put("data", entry.getValue());
  1001. ObjectMapper objmapper = new ObjectMapper();
  1002. csvJsonString = objmapper.writeValueAsString(map);
  1003. xslJsonMap.put(entry.getKey(), csvJsonString);
  1004. }
  1005. }
  1006. return xslJsonMap;
  1007. }
  1008. //Method added to remove cols having no values PE-9452
  1009. public HashMap<String, List<HashMap<String, String>>> RemoveColsWithNoValue(HashMap<String, List<HashMap<String, String>>> xlsxDataMap) throws Exception{
  1010. List<HashMap<String, String>> xslJsonMapEntry = null;;
  1011. HashMap<String, List<HashMap<String, String>>> xlsxDataMapWithoutEmptyCols = new HashMap<String, List<HashMap<String, String>>>();
  1012. HashMap<String, String> hm = null;
  1013. for (Entry<String, List<HashMap<String, String>>> entry : xlsxDataMap.entrySet()) {
  1014. xslJsonMapEntry = new ArrayList<HashMap<String, String>>();
  1015. for(HashMap<String, String> hm1 : entry.getValue()){
  1016. hm = new HashMap<String, String>();
  1017. for(Entry<String,String> entry1 : hm1.entrySet()){
  1018. if(entry1.getValue().length() == 0){
  1019. //hm.remove(entry.getKey());
  1020. }else{
  1021. hm.put(entry1.getKey(), entry1.getValue());
  1022. }
  1023. }
  1024. xslJsonMapEntry.add(hm);
  1025. }
  1026. xlsxDataMapWithoutEmptyCols.put(entry.getKey(),xslJsonMapEntry);
  1027. }
  1028. return xlsxDataMapWithoutEmptyCols;
  1029. }
  1030. // PE : 2449 to check duplication of EEID start in case of entity data in
  1031. // request body
  1032. public Map<String,String> checkUniqueNessForEEID(String enetityJson,String dataAsJson) throws Exception{
  1033. //logger.info(String.format("%s %s", Constants.INTIATE ,Constants.LOG_CHECKUNIQUENESSFOREEID));
  1034. @SuppressWarnings("unchecked")
  1035. Map<String,String> empIdMap= new HashMap<>();
  1036. empIdMap.put(Constants.ISUNIQUE, "true");
  1037. JsonNode entityNode = null;
  1038. boolean flag = false;
  1039. String code = "";
  1040. JsonNode sectionStructureNode = null;
  1041. String empIdColumn="";
  1042. ArrayList<JsonNode> columnNodeList = null;
  1043. columnNodeList = new ArrayList<JsonNode>();
  1044. JsonNode entittiesNode = mapper.readValue(enetityJson, JsonNode.class);
  1045. Set<String> eeidSet = null;
  1046. if (entittiesNode != null) {
  1047. for (int i = 0; i < entittiesNode.size(); i++) {
  1048. eeidSet = new HashSet<>();
  1049. entityNode = entittiesNode.get(i);
  1050. sectionStructureNode = entityNode.get(Constants.SECTION_STRUCTURE);
  1051. for (int j = 0; j < sectionStructureNode.get(Constants.COLUMNS).size(); j++) {
  1052. columnNodeList.add(sectionStructureNode.get(Constants.COLUMNS).get(j));
  1053. }
  1054. if (columnNodeList != null && columnNodeList.size() > 0) {
  1055. for (JsonNode node : columnNodeList) {
  1056. if (node.get(Constants.CODE) != null)
  1057. code = node.get(Constants.CODE).asText();
  1058. if (code.equals(Constants.EMPLOYEE_EEID))
  1059. {
  1060. flag = true;
  1061. if(node.get(Constants.MAPPED_COLUMN_NAME)!=null && !node.get(Constants.MAPPED_COLUMN_NAME).asText().equals(""))
  1062. {
  1063. empIdColumn = node.get(Constants.MAPPED_COLUMN_NAME).asText();
  1064. empIdMap.put("empIdColumn", empIdColumn);
  1065. }
  1066. }
  1067. }
  1068. }
  1069. if (flag) {
  1070. JsonNode dataNode = entittiesNode.get(i).get(Constants.DATA);
  1071. if (dataNode != null) {
  1072. for (int k = 0; k < dataNode.size(); k++) {
  1073. if (dataNode.get(k).get(Constants.EMPLOYEE_EEID) != null
  1074. && !dataNode.get(k).get(Constants.EMPLOYEE_EEID).asText().equals("")) {
  1075. String eeId = dataNode.get(k).get(Constants.EMPLOYEE_EEID).asText();
  1076. if (!eeidSet.add(eeId)) {
  1077. eeidSet.clear();
  1078. empIdMap.put(Constants.ISUNIQUE,Constants.DUPLICATE);
  1079. return empIdMap;
  1080. }
  1081. } else {
  1082. empIdMap.put(Constants.ISUNIQUE,Constants.MISSING);
  1083. return empIdMap;
  1084. }
  1085. }
  1086. }
  1087. if(dataAsJson!=null)
  1088. {
  1089. empIdMap = DataUtility.checkUniqueEEIDForRequestDataJson(dataAsJson,empIdMap);
  1090. return empIdMap;
  1091. }
  1092. }
  1093. }
  1094. }
  1095. return empIdMap;
  1096. }
  1097. // PE : 2449 to prepare auto-correct validation object in case of missing EEID..
  1098. public ObjectNode prepareEeidAutoCorrectObject(String code, HashMap<String, JsonNode> dataMap, JsonNode dataNode,
  1099. HashMap<String, String> columnMappingMap) throws Exception {
  1100. ObjectNode obj = null;
  1101. if (dataMap != null && ((!JsonUtils.isNullOrBlankOrNullNode(dataMap.get(Constants.EMPLOYEE_EEID))
  1102. && !JsonUtils.isBlankTextNode(dataMap.get(Constants.EMPLOYEE_EEID)) )
  1103. || (!JsonUtils.isNullOrBlankOrNullNode(dataMap.get(columnMappingMap.get(code)))
  1104. && !JsonUtils.isBlankTextNode(dataMap.get(columnMappingMap.get(code))) )))
  1105. {
  1106. return obj;
  1107. } else {
  1108. Strin

Large files files are truncated, but you can click here to view the full file