PageRenderTime 78ms CodeModel.GetById 21ms 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
  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++) {
  1123. mlItr = mlNode.get(k).fields();
  1124. while (mlItr.hasNext()) {
  1125. entry = mlItr.next();
  1126. if (entry.getKey().contains("_Replace") || entry.getKey().contains("_ACflag")) {
  1127. ((ObjectNode) mlNode.get(k)).remove(entry.getKey());
  1128. }
  1129. }
  1130. }
  1131. }
  1132. return mlJsonDataArray;
  1133. }
  1134. public void performL0Validation(String entitiesJson, String csvJsonString, boolean isAggregateRequest,
  1135. HashMap<String, String> xslJsonMap, String FirstSheetName) throws Exception
  1136. {
  1137. //logger.info(String.format("%s %s", Constants.INTIATE ,Constants.LOG_PERFORML0VALIDATION));
  1138. JsonNode sectionStructureNode = null;
  1139. JsonNode contextDataNode = null;
  1140. JsonNode csvNode = null;
  1141. JsonNode entityNode = null;
  1142. long startTime=0;
  1143. long stopTime=0;
  1144. Set<String> xslJsonSheets = null;
  1145. String code = "";
  1146. JsonNode validationNode = null;
  1147. String returnValue="";
  1148. Pattern pattern = Pattern.compile(Constants.EXP_PATTERN);
  1149. boolean columnMissflag = true;
  1150. Map<String,String> mappedColumnMap = new HashMap<String,String>();
  1151. // 8395 JP
  1152. String field=null;
  1153. Map<String,String> metaDataColumnMap = new HashMap<String,String>();
  1154. ArrayNode entitiesNode = mapper.readValue(entitiesJson, ArrayNode.class);
  1155. if (xslJsonMap != null) {
  1156. xslJsonSheets = new HashSet<String>(xslJsonMap.keySet());
  1157. }
  1158. for (int i = 0; i < entitiesNode.size(); i++) {
  1159. entityNode = entitiesNode.get(i);
  1160. if(entitiesNode.get(i).get(Constants.DATA)!=null && entitiesNode.get(i).get(Constants.DATA).size()>0)
  1161. {
  1162. break;
  1163. }
  1164. sectionStructureNode = entityNode.get(Constants.SECTION_STRUCTURE);
  1165. contextDataNode = entityNode.get(Constants.CONTEXTDATAKEY);
  1166. if (csvJsonString != null && !csvJsonString.equals("")) {
  1167. csvNode = mapper.readValue(csvJsonString, JsonNode.class);
  1168. } else if (xslJsonMap != null && xslJsonMap.size() > 0) {
  1169. String coName_CtryCode = contextDataNode.get("companyName").asText() + "_"
  1170. + contextDataNode.get("ctryCode").asText();
  1171. if (FirstSheetName != null) {
  1172. csvNode = mapper.readValue(xslJsonMap.get(FirstSheetName), JsonNode.class);
  1173. } else if (xslJsonMap.get(coName_CtryCode) != null) {
  1174. if (xslJsonSheets.contains(coName_CtryCode)) {
  1175. csvNode = mapper.readValue(xslJsonMap.get(coName_CtryCode), JsonNode.class);
  1176. }
  1177. } else if (xslJsonMap.get(coName_CtryCode) == null) {
  1178. /*throw new CustomStatusException(Constants.HTTPSTATUS_400,
  1179. String.format(Constants.ERROR_SHEET_NOT_FOUND, coName_CtryCode));*/
  1180. paramValueList = new ArrayList<String>();
  1181. paramValueList.add(""+coName_CtryCode);
  1182. throw new CustomStatusException(Constants.HTTPSTATUS_400,Cache.getPropertyFromError(ErrorCacheConstant.ERR_035),
  1183. Cache.getPropertyFromError(ErrorCacheConstant.ERR_035+Constants.PARAMS),paramValueList);
  1184. }
  1185. }
  1186. if (!JsonUtils.isNullOrBlankOrNullNode(csvNode)
  1187. && csvNode.get(Constants.DATA).size() > 0 ) {
  1188. sectionStructureNode = entityNode.get(Constants.SECTION_STRUCTURE);
  1189. ArrayList<JsonNode> columnNodeList = new ArrayList<JsonNode>();
  1190. for (int j = 0; j < sectionStructureNode.get(Constants.COLUMNS).size(); j++) {
  1191. columnNodeList.add(sectionStructureNode.get(Constants.COLUMNS).get(j));
  1192. //Code added for 8395
  1193. /*if(null != columnNodeList.get(j).get(Constants.CODE) && null != columnNodeList.get(j).get(Constants.MAPPED_COLUMN_NAME)){
  1194. mappedColumnMap.put(columnNodeList.get(j).get(Constants.CODE).asText(), columnNodeList.get(j).get(Constants.MAPPED_COLUMN_NAME).asText());
  1195. }
  1196. if(null != columnNodeList.get(j).get(Constants.CODE)) {
  1197. metaDataColumnsSet.add(columnNodeList.get(j).get(Constants.CODE).asText());
  1198. }*/
  1199. //8395 JP
  1200. if (null != columnNodeList.get(j).get(Constants.CODE)) {
  1201. mappedColumnMap.put(columnNodeList.get(j).get(Constants.CODE).asText(),columnNodeList.get(j).get(Constants.CODE).asText());
  1202. if (null != columnNodeList.get(j).get(Constants.MAPPED_COLUMN_NAME)) {
  1203. mappedColumnMap.put(columnNodeList.get(j).get(Constants.CODE).asText(),
  1204. columnNodeList.get(j).get(Constants.MAPPED_COLUMN_NAME).asText());
  1205. }
  1206. }
  1207. }
  1208. if (columnNodeList != null && columnNodeList.size() > 0) {
  1209. for (JsonNode node : columnNodeList) {
  1210. if (node.get(Constants.CODE) != null)
  1211. code = node.get(Constants.CODE).asText();
  1212. if (node.get(Constants.VALIDATIONS) != null
  1213. && node.get(Constants.VALIDATIONS).size() > 0) {
  1214. for (int k = 0; k < node.get(Constants.VALIDATIONS).size(); k++) {
  1215. validationNode = node.get(Constants.VALIDATIONS).get(k);
  1216. columnMissflag = true;
  1217. if (validationNode != null && validationNode.get("category") != null
  1218. && validationNode.get("category").asText().equalsIgnoreCase("file_acceptance")) {
  1219. if (validationNode.get(Constants.EXPRESSION) != null && validationNode
  1220. .get(Constants.EXPRESSION).asText().contains("ISBLANK")) {
  1221. Matcher matcher = pattern.matcher(validationNode.get(Constants.EXPRESSION).asText()
  1222. .replaceAll(Constants.CURLY_BRACES, ""));
  1223. List<String> fields = new ArrayList<String>();
  1224. while (matcher.find()) {
  1225. // 8395 JP
  1226. field=matcher.group().replace("this.", "").trim();
  1227. if(mappedColumnMap.containsKey(field)) {
  1228. fields.add(field);
  1229. }
  1230. }
  1231. for (int fieldSize = 0; fieldSize < fields.size(); fieldSize++) {
  1232. // if(csvNode.get(Constants.DATA).get(0).has(fields.get(fieldSize))){
  1233. if (csvNode.get(Constants.DATA).get(0)
  1234. .has(mappedColumnMap.get(fields.get(fieldSize)))) {
  1235. // if (csvNode.get(Constants.DATA).get(0).get(fields.get(fieldSize)) !=
  1236. // null) {
  1237. columnMissflag = false;
  1238. break;
  1239. }
  1240. }
  1241. if (!columnMissflag) {
  1242. startTime = System.currentTimeMillis();
  1243. //Code added for 8395
  1244. columnMissflag = checkforBlank(fields, csvNode,mappedColumnMap);
  1245. stopTime = System.currentTimeMillis();
  1246. //logger.info(String.format("Time taken for checkforBlank() in FormValidator..%d", (stopTime-startTime)));
  1247. }
  1248. if (columnMissflag) {
  1249. paramValueList = new ArrayList<String>();
  1250. paramValueList.add(validationNode.get("_id").asText());
  1251. paramValueList.add(code);
  1252. throw new CustomStatusException(Constants.HTTPSTATUS_400,
  1253. Cache.getPropertyFromError(ErrorCacheConstant.ERR_060),
  1254. Cache.getPropertyFromError(ErrorCacheConstant.ERR_060 + Constants.PARAMS),
  1255. paramValueList);
  1256. //return validationNode.get(Constants.MESSAGE).asText();
  1257. }
  1258. }
  1259. }
  1260. }
  1261. }
  1262. }
  1263. }
  1264. }
  1265. }
  1266. //return returnValue;
  1267. }
  1268. public boolean checkforBlank(List<String> fields,JsonNode csvNode,Map<String,String> mappedColumn)throws Exception
  1269. {
  1270. boolean returnValue = true;
  1271. JsonNode dataNode = csvNode.get(Constants.DATA);
  1272. for (String field : fields) {
  1273. if (returnValue == false)
  1274. break;
  1275. JsonNode dataNodeValue = null;
  1276. for (int i = 0; i < dataNode.size(); i++) {
  1277. dataNodeValue = dataNode.get(i);
  1278. //Code added for 8395
  1279. if ((dataNodeValue != null && !JsonUtils.isNullOrBlankOrNullNode(dataNodeValue.get(field))
  1280. && dataNodeValue.get(field).asText() != null && !dataNodeValue.get(field).asText().trim().equals("")) ||
  1281. ((dataNodeValue != null && !JsonUtils.isNullOrBlankOrNullNode(dataNodeValue.get(mappedColumn.get(field)))
  1282. && dataNodeValue.get(mappedColumn.get(field)).asText() != null && !dataNodeValue.get(mappedColumn.get(field)).asText().trim().equals("")))
  1283. /*(mappedColumn.get(dataNode.get(i)) != null)*/) {
  1284. returnValue = false;
  1285. break;
  1286. }
  1287. }
  1288. }
  1289. return returnValue;
  1290. }
  1291. // PE-7241 Changes
  1292. public static ArrayList<ObjectNode> validatePredefinedValidation(JsonNode dataNode, JsonNode columnNode,
  1293. JsonNode validationNode, HashMap<String, JsonNode> dataMap, String mappedColumnName, String errorType)
  1294. throws Exception {
  1295. ArrayList<ObjectNode> emailObjList = new ArrayList<ObjectNode>();
  1296. // Get Regex depending upon error Type
  1297. Pattern COMMON_REGEX_PATTERN = null;
  1298. switch (errorType) {
  1299. case Constants.EMAIL:
  1300. COMMON_REGEX_PATTERN = VALID_EMAIL_ADDRESS_REGEX;
  1301. break;
  1302. case Constants.PHONE:
  1303. COMMON_REGEX_PATTERN = VALID_PHONE_NUMBER_REGEX;
  1304. break;
  1305. case Constants.REQUIRED:
  1306. break;
  1307. }
  1308. boolean checkCode = false;
  1309. // Mapped Columns matching
  1310. if(columnNode.has(Constants.CODE) && !JsonUtils.isNullOrBlankOrNullNode(columnNode.get(Constants.CODE))){
  1311. checkCode = true;
  1312. }
  1313. // Dimensions
  1314. if (columnNode.has(Constants.DIMENSIONS) && !JsonUtils.isNullNode(columnNode.get(Constants.DIMENSIONS))) {
  1315. JsonNode dimensionNode = dataNode.get(checkCode ? columnNode.get(Constants.CODE).asText() : mappedColumnName);
  1316. // PE-8463 NULL Handling
  1317. if (!JsonUtils.isNullOrBlankOrNullNode(dimensionNode)) {
  1318. dimensionNode = dimensionNode.deepCopy();
  1319. }
  1320. else {
  1321. // PE-8814 - No data for dimension
  1322. dimensionNode = createNullNodesForDimension(columnNode.get(Constants.CODE).asText(),
  1323. columnNode.get(Constants.DIMENSIONS));
  1324. //PE-8814
  1325. }
  1326. if(!JsonUtils.isNullOrBlankOrNullNode(dimensionNode)){
  1327. // PE-8463 NULL Handling
  1328. for (JsonNode dimensionAttribute : columnNode.get(Constants.DIMENSIONS)) {
  1329. if (dimensionNode.has(dimensionAttribute.asText())) {
  1330. switch (dimensionNode.get(dimensionAttribute.asText()).getNodeType()) {
  1331. case OBJECT:
  1332. // No object Expected
  1333. return emailObjList;
  1334. // For Checkbox Array
  1335. case ARRAY:
  1336. for (final JsonNode checkBoxObj : dimensionNode.get(dimensionAttribute.asText())) {
  1337. String inputValue = checkInputNodeType(checkBoxObj);
  1338. ObjectNode objNode = buildValidationObjectForPredefinedValidation(COMMON_REGEX_PATTERN,
  1339. inputValue, dimensionAttribute, columnNode, validationNode, dataMap,checkCode,
  1340. errorType);
  1341. if (objNode.size() > 0) {
  1342. emailObjList.add(objNode);
  1343. }
  1344. }
  1345. break;
  1346. case STRING:
  1347. case BINARY:
  1348. case BOOLEAN:
  1349. case MISSING:
  1350. case NULL:
  1351. case NUMBER:
  1352. case POJO:
  1353. // For Normal Values / CheckBox String
  1354. if (!JsonUtils.isNullOrBlankOrNullNode(dimensionNode.get(dimensionAttribute.asText()))) {
  1355. String[] splitValues = dimensionNode.get(dimensionAttribute.asText()).asText().split(",");
  1356. for (String splitValue : splitValues) {
  1357. /*emailObjList.add(new APIExpressionEvaluator().prepareOutputJson(validationNode, columnNode,
  1358. null, ValidationTypes.expression, null, null, null, null));*/
  1359. ObjectNode objNode = buildValidationObjectForPredefinedValidation(COMMON_REGEX_PATTERN,
  1360. splitValue, dimensionAttribute, columnNode, validationNode, dataMap,checkCode, errorType);
  1361. if (objNode.size() > 0) {
  1362. emailObjList.add(objNode);
  1363. }
  1364. }
  1365. break;
  1366. }else{
  1367. ObjectNode objNode = buildValidationObjectForPredefinedValidation(COMMON_REGEX_PATTERN,
  1368. null, dimensionAttribute, columnNode, validationNode, dataMap,checkCode, errorType);
  1369. if (objNode.size() > 0) {
  1370. emailObjList.add(objNode);
  1371. }
  1372. }
  1373. }
  1374. }
  1375. // Dimension not found and Validation is required
  1376. else if (errorType.equals(Constants.REQUIRED)) {
  1377. ObjectNode objNode = new APIExpressionEvaluator().prepareOutputJson(validationNode, dimensionAttribute, null,
  1378. ValidationTypes.predefinedValidations,
  1379. checkCode ? columnNode.get(Constants.CODE).asText() : mappedColumnName, null, null, null);
  1380. if (objNode.size() > 0) {
  1381. emailObjList.add(objNode);
  1382. }
  1383. }
  1384. }
  1385. }
  1386. } else if ((columnNode.has(Constants.QUESTION_TYPE)
  1387. && (!JsonUtils.isNullNode(columnNode.get(Constants.QUESTION_TYPE))
  1388. && columnNode.get(Constants.QUESTION_TYPE).asText().equals(Constants.CHECKBOXES)))
  1389. && (!JsonUtils.isNullNode(
  1390. dataNode.get(checkCode ?
  1391. columnNode.get(Constants.CODE).asText() :
  1392. mappedColumnName)))) {
  1393. JsonNode checkBoxData = dataNode.get(checkCode ? columnNode.get(Constants.CODE).asText() : mappedColumnName);
  1394. if (!JsonUtils.isNullOrBlankOrNullNode(checkBoxData)) {
  1395. switch (checkBoxData.getNodeType()) {
  1396. case ARRAY:
  1397. if(checkBoxData.size()==0) {
  1398. ObjectNode objNode = buildValidationObjectForPredefinedValidation(COMMON_REGEX_PATTERN,
  1399. null, null, columnNode, validationNode, dataMap, checkCode, errorType);
  1400. if (objNode.size() > 0) {
  1401. emailObjList.add(objNode);
  1402. }
  1403. }else {
  1404. for (final JsonNode checkBoxObj : checkBoxData) {
  1405. String inputValue = checkInputNodeType(checkBoxObj);
  1406. ObjectNode objNode = buildValidationObjectForPredefinedValidation(COMMON_REGEX_PATTERN,
  1407. inputValue, null, columnNode, validationNode, dataMap, checkCode, errorType);
  1408. if (objNode.size() > 0) {
  1409. emailObjList.add(objNode);
  1410. }
  1411. }
  1412. }
  1413. break;
  1414. case STRING:
  1415. case BINARY:
  1416. case BOOLEAN:
  1417. case MISSING:
  1418. case NULL:
  1419. case NUMBER:
  1420. case POJO:
  1421. // String Value (Comma Separated)
  1422. if (!JsonUtils.isNullOrBlankOrNullNode(
  1423. dataNode.get(checkCode ? columnNode.get(Constants.CODE).asText() : mappedColumnName))) {
  1424. String[] splitValues = dataNode
  1425. .get(checkCode ? columnNode.get(Constants.CODE).asText() : mappedColumnName).asText()
  1426. .split(",");
  1427. for (String splitValue : splitValues) {
  1428. /*emailObjList.add(new APIExpressionEvaluator().prepareOutputJson(validationNode, columnNode,
  1429. null, ValidationTypes.expression, null, null, null, null));*/
  1430. ObjectNode objNode = buildValidationObjectForPredefinedValidation(COMMON_REGEX_PATTERN,
  1431. splitValue, null, columnNode, validationNode, dataMap, checkCode, errorType);
  1432. if (objNode.size() > 0) {
  1433. emailObjList.add(objNode);
  1434. }
  1435. }
  1436. } else {
  1437. ObjectNode objNode = buildValidationObjectForPredefinedValidation(COMMON_REGEX_PATTERN, dataNode
  1438. .get(checkCode ? columnNode.get(Constants.CODE).asText() : mappedColumnName).asText(),
  1439. null, columnNode, validationNode, dataMap, checkCode, errorType);
  1440. if (objNode.size() > 0) {
  1441. emailObjList.add(objNode);
  1442. }
  1443. }
  1444. break;
  1445. }
  1446. }
  1447. } else {
  1448. /*emailObjList.add(new APIExpressionEvaluator().prepareOutputJson(validationNode, columnNode,
  1449. null, ValidationTypes.expression, null, null, null, null));*/
  1450. ObjectNode objNode = buildValidationObjectForPredefinedValidation(COMMON_REGEX_PATTERN,
  1451. (!JsonUtils.isNullOrBlankOrNullNode(dataNode.get(checkCode ? columnNode.get(Constants.CODE).asText() : mappedColumnName)) ? dataNode.get(checkCode ? columnNode.get(Constants.CODE).asText() : mappedColumnName).asText() : null), null,
  1452. columnNode, validationNode, dataMap, checkCode, errorType);
  1453. if (objNode.size() > 0) {
  1454. emailObjList.add(objNode);
  1455. }
  1456. }
  1457. return emailObjList;
  1458. }
  1459. private static JsonNode createNullNodesForDimension(String code, JsonNode dimensions) {
  1460. ObjectNode dimensionsObject = mapper.createObjectNode();
  1461. for (JsonNode dimensionNode : dimensions) {
  1462. dimensionsObject.set(dimensionNode.asText(),NullNode.getInstance());
  1463. }
  1464. return mapper.createObjectNode().set(code, dimensionsObject);
  1465. }
  1466. static String checkInputNodeType(JsonNode node) {
  1467. String inputValue = node.asText();
  1468. switch (node.getNodeType()) {
  1469. case STRING:
  1470. case BINARY:
  1471. case BOOLEAN:
  1472. break;
  1473. case MISSING:
  1474. case NULL:
  1475. inputValue = null;
  1476. break;
  1477. case NUMBER:
  1478. case POJO:
  1479. break;
  1480. }
  1481. return inputValue;
  1482. }
  1483. static ObjectNode buildValidationObjectForPredefinedValidation(Pattern COMMON_REGEX_PATTERN, String inputValue,
  1484. JsonNode dimensionAttribute, JsonNode columnNode, JsonNode validationNode, HashMap<String, JsonNode> dataMap, boolean checkCode, String errorType)
  1485. throws Exception {
  1486. ObjectNode errorObjNode = mapper.createObjectNode();
  1487. switch (errorType) {
  1488. case Constants.EMAIL:
  1489. case Constants.PHONE:
  1490. // (null == inputValue)
  1491. if (!StringUtils.isBlank(inputValue) && (null != COMMON_REGEX_PATTERN)
  1492. && !COMMON_REGEX_PATTERN.matcher(inputValue).find()) {
  1493. if ((null != dimensionAttribute) && !JsonUtils.isNullNode(dimensionAttribute)) {
  1494. ((ObjectNode) validationNode).put("dimension", dimensionAttribute.asText());
  1495. }
  1496. switch (validationNode.get(Constants.ERROR_TYPE).asText()) {
  1497. case Constants.ENHANCEMENT:
  1498. case Constants.ALERT:
  1499. case Constants.ERROR:
  1500. errorObjNode = new APIExpressionEvaluator().prepareOutputJson(validationNode,
  1501. columnNode, null, ValidationTypes.expression, null, null, null, null);
  1502. break;
  1503. case Constants.AUTOCORRECT:
  1504. /*((ObjectNode) validationNode).set("OriginalValue", dimensionNode.get(jsonNode.asText()));
  1505. ((ObjectNode) (dimensionNode)).put(jsonNode.asText(), result);
  1506. ((ObjectNode) validationNode).put("dimension", jsonNode.asText());
  1507. emailObjList.add(prepareOutputJson(validationNode, columnNode, result, ValidationTypes.expression, null,
  1508. null, null, null));*/
  1509. break;
  1510. }
  1511. }
  1512. break;
  1513. case Constants.REQUIRED:
  1514. /*ObjectNode requiredObjNode = new APIExpressionEvaluator().checkMandatoryFields(dataMap, code,
  1515. columnNode.get(Constants.DATA_TYPE).asText(), mappedColumnName);*/
  1516. //return new APIExpressionEvaluator().checkRequiredField(inputValue, code, columnNode.get(Constants.DATA_TYPE).asText());
  1517. if (StringUtils.isBlank(inputValue)) {
  1518. String code = null;
  1519. if (checkCode) {
  1520. code = columnNode.get(Constants.CODE).asText();
  1521. } else {
  1522. code = columnNode.get(Constants.MAPPED_COLUMN_NAME).asText();
  1523. }
  1524. errorObjNode = new APIExpressionEvaluator().prepareOutputJson(validationNode, dimensionAttribute, null,
  1525. ValidationTypes.predefinedValidations, code, inputValue, null, null);
  1526. }
  1527. }
  1528. return errorObjNode;
  1529. }
  1530. public JsonNode preparyCompanyWiseData(JsonNode dataNode,JsonNode contextDataNode)throws Exception
  1531. {
  1532. String comppany_Column=null;
  1533. String country_Column=null;
  1534. JsonNode mappedCompany=null;
  1535. JsonNode node=null;
  1536. JsonNode companyDataNode = mapper.createObjectNode();;
  1537. boolean found=false;
  1538. ArrayNode arr = mapper.createArrayNode();
  1539. HashMap<String,String> nodeMap=null;
  1540. List<HashMap<String,String>> companyList= new ArrayList<HashMap<String,String>>();
  1541. if(!JsonUtils.isNullOrBlankOrNullNode(contextDataNode))
  1542. {
  1543. if (!JsonUtils.isNullOrBlankOrNullNode(contextDataNode.get(Constants.ENTITY_NAME_COLUMN_CODE))
  1544. && JsonUtils.isStringExist(contextDataNode.get(Constants.ENTITY_NAME_COLUMN_CODE).asText())) {
  1545. comppany_Column=contextDataNode.get(Constants.ENTITY_NAME_COLUMN_CODE).asText();
  1546. if (!JsonUtils.isNullOrBlankOrNullNode(contextDataNode.get(Constants.MAPPED_COMPANY))) {
  1547. mappedCompany=contextDataNode.get(Constants.MAPPED_COMPANY);
  1548. Iterator<JsonNode> it=mappedCompany.iterator();
  1549. while(it.hasNext())
  1550. {
  1551. node=(JsonNode)it.next();
  1552. nodeMap=new HashMap<String,String>();
  1553. nodeMap.put("name",(!JsonUtils.isNullOrBlankOrNullNode(node.get("name"))? node.get("name").asText():""));
  1554. nodeMap.put("country",(!JsonUtils.isNullOrBlankOrNullNode(node.get("country"))? node.get("country").asText():"")); // check null poiter here
  1555. companyList.add(nodeMap);
  1556. }
  1557. }
  1558. }
  1559. if (!JsonUtils.isNullOrBlankOrNullNode(contextDataNode.get(Constants.ENTITY_COUNTRY_COLUMN_CODE))
  1560. && JsonUtils.isStringExist(contextDataNode.get(Constants.ENTITY_COUNTRY_COLUMN_CODE).asText())) {
  1561. country_Column=contextDataNode.get(Constants.ENTITY_COUNTRY_COLUMN_CODE).asText();
  1562. }
  1563. }
  1564. if(!JsonUtils.isNullOrBlankOrNullNode(dataNode) && JsonUtils.isStringExist(comppany_Column) && !JsonUtils.isNullOrBlankOrNullNode(mappedCompany))
  1565. {
  1566. for(JsonNode data:dataNode)
  1567. {
  1568. found=false;
  1569. if(!JsonUtils.isNullOrBlankOrNullNode(data.get(comppany_Column)))
  1570. {
  1571. for(HashMap<String,String> map:companyList)
  1572. {
  1573. if(!map.get("country").equals(""))
  1574. {
  1575. if(data.get(country_Column).asText().equals(map.get("country")) && data.get(comppany_Column).asText().equals(map.get("name")))
  1576. {
  1577. found=true;
  1578. break;
  1579. }
  1580. }
  1581. else if(data.get(comppany_Column).asText().equals(map.get("name")))
  1582. {
  1583. found=true;
  1584. break;
  1585. }
  1586. }
  1587. if(found)
  1588. {
  1589. arr.add(data);
  1590. }
  1591. }
  1592. }
  1593. ((ObjectNode) (companyDataNode)).set(Constants.DATA, arr);
  1594. }
  1595. else
  1596. {
  1597. return ((ObjectNode) (companyDataNode)).set(Constants.DATA, dataNode);
  1598. }
  1599. return companyDataNode;
  1600. }
  1601. public HashMap<String, JsonNode> updateDataMapWithEmptyDimension(HashMap<String, JsonNode> dataMap ,HashMap<String, JsonNode> dimMap)
  1602. {
  1603. JsonNode value=null;
  1604. String code="";
  1605. String key="";
  1606. if(dimMap!=null && dimMap.size()>0)
  1607. {
  1608. for (Map.Entry<String, JsonNode> entry : dimMap.entrySet())
  1609. {
  1610. code = entry.getKey();
  1611. value = entry.getValue();
  1612. for(JsonNode dim : value)
  1613. {
  1614. key=code+"."+dim.asText();
  1615. if(JsonUtils.isNullOrBlankOrNullNode(dataMap.get(key)))
  1616. {
  1617. dataMap.put(key, JsonNodeFactory.instance.nullNode());
  1618. }
  1619. }
  1620. //use key and value
  1621. }
  1622. }
  1623. return dataMap;
  1624. }
  1625. /**
  1626. *
  1627. * @param entitiesJson
  1628. * @param csvJsonString
  1629. * @param isAggregateRequest
  1630. * @param xslJsonMap
  1631. * @param firstSheetName
  1632. * @param isMultiPartRequest
  1633. * @param isEEIDMissingInAsyncL0
  1634. * @return
  1635. * @throws Exception
  1636. */
  1637. public JsonNode preparingL1Input(String entitiesJson, String csvJsonString, boolean isAggregateRequest,
  1638. HashMap<String, String> xslJsonMap, String firstSheetName, boolean isMultiPartRequest,Object isEEIDMissingInAsyncL0) throws Exception {
  1639. JsonNode resultNode = null;
  1640. ArrayNode entityArr = null;
  1641. Set<String> xslJsonSheets = null;
  1642. JsonNode resultEntiryNode = null;
  1643. JsonNode sectionStructureNode = null;
  1644. JsonNode dataNode = null;
  1645. JsonNode otherSecDataNode = null;
  1646. JsonNode contextDataNode = null;
  1647. JsonNode csvNode = null;
  1648. String uniqueIdColumnCode = "";
  1649. JsonNode entityNode = null;
  1650. resultNode = mapper.createObjectNode();
  1651. entityArr = mapper.createArrayNode();
  1652. Iterator<String> fieldIter=null;
  1653. ArrayNode entitiesNode = mapper.readValue(entitiesJson, ArrayNode.class);
  1654. StringBuffer coName_CtryCode = new StringBuffer();
  1655. String countryCode = null;
  1656. ArrayList<String> fieldList=new ArrayList<>();
  1657. JsonNode companyDataNode = null;
  1658. ArrayNode objNode=null;
  1659. String fieldName=null;
  1660. String code="";
  1661. String mappedCode="";
  1662. // For .xlsx data
  1663. if (xslJsonMap != null) {
  1664. xslJsonSheets = new HashSet<String>(xslJsonMap.keySet());
  1665. }
  1666. JsonNode colNode = null;
  1667. HashMap<String,String> metaDataCodes=new HashMap<>();
  1668. for (int i = 0; i < entitiesNode.size(); i++) {
  1669. countryCode = "";
  1670. entityNode = entitiesNode.get(i);
  1671. resultEntiryNode = mapper.createObjectNode();
  1672. sectionStructureNode = entityNode.get(Constants.SECTION_STRUCTURE);
  1673. dataNode = entityNode.get(Constants.DATA);
  1674. otherSecDataNode = entityNode.get(Constants.OTHERSECTIONDATAKEY);
  1675. contextDataNode = entityNode.get(Constants.CONTEXTDATAKEY);
  1676. colNode = sectionStructureNode.get(Constants.COLUMNS);
  1677. // PE: 8976 Start
  1678. for (JsonNode col : colNode) {
  1679. if (!JsonUtils.isNullOrBlankOrNullNode(col.get("mappedColumnName"))) {
  1680. mappedCode = col.get("mappedColumnName").asText();
  1681. }
  1682. if (!JsonUtils.isNullOrBlankOrNullNode(col.get("code"))) {
  1683. code = col.get("code").asText();
  1684. }
  1685. if(mappedCode.length() > 0 )
  1686. {
  1687. if (!JsonUtils.isNullOrBlankOrNullNode(col.get("skip"))) {
  1688. metaDataCodes.put(mappedCode, "skipEnabled");
  1689. } else if (code.length() > 0) {
  1690. metaDataCodes.put(mappedCode, code);
  1691. }
  1692. }
  1693. }
  1694. // PE: 8976 End
  1695. // Added uniqueIdColumnCode for PE: 8315 . Following line is
  1696. // assigned for merging.
  1697. uniqueIdColumnCode = contextDataNode.get("uniqueIdColumnCode").asText();
  1698. if (!contextDataNode.isNull() && contextDataNode.has("ctryCode")) {
  1699. countryCode = contextDataNode.get("ctryCode").asText();
  1700. }
  1701. if (csvJsonString != null && !csvJsonString.equals("")) {
  1702. csvNode = mapper.readValue(csvJsonString, JsonNode.class);
  1703. } else if (xslJsonMap != null && xslJsonMap.size() > 0) {
  1704. coName_CtryCode.delete(0, coName_CtryCode.length());
  1705. coName_CtryCode.append(contextDataNode.get("companyName").asText());
  1706. coName_CtryCode.append("_");
  1707. coName_CtryCode.append(countryCode);
  1708. // Default condition - Need to check usage of FirstSheetName !!
  1709. if (firstSheetName != null) {
  1710. csvNode = mapper.readValue(xslJsonMap.get(firstSheetName), JsonNode.class);
  1711. // If sheet is found
  1712. } else if (xslJsonMap.get(coName_CtryCode.toString()) != null) {
  1713. // If sheet not previously used
  1714. if (xslJsonSheets.contains(coName_CtryCode.toString())) {
  1715. csvNode = mapper.readValue(xslJsonMap.get(coName_CtryCode.toString()), JsonNode.class);
  1716. xslJsonSheets.remove(coName_CtryCode.toString());
  1717. // If sheet previously used
  1718. } else {
  1719. paramValueList = new ArrayList<String>();
  1720. paramValueList.add("" + contextDataNode.get("companyName").asText());
  1721. paramValueList.add("" + countryCode );
  1722. throw new CustomStatusException(Constants.HTTPSTATUS_400,
  1723. Cache.getPropertyFromError(ErrorCacheConstant.ERR_034),
  1724. Cache.getPropertyFromError(ErrorCacheConstant.ERR_034 + Constants.PARAMS),
  1725. paramValueList);
  1726. }
  1727. // If sheet not found
  1728. } else if (xslJsonMap.get(coName_CtryCode.toString()) == null) {
  1729. paramValueList = new ArrayList<String>();
  1730. paramValueList.add("" + coName_CtryCode.toString());
  1731. throw new CustomStatusException(Constants.HTTPSTATUS_400,
  1732. Cache.getPropertyFromError(ErrorCacheConstant.ERR_035),
  1733. Cache.getPropertyFromError(ErrorCacheConstant.ERR_035 + Constants.PARAMS), paramValueList);
  1734. }
  1735. }
  1736. if (csvNode != null) {
  1737. companyDataNode = preparyCompanyWiseData(csvNode.get("data"), contextDataNode);
  1738. dataNode = findAndMerge(dataNode, (ArrayNode) companyDataNode.get("data"), uniqueIdColumnCode);
  1739. }
  1740. // L0 Validations Ends Here
  1741. // Returning Input Json for L1 Validation
  1742. // PE 8976 Start : To send column code in the L0response
  1743. if (metaDataCodes.size() > 0) {
  1744. fieldIter = dataNode.get(0).fieldNames();
  1745. while (fieldIter != null && fieldIter.hasNext()) {
  1746. fieldName = fieldIter.next();
  1747. if (null != metaDataCodes.get(fieldName) && !metaDataCodes.get(fieldName).equals("skipEnabled")) {
  1748. fieldList.add(fieldName);
  1749. }
  1750. }
  1751. if (metaDataCodes.keySet().containsAll(fieldList)) {
  1752. objNode = mapper.createArrayNode();
  1753. JsonNode node = null;
  1754. for (JsonNode data : dataNode) {
  1755. node = mapper.createObjectNode();
  1756. for (String field : fieldList) {
  1757. if (metaDataCodes.get(field) != null) {
  1758. ((ObjectNode) node).set(metaDataCodes.get(field), data.get(field));
  1759. }
  1760. }
  1761. objNode.add(node);
  1762. }
  1763. }
  1764. }
  1765. // PE 8976 End
  1766. //PE-8933 - Starts
  1767. if (null != isEEIDMissingInAsyncL0) {
  1768. if ((boolean) isEEIDMissingInAsyncL0) {
  1769. ((ObjectNode) (contextDataNode)).put(Constants.MISSING_EEID, true);
  1770. } else {
  1771. ((ObjectNode) (contextDataNode)).put(Constants.MISSING_EEID, false);
  1772. }
  1773. ((ObjectNode) (entityNode)).set(Constants.CONTEXTDATAKEY, contextDataNode);
  1774. }
  1775. //PE-8933 - Ends
  1776. resultEntiryNode = entityNode;
  1777. if(null!=objNode && objNode.size()>0)
  1778. {
  1779. ((ObjectNode) (resultEntiryNode)).set(Constants.DATA, objNode);
  1780. }
  1781. else
  1782. {
  1783. ((ObjectNode) (resultEntiryNode)).set(Constants.DATA, dataNode);
  1784. }
  1785. entityArr.add(resultEntiryNode);
  1786. metaDataCodes.clear();
  1787. }
  1788. resultNode = mapper.createObjectNode().set(Constants.ENTITIES, entityArr);
  1789. return resultNode;
  1790. }
  1791. public JsonNode perform_L1_L2Validations(JsonNode entitiesNodeResponse, boolean isAggregateRequest,
  1792. boolean isMultiPartRequest) throws Exception {
  1793. JsonNode dataNode = null;
  1794. HashMap<String, String> columnMappingMap = null;
  1795. JsonNode sectionStructureNode = null;
  1796. HashMap<String, JsonNode> dimMap = new HashMap<String, JsonNode>();
  1797. String countryCode = null;
  1798. JsonNode otherSecDataNode = null;
  1799. JsonNode contextDataNode = null;
  1800. JsonNode resultNode = null;
  1801. JsonNode mlNode = null;
  1802. ArrayNode entityArr = null;
  1803. ArrayNode arr = null;
  1804. JsonNode entityNode = null;
  1805. JsonNode resultEntiryNode = null;
  1806. Map.Entry<String, JsonNode> entry = null;
  1807. Map.Entry<String, JsonNode> entry1 = null;
  1808. List<String> otherAndContextKeys = new ArrayList<>();
  1809. String tempArrayName = null;
  1810. entityArr = mapper.createArrayNode();
  1811. ArrayNode entitiesNode = (ArrayNode) entitiesNodeResponse.get(Constants.ENTITIES);
  1812. boolean mlAutoCoorect=false;
  1813. JsonNode mLdataNode = null;
  1814. // Making csv out of JSON single level
  1815. for (int i = 0; i < entitiesNode.size(); i++) {
  1816. countryCode = "";
  1817. arr = mapper.createArrayNode();
  1818. entityNode = entitiesNode.get(i);
  1819. resultEntiryNode = mapper.createObjectNode();
  1820. sectionStructureNode = entityNode.get(Constants.SECTION_STRUCTURE);
  1821. dataNode = entityNode.get(Constants.DATA);
  1822. otherSecDataNode = entityNode.get(Constants.OTHERSECTIONDATAKEY);
  1823. contextDataNode = entityNode.get(Constants.CONTEXTDATAKEY);
  1824. // Before L1 for File upload ML Auto-correction API call will be executed.
  1825. // PE-6254 ML Integration works only for File upload case.
  1826. // Check flag from config file located in API_HOME
  1827. if ( isMultiPartRequest
  1828. && "Y".equalsIgnoreCase(Cache.getMLProperty(CacheConstats.IS_AUTOCORRECTION).trim()) ) {
  1829. mlNode = MachineLearningRestClient.callMLRestAPI(entityNode);
  1830. if( null != mlNode) {
  1831. dataNode = mlNode;
  1832. mlAutoCoorect=true;
  1833. }
  1834. }
  1835. //PE-6254 ML End.
  1836. if (null != contextDataNode && contextDataNode.has("ctryCode")) {
  1837. countryCode = contextDataNode.get("ctryCode").asText();
  1838. }
  1839. HashMap<String, JsonNode> dataMap = new HashMap<String, JsonNode>();
  1840. contextAndOtherSectionDataToMap(dataMap, otherSecDataNode, contextDataNode, otherAndContextKeys, entry,
  1841. entry1, tempArrayName, isMultiPartRequest);
  1842. //PE-8552
  1843. HashMap<String, JsonNode> contextDataAndOtherDataMap = new HashMap<String, JsonNode>(dataMap);
  1844. ArrayList<JsonNode> columnNodeList = new ArrayList<JsonNode>();
  1845. columnMappingMap = new HashMap<String, String>();
  1846. APIExpressionEvaluator apiExpressionEvaluator = new APIExpressionEvaluator();
  1847. String uuid = setColumnMappingAndDataForAggregation(apiExpressionEvaluator, columnNodeList,
  1848. otherAndContextKeys, columnMappingMap, sectionStructureNode, dataMap, dimMap, dataNode,
  1849. countryCode);
  1850. // Added by Nikhil
  1851. // Start PE-7056 Expression should not executed if columns are not
  1852. // present in MetaData.
  1853. List<String> metaDataColumnsOnly = null;
  1854. metaDataColumnsOnly = DataUtility.extractColumnsFromMetaData(apiExpressionEvaluator);
  1855. if (!otherAndContextKeys.isEmpty()) {
  1856. metaDataColumnsOnly.addAll(otherAndContextKeys);
  1857. }
  1858. // End PE-7056
  1859. Iterator<Map.Entry<String, JsonNode>> iterator = null;
  1860. for (int k = 0; k < dataNode.size(); k++) {
  1861. if(mlAutoCoorect)
  1862. {
  1863. mLdataNode = dataNode.get(k);
  1864. }
  1865. iterator = dataNode.get(k).fields();
  1866. while (iterator.hasNext()) {
  1867. entry = iterator.next();
  1868. //8552
  1869. JsonNode value = JsonUtils.isNullNode(entry.getValue()) ? null : entry.getValue();
  1870. if (entry.getValue().getNodeType() != JsonNodeType.OBJECT) {
  1871. // PE-6254 ML Integration works start
  1872. if(mlAutoCoorect)
  1873. {
  1874. if(entry.getKey().trim().contains("_ACflag") || entry.getKey().trim().contains("_Replace"))
  1875. {
  1876. continue;
  1877. }
  1878. else
  1879. {
  1880. if(mLdataNode.get(entry.getKey()+"_ACflag").asText().equalsIgnoreCase("R"))
  1881. {
  1882. dataMap.put(entry.getKey().trim(), mLdataNode.get(entry.getKey()+"_Replace"));
  1883. }
  1884. else
  1885. {
  1886. dataMap.put(entry.getKey().trim(), value);
  1887. }
  1888. }
  1889. }
  1890. // PE-6254 ML Integration works end
  1891. else
  1892. {
  1893. dataMap.put(entry.getKey().trim(), value);
  1894. }
  1895. } else {
  1896. dataMap = parseJsonObjectMap(entry.getKey(), value, dataMap, null,
  1897. mapper.valueToTree(columnNodeList), null); // PE-7605 (2)
  1898. }
  1899. }
  1900. dataMap = updateDataMapWithEmptyDimension(dataMap, dimMap);
  1901. // logger.debug(String.format("dataMap..%s", dataMap));
  1902. resultNode = validate(dataMap, columnNodeList, dataNode.get(k), apiExpressionEvaluator, false,
  1903. columnMappingMap, dimMap, metaDataColumnsOnly,mlAutoCoorect);
  1904. arr.add(resultNode);
  1905. // logger.debug(String.format("resultNode..%s", resultNode));
  1906. //tempMetaDataColumn.removeAll(dataNodeColumnsOnly);
  1907. /*if (tempMetaDataColumn != null && tempMetaDataColumn.size() > 0) {
  1908. for (String key : tempMetaDataColumn) {
  1909. dataMap.remove(key);
  1910. }
  1911. }*/
  1912. dataMap = new HashMap<String, JsonNode>(contextDataAndOtherDataMap);
  1913. }
  1914. ((ObjectNode) (resultEntiryNode)).set(Constants.DATA, arr);
  1915. if (null != contextDataNode)
  1916. ((ObjectNode) (resultEntiryNode)).set(Constants.CONTEXTDATAKEY, contextDataNode);
  1917. entityArr.add(resultEntiryNode);
  1918. // removing csv from expression evaluator
  1919. // added by Nikhil
  1920. apiExpressionEvaluator.getExpressionEvaluatorDriver().removeCsvData(uuid);
  1921. }
  1922. resultNode = mapper.createObjectNode().set("entities", entityArr);
  1923. // logger.info(String.format("%s %s", Constants.EXIT ,Constants.LOG_PARSEANDVALIDATE));
  1924. return resultNode;
  1925. }
  1926. private String setColumnMappingAndDataForAggregation(APIExpressionEvaluator apiExpressionEvaluator, ArrayList<JsonNode> columnNodeList,
  1927. List<String> otherAndContextKeys, HashMap<String, String> columnMappingMap, JsonNode sectionStructureNode,
  1928. HashMap<String, JsonNode> dataMap, HashMap<String, JsonNode> dimMap, JsonNode dataNode,
  1929. String countryCode) throws UnsupportedEncodingException, JSONException {
  1930. if (sectionStructureNode.has(Constants.COLUMNS)) {
  1931. for (int j = 0; j < sectionStructureNode.get(Constants.COLUMNS).size(); j++) {
  1932. columnNodeList.add(sectionStructureNode.get(Constants.COLUMNS).get(j));
  1933. if (!JsonUtils.isNullOrBlankOrNullNode(
  1934. sectionStructureNode.get(Constants.COLUMNS).get(j).get("mappedColumnName"))
  1935. && !sectionStructureNode.get(Constants.COLUMNS).get(j).get("mappedColumnName").equals(""))
  1936. if (!JsonUtils
  1937. .isNullOrBlankOrNullNode(sectionStructureNode.get(Constants.COLUMNS).get(j).get("code")))
  1938. columnMappingMap.put(sectionStructureNode.get(Constants.COLUMNS).get(j).get("code").asText(),
  1939. sectionStructureNode.get(Constants.COLUMNS).get(j).get("mappedColumnName").asText());
  1940. }
  1941. }
  1942. if (!JsonUtils.isNullOrBlankOrNullNode(dataNode)) {
  1943. JSONArray myArr = new JSONArray(dataNode.toString());
  1944. Set<String> keyList = new HashSet<>();
  1945. for (int j = 0; j < myArr.length(); j++) {
  1946. JSONObject json = myArr.getJSONObject(j);
  1947. Iterator<String> keys = json.keys();
  1948. while (keys.hasNext()) {
  1949. keyList.add(keys.next());
  1950. }
  1951. }
  1952. logger.info("FormValidator >> setColumnMappingAndDataForAggregation() >> CSVParser.parseFile : start");
  1953. long startTImeForCSVParseFile = System.currentTimeMillis();
  1954. CSVParser.parseFile(new ByteArrayInputStream(
  1955. (JsonUtils.rowToString(new JSONArray(keyList)) + JsonUtils.toString(new JSONArray(keyList), myArr))
  1956. .toString().getBytes("UTF-8")));
  1957. logger.info("FormValidator >> setColumnMappingAndDataForAggregation() >> CSVParser.parseFile : end. Took : "
  1958. + (System.currentTimeMillis() - startTImeForCSVParseFile) + " msec");
  1959. }
  1960. // Set Column - data type mapping - PE
  1961. apiExpressionEvaluator.setColumnDataTypeMapping(new HashMap<String, String>());
  1962. APIExpressionEvaluator.df.setMaximumFractionDigits(16);
  1963. APIExpressionEvaluator.df.setMinimumFractionDigits(1);
  1964. /**
  1965. * @author Vivek Kasadwar
  1966. */
  1967. for (JsonNode columnNode : columnNodeList) {
  1968. if ((!JsonUtils.isNullOrBlankOrNullNode(columnNode.get(Constants.CODE))
  1969. && !StringUtils.isBlank(columnNode.get(Constants.CODE).asText()))
  1970. && (null != columnNode.get(Constants.DATA_TYPE))) {
  1971. apiExpressionEvaluator.getColumnDataTypeMapping().put(columnNode.get(Constants.CODE).asText(),
  1972. columnNode.get(Constants.DATA_TYPE).asText());
  1973. /**
  1974. * @author Akhileshwar
  1975. * @throws Exception
  1976. * PE-7045
  1977. */
  1978. if (!JsonUtils.isNullOrBlankOrNullNode(columnNode.get(Constants.DIMENSIONS))) {
  1979. for (JsonNode dimensioNode : columnNode.get(Constants.DIMENSIONS)) {
  1980. apiExpressionEvaluator.getColumnDataTypeMapping().put(
  1981. columnNode.get(Constants.CODE).asText() + Constants.DOT + dimensioNode.asText(),
  1982. columnNode.get(Constants.DATA_TYPE).asText());
  1983. }
  1984. dimMap.put(columnNode.get(Constants.CODE).asText(), columnNode.get(Constants.DIMENSIONS));
  1985. }
  1986. }
  1987. }
  1988. HashMap<String, Object> otherParams = null;
  1989. if (!StringUtils.isEmpty(countryCode)) {
  1990. otherParams = new HashMap<String, Object>();
  1991. otherParams.put("countryCode", countryCode);
  1992. }
  1993. String uuid = apiExpressionEvaluator.getExpressionEvaluatorDriver().setCsvData(CSVParser.dataForAggregation, otherParams);
  1994. return uuid;
  1995. }
  1996. void contextAndOtherSectionDataToMap(HashMap<String, JsonNode> dataMap, JsonNode otherSecDataNode,
  1997. JsonNode contextDataNode, List<String> otherAndContextKeys, Entry<String, JsonNode> entry,
  1998. Entry<String, JsonNode> entry1, String tempArrayName, boolean isMultiPartRequest) throws Exception {
  1999. // Other Section data iterator
  2000. if (!JsonUtils.isNullOrBlankOrNullNode(otherSecDataNode) && !otherSecDataNode.toString().equals("")) {
  2001. Iterator<Map.Entry<String, JsonNode>> osdIt = otherSecDataNode.fields();
  2002. while (osdIt.hasNext()) {
  2003. entry = osdIt.next();
  2004. if (entry.getValue().getNodeType() != JsonNodeType.OBJECT) {
  2005. dataMap.put(Constants.OTHERSECTIONDATAKEY + "." + entry.getKey().trim(), entry.getValue());
  2006. // PE-7056
  2007. otherAndContextKeys.add(Constants.OTHERSECTIONDATAKEY + "." + entry.getKey().trim());
  2008. } else {
  2009. dataMap = parseJsonObjectMap(entry.getKey().trim(), entry.getValue(), dataMap,
  2010. Constants.OTHERSECTIONDATAKEY, null, otherAndContextKeys);
  2011. }
  2012. }
  2013. entry = null;
  2014. }
  2015. // Context data node iterator
  2016. // Populate dataMap with values from "contextDataNode"
  2017. if (!JsonUtils.isNullOrBlankOrNullNode(contextDataNode) && !contextDataNode.toString().equals("")) {
  2018. Iterator<Map.Entry<String, JsonNode>> contextIt = contextDataNode.fields();
  2019. while (contextIt.hasNext()) {
  2020. entry = contextIt.next();
  2021. if (entry.getValue().getNodeType() != JsonNodeType.OBJECT
  2022. && entry.getValue().getNodeType() != JsonNodeType.ARRAY) {
  2023. dataMap.put(Constants.CONTEXTDATAKEY + "." + entry.getKey().trim(), entry.getValue());
  2024. // PE-7056
  2025. otherAndContextKeys.add(Constants.CONTEXTDATAKEY + "." + entry.getKey().trim());
  2026. } else if (entry.getValue().getNodeType() == JsonNodeType.ARRAY && (entry.getValue().size() > 0)) {
  2027. Iterator<Map.Entry<String, JsonNode>> arrIt = contextDataNode.fields();
  2028. tempArrayName = entry.getKey();
  2029. // PE - 7257
  2030. if (entry.getValue().getNodeType() == JsonNodeType.ARRAY && isMultiPartRequest) {
  2031. dataMap.put(Constants.CONTEXTDATAKEY + "." + entry.getKey().trim(), entry.getValue());
  2032. // PE-7056
  2033. otherAndContextKeys.add(Constants.CONTEXTDATAKEY + "." + entry.getKey().trim());
  2034. } else {
  2035. if (entry.getValue().size() > 0) {
  2036. arrIt = entry.getValue().get(0).fields();
  2037. while (arrIt.hasNext()) {
  2038. entry1 = arrIt.next();
  2039. dataMap.put(
  2040. Constants.CONTEXTDATAKEY + "." + tempArrayName + "." + entry1.getKey().trim(),
  2041. entry1.getValue());
  2042. // PE-7056
  2043. otherAndContextKeys.add(
  2044. Constants.CONTEXTDATAKEY + "." + tempArrayName + "." + entry1.getKey().trim());
  2045. }
  2046. }
  2047. }
  2048. } else {
  2049. dataMap = parseJsonObjectMap(entry.getKey(), entry.getValue(), dataMap, Constants.CONTEXTDATAKEY,
  2050. null, otherAndContextKeys);
  2051. }
  2052. }
  2053. entry = null;
  2054. }
  2055. }
  2056. public JsonNode performValidateAggregateRequest(JsonNode entitiesNodeResponse, boolean isAggregateRequest, boolean isMultiPartRequest) throws Exception {
  2057. JsonNode dataNode = null;
  2058. HashMap<String, String> columnMappingMap = null;
  2059. JsonNode sectionStructureNode = null;
  2060. HashMap<String, JsonNode> dimMap = new HashMap<String, JsonNode>();
  2061. String countryCode = null;
  2062. JsonNode otherSecDataNode = null;
  2063. JsonNode contextDataNode = null;
  2064. JsonNode resultNode = null;
  2065. ArrayNode entityArr = null;
  2066. JsonNode entityNode = null;
  2067. JsonNode resultEntiryNode = null;
  2068. Map.Entry<String, JsonNode> entry = null;
  2069. Map.Entry<String, JsonNode> entry1 = null;
  2070. List<String> otherAndContextKeys = new ArrayList<>();
  2071. String tempArrayName = null;
  2072. entityArr = mapper.createArrayNode();
  2073. ArrayNode entitiesNode = (ArrayNode) entitiesNodeResponse.get(Constants.ENTITIES);
  2074. // Making csv out of JSON single level
  2075. for (int i = 0; i < entitiesNode.size(); i++) {
  2076. countryCode = "";
  2077. entityNode = entitiesNode.get(i);
  2078. resultEntiryNode = mapper.createObjectNode();
  2079. if (entityNode.has(Constants.SECTION_STRUCTURE)) {
  2080. sectionStructureNode = entityNode.get(Constants.SECTION_STRUCTURE);
  2081. }
  2082. if (entityNode.has(Constants.DATA)) {
  2083. dataNode = entityNode.get(Constants.DATA);
  2084. }
  2085. if (entityNode.has(Constants.OTHERSECTIONDATAKEY)) {
  2086. otherSecDataNode = entityNode.get(Constants.OTHERSECTIONDATAKEY);
  2087. }
  2088. if (entityNode.has(Constants.CONTEXTDATAKEY)) {
  2089. contextDataNode = entityNode.get(Constants.CONTEXTDATAKEY);
  2090. }
  2091. if (null != contextDataNode && contextDataNode.has("ctryCode")) {
  2092. countryCode = contextDataNode.get("ctryCode").asText();
  2093. }
  2094. HashMap<String, JsonNode> dataMap = new HashMap<String, JsonNode>();
  2095. contextAndOtherSectionDataToMap(dataMap, otherSecDataNode, contextDataNode, otherAndContextKeys, entry,
  2096. entry1, tempArrayName, isMultiPartRequest);
  2097. ArrayList<JsonNode> columnNodeList = new ArrayList<JsonNode>();
  2098. columnMappingMap = new HashMap<String, String>();
  2099. APIExpressionEvaluator apiExpressionEvaluator = new APIExpressionEvaluator();
  2100. String uuid = setColumnMappingAndDataForAggregation(apiExpressionEvaluator, columnNodeList,
  2101. otherAndContextKeys, columnMappingMap, sectionStructureNode, dataMap, dimMap, dataNode,
  2102. countryCode);
  2103. // Added by Nikhil
  2104. // Start PE-7056 Expression should not executed if columns are not
  2105. // present in MetaData.
  2106. List<String> metaDataColumnsOnly = null;
  2107. metaDataColumnsOnly = DataUtility.extractColumnsFromMetaData(apiExpressionEvaluator);
  2108. if (!otherAndContextKeys.isEmpty()) {
  2109. metaDataColumnsOnly.addAll(otherAndContextKeys);
  2110. }
  2111. // End PE-7056
  2112. // PE : 2449 to update datamap with entity data which was
  2113. // missing in case of aggregate
  2114. Iterator<Map.Entry<String, JsonNode>> iterator = null;
  2115. if(dataNode.isArray() && dataNode.size()!=0) { // Remove NullPointer when there is no object in data-node.
  2116. iterator = dataNode.get(0).fields();
  2117. while (iterator.hasNext()) {
  2118. entry = iterator.next();
  2119. JsonNode value = JsonUtils.isNullNode(entry.getValue()) ? null : entry.getValue();
  2120. if (entry.getValue().getNodeType() != JsonNodeType.OBJECT) {
  2121. dataMap.put(entry.getKey().trim(), value);
  2122. } else {
  2123. dataMap = parseJsonObjectMap(entry.getKey(), value, dataMap, null, null, null);
  2124. }
  2125. }
  2126. }
  2127. resultNode = validate(dataMap, columnNodeList, dataNode.get(0), apiExpressionEvaluator, true,
  2128. columnMappingMap, dimMap, metaDataColumnsOnly,false);
  2129. ((ObjectNode) (resultEntiryNode)).set(Constants.VALIDATION_RESULTS, resultNode);
  2130. if (null != contextDataNode)
  2131. ((ObjectNode) (resultEntiryNode)).set(Constants.CONTEXTDATAKEY, contextDataNode);
  2132. entityArr.add(resultEntiryNode);
  2133. apiExpressionEvaluator.getExpressionEvaluatorDriver().removeCsvData(uuid);
  2134. }
  2135. resultNode = mapper.createObjectNode().set("entities", entityArr);
  2136. // logger.info(String.format("%s %s", Constants.EXIT ,Constants.LOG_PARSEANDVALIDATE));
  2137. return resultNode;
  2138. }
  2139. // PE-6254 ML Integration works start
  2140. public ObjectNode prepareMLAutocorrectObject(String field,String validationType,JsonNode originalvalue)
  2141. {
  2142. ObjectNode validation = mapper.createObjectNode();
  2143. validation.put(Constants.FIELD, field);
  2144. validation.put(Constants.ERROR_TYPE, Constants.AUTOCORRECT);
  2145. // validation.put(Constants.MESSAGE, result);
  2146. validation.put(Constants.MESSAGE_KEY,
  2147. in.lnt.utility.general.Cache.getPropertyFromError(ErrorCacheConstant.ERR_059));
  2148. if(!JsonUtils.isNullOrBlankOrNullNode((originalvalue)))
  2149. validation.put(Constants.ORIGINAL_VALUE,originalvalue.asText());
  2150. else
  2151. validation.put(Constants.ORIGINAL_VALUE,"");
  2152. return validation;
  2153. }
  2154. public void removeDataNodeACFields(JsonNode dataNode)
  2155. {
  2156. Iterator<Map.Entry<String, JsonNode>> iterator = null;
  2157. iterator = dataNode.fields();
  2158. //dataNode.
  2159. List<String> fieldsToDelete=new ArrayList<String>();
  2160. Map.Entry<String, JsonNode> entry = null;
  2161. while (iterator.hasNext()) {
  2162. entry = iterator.next();
  2163. if(entry.getKey().trim().contains("_ACflag") || entry.getKey().trim().contains("_Replace"))
  2164. {}
  2165. else{
  2166. fieldsToDelete.add(entry.getKey());
  2167. }
  2168. }
  2169. ((ObjectNode)dataNode).retain(fieldsToDelete);
  2170. }
  2171. // PE-6254 ML Integration works end
  2172. }