PageRenderTime 168ms CodeModel.GetById 28ms RepoModel.GetById 0ms app.codeStats 1ms

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

https://bitbucket.org/team_mercer/mercer_api_production
Java | 818 lines | 611 code | 89 blank | 118 comment | 187 complexity | ddff26e2a591223918795c873027d319 MD5 | raw file
  1. package in.lnt.validations;
  2. import java.io.ByteArrayInputStream;
  3. import java.util.ArrayList;
  4. import java.util.HashMap;
  5. import java.util.HashSet;
  6. import java.util.Iterator;
  7. import java.util.List;
  8. import java.util.Map;
  9. import java.util.Set;
  10. import java.util.regex.Pattern;
  11. import org.apache.commons.lang3.EnumUtils;
  12. import org.apache.commons.lang3.StringUtils;
  13. import org.json.JSONArray;
  14. import org.json.JSONObject;
  15. import org.slf4j.Logger;
  16. import org.slf4j.LoggerFactory;
  17. import com.fasterxml.jackson.databind.JsonNode;
  18. import com.fasterxml.jackson.databind.ObjectMapper;
  19. import com.fasterxml.jackson.databind.node.ArrayNode;
  20. import com.fasterxml.jackson.databind.node.JsonNodeType;
  21. import com.fasterxml.jackson.databind.node.ObjectNode;
  22. import in.lnt.constants.Constants;
  23. import in.lnt.enums.ValidationTypes;
  24. import in.lnt.exceptions.CustomStatusException;
  25. import in.lnt.parser.CSVParser;
  26. import in.lnt.service.db.DBUtils;
  27. import in.lnt.utility.general.JsonUtils;
  28. import in.lnt.validations.evaluator.APIExpressionEvaluator;
  29. public class FormValidator_CSC {
  30. private static final Logger logger = LoggerFactory.getLogger(FormValidator_CSC.class);
  31. ObjectMapper mapper = new ObjectMapper();
  32. List<String> uuidList = new ArrayList<>();
  33. static Pattern VALID_EMAIL_ADDRESS_REGEX =
  34. Pattern.compile("^(.+)@(.+)$", Pattern.CASE_INSENSITIVE);
  35. static Pattern VALID_PHONE_NUMBER_REGEX =
  36. Pattern.compile("^(\\(?\\+?[0-9]*\\)?)?[0-9_\\- \\(\\)]*$", Pattern.CASE_INSENSITIVE);
  37. // ^[A-Z0-9._%+-]+@[A-Z0-9.-]+\\.[A-Z]{2,6}$
  38. public JsonNode parseAndValidate_CrossSectionCheck(String entitiesJson, boolean isMDARequest) throws Exception {
  39. //logger.info(String.format("%s %s", Constants.INTIATE ,Constants.LOG_PARSEANDVALIDATE));
  40. JsonNode resultNode = null;
  41. ArrayNode entityArr = null;
  42. ArrayNode arr = null;
  43. JsonNode resultEntiryNode=null;
  44. HashMap<String,JsonNode> dimMap = new HashMap<String,JsonNode>();
  45. JsonNode dataNode=null;
  46. JsonNode contextDataNode=null;
  47. JsonNode entityNode=null;
  48. resultNode=mapper.createObjectNode();
  49. resultEntiryNode=null;
  50. entityArr= mapper.createArrayNode();
  51. Map.Entry<String, JsonNode> entry = null;
  52. Map.Entry<String, JsonNode> entry1 = null;
  53. ArrayNode entitiesNode = mapper.readValue(entitiesJson, ArrayNode.class); // "Entities" node
  54. JsonNode sectionsNode = null; // "sections"
  55. // PE-7056 contexDataKeys and otherDataKeys.are append together in otherAndContextKeys.
  56. List<String> otherAndContextKeys = new ArrayList<>();
  57. //logger.info(String.format("nodetype...%d", entitiesNode.size()));
  58. HashMap<String, JsonNode> dataMap = new HashMap<>();
  59. Iterator<Map.Entry<String, JsonNode>> it =null;
  60. Iterator<Map.Entry<String, JsonNode>> contextIt = null;
  61. // Fixed along with PE-8070
  62. List<ArrayList<JsonNode>> columnNodeList_Master = null;
  63. List<ArrayList<HashMap<String, JsonNode>>> dataMap2_Sections = null;
  64. Set<String> metaDataColumnsOnly;
  65. APIExpressionEvaluator.df.setMaximumFractionDigits(16);
  66. APIExpressionEvaluator.df.setMinimumFractionDigits(1);
  67. /************ Iterating entities *****************/
  68. for(int i=0;i<entitiesNode.size();i++) {
  69. entityNode = entitiesNode.get(i);
  70. resultEntiryNode = mapper.createObjectNode();
  71. dataNode = mapper.createArrayNode(); //entityNode.get(Constants.DATA);
  72. sectionsNode = entityNode.get(Constants.SECTIONS);
  73. contextDataNode = entityNode.get(Constants.CONTEXTDATAKEY);
  74. metaDataColumnsOnly = new HashSet<>();
  75. /*
  76. * 1. Populate "dataMap" with "contextData" object
  77. */
  78. if (contextDataNode != null && !contextDataNode.toString().equals("")) {
  79. contextIt = contextDataNode.fields();
  80. while (contextIt.hasNext()) {
  81. entry = contextIt.next();
  82. JsonNode value = JsonUtils.isNullNode(entry.getValue())?null:entry.getValue();
  83. if (entry.getValue().getNodeType() != JsonNodeType.OBJECT // PE-8070
  84. && entry.getValue().getNodeType() != JsonNodeType.ARRAY) {
  85. dataMap.put(Constants.CONTEXTDATAKEY + "." + entry.getKey().trim(), value);
  86. //PE-7056
  87. otherAndContextKeys.add(Constants.CONTEXTDATAKEY + "." + entry.getKey().trim());
  88. } else if (value.getNodeType() == JsonNodeType.ARRAY) {
  89. Iterator<Map.Entry<String, JsonNode>> arrIt = value.get(0).fields();
  90. while (arrIt.hasNext()) {
  91. entry1 = arrIt.next();
  92. dataMap.put(Constants.CONTEXTDATAKEY + ".industry." + entry1.getKey().trim(),
  93. entry1.getValue());
  94. //PE-7056
  95. otherAndContextKeys.add(Constants.CONTEXTDATAKEY + ".industry." + entry1.getKey().trim());
  96. }
  97. } else {
  98. dataMap = new FormValidator().parseJsonObjectMap(entry.getKey(), value, dataMap,
  99. Constants.CONTEXTDATAKEY, null,otherAndContextKeys);
  100. }
  101. }
  102. entry = null;
  103. }
  104. /*
  105. * 1. Ended
  106. */
  107. /*********** 2. Iterating sections ******************/
  108. /* Generate :
  109. * dataMap2_Sections => [[{Q1=a,Q2=b},{Q1=x,Q2=y}],[{Q6=q},{Q6=r},{Q6=s}]]
  110. */
  111. columnNodeList_Master = new ArrayList<>();
  112. dataMap2_Sections = new ArrayList<>();
  113. APIExpressionEvaluator apiExpressionEvaluator = new APIExpressionEvaluator();
  114. //Set Column - data type mapping - PE
  115. apiExpressionEvaluator.setColumnDataTypeMapping(new HashMap<String,String>());
  116. for (int sctnCtr=0; sctnCtr<sectionsNode.size(); sctnCtr++){
  117. ArrayList<HashMap<String, JsonNode>> dataMap2 = new ArrayList<>();
  118. /******** 2.1 Iterating columns : Generate columnNodeList_Master for all sections ********/
  119. ArrayList<JsonNode> columnNodeList_Section = new ArrayList<>();
  120. JsonNode sectionNode_sectionStructure_columns = sectionsNode.get(sctnCtr).get(Constants.SECTION_STRUCTURE).get(Constants.COLUMNS);
  121. for(int clmCtr = 0; clmCtr<sectionNode_sectionStructure_columns.size(); clmCtr++){
  122. columnNodeList_Section.add(sectionNode_sectionStructure_columns.get(clmCtr));
  123. // SG : Start PE-7056 Expression should not executed if columns are not present in MetaData.
  124. // Populate "metaDataColumnsOnly"
  125. if(!JsonUtils.isNullOrBlankOrNullNode(
  126. sectionNode_sectionStructure_columns.get(clmCtr).get(Constants.CODE))) {
  127. metaDataColumnsOnly.add(
  128. sectionNode_sectionStructure_columns.get(clmCtr).get(Constants.CODE).asText());
  129. // PE-8070 : Add dimensions also in "metaDataColumnsOnly"
  130. if(sectionNode_sectionStructure_columns.get(clmCtr).has(Constants.DIMENSIONS)) {
  131. ArrayNode dimensionArray = (ArrayNode)sectionNode_sectionStructure_columns.get(clmCtr).get("dimensions");
  132. for(int j = 0; j<dimensionArray.size(); j++) {
  133. if(!JsonUtils.isNullOrBlankOrNullNode(dimensionArray.get(j))) {
  134. metaDataColumnsOnly.add(sectionNode_sectionStructure_columns.get(clmCtr).get(Constants.CODE).asText()
  135. +"."+dimensionArray.get(j).asText());
  136. }
  137. }
  138. dimensionArray = null;
  139. }
  140. }
  141. // End PE-7056
  142. }
  143. columnNodeList_Master.add(columnNodeList_Section);
  144. /******** 2.1 Ended ********/
  145. for (ArrayList<JsonNode> columnNodeList : columnNodeList_Master) {
  146. for (JsonNode columnNode : columnNodeList) {
  147. if ((null != columnNode.get(Constants.CODE)
  148. && !StringUtils.isBlank(columnNode.get(Constants.CODE).asText()))
  149. && (null != columnNode.get(Constants.DATA_TYPE))) {
  150. apiExpressionEvaluator.getColumnDataTypeMapping().put(
  151. columnNode.get(Constants.CODE).asText(),
  152. columnNode.get(Constants.DATA_TYPE).asText());
  153. /**
  154. * @author Akhileshwar
  155. * PE-7045
  156. */
  157. // dimension map created
  158. if (columnNode.get(Constants.DIMENSIONS) != null) {
  159. for (JsonNode dimensioNode : columnNode.get(Constants.DIMENSIONS)) { // Code by Vivek
  160. apiExpressionEvaluator.getColumnDataTypeMapping().put(columnNode.get(Constants.CODE).asText() +Constants.DOT + dimensioNode.asText(),
  161. columnNode.get(Constants.DATA_TYPE).asText());
  162. }
  163. dimMap.put(columnNode.get(Constants.CODE).asText(),columnNode.get(Constants.DIMENSIONS));
  164. }
  165. }
  166. }
  167. }
  168. /*********** Iterating Data : Generate DataMap for all sections ******************/
  169. dataNode = mapper.createArrayNode();
  170. for(int dataCtr = 0; dataCtr<sectionsNode.get(sctnCtr).get(Constants.DATA).size(); dataCtr++){
  171. HashMap<String, JsonNode> dataMapTmp = new HashMap<String, JsonNode>();
  172. // PE-7506
  173. // TODO Check if these 2 variables can be declared above.
  174. JsonNode dNode = sectionsNode.get(sctnCtr).get(Constants.DATA).get(dataCtr);
  175. JsonNode sect_sectStruc_col = sectionsNode.get(sctnCtr).get(Constants.SECTION_STRUCTURE).get(Constants.COLUMNS);
  176. // for(int k=0;k<dNode.size();k++) {
  177. it = dNode.fields();
  178. while (it.hasNext()) {
  179. entry = it.next();
  180. JsonNode value = JsonUtils.isNullNode(entry.getValue()) ? null : entry.getValue();
  181. if(null != value) {
  182. if (value.getNodeType() != JsonNodeType.OBJECT) {
  183. dataMapTmp.put(entry.getKey().trim(), value);
  184. } else {
  185. dataMapTmp = new FormValidator().parseJsonObjectMap(entry.getKey(), value, dataMapTmp,
  186. null, sect_sectStruc_col,null); // PE-7506
  187. }
  188. }else{
  189. dataMapTmp.put(entry.getKey().trim(), null);
  190. }
  191. value = null;
  192. }
  193. ((ArrayNode)dataNode).add(dNode);
  194. // }
  195. for (JsonNode columnNode : sect_sectStruc_col) {
  196. if (!JsonUtils.isNullOrBlankOrNullNode(columnNode.get(Constants.DIMENSIONS))) {
  197. dimMap.put(columnNode.get(Constants.CODE).asText(), columnNode.get(Constants.DIMENSIONS));
  198. }
  199. // PE-8292 Add null to dataMapTmp if Question is present in metadata-json but absent in data-json
  200. if (!JsonUtils.isNullOrBlankOrNullNode(columnNode.get(Constants.CODE))
  201. && !dataMapTmp.containsKey(columnNode.get(Constants.CODE).asText())) {
  202. dataMapTmp.put(columnNode.get(Constants.CODE).asText().trim(), null);
  203. }
  204. }
  205. dataMapTmp= new FormValidator().updateDataMapWithEmptyDimension(dataMapTmp,dimMap);
  206. dataMap2.add(dataMapTmp);
  207. dNode = null;
  208. sect_sectStruc_col = null;
  209. dataMapTmp = null;
  210. }
  211. //Making csv out of JSON single level
  212. if(null != dataNode) {
  213. //logger.info(dataNode.toString());
  214. JSONArray myArr = new JSONArray(dataNode.toString());
  215. Set<String> keyList = new HashSet();
  216. for (int j = 0; j < myArr.length(); j++) {
  217. JSONObject json = myArr.getJSONObject(j);
  218. Iterator<String> keys = json.keys();
  219. while (keys.hasNext()) {
  220. keyList.add(keys.next());
  221. }
  222. }
  223. CSVParser.parseFile(new ByteArrayInputStream(
  224. (JsonUtils.rowToString(new JSONArray(keyList)) + JsonUtils.toString(new JSONArray(keyList), myArr))
  225. .toString().getBytes("UTF-8")));
  226. }
  227. uuidList.add(apiExpressionEvaluator.getExpressionEvaluatorDriver().setCsvData(CSVParser.dataForAggregation, null));
  228. dataMap2_Sections.add(dataMap2);
  229. }
  230. /*********** 2. Ended ******************/
  231. // //Start PE-7056 Expression should not executed if columns are not present in MetaData.
  232. if(!otherAndContextKeys.isEmpty()){
  233. metaDataColumnsOnly.addAll(otherAndContextKeys);
  234. }
  235. // //End PE-7056
  236. /*********** 3. Iterating sections and perform validations ***********/
  237. JsonNode sectionNodeNum = null;
  238. ArrayNode sectionArray = mapper.createArrayNode();
  239. for (int sctnCtr=0; sctnCtr<sectionsNode.size(); sctnCtr++){
  240. sectionNodeNum = mapper.createObjectNode();
  241. arr = mapper.createArrayNode();
  242. /*********** 3.1 Generate DataMap for the section (not including self dataMap values) ***********/
  243. int c=0;
  244. Map<String, Integer> duplicateChkMap = new HashMap<>();
  245. for(ArrayList<HashMap<String, JsonNode>> dataMap2: dataMap2_Sections){
  246. if(sctnCtr != c){
  247. for(HashMap<String, JsonNode> hm : dataMap2 ){
  248. for(Map.Entry<String,JsonNode> e : hm.entrySet()){
  249. dataMap.put(e.getKey(), e.getValue()); // Put key in dataMap
  250. if(duplicateChkMap.containsKey(e.getKey())){
  251. int val= Integer.parseInt(duplicateChkMap.get(e.getKey()).toString());
  252. duplicateChkMap.put(e.getKey(), val+1);
  253. }else{
  254. duplicateChkMap.put(e.getKey(), 1);
  255. }
  256. }
  257. }
  258. }
  259. c++;
  260. }
  261. // TODO Optimize code by merging below for in above loop
  262. for(Map.Entry<String, Integer> e : duplicateChkMap.entrySet()){
  263. if(e.getValue()!=1){
  264. dataMap.remove(e.getKey());
  265. }
  266. }
  267. /*********** 3.1 Ended ******************/
  268. /*********** 3.2 Iterating Rows (populating self dataMap values) and perform validations ***********/
  269. for(int dataCtr = 0; dataCtr<sectionsNode.get(sctnCtr).get(Constants.DATA).size(); dataCtr++){
  270. HashMap<String, JsonNode> dataMapFinal = new HashMap<>();
  271. // Put all other section dataMap
  272. dataMapFinal.putAll(dataMap);
  273. // Put all self section dataMap
  274. dataMapFinal.putAll(dataMap2_Sections.get(sctnCtr).get(dataCtr));
  275. //logger.debug(String.format("dataMap..%s" , dataMap));
  276. dataNode = sectionsNode.get(sctnCtr).get(Constants.DATA);
  277. //7045 dimMap added and 7056 metaDataColumnsOnly
  278. resultNode = validate(dataMapFinal, columnNodeList_Master.get(sctnCtr), dataNode.get(dataCtr),
  279. apiExpressionEvaluator, duplicateChkMap,isMDARequest,dimMap, new ArrayList(metaDataColumnsOnly));
  280. arr.add(resultNode);
  281. dataMapFinal.clear();
  282. } // SECTION END
  283. /*********** 3.2 Ended ***********/
  284. ((ObjectNode) (sectionNodeNum)).set(Constants.SECTIONCODE, sectionsNode.get(sctnCtr).get(Constants.SECTIONCODE));
  285. ((ObjectNode) (sectionNodeNum)).set(Constants.DATA, arr);
  286. ((ArrayNode) sectionArray).add(sectionNodeNum);
  287. }
  288. /*********** 3. Ended ***********/
  289. ((ObjectNode) resultEntiryNode).set(Constants.SECTIONS, sectionArray); // Add sections
  290. if(null != contextDataNode)
  291. ((ObjectNode) (resultEntiryNode)).set(Constants.CONTEXTDATAKEY, contextDataNode); // Add ContextData
  292. entityArr.add(resultEntiryNode);
  293. for (String uuid : uuidList) {
  294. apiExpressionEvaluator.getExpressionEvaluatorDriver().removeCsvData(uuid);
  295. }
  296. metaDataColumnsOnly = null;
  297. //PE-8070 end
  298. }
  299. resultNode=mapper.createObjectNode().set("entities", entityArr);
  300. //logger.info(String.format("%s %s", Constants.EXIT ,Constants.LOG_PARSEANDVALIDATE));
  301. return resultNode;
  302. }
  303. public JsonNode validate(HashMap<String, JsonNode> dataMap, ArrayList<JsonNode> columnNodeList,
  304. JsonNode dataNode, APIExpressionEvaluator apiExpressionEvaluator, Map<String, Integer> cscDuplicateChkMap, boolean isMDARequest,
  305. HashMap<String, JsonNode> dimMap, List<String> metaDataColumnsOnly ) throws Exception { //7045
  306. //logger.info(String.format("%s %s", Constants.INTIATE ,Constants.LOG_VALIDATE));
  307. JsonNode validationNode = null;
  308. ObjectNode obj = null;
  309. String code = "";
  310. ArrayNode arr = null;
  311. JsonNode nodeDTObject = null;
  312. JsonNode dnCodeObject = null;
  313. Map<String, String> incorrectDataType = new HashMap<>();
  314. String result = null;
  315. JsonNode validationObjNode = null;
  316. ArrayList<ObjectNode> predefinedObjList = null;
  317. List<ObjectNode> rangeOrSeqObjList = null;
  318. ArrayList<String> dimList=null;
  319. ArrayList<ObjectNode> seqCheckList=null;
  320. //PE-5643 by default true because for true type do not fire validations.
  321. boolean isOptionType = true;
  322. JsonNode validationOBJ = null;
  323. JsonNode dimNode = null;
  324. int endPoint = Constants.ENDPOINT_DEFAULT;
  325. JsonNode questionType = null; //Added for 8916 Remove %
  326. try {
  327. if(isMDARequest) {
  328. endPoint = Constants.ENDPOINT_PERFORM_DEFAULT_ACTIONS;
  329. }
  330. if (columnNodeList != null && columnNodeList.size() > 0) {
  331. arr = mapper.createArrayNode();
  332. for (JsonNode node : columnNodeList) {
  333. code = node.get(Constants.CODE).asText();
  334. if (dataNode != null ) {
  335. //Added for 8916 Remove %
  336. questionType = node.get(Constants.QUESTION_TYPE);
  337. if(!JsonUtils.isNullOrBlankOrNullNode(questionType) && questionType.asText().equals(Constants.PERCENTAGE)){
  338. if (null != dataMap && !JsonUtils.isNullOrBlankOrNullNode(dataMap.get(code)) && dataNode.get(code) != null) {
  339. String percentageValue = dataMap.get(code).asText().trim();
  340. if(!percentageValue.isEmpty() && percentageValue.endsWith("%")){
  341. percentageValue = percentageValue.substring(0, percentageValue.length()-1);
  342. dataMap.put(code, mapper.readTree(percentageValue));
  343. ((ObjectNode) dataNode).put(code, mapper.readTree(percentageValue));
  344. }
  345. }
  346. } //PE -5216 and PE-5643 Check for drop down options exist in metadata or in database.
  347. if (questionType != null
  348. && ( questionType.asText().equals("dropdown") ||
  349. questionType.asText().equals("radio_buttons") )) {
  350. //logger.info(String.format("Question type is %s", node.get("questionType").asText()));
  351. // PE-8070 Clear & Prepare outputJson for dimensions
  352. if(!JsonUtils.isNullOrBlankOrNullNode(dataNode.get(code)) && dataNode.get(code).getNodeType()==JsonNodeType.OBJECT) {
  353. Iterator<String> it = dataNode.get(code).fieldNames();
  354. String dimensionKey = null;
  355. while(null!=it && it.hasNext() ) {
  356. dimensionKey = it.next();
  357. isOptionType = checkAnswerExists(node, dataNode.get(code).get(dimensionKey));
  358. // TODO Further task (Make it a function)
  359. if ( ! isOptionType ) {
  360. // PE-8397
  361. // // Implementation start PE : 5643
  362. // // Clear the value anyways if checkAnswerExists==false
  363. if(isMDARequest)
  364. {
  365. ((ObjectNode) (dataNode.get(code))).put(dimensionKey, "");
  366. }
  367. // ((ObjectNode) (dataNode.get(code))).put(dimensionKey, "");
  368. // // Implementation end PE : 5643
  369. // Generate error for dimension in format : Question1.Dimension1
  370. obj = apiExpressionEvaluator.prepareOutputJson(null, null, null, ValidationTypes.dropDown,
  371. code+"."+dimensionKey, null, null,node.has("displayLabel") ? node.get("displayLabel").asText() : null);
  372. }
  373. if (obj != null) {
  374. arr.add(obj);
  375. obj = null;
  376. }
  377. }
  378. // Clear & Prepare outputJson for non-dimensional questions (ie. simple values)
  379. } else {
  380. isOptionType = checkAnswerExists(node, dataNode.get(code));
  381. if ( ! isOptionType ) {
  382. // PE-8397
  383. // // Implementation start PE : 5643
  384. // // Clear the value anyways if checkAnswerExists==false
  385. if (isMDARequest) {
  386. ((ObjectNode) (dataNode)).put(code, "");
  387. }
  388. // ((ObjectNode) (dataNode)).put(code, "");
  389. // // Implementation end PE : 5643
  390. obj = apiExpressionEvaluator.prepareOutputJson(null, null, null, ValidationTypes.dropDown,
  391. code, null, null,node.has("displayLabel") ? node.get("displayLabel").asText() : null);
  392. }
  393. if (obj != null) {
  394. arr.add(obj);
  395. obj = null;
  396. }
  397. }
  398. }
  399. // PE 9145 : Clear code value in MDA in case of data type error
  400. if(isMDARequest)
  401. {
  402. nodeDTObject = node.get(Constants.DATA_TYPE);
  403. if (!JsonUtils.isNullOrBlankOrNullNode(nodeDTObject)) {
  404. dnCodeObject = dataNode.get(code);
  405. if (isMDARequest && !JsonUtils.isNullOrBlankOrNullNode(dnCodeObject)
  406. && !StringUtils.isEmpty(dnCodeObject.asText().trim())) {
  407. incorrectDataType = new FormValidator().dataTypeCheck(dataMap, dataNode, code,
  408. nodeDTObject, dnCodeObject, false, null, null);
  409. if (!Boolean.parseBoolean(incorrectDataType.get("dataTypeFlag"))) {
  410. ((ObjectNode) (dataNode)).put(code, "");
  411. }
  412. }
  413. }
  414. }
  415. // PE 9145 end
  416. if (node.get(Constants.VALIDATIONS) != null && node.get(Constants.VALIDATIONS).size() > 0) {
  417. for (int i = 0; i < node.get(Constants.VALIDATIONS).size(); i++) {
  418. boolean rangeAlertFlag = false;
  419. try {
  420. validationNode = node.get(Constants.VALIDATIONS).get(i);
  421. if (validationNode.get(Constants.VALIDATION_TYPE) != null
  422. && EnumUtils.isValidEnum(ValidationTypes.class,
  423. validationNode.get(Constants.VALIDATION_TYPE).asText())) {
  424. switch (ValidationTypes
  425. .valueOf(validationNode.get(Constants.VALIDATION_TYPE).asText())) {
  426. case required:
  427. // PE - 7241
  428. predefinedObjList = FormValidator.validatePredefinedValidation(dataNode,node,validationNode,dataMap,null,Constants.REQUIRED);
  429. break;
  430. case phone:
  431. // PE - 7241
  432. predefinedObjList = FormValidator.validatePredefinedValidation(dataNode,node,validationNode,null,null,Constants.PHONE);
  433. break;
  434. case email:
  435. // PE - 7241
  436. predefinedObjList = FormValidator.validatePredefinedValidation(dataNode,node,validationNode,null,null,Constants.EMAIL);
  437. break;
  438. case range:
  439. rangeOrSeqObjList = apiExpressionEvaluator.prepareRangeObject(dataMap, validationNode, node,dataNode);
  440. //rangeAlertFlag = true;
  441. break;
  442. case rangeValidationRefTable:
  443. rangeOrSeqObjList = apiExpressionEvaluator.prepareRefernceRangeObject(dataMap, validationNode,node, dataNode);
  444. //rangeAlertFlag = true;
  445. break;
  446. case expression:
  447. obj = apiExpressionEvaluator.expressionEvaluator(dataMap, validationNode, node,
  448. dataNode, cscDuplicateChkMap,columnNodeList, metaDataColumnsOnly, endPoint);
  449. break;
  450. case eligibility:
  451. arr.addAll(apiExpressionEvaluator.checkValidity(dataMap, validationNode, node,
  452. dataNode, isMDARequest,metaDataColumnsOnly));
  453. break;
  454. /**
  455. * @author Akhileshwar
  456. * PE-7045
  457. */
  458. case sequentialCheck://PE-7989 metaDataColumnsOnly added in method signature
  459. rangeOrSeqObjList = apiExpressionEvaluator.performSequentialCheck(dataMap, validationNode, node,
  460. dataNode,dimMap,apiExpressionEvaluator.getColumnDataTypeMapping(), false, metaDataColumnsOnly);
  461. break;
  462. default:
  463. }
  464. } else {
  465. result = Constants.MANDATORY_VALIDATIONTYPE;
  466. obj = apiExpressionEvaluator.prepareOutputJson(null, null, result, null, null, null,
  467. null, null);
  468. }
  469. if (obj != null) {
  470. arr.add(obj);
  471. obj = null;
  472. }
  473. if(rangeOrSeqObjList!=null)
  474. {
  475. for(int j=0;j<rangeOrSeqObjList.size();j++)
  476. {
  477. arr.add(rangeOrSeqObjList.get(j));
  478. }
  479. rangeOrSeqObjList=null;
  480. }
  481. if((null != predefinedObjList) && (predefinedObjList.size() > 0)){
  482. arr.addAll(predefinedObjList);
  483. predefinedObjList = null;
  484. }
  485. // PE-8353 : Log all exceptions and don't throw outside
  486. } catch (CustomStatusException e) {
  487. // if(e.getHttpStatus()==Constants.HTTPSTATUS_400) {
  488. logger.info(JsonUtils.updateErrorNode(e, mapper.createObjectNode()).toString());
  489. // }
  490. } catch(Exception ex) {
  491. logger.info(ex.getMessage());
  492. }
  493. if(arr != null && arr.size() > 0) {
  494. //for(int valCnt=0; valCnt<node.get(Constants.VALIDATIONS).size(); valCnt++) {
  495. if(null!=node.get(Constants.VALIDATIONS)) {
  496. validationOBJ = validationNode;
  497. // Check if MDA action available
  498. if (null!=validationOBJ && null != validationOBJ.get(Constants.MDA)
  499. && !validationOBJ.get(Constants.MDA).asText().equals("")
  500. && !validationOBJ.get(Constants.VALIDATION_TYPE).asText().equals("expression"))
  501. {
  502. //if(rangeAlertFlag == true){
  503. for(JsonNode jnode : arr){
  504. //System.out.println(jnode.get(Constants.VALIDATION_TYPE)+"------"+);
  505. if(Constants.ERROR.equals(jnode.get(Constants.ERROR_TYPE).asText()) && validationOBJ.get(Constants.VALIDATION_TYPE).asText().equals(jnode.get(Constants.VALIDATION_TYPE).asText())){
  506. rangeAlertFlag = true;
  507. break;
  508. }
  509. }
  510. //}
  511. if(rangeAlertFlag == true){
  512. // MDA = exclude_row
  513. if (validationOBJ.get(Constants.MDA).asText().equalsIgnoreCase(Constants.EXECLUE_ROW)) {
  514. //((ObjectNode) (dataNode)).put(Constants.EXCLUDE_FLAG, "Y");
  515. List<String> columnNodeList_Section = new ArrayList<>();
  516. //Getting columns in current section PE-7771
  517. for(int index = 0; index < columnNodeList.size(); index++){
  518. columnNodeList_Section.add(columnNodeList.get(index).get(Constants.CODE).asText());
  519. }
  520. if(columnNodeList_Section != null && columnNodeList_Section.contains(Constants.EXCLUDE_FLAG)){//PE-7771
  521. ((ObjectNode) (dataNode)).put(Constants.EXCLUDE_FLAG, Constants.ANSWER_YES);
  522. }
  523. // MDA = clear_value
  524. } else if (validationOBJ.get(Constants.MDA).asText().equalsIgnoreCase(Constants.CLEAR_VALUE)) {
  525. ((ObjectNode) (dataNode)).put(code, "");
  526. } else {//7044 condition added
  527. String responseData= apiExpressionEvaluator.
  528. expressionEvaluatorForMDA(dataMap, validationOBJ, node, cscDuplicateChkMap, metaDataColumnsOnly);
  529. if(node.get(Constants.DIMENSIONS)!=null)
  530. {
  531. dimList=APIExpressionEvaluator.extractDimensions(node.get(Constants.DIMENSIONS));
  532. dimNode = mapper.createObjectNode();
  533. for(String dim:dimList)
  534. {
  535. ((ObjectNode)dimNode).put(dim,responseData);
  536. }
  537. ((ObjectNode) (dataNode)).set(code, dimNode);
  538. }
  539. else{
  540. ((ObjectNode) (dataNode)).put(code, responseData);
  541. }
  542. }
  543. }
  544. }
  545. }
  546. }
  547. }
  548. // PE 9145 removed below unused code
  549. /*result = Constants.INVALID_DATATYPE_FOR_ERROR;
  550. if (null != nodeDTObject && null != dnCodeObject) {
  551. obj = apiExpressionEvaluator.prepareOutputJson(validationObjNode, node, result,
  552. ValidationTypes.dataTypeError, dnCodeObject.asText(), nodeDTObject.asText(),
  553. nodeDTObject.asText(), null);
  554. }*/
  555. if (obj != null) {
  556. arr.add(obj);
  557. obj = null;
  558. }
  559. }
  560. if (node.get("questionType") != null
  561. && node.get("questionType").asText().equals("checkboxes")) {
  562. buildCheckboxArray(dataNode,code);
  563. }
  564. }
  565. }
  566. if ((arr != null && arr.size() > 0)) {
  567. if (dataNode.get(code) != null) {
  568. ((ObjectNode) (dataNode)).set(code, dataNode.get(code));
  569. }
  570. ((ObjectNode) (dataNode)).set(Constants.VALIDATION_RESULTS, arr);
  571. arr = null;
  572. }
  573. }
  574. // PE-8353 : Log all exceptions and don't throw outside
  575. } catch (CustomStatusException e) {
  576. // if(e.getHttpStatus()==Constants.HTTPSTATUS_400) {
  577. logger.info(JsonUtils.updateErrorNode(e, mapper.createObjectNode()).toString());
  578. // }
  579. } catch(Exception ex) {
  580. logger.info(ex.getMessage());
  581. }
  582. //logger.info(String.format("%s %s", Constants.EXIT ,Constants.LOG_VALIDATE));
  583. return dataNode;
  584. }
  585. public void buildCheckboxArray(JsonNode dataNode,String code) throws Exception
  586. {
  587. if(!JsonUtils.isNullOrBlankOrNullNode(dataNode.get(code)))//PE-8704
  588. {
  589. if( dataNode.get(code).getNodeType() != JsonNodeType.OBJECT)
  590. {
  591. ArrayNode arrNode = mapper.createArrayNode();
  592. String arr1[] = null;
  593. if( !JsonUtils.isNullNode(dataNode.get(code))) {
  594. switch (dataNode.get(code).getNodeType()) {
  595. case ARRAY:
  596. for (JsonNode node : dataNode.get(code)) {
  597. arrNode.add(node);
  598. }
  599. break;
  600. case NULL:
  601. arrNode = null;
  602. break;
  603. case STRING:
  604. arr1 = dataNode.get(code).asText().split(",");
  605. if (arr1 != null && arr1.length > 0) {
  606. for (int i = 0; i < arr1.length; i++) {
  607. arrNode.add(arr1[i]);
  608. }
  609. }
  610. break;
  611. }
  612. }
  613. ((ObjectNode) (dataNode)).set(code, arrNode);
  614. }
  615. else
  616. {
  617. Iterator<Map.Entry<String, JsonNode>> it = dataNode.get(code).fields();
  618. Map.Entry<String, JsonNode> entry = null;
  619. while(it!=null && it.hasNext())
  620. {
  621. entry =it.next();
  622. ArrayNode arrNode = mapper.createArrayNode();
  623. String arr1[]=entry.getValue().asText().split(",");
  624. if(arr1!=null && arr1.length >0)
  625. {
  626. for(int i=0;i<arr1.length;i++)
  627. {
  628. arrNode.add(arr1[i]);
  629. }
  630. }
  631. ((ObjectNode)(dataNode.get(code))).set(entry.getKey(), arrNode);
  632. }
  633. }
  634. }//PE-8704
  635. else
  636. {
  637. ((ObjectNode) (dataNode)).set(code, mapper.createArrayNode());
  638. }
  639. }
  640. public String checkUniqueNessForEEID(String enetityJson) throws Exception
  641. {
  642. String isUnique="true";
  643. JsonNode entityNode=null;
  644. JsonNode sectionsNode = null;
  645. JsonNode dataNode=null;
  646. HashSet<String> eeidSet=null;
  647. ArrayNode entitiesNode = mapper.readValue(enetityJson, ArrayNode.class);
  648. for(int i=0;i<entitiesNode.size();i++) {
  649. entityNode = entitiesNode.get(i);
  650. sectionsNode = entityNode.get(Constants.SECTIONS);
  651. for (int sctnCtr=0; sctnCtr<sectionsNode.size(); sctnCtr++){
  652. eeidSet = new HashSet<String>();
  653. dataNode = sectionsNode.get(sctnCtr).get(Constants.DATA);
  654. if(dataNode!=null)
  655. {
  656. for (int k = 0; k < dataNode.size(); k++) {
  657. if(dataNode.get(k).get(Constants.EMPLOYEE_EEID)!=null && !dataNode.get(k).get(Constants.EMPLOYEE_EEID).asText().equals(""))
  658. {
  659. String eeId = dataNode.get(k).get(Constants.EMPLOYEE_EEID).asText();
  660. if(!eeidSet.add(eeId))
  661. {
  662. eeidSet=null;
  663. return Constants.DUPLICATE;
  664. }
  665. }
  666. else
  667. {
  668. return Constants.MISSING;
  669. }
  670. }
  671. }
  672. }
  673. }
  674. return isUnique;
  675. }
  676. /**
  677. *
  678. * @param dropDownOptions
  679. * @param dataNode
  680. * @param code
  681. * @param key
  682. * @return boolean value
  683. */
  684. public static boolean checkAnswerExists(JsonNode dropDownOptions, JsonNode dataNode_code) throws Exception {
  685. // logger.info("Entering checkAnswerExists method "+dataNode+" code
  686. // "+code+ " key is "+ key);
  687. ArrayNode optionsArrNode = null;
  688. JsonNode dbNode = null;
  689. Map<String, String> optionsDictionary = null;
  690. Map<String, String> dbData = null;
  691. boolean found = false;
  692. boolean fromDB = false;
  693. boolean fromJson = false;
  694. // PE-8269 If value is blank, return found=true. - only for /performDefaultActions
  695. if (JsonUtils.isNullOrBlankOrNullNode(dataNode_code) || "".equals(dataNode_code.asText()) ) {
  696. return true; // Reverted temporarily due to requirement changes
  697. }
  698. dbData = new HashMap<>();
  699. optionsDictionary = new HashMap<>();
  700. if (null != dropDownOptions && null != dropDownOptions.get(Constants.OPTIONS)) {
  701. if (null != dropDownOptions.get(Constants.OPTIONS).get("items")) {
  702. optionsArrNode = (ArrayNode) dropDownOptions.get(Constants.OPTIONS).get("items");
  703. if (optionsArrNode.size() > 0)
  704. fromJson = true;
  705. }
  706. if (null != dropDownOptions.get(Constants.OPTIONS).get(Constants.REFERENCETABLE)) {
  707. dbNode = dropDownOptions.get(Constants.OPTIONS).get(Constants.REFERENCETABLE);
  708. fromDB = true;
  709. dbData = DBUtils.getRefTableData(dbNode.get(Constants.CODE).asText());
  710. }
  711. }
  712. if (fromJson) {
  713. for (int i = 0; i < optionsArrNode.size(); i++) {
  714. if (!JsonUtils.isNullOrBlankOrNullNode(optionsArrNode.get(i).get("value"))
  715. && !JsonUtils.isNullOrBlankOrNullNode(optionsArrNode.get(i).get("displayName"))) {
  716. optionsDictionary.put(optionsArrNode.get(i).get("value").asText(),
  717. optionsArrNode.get(i).get("displayName").asText());
  718. }
  719. }
  720. if (optionsDictionary.containsKey(dataNode_code.asText())) {
  721. found = true;
  722. }
  723. } else if (fromDB && dbData.containsKey(dataNode_code.asText())) {
  724. found = true;
  725. }
  726. // logger.info("Existing checkAnswerExists method ");
  727. return found;
  728. }
  729. }