PageRenderTime 31ms CodeModel.GetById 16ms RepoModel.GetById 0ms app.codeStats 1ms

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

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

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