Merge "Fixing issue with validation errors"
[policy/engine.git] / ONAP-REST / src / main / java / org / onap / policy / rest / util / PolicyValidation.java
1 /*-
2  * ============LICENSE_START=======================================================
3  * ONAP Policy Engine
4  * ================================================================================
5  * Copyright (C) 2017-2018 AT&T Intellectual Property. All rights reserved.
6  * ================================================================================
7  * Licensed under the Apache License, Version 2.0 (the "License");
8  * you may not use this file except in compliance with the License.
9  * You may obtain a copy of the License at
10  * 
11  *      http://www.apache.org/licenses/LICENSE-2.0
12  * 
13  * Unless required by applicable law or agreed to in writing, software
14  * distributed under the License is distributed on an "AS IS" BASIS,
15  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
16  * See the License for the specific language governing permissions and
17  * limitations under the License.
18  * ============LICENSE_END=========================================================
19  */
20
21 package org.onap.policy.rest.util;
22
23 import com.fasterxml.jackson.core.JsonProcessingException;
24 import com.fasterxml.jackson.databind.JsonNode;
25 import com.fasterxml.jackson.databind.ObjectMapper;
26 import com.google.common.base.Splitter;
27 import com.google.common.base.Strings;
28
29 import oasis.names.tc.xacml._3_0.core.schema.wd_17.PolicySetType;
30 import oasis.names.tc.xacml._3_0.core.schema.wd_17.PolicyType;
31
32 import java.io.ByteArrayInputStream;
33 import java.io.IOException;
34 import java.io.StringReader;
35 import java.nio.charset.StandardCharsets;
36 import java.util.ArrayList;
37 import java.util.HashMap;
38 import java.util.HashSet;
39 import java.util.Iterator;
40 import java.util.LinkedHashMap;
41 import java.util.List;
42 import java.util.Map;
43 import java.util.Map.Entry;
44 import java.util.Set;
45 import javax.json.Json;
46 import javax.json.JsonException;
47 import javax.json.JsonObject;
48 import javax.json.JsonReader;
49 import javax.json.JsonValue;
50
51 import org.apache.commons.lang3.StringEscapeUtils;
52 import org.apache.commons.lang3.StringUtils;
53 import org.json.JSONArray;
54 import org.json.JSONObject;
55 import org.onap.policy.common.logging.flexlogger.FlexLogger;
56 import org.onap.policy.common.logging.flexlogger.Logger;
57 import org.onap.policy.rest.adapter.ClosedLoopFaultBody;
58 import org.onap.policy.rest.adapter.ClosedLoopPMBody;
59 import org.onap.policy.rest.adapter.PolicyRestAdapter;
60 import org.onap.policy.rest.dao.CommonClassDao;
61 import org.onap.policy.rest.jpa.MicroServiceModels;
62 import org.onap.policy.rest.jpa.OptimizationModels;
63 import org.onap.policy.rest.jpa.SafePolicyWarning;
64 import org.onap.policy.utils.PolicyUtils;
65 import org.onap.policy.xacml.api.XACMLErrorConstants;
66 import org.onap.policy.xacml.util.XACMLPolicyScanner;
67 import org.springframework.beans.factory.annotation.Autowired;
68 import org.springframework.stereotype.Service;
69
70
71 @Service
72 public class PolicyValidation {
73
74     private static final Logger LOGGER = FlexLogger.getLogger(PolicyValidation.class);
75
76     public static final String CONFIG_POLICY = "Config";
77     public static final String ACTION_POLICY = "Action";
78     public static final String DECISION_POLICY = "Decision";
79     public static final String DECISION_POLICY_MS = "Decision_MS";
80     public static final String CLOSEDLOOP_POLICY = "ClosedLoop_Fault";
81     public static final String CLOSEDLOOP_PM = "ClosedLoop_PM";
82     public static final String ENFORCER_CONFIG_POLICY = "Enforcer Config";
83     public static final String MICROSERVICES = "Micro Service";
84     public static final String FIREWALL = "Firewall Config";
85     public static final String OPTIMIZATION="Optimization";
86     public static final String BRMSPARAM = "BRMS_Param";
87     public static final String BRMSRAW = "BRMS_Raw";
88     public static final String HTML_ITALICS_LNBREAK = "</i><br>";
89     public static final String SUCCESS = "success";
90     public static final String EMPTY_COMPONENT_ATTR =
91             "Component Attributes: One or more Fields in Component Attributes is Empty.";
92     public static final String ISREQUIRED = " is required";
93     public static final String SPACESINVALIDCHARS = " : value has spaces or invalid characters</i><br>";
94     private static final String REQUIRED_ATTRIBUTE = "required-true";
95     private static final String DECISION_MS_MODEL = "MicroService_Model";
96     private static final String RAW = "Raw";
97
98     private static Map<String, String> mapAttribute = new HashMap<>();
99     private static Map<String, String> jsonRequestMap = new HashMap<>();
100     private static List<String> modelRequiredFieldsList = new ArrayList<>();
101     private Set<String> allReqTrueKeys = new HashSet<>();
102
103     private static CommonClassDao commonClassDao;
104
105     @Autowired
106     public PolicyValidation(CommonClassDao commonClassDao) {
107         PolicyValidation.commonClassDao = commonClassDao;
108     }
109
110     /*
111      * This is an empty constructor
112      */
113     public PolicyValidation() {
114         // Empty constructor
115     }
116
117
118     /**
119      * Validate policy.
120      *
121      * @param policyData the policy data
122      * @return the string builder
123      * @throws IOException Signals that an I/O exception has occurred.
124      */
125     public StringBuilder validatePolicy(PolicyRestAdapter policyData) throws IOException {
126         try {
127             boolean valid = true;
128             StringBuilder responseString = new StringBuilder();
129             ObjectMapper mapper = new ObjectMapper();
130
131             if (policyData.getPolicyName() != null) {
132                 String policyNameValidate = PolicyUtils.policySpecialCharValidator(policyData.getPolicyName());
133                 if (!policyNameValidate.contains(SUCCESS)) {
134                     responseString.append("<b>PolicyName</b>:<i>" + policyNameValidate + HTML_ITALICS_LNBREAK);
135                     valid = false;
136                 }
137             } else {
138                 responseString.append("<b>PolicyName</b>: PolicyName Should not be empty" + HTML_ITALICS_LNBREAK);
139                 valid = false;
140             }
141             if (policyData.getPolicyDescription() != null) {
142                 String descriptionValidate = PolicyUtils.descriptionValidator(policyData.getPolicyDescription());
143                 if (!descriptionValidate.contains(SUCCESS)) {
144                     responseString.append("<b>Description</b>:<i>" + descriptionValidate + HTML_ITALICS_LNBREAK);
145                     valid = false;
146                 }
147             }
148
149             if (!"API".equals(policyData.getApiflag()) && policyData.getAttributes() != null
150                     && !policyData.getAttributes().isEmpty()) {
151                 for (Object attribute : policyData.getAttributes()) {
152                     if (attribute instanceof LinkedHashMap<?, ?>) {
153                         String value = null;
154                         String key = null;
155                         if (((LinkedHashMap<?, ?>) attribute).get("key") != null) {
156                             key = ((LinkedHashMap<?, ?>) attribute).get("key").toString();
157                             if (!PolicyUtils.policySpecialCharWithDashValidator(key).contains(SUCCESS)) {
158                                 responseString.append("<b>Attributes or Component Attributes</b>:<i>" + value
159                                         + SPACESINVALIDCHARS);
160                                 valid = false;
161                             }
162                         } else {
163                             if (CONFIG_POLICY.equals(policyData.getPolicyType())) {
164                                 if ("Base".equals(policyData.getConfigPolicyType())) {
165                                     responseString
166                                     .append("<b>Attributes</b>:<i> has one missing Attribute key</i><br>");
167                                 }
168                                 if (BRMSPARAM.equals(policyData.getConfigPolicyType())
169                                         || BRMSRAW.equals(policyData.getConfigPolicyType())) {
170                                     responseString
171                                     .append("<b>Rule Attributes</b>:<i> has one missing Attribute key</i><br>");
172                                 }
173                             } else {
174                                 responseString.append(
175                                         "<b>Component Attributes</b>:<i> has one missing Component Attribute key</i><br>");
176                             }
177                             valid = false;
178                         }
179                         if (((LinkedHashMap<?, ?>) attribute).get("value") != null) {
180                             value = ((LinkedHashMap<?, ?>) attribute).get("value").toString();
181                             if (!PolicyUtils.policySpecialCharWithDashValidator(value).contains(SUCCESS)) {
182                                 if (CONFIG_POLICY.equals(policyData.getPolicyType())) {
183                                     if ("Base".equals(policyData.getConfigPolicyType())) {
184                                         responseString.append("<b>Attributes</b>:<i>" + value
185                                                 + SPACESINVALIDCHARS);
186                                     }
187                                     if (BRMSPARAM.equals(policyData.getConfigPolicyType())
188                                             || BRMSRAW.equals(policyData.getConfigPolicyType())) {
189                                         responseString.append("<b>Rule Attributes</b>:<i>" + value
190                                                 + SPACESINVALIDCHARS);
191                                     }
192                                 } else {
193                                     responseString.append("<b>Component Attributes</b>:<i>" + value
194                                             + SPACESINVALIDCHARS);
195                                 }
196                                 valid = false;
197                             }
198                         } else {
199                             if (CONFIG_POLICY.equals(policyData.getPolicyType())) {
200                                 if ("Base".equals(policyData.getConfigPolicyType())) {
201                                     responseString
202                                     .append("<b>Attributes</b>:<i> has one missing Attribute value</i><br>");
203                                 }
204                                 if (BRMSPARAM.equals(policyData.getConfigPolicyType())
205                                         || BRMSRAW.equals(policyData.getConfigPolicyType())) {
206                                     responseString.append(
207                                             "<b>Rule Attributes</b>:<i> has one missing Attribute value</i><br>");
208                                 }
209                             } else {
210                                 responseString.append(
211                                         "<b>Component Attributes</b>:<i> has one missing Component Attribute value</i><br>");
212                             }
213                             valid = false;
214                         }
215                     }
216                 }
217             }
218
219             // Decision Policy Attributes Validation
220             if (!"API".equals(policyData.getApiflag()) && policyData.getSettings() != null
221                     && !policyData.getSettings().isEmpty()) {
222                 for (Object attribute : policyData.getAttributes()) {
223                     if (attribute instanceof LinkedHashMap<?, ?>) {
224                         String value = null;
225                         if (((LinkedHashMap<?, ?>) attribute).get("key") == null) {
226                             responseString
227                             .append("<b>Settings Attributes</b>:<i> has one missing Attribute key</i><br>");
228                             valid = false;
229                         }
230                         if (((LinkedHashMap<?, ?>) attribute).get("value") != null) {
231                             value = ((LinkedHashMap<?, ?>) attribute).get("value").toString();
232                             if (!PolicyUtils.policySpecialCharValidator(value).contains(SUCCESS)) {
233                                 responseString.append("<b>Settings Attributes</b>:<i>" + value
234                                         + SPACESINVALIDCHARS);
235                                 valid = false;
236                             }
237                         } else {
238                             responseString
239                             .append("<b>Settings Attributes</b>:<i> has one missing Attribute Value</i><br>");
240                             valid = false;
241                         }
242                     }
243                 }
244             }
245
246             if (!"API".equals(policyData.getApiflag()) && policyData.getRuleAlgorithmschoices() != null
247                     && !policyData.getRuleAlgorithmschoices().isEmpty()) {
248                 for (Object attribute : policyData.getRuleAlgorithmschoices()) {
249                     if (attribute instanceof LinkedHashMap<?, ?>) {
250                         String label = ((LinkedHashMap<?, ?>) attribute).get("id").toString();
251                         if (((LinkedHashMap<?, ?>) attribute).get("dynamicRuleAlgorithmField1") == null) {
252                             responseString.append(
253                                     "<b>Rule Algorithms</b>:<i>" + label + " : Field 1 value is not selected</i><br>");
254                             valid = false;
255                         }
256                         if (((LinkedHashMap<?, ?>) attribute).get("dynamicRuleAlgorithmCombo") == null) {
257                             responseString.append(
258                                     "<b>Rule Algorithms</b>:<i>" + label + " : Field 2 value is not selected</i><br>");
259                             valid = false;
260                         }
261                         if (((LinkedHashMap<?, ?>) attribute).get("dynamicRuleAlgorithmField2") != null) {
262                             String value =
263                                     ((LinkedHashMap<?, ?>) attribute).get("dynamicRuleAlgorithmField2").toString();
264                             if (!PolicyUtils.policySpecialCharValidator(value).contains(SUCCESS)) {
265                                 responseString.append("<b>Rule Algorithms</b>:<i>" + label
266                                         + " : Field 3 value has special characters</i><br>");
267                                 valid = false;
268                             }
269                         } else {
270                             responseString
271                             .append("<b>Rule Algorithms</b>:<i>" + label + " : Field 3 value is empty</i><br>");
272                             valid = false;
273                         }
274                     }
275                 }
276             }
277
278             if (CONFIG_POLICY.equalsIgnoreCase(policyData.getPolicyType())) {
279                 if ("Base".equals(policyData.getConfigPolicyType())
280                         || CLOSEDLOOP_POLICY.equals(policyData.getConfigPolicyType())
281                         || CLOSEDLOOP_PM.equals(policyData.getConfigPolicyType())
282                         || ENFORCER_CONFIG_POLICY.equals(policyData.getConfigPolicyType())
283                         || MICROSERVICES.equals(policyData.getConfigPolicyType())
284                         || OPTIMIZATION.equals(policyData.getConfigPolicyType())) {
285
286                     if (!Strings.isNullOrEmpty(policyData.getOnapName())) {
287                         String onapNameValidate = PolicyUtils.policySpecialCharWithDashValidator(policyData.getOnapName());
288                         if (!onapNameValidate.contains(SUCCESS)) {
289                             responseString.append("<b>OnapName</b>:<i>" + onapNameValidate + HTML_ITALICS_LNBREAK);
290                             valid = false;
291                         }
292                     } else {
293                         responseString.append("<b>Onap Name</b>: Onap Name Should not be empty" + HTML_ITALICS_LNBREAK);
294                         valid = false;
295                     }
296                 }
297
298                 if (!Strings.isNullOrEmpty(policyData.getRiskType())) {
299                     String riskTypeValidate = PolicyUtils.policySpecialCharValidator(policyData.getRiskType());
300                     if (!riskTypeValidate.contains(SUCCESS)) {
301                         responseString.append("<b>RiskType</b>:<i>" + riskTypeValidate + HTML_ITALICS_LNBREAK);
302                         valid = false;
303                     }
304                 } else {
305                     responseString.append("<b>RiskType</b>: Risk Type Should not be Empty" + HTML_ITALICS_LNBREAK);
306                     valid = false;
307                 }
308
309                 if (!Strings.isNullOrEmpty(policyData.getRiskLevel())) {
310                     String validateRiskLevel = PolicyUtils.policySpecialCharValidator(policyData.getRiskLevel());
311                     if (!validateRiskLevel.contains(SUCCESS)) {
312                         responseString.append("<b>RiskLevel</b>:<i>" + validateRiskLevel + HTML_ITALICS_LNBREAK);
313                         valid = false;
314                     }
315                 } else {
316                     responseString.append("<b>RiskLevel</b>: Risk Level Should not be Empty" + HTML_ITALICS_LNBREAK);
317                     valid = false;
318                 }
319
320                 if (!Strings.isNullOrEmpty(policyData.getGuard())) {
321                     String validateGuard = PolicyUtils.policySpecialCharValidator(policyData.getGuard());
322                     if (!validateGuard.contains(SUCCESS)) {
323                         responseString.append("<b>Guard</b>:<i>" + validateGuard + HTML_ITALICS_LNBREAK);
324                         valid = false;
325                     }
326                 } else {
327                     responseString.append("<b>Guard</b>: Guard Value Should not be Empty" + HTML_ITALICS_LNBREAK);
328                     valid = false;
329                 }
330
331                 // Validate Config Base Policy Data
332                 if ("Base".equalsIgnoreCase(policyData.getConfigPolicyType())) {
333                     if (!Strings.isNullOrEmpty(policyData.getConfigName())) {
334                         String configNameValidate = PolicyUtils.policySpecialCharValidator(policyData.getConfigName());
335                         if (!configNameValidate.contains(SUCCESS)) {
336                             responseString.append("ConfigName:" + configNameValidate + HTML_ITALICS_LNBREAK);
337                             valid = false;
338                         }
339                     } else {
340                         responseString.append("Config Name: Config Name Should not be Empty" + HTML_ITALICS_LNBREAK);
341                         valid = false;
342                     }
343                     if (!Strings.isNullOrEmpty(policyData.getConfigType())) {
344                         String configTypeValidate = PolicyUtils.policySpecialCharValidator(policyData.getConfigType());
345                         if (!configTypeValidate.contains(SUCCESS)) {
346                             responseString.append("ConfigType:" + configTypeValidate + HTML_ITALICS_LNBREAK);
347                             valid = false;
348                         }
349                     } else {
350                         responseString.append("Config Type: Config Type Should not be Empty" + HTML_ITALICS_LNBREAK);
351                         valid = false;
352                     }
353                     if (!Strings.isNullOrEmpty(policyData.getConfigBodyData())) {
354                         String configBodyData = policyData.getConfigBodyData();
355                         String configType = policyData.getConfigType();
356                         if (configType != null) {
357                             if ("JSON".equals(configType)) {
358                                 if (!PolicyUtils.isJSONValid(configBodyData)) {
359                                     responseString
360                                     .append("Config Body: JSON Content is not valid" + HTML_ITALICS_LNBREAK);
361                                     valid = false;
362                                 }
363                             } else if ("XML".equals(configType)) {
364                                 if (!PolicyUtils.isXMLValid(configBodyData)) {
365                                     responseString.append(
366                                             "Config Body: XML Content data is not valid" + HTML_ITALICS_LNBREAK);
367                                     valid = false;
368                                 }
369                             } else if ("PROPERTIES".equals(configType)) {
370                                 if (!PolicyUtils.isPropValid(configBodyData) || "".equals(configBodyData)) {
371                                     responseString
372                                     .append("Config Body: Property data is not valid" + HTML_ITALICS_LNBREAK);
373                                     valid = false;
374                                 }
375                             } else if ("OTHER".equals(configType) && ("".equals(configBodyData))) {
376                                 responseString
377                                 .append("Config Body: Config Body Should not be Empty" + HTML_ITALICS_LNBREAK);
378                                 valid = false;
379                             }
380                         }
381                     } else {
382                         responseString.append("Config Body: Config Body Should not be Empty" + HTML_ITALICS_LNBREAK);
383                         valid = false;
384                     }
385                 }
386                 // Validate Config Firewall Policy Data
387                 if (FIREWALL.equalsIgnoreCase(policyData.getConfigPolicyType())) {
388                     if (policyData.getConfigName() != null && !policyData.getConfigName().isEmpty()) {
389                         String configNameValidate = PolicyUtils.policySpecialCharValidator(policyData.getConfigName());
390                         if (!configNameValidate.contains(SUCCESS)) {
391                             responseString.append("<b>ConfigName</b>:<i>" + configNameValidate + HTML_ITALICS_LNBREAK);
392                             valid = false;
393                         }
394                     } else {
395                         responseString.append("<b>Config Name</b>:<i> Config Name is required" + HTML_ITALICS_LNBREAK);
396                         valid = false;
397                     }
398                     if (policyData.getSecurityZone() == null || policyData.getSecurityZone().isEmpty()) {
399                         responseString
400                         .append("<b>Security Zone</b>:<i> Security Zone is required" + HTML_ITALICS_LNBREAK);
401                         valid = false;
402                     }
403                 }
404                 // Validate BRMS_Param Policy Data
405                 if (BRMSPARAM.equalsIgnoreCase(policyData.getConfigPolicyType())
406                         && Strings.isNullOrEmpty(policyData.getRuleName())) {
407                     responseString.append("<b>BRMS Template</b>:<i>BRMS Template is required" + HTML_ITALICS_LNBREAK);
408                     valid = false;
409                 }
410                 // Validate BRMS_Raw Policy Data
411                 if (BRMSRAW.equalsIgnoreCase(policyData.getConfigPolicyType())) {
412                     if (policyData.getConfigBodyData() != null && !policyData.getConfigBodyData().isEmpty()) {
413                         String message = PolicyUtils.brmsRawValidate(policyData.getConfigBodyData());
414
415                         // If there are any error other than Annotations then this is not Valid
416                         if (message.contains("[ERR")) {
417                             responseString.append(
418                                     "<b>Raw Rule Validate</b>:<i>Raw Rule has error" + message + HTML_ITALICS_LNBREAK);
419                             valid = false;
420                         }
421                     } else {
422                         responseString.append("<b>Raw Rule</b>:<i>Raw Rule is required" + HTML_ITALICS_LNBREAK);
423                         valid = false;
424                     }
425                 }
426                 // Validate ClosedLoop_PM Policy Data
427                 if (CLOSEDLOOP_PM.equalsIgnoreCase(policyData.getConfigPolicyType())) {
428                     try {
429                         if (Strings.isNullOrEmpty(
430                                 policyData.getServiceTypePolicyName().get("serviceTypePolicyName").toString())) {
431                             responseString.append("<b>ServiceType PolicyName</b>:<i>ServiceType PolicyName is required"
432                                     + HTML_ITALICS_LNBREAK);
433                             valid = false;
434                         }
435
436                     } catch (Exception e) {
437                         LOGGER.error("ERROR in ClosedLoop_PM PolicyName", e);
438                         responseString.append("<b>ServiceType PolicyName</b>:<i>ServiceType PolicyName is required"
439                                 + HTML_ITALICS_LNBREAK);
440                         valid = false;
441                     }
442
443                     if (policyData.getJsonBody() != null) {
444
445                         ClosedLoopPMBody pmBody = mapper.readValue(policyData.getJsonBody(), ClosedLoopPMBody.class);
446                         if (pmBody.getEmailAddress() != null) {
447                             String result = emailValidation(pmBody.getEmailAddress(), responseString.toString());
448                             if (result != SUCCESS) {
449                                 responseString.append(result + HTML_ITALICS_LNBREAK);
450                                 valid = false;
451                             }
452                         }
453                         if ((pmBody.isGamma() || pmBody.isMcr() || pmBody.isTrinity() || pmBody.isvDNS()
454                                 || pmBody.isvUSP()) != true) {
455                             responseString
456                             .append("<b>D2/Virtualized Services</b>: <i>Select at least one D2/Virtualized Services"
457                                     + HTML_ITALICS_LNBREAK);
458                             valid = false;
459                         }
460                         if (pmBody.getGeoLink() != null && !pmBody.getGeoLink().isEmpty()) {
461                             String result = PolicyUtils.policySpecialCharValidator(pmBody.getGeoLink());
462                             if (!result.contains(SUCCESS)) {
463                                 responseString.append("<b>GeoLink</b>:<i>" + result + HTML_ITALICS_LNBREAK);
464                                 valid = false;
465                             }
466                         }
467                         if (pmBody.getAttributes() != null && !pmBody.getAttributes().isEmpty()) {
468                             for (Entry<String, String> entry : pmBody.getAttributes().entrySet()) {
469                                 String key = entry.getKey();
470                                 String value = entry.getValue();
471                                 if (!key.contains("Message")) {
472                                     String attributeValidate = PolicyUtils.policySpecialCharValidator(value);
473                                     if (!attributeValidate.contains(SUCCESS)) {
474                                         responseString.append("<b>Attributes</b>:<i>" + key
475                                                 + " : value has spaces or invalid characters" + HTML_ITALICS_LNBREAK);
476                                         valid = false;
477                                     }
478                                 }
479                             }
480                         }
481                     } else {
482                         responseString
483                         .append("<b>D2/Virtualized Services</b>:<i>Select atleast one D2/Virtualized Services"
484                                 + HTML_ITALICS_LNBREAK);
485                         valid = false;
486                     }
487                 }
488                 if (CLOSEDLOOP_POLICY.equalsIgnoreCase(policyData.getConfigPolicyType())) {
489                     if (policyData.getJsonBody() != null) {
490
491                         // For API we need to get the conditions key from the Json request and check it before
492                         // deserializing to POJO due to the enum
493                         if ("API".equals(policyData.getApiflag())) {
494                             JSONObject json = new JSONObject(policyData.getJsonBody());
495                             if (!json.isNull("conditions")) {
496                                 String apiCondition = (String) json.get("conditions");
497                                 if (Strings.isNullOrEmpty(apiCondition)) {
498                                     responseString.append("<b>Conditions</b>: <i>Select At least one Condition"
499                                             + HTML_ITALICS_LNBREAK);
500                                     return responseString;
501                                 }
502                             } else {
503                                 responseString
504                                 .append("<b>Conditions</b>: <i>There were no conditions provided in configBody json"
505                                         + HTML_ITALICS_LNBREAK);
506                                 return responseString;
507                             }
508                         } else {
509                             if (policyData.getTrapDatas().getTrap1() != null) {
510                                 if (policyData.getClearTimeOut() == null) {
511                                     responseString.append(
512                                             "<b>Trigger Clear TimeOut</b>: <i>Trigger Clear TimeOut is required when atleast One Trigger Signature is enabled</i><br>");
513                                     valid = false;
514                                 }
515                                 if (policyData.getTrapMaxAge() == null) {
516                                     responseString.append(
517                                             "<b>Trap Max Age</b>: <i>Trap Max Age is required when atleast One Trigger Signature is enabled</i><br>");
518                                     valid = false;
519                                 }
520                             }
521                             if (policyData.getFaultDatas().getTrap1() != null
522                                     && policyData.getVerificationclearTimeOut() == null) {
523                                 responseString.append(
524                                         "<b>Fault Clear TimeOut</b>: <i>Fault Clear TimeOut is required when atleast One Fault Signature is enabled</i><br>");
525                                 valid = false;
526                             }
527                         }
528
529                         ClosedLoopFaultBody faultBody =
530                                 mapper.readValue(policyData.getJsonBody(), ClosedLoopFaultBody.class);
531                         if (faultBody.getEmailAddress() != null && !faultBody.getEmailAddress().isEmpty()) {
532                             String result = emailValidation(faultBody.getEmailAddress(), responseString.toString());
533                             if (!SUCCESS.equals(result)) {
534                                 responseString.append(result + HTML_ITALICS_LNBREAK);
535                                 valid = false;
536                             }
537                         }
538                         if (!(faultBody.isGamma() || faultBody.isMcr() || faultBody.isTrinity() || faultBody.isvDNS()
539                                 || faultBody.isvUSP())) {
540                             responseString
541                             .append("<b>D2/Virtualized Services</b>: <i>Select at least one D2/Virtualized Services"
542                                     + HTML_ITALICS_LNBREAK);
543                             valid = false;
544                         }
545                         if (faultBody.getActions() == null || faultBody.getActions().isEmpty()) {
546                             responseString
547                             .append("<b>vPRO Actions</b>: <i>vPRO Actions is required" + HTML_ITALICS_LNBREAK);
548                             valid = false;
549                         }
550                         if (faultBody.getClosedLoopPolicyStatus() == null
551                                 || faultBody.getClosedLoopPolicyStatus().isEmpty()) {
552                             responseString.append(
553                                     "<b>Policy Status</b>: <i>Policy Status is required" + HTML_ITALICS_LNBREAK);
554                             valid = false;
555                         }
556                         if (faultBody.getConditions() == null) {
557                             responseString.append(
558                                     "<b>Conditions</b>: <i>Select At least one Condition" + HTML_ITALICS_LNBREAK);
559                             valid = false;
560                         }
561                         if (faultBody.getGeoLink() != null && !faultBody.getGeoLink().isEmpty()) {
562                             String result = PolicyUtils.policySpecialCharWithSpaceValidator(faultBody.getGeoLink());
563                             if (!result.contains(SUCCESS)) {
564                                 responseString.append("<b>GeoLink</b>:<i>" + result + HTML_ITALICS_LNBREAK);
565                                 valid = false;
566                             }
567                         }
568                         if (faultBody.getAgingWindow() == 0) {
569                             responseString
570                             .append("<b>Aging Window</b>: <i>Aging Window is required" + HTML_ITALICS_LNBREAK);
571                             valid = false;
572                         }
573                         if (faultBody.getTimeInterval() == 0) {
574                             responseString.append(
575                                     "<b>Time Interval</b>: <i>Time Interval is required" + HTML_ITALICS_LNBREAK);
576                             valid = false;
577                         }
578                         if (faultBody.getRetrys() == 0) {
579                             responseString.append("<b>Number of Retries</b>: <i>Number of Retries is required"
580                                     + HTML_ITALICS_LNBREAK);
581                             valid = false;
582                         }
583                         if (faultBody.getTimeOutvPRO() == 0) {
584                             responseString.append(
585                                     "<b>APP-C Timeout</b>: <i>APP-C Timeout is required" + HTML_ITALICS_LNBREAK);
586                             valid = false;
587                         }
588                         if (faultBody.getTimeOutRuby() == 0) {
589                             responseString
590                             .append("<b>TimeOutRuby</b>: <i>TimeOutRuby is required" + HTML_ITALICS_LNBREAK);
591                             valid = false;
592                         }
593                         if (faultBody.getVnfType() == null || faultBody.getVnfType().isEmpty()) {
594                             responseString.append("<b>Vnf Type</b>: <i>Vnf Type is required" + HTML_ITALICS_LNBREAK);
595                             valid = false;
596                         }
597                     } else {
598                         responseString
599                         .append("<b>D2/Virtualized Services</b>: <i>Select atleast one D2/Virtualized Services"
600                                 + HTML_ITALICS_LNBREAK);
601                         responseString
602                         .append("<b>vPRO Actions</b>: <i>vPRO Actions is required" + HTML_ITALICS_LNBREAK);
603                         responseString
604                         .append("<b>Aging Window</b>: <i>Aging Window is required" + HTML_ITALICS_LNBREAK);
605                         responseString
606                         .append("<b>Policy Status</b>: <i>Policy Status is required" + HTML_ITALICS_LNBREAK);
607                         responseString
608                         .append("<b>Conditions</b>: <i>Select Atleast one Condition" + HTML_ITALICS_LNBREAK);
609                         responseString.append("<b>PEP Name</b>: <i>PEP Name is required" + HTML_ITALICS_LNBREAK);
610                         responseString.append("<b>PEP Action</b>: <i>PEP Action is required" + HTML_ITALICS_LNBREAK);
611                         responseString
612                         .append("<b>Time Interval</b>: <i>Time Interval is required" + HTML_ITALICS_LNBREAK);
613                         responseString.append(
614                                 "<b>Number of Retries</b>: <i>Number of Retries is required" + HTML_ITALICS_LNBREAK);
615                         responseString
616                         .append("<b>APP-C Timeout</b>: <i>APP-C Timeout is required" + HTML_ITALICS_LNBREAK);
617                         responseString.append("<b>TimeOutRuby</b>: <i>TimeOutRuby is required" + HTML_ITALICS_LNBREAK);
618                         responseString.append("<b>Vnf Type</b>: <i>Vnf Type is required" + HTML_ITALICS_LNBREAK);
619                         valid = false;
620                     }
621                 }
622
623                 if (MICROSERVICES.equals(policyData.getConfigPolicyType())) {
624                     boolean tmpValid = validateMsModel(policyData, responseString);
625                     if (!tmpValid) {
626                         valid = false;
627                     }
628                 }
629
630                 // Validate Optimization Policy Data
631                 if (OPTIMIZATION.equals(policyData.getConfigPolicyType())){
632
633                     if(!Strings.isNullOrEmpty(policyData.getServiceType())){
634
635                         modelRequiredFieldsList.clear();
636                         pullJsonKeyPairs((JsonNode) policyData.getPolicyJSON());
637
638                         String service;
639                         String version;
640                         if (policyData.getServiceType().contains("-v")){
641                             service = policyData.getServiceType().split("-v")[0];
642                             version = policyData.getServiceType().split("-v")[1];
643                         }else {
644                             service = policyData.getServiceType();
645                             version = policyData.getVersion();
646                         }
647
648                         if (!Strings.isNullOrEmpty(version)) {
649                             OptimizationModels returnModel = getOptimizationModelData(service, version);
650
651                             if (returnModel != null) {
652
653                                 String annotation = returnModel.getAnnotation();
654                                 String refAttributes = returnModel.getRefattributes();
655                                 String subAttributes = returnModel.getSubattributes();
656                                 String modelAttributes = returnModel.getAttributes();
657
658                                 if (!Strings.isNullOrEmpty(annotation)) {
659                                     Map<String, String> rangeMap = Splitter.on(",").withKeyValueSeparator("=")
660                                             .split(annotation);
661                                     for (Entry<String, String> rMap : rangeMap.entrySet()) {
662                                         if (rMap.getValue().contains("range::")) {
663                                             String value = mapAttribute.get(rMap.getKey().trim());
664                                             String[] tempString = rMap.getValue().split("::")[1].split("-");
665                                             int startNum = Integer.parseInt(tempString[0]);
666                                             int endNum = Integer.parseInt(tempString[1]);
667                                             String returnString = "InvalidreturnModel Range:" + rMap.getKey()
668                                             + " must be between " + startNum + " - " + endNum + ",";
669
670                                             if (value != null) {
671                                                 if (PolicyUtils.isInteger(value.replace("\"", ""))) {
672                                                     int result = Integer.parseInt(value.replace("\"", ""));
673                                                     if (result < startNum || result > endNum) {
674                                                         responseString.append(returnString);
675                                                         valid = false;
676                                                     }
677                                                 } else {
678                                                     responseString.append(returnString);
679                                                     valid = false;
680                                                 }
681                                             } else {
682                                                 responseString.append("<b>" + rMap.getKey() + "</b>:<i>" + rMap.getKey()
683                                                 + " is required for the Optimization model " + service
684                                                 + HTML_ITALICS_LNBREAK);
685                                                 valid = false;
686                                             }
687
688                                         }
689                                     }
690                                 }
691
692                                 // If request comes from the API we need to validate required fields in the
693                                 // Micro Service Model
694                                 // GUI request are already validated from the SDK-APP
695                                 if ("API".equals(policyData.getApiflag())) {
696                                     // get list of required fields from the sub_Attributes of the Model
697                                     if (!Strings.isNullOrEmpty(subAttributes)) {
698                                         JsonObject subAttributesJson = stringToJsonObject(subAttributes);
699                                         findRequiredFields(subAttributesJson);
700                                     }
701
702                                     // get list of required fields from the attributes of the Model
703                                     if (!Strings.isNullOrEmpty(modelAttributes)) {
704                                         Map<String, String> modelAttributesMap = null;
705                                         if (",".equals(modelAttributes.substring(modelAttributes.length() - 1))) {
706                                             String attributeString = modelAttributes.substring(0,
707                                                     modelAttributes.length() - 1);
708                                             modelAttributesMap = Splitter.on(",").withKeyValueSeparator("=")
709                                                     .split(attributeString);
710                                         } else {
711                                             modelAttributesMap = Splitter.on(",").withKeyValueSeparator("=")
712                                                     .split(modelAttributes);
713                                         }
714                                         String json = new ObjectMapper().writeValueAsString(modelAttributesMap);
715                                         findRequiredFields(stringToJsonObject(json));
716                                     }
717
718                                     // get list of required fields from the ref_Attributes of the Model
719                                     if (!Strings.isNullOrEmpty(refAttributes)) {
720                                         Map<String, String> refAttributesMap = null;
721                                         if (",".equals(refAttributes.substring(refAttributes.length() - 1))) {
722                                             String attributesString = refAttributes.substring(0,
723                                                     refAttributes.length() - 1);
724                                             refAttributesMap = Splitter.on(",").withKeyValueSeparator("=")
725                                                     .split(attributesString);
726                                         } else {
727                                             refAttributesMap = Splitter.on(",").withKeyValueSeparator("=")
728                                                     .split(modelAttributes);
729                                         }
730                                         String json = new ObjectMapper().writeValueAsString(refAttributesMap);
731                                         findRequiredFields(stringToJsonObject(json));
732                                     }
733
734                                     if (modelRequiredFieldsList != null || !modelRequiredFieldsList.isEmpty()) {
735                                         // create jsonRequestMap with all json keys and values from request
736                                         JsonNode rootNode = (JsonNode) policyData.getPolicyJSON();
737                                         jsonRequestMap.clear();
738                                         pullModelJsonKeyPairs(rootNode);
739
740                                         // validate if the requiredFields are in the request
741                                         for (String requiredField : modelRequiredFieldsList) {
742                                             if (jsonRequestMap.containsKey(requiredField)) {
743                                                 String value = jsonRequestMap.get(requiredField);
744                                                 if (Strings.isNullOrEmpty(jsonRequestMap.get(requiredField))
745                                                         || "\"\"".equals(value)
746                                                         || "".equals(jsonRequestMap.get(requiredField))) {
747                                                     responseString.append("<b>Optimization Service Model</b>:<i> "
748                                                             + requiredField + ISREQUIRED + HTML_ITALICS_LNBREAK);
749                                                     valid = false;
750                                                 }
751                                             } else {
752                                                 responseString.append("<b>Optimization Service Model</b>:<i> "
753                                                         + requiredField + ISREQUIRED + HTML_ITALICS_LNBREAK);
754                                                 valid = false;
755                                             }
756                                         }
757                                     }
758                                 }
759                             } else {
760                                 responseString
761                                 .append("<b>Optimization Service Model</b>:<i> Invalid Model. The model name, "
762                                         + service + " of version, " + version
763                                         + " was not found in the dictionary" + HTML_ITALICS_LNBREAK);
764                                 valid = false;
765                             }
766                         } else {
767                             responseString.append(
768                                     "<b>Optimization Service Version</b>:<i> Optimization Service Version is required"
769                                             + HTML_ITALICS_LNBREAK);
770                             valid = false;
771                         }
772                     } else {
773                         responseString.append("<b>Optimization Service</b>:<i> Optimization Service Model is required"
774                                 + HTML_ITALICS_LNBREAK);
775                         valid = false;
776                     }
777
778                     if (Strings.isNullOrEmpty(policyData.getPriority())) {
779                         responseString.append("<b>Priority</b>:<i> Priority is required" + HTML_ITALICS_LNBREAK);
780                         valid = false;
781                     }
782                 }
783             }
784
785             if ((DECISION_POLICY.equalsIgnoreCase(policyData.getPolicyType()))
786                     || (DECISION_POLICY_MS.equalsIgnoreCase(policyData.getPolicyType()))) {
787                 if (!RAW.equalsIgnoreCase(policyData.getRuleProvider())) {
788                     if (!Strings.isNullOrEmpty(policyData.getOnapName())) {
789                         String onapNameValidate = PolicyUtils.policySpecialCharValidator(policyData.getOnapName());
790                         if (!onapNameValidate.contains(SUCCESS)) {
791                             responseString.append("OnapName:" + onapNameValidate + HTML_ITALICS_LNBREAK);
792                             valid = false;
793                         }
794                     } else {
795                         responseString.append("Onap Name: Onap Name Should not be empty" + HTML_ITALICS_LNBREAK);
796                         valid = false;
797                     }
798                 }
799                 if (RAW.equalsIgnoreCase(policyData.getRuleProvider())) {
800                     Object policy = XACMLPolicyScanner.readPolicy(new ByteArrayInputStream(StringEscapeUtils.unescapeXml(policyData.getRawXacmlPolicy()).getBytes(StandardCharsets.UTF_8)));
801                     if (!(policy instanceof PolicySetType || policy instanceof PolicyType)) {
802                         responseString.append("Raw XACML: The XACML Content is not valid" + HTML_ITALICS_LNBREAK);
803                         valid = false;
804                     }
805                 }
806
807                 if (DECISION_MS_MODEL.equals(policyData.getRuleProvider())) {
808                     LOGGER.info("Validating Decision MS Policy - ");
809                     boolean tmpValid = validateMsModel(policyData, responseString);
810                     if (!tmpValid) {
811                         valid = false;
812                     }
813                 }
814
815                 if ("Rainy_Day".equals(policyData.getRuleProvider())) {
816                     if (policyData.getRainyday() == null) {
817                         responseString.append("<b> Rainy Day Parameters are Required </b><br>");
818                         valid = false;
819                     } else {
820                         if (Strings.isNullOrEmpty(policyData.getRainyday().getServiceType())) {
821                             responseString.append("Rainy Day <b>Service Type</b> is Required<br>");
822                             valid = false;
823                         }
824                         if (Strings.isNullOrEmpty(policyData.getRainyday().getVnfType())) {
825                             responseString.append("Rainy Day <b>VNF Type</b> is Required<br>");
826                             valid = false;
827                         }
828                         if (Strings.isNullOrEmpty(policyData.getRainyday().getBbid())) {
829                             responseString.append("Rainy Day <b>Building Block ID</b> is Required<br>");
830                             valid = false;
831                         }
832                         if (Strings.isNullOrEmpty(policyData.getRainyday().getWorkstep())) {
833                             responseString.append("Rainy Day <b>Work Step</b> is Required<br>");
834                             valid = false;
835                         }
836                         if (!policyData.getRainyday().getTreatmentTableChoices().isEmpty()
837                                 && policyData.getRainyday().getTreatmentTableChoices() != null) {
838
839                             for (Object treatmentMap : policyData.getRainyday().getTreatmentTableChoices()) {
840                                 String errorCode = null;
841                                 String treatment = null;
842                                 if (treatmentMap instanceof LinkedHashMap<?, ?>) {
843
844                                     if (((LinkedHashMap<?, ?>) treatmentMap).containsKey("errorcode")) {
845                                         errorCode = ((LinkedHashMap<?, ?>) treatmentMap).get("errorcode").toString();
846                                     }
847                                     if (((LinkedHashMap<?, ?>) treatmentMap).containsKey("treatment")) {
848                                         treatment = ((LinkedHashMap<?, ?>) treatmentMap).get("treatment").toString();
849                                     }
850
851                                 }
852                                 if (Strings.isNullOrEmpty(errorCode) && Strings.isNullOrEmpty(treatment)) {
853                                     responseString.append(
854                                             "Rainy Day <b>Error Code</b> and <b>Desired Treatment</b> cannot be empty<br>");
855                                     valid = false;
856                                     break;
857                                 }
858                                 if (Strings.isNullOrEmpty(errorCode)) {
859                                     responseString.append(
860                                             "Rainy Day <b>Error Code</b> is Required for each Desired Treatment<br>");
861                                     valid = false;
862                                     break;
863                                 }
864                                 if (Strings.isNullOrEmpty(treatment)) {
865                                     responseString.append(
866                                             "Rainy Day <b>Desired Treatment</b> is Required for each Error Code<br>");
867                                     valid = false;
868                                     break;
869                                 }
870                             }
871
872                         } else {
873                             responseString.append("Rainy Day <b>Desired Automated Treatments</b> are Required<br>");
874                             valid = false;
875                         }
876                     }
877                 }
878
879                 if ("GUARD_YAML".equals(policyData.getRuleProvider())
880                         || "GUARD_BL_YAML".equals(policyData.getRuleProvider())
881                         || "GUARD_MIN_MAX".equals(policyData.getRuleProvider())) {
882                     if (policyData.getYamlparams() == null) {
883                         responseString.append("<b> Guard Params are Required </b>" + HTML_ITALICS_LNBREAK);
884                         valid = false;
885                     } else {
886                         if (Strings.isNullOrEmpty(policyData.getYamlparams().getActor())) {
887                             responseString.append("Guard Params <b>Actor</b> is Required " + HTML_ITALICS_LNBREAK);
888                             valid = false;
889                         }
890                         if (Strings.isNullOrEmpty(policyData.getYamlparams().getRecipe())) {
891                             responseString.append("Guard Params <b>Recipe</b> is Required " + HTML_ITALICS_LNBREAK);
892                             valid = false;
893                         }
894                         if (Strings.isNullOrEmpty(policyData.getYamlparams().getGuardActiveStart())) {
895                             responseString.append(
896                                     "Guard Params <b>Guard Active Start</b> is Required " + HTML_ITALICS_LNBREAK);
897                             valid = false;
898                         }
899                         if (Strings.isNullOrEmpty(policyData.getYamlparams().getGuardActiveEnd())) {
900                             responseString
901                             .append("Guard Params <b>Guard Active End</b> is Required " + HTML_ITALICS_LNBREAK);
902                             valid = false;
903                         }
904                         if ("GUARD_YAML".equals(policyData.getRuleProvider())) {
905                             if (Strings.isNullOrEmpty(policyData.getYamlparams().getLimit())) {
906                                 responseString.append(" Guard Params <b>Limit</b> is Required " + HTML_ITALICS_LNBREAK);
907                                 valid = false;
908                             } else if (!PolicyUtils.isInteger(policyData.getYamlparams().getLimit())) {
909                                 responseString
910                                 .append(" Guard Params <b>Limit</b> Should be Integer " + HTML_ITALICS_LNBREAK);
911                                 valid = false;
912                             }
913                             if (Strings.isNullOrEmpty(policyData.getYamlparams().getTimeWindow())) {
914                                 responseString
915                                 .append("Guard Params <b>Time Window</b> is Required" + HTML_ITALICS_LNBREAK);
916                                 valid = false;
917                             } else if (!PolicyUtils.isInteger(policyData.getYamlparams().getTimeWindow())) {
918                                 responseString.append(
919                                         " Guard Params <b>Time Window</b> Should be Integer " + HTML_ITALICS_LNBREAK);
920                                 valid = false;
921                             }
922                             if (Strings.isNullOrEmpty(policyData.getYamlparams().getTimeUnits())) {
923                                 responseString
924                                 .append("Guard Params <b>Time Units</b> is Required" + HTML_ITALICS_LNBREAK);
925                                 valid = false;
926                             }
927                         } else if ("GUARD_MIN_MAX".equals(policyData.getRuleProvider())) {
928                             if (Strings.isNullOrEmpty(policyData.getYamlparams().getMin())) {
929                                 responseString.append(" Guard Params <b>Min</b> is Required " + HTML_ITALICS_LNBREAK);
930                                 valid = false;
931                             } else if (!PolicyUtils.isInteger(policyData.getYamlparams().getMin())) {
932                                 responseString
933                                 .append(" Guard Params <b>Min</b> Should be Integer " + HTML_ITALICS_LNBREAK);
934                                 valid = false;
935                             }
936                             if (Strings.isNullOrEmpty(policyData.getYamlparams().getMax())) {
937                                 responseString.append(" Guard Params <b>Max</b> is Required " + HTML_ITALICS_LNBREAK);
938                                 valid = false;
939                             } else if (!PolicyUtils.isInteger(policyData.getYamlparams().getMax())) {
940                                 responseString
941                                 .append(" Guard Params <b>Max</b> Should be Integer " + HTML_ITALICS_LNBREAK);
942                                 valid = false;
943                             }
944                         } else if ("GUARD_BL_YAML".equals(policyData.getRuleProvider())
945                                 && "Use Manual Entry".equals(policyData.getBlackListEntryType())) {
946
947                             if (policyData.getYamlparams().getBlackList() == null
948                                     || policyData.getYamlparams().getBlackList().isEmpty()) {
949                                 responseString
950                                 .append(" Guard Params <b>BlackList</b> is Required " + HTML_ITALICS_LNBREAK);
951                                 valid = false;
952                             } else {
953                                 for (String blackList : policyData.getYamlparams().getBlackList()) {
954                                     if (blackList == null
955                                             || !(SUCCESS.equals(PolicyUtils.policySpecialCharValidator(blackList)))) {
956                                         responseString.append(" Guard Params <b>BlackList</b> Should be valid String"
957                                                 + HTML_ITALICS_LNBREAK);
958                                         valid = false;
959                                         break;
960                                     }
961                                 }
962                             }
963                         }
964                     }
965                 }
966             }
967
968             if (ACTION_POLICY.equalsIgnoreCase(policyData.getPolicyType())) {
969                 if (!Strings.isNullOrEmpty(policyData.getActionPerformer())) {
970                     String actionPerformer = PolicyUtils.policySpecialCharValidator(policyData.getActionPerformer());
971                     if (!actionPerformer.contains(SUCCESS)) {
972                         responseString.append("<b>ActionPerformer</b>:<i>" + actionPerformer + HTML_ITALICS_LNBREAK);
973                         valid = false;
974                     }
975                 } else {
976                     responseString.append(
977                             "<b>ActionPerformer</b>:<i> ActionPerformer Should not be empty" + HTML_ITALICS_LNBREAK);
978                     valid = false;
979                 }
980
981                 if (!Strings.isNullOrEmpty(policyData.getActionAttributeValue())) {
982                     String actionAttribute =
983                             PolicyUtils.policySpecialCharValidator(policyData.getActionAttributeValue());
984                     if (!actionAttribute.contains(SUCCESS)) {
985                         responseString.append("<b>ActionAttribute</b>:<i>" + actionAttribute + HTML_ITALICS_LNBREAK);
986                         valid = false;
987                     }
988                 } else {
989                     responseString.append(
990                             "<b>ActionAttribute</b>:<i> ActionAttribute Should not be empty" + HTML_ITALICS_LNBREAK);
991                     valid = false;
992                 }
993             }
994
995             if (CONFIG_POLICY.equals(policyData.getPolicyType())) {
996                 String value = "";
997                 if (valid) {
998                     if (commonClassDao != null) {
999                         List<Object> spData = commonClassDao.getDataById(SafePolicyWarning.class, "riskType",
1000                                 policyData.getRiskType());
1001                         if (!spData.isEmpty()) {
1002                             SafePolicyWarning safePolicyWarningData = (SafePolicyWarning) spData.get(0);
1003                             value = "<b>Message</b>:<i>" + safePolicyWarningData.getMessage() + "</i>";
1004                         }
1005                     }
1006                     responseString.append(SUCCESS + "@#" + value);
1007                 }
1008             } else {
1009                 if (valid) {
1010                     responseString.append(SUCCESS);
1011                 }
1012             }
1013
1014             return responseString;
1015         } catch (Exception e) {
1016             LOGGER.error("Exception Occured during Policy Validation" + e);
1017             return null;
1018         }
1019     }
1020
1021     protected String emailValidation(String email, String response) {
1022         String res = response;
1023         if (email != null) {
1024             String validateEmail = PolicyUtils.validateEmailAddress(email.replace("\"", ""));
1025             if (!validateEmail.contains(SUCCESS)) {
1026                 res += "<b>Email</b>:<i>" + validateEmail + HTML_ITALICS_LNBREAK;
1027             } else {
1028                 return SUCCESS;
1029             }
1030         }
1031         return res;
1032     }
1033
1034     private MicroServiceModels getAttributeObject(String name, String version) {
1035         MicroServiceModels workingModel = null;
1036         try {
1037             List<Object> microServiceModelsData =
1038                     commonClassDao.getDataById(MicroServiceModels.class, "modelName:version", name + ":" + version);
1039             if (microServiceModelsData != null) {
1040                 workingModel = (MicroServiceModels) microServiceModelsData.get(0);
1041             }
1042         } catch (Exception e) {
1043             String message = XACMLErrorConstants.ERROR_DATA_ISSUE + "Invalid Template.  The template name, " + name
1044                     + " was not found in the dictionary: ";
1045             LOGGER.error(XACMLErrorConstants.ERROR_DATA_ISSUE + message + e);
1046             return null;
1047         }
1048
1049         return workingModel;
1050     }
1051
1052     private OptimizationModels getOptimizationModelData(String name, String version) {  
1053         OptimizationModels workingModel = null;
1054         try{
1055             List<Object> optimizationModelsData = commonClassDao.getDataById(OptimizationModels.class, "modelName:version", name+":"+version);
1056             if(optimizationModelsData != null){
1057                 workingModel = (OptimizationModels) optimizationModelsData.get(0);
1058             }
1059         }catch(Exception e){
1060             String message = XACMLErrorConstants.ERROR_DATA_ISSUE + "Invalid Template.  The template name, " 
1061                     + name + " was not found in the dictionary: ";
1062             LOGGER.error(XACMLErrorConstants.ERROR_DATA_ISSUE + message + e);
1063             return null;
1064         }
1065
1066         return workingModel;
1067     }
1068
1069     private void pullJsonKeyPairs(JsonNode rootNode) {
1070         Iterator<Map.Entry<String, JsonNode>> fieldsIterator = rootNode.fields();
1071
1072         while (fieldsIterator.hasNext()) {
1073             Map.Entry<String, JsonNode> field = fieldsIterator.next();
1074             final String key = field.getKey();
1075             final JsonNode value = field.getValue();
1076             if (value.isContainerNode() && !value.isArray()) {
1077                 pullJsonKeyPairs(value); // RECURSIVE CALL
1078             } else {
1079                 if (value.isArray()) {
1080                     String newValue = StringUtils.replaceEach(value.toString(), new String[] {"[", "]", "\""},
1081                             new String[] {"", "", ""});
1082                     mapAttribute.put(key, newValue);
1083                 } else {
1084                     mapAttribute.put(key, value.toString().trim());
1085                 }
1086             }
1087         }
1088     }
1089
1090     private void pullModelJsonKeyPairs(JsonNode rootNode) {
1091         Iterator<Map.Entry<String, JsonNode>> fieldsIterator = rootNode.fields();
1092
1093         while (fieldsIterator.hasNext()) {
1094             Map.Entry<String, JsonNode> field = fieldsIterator.next();
1095             final String key = field.getKey();
1096             final JsonNode value = field.getValue();
1097
1098             if (value.isContainerNode() && !value.isArray()) {
1099                 jsonRequestMap.put(key.trim(), value.toString().trim());
1100                 pullModelJsonKeyPairs(value); // RECURSIVE CALL
1101             } else if (value.isArray()) {
1102                 try {
1103                     String valueStr = value.toString();
1104                     String stringValue = valueStr.substring(valueStr.indexOf('[') + 1, valueStr.lastIndexOf(']'));
1105                     ObjectMapper mapper = new ObjectMapper();
1106                     JsonNode newValue = mapper.readTree(stringValue);
1107                     jsonRequestMap.put(key.trim(), value.toString().trim());
1108                     pullModelJsonKeyPairs(newValue);
1109                 } catch (IOException e) {
1110                     LOGGER.info("PolicyValidation: Exception occurred while mapping string to JsonNode " + e);
1111                 }
1112             } else {
1113                 jsonRequestMap.put(key.trim(), value.toString().trim());
1114             }
1115         }
1116
1117     }
1118
1119     private JsonObject stringToJsonObject(String value) {
1120         try (JsonReader jsonReader = Json.createReader(new StringReader(value))) {
1121             return jsonReader.readObject();
1122         } catch (JsonException | IllegalStateException e) {
1123             LOGGER.info(
1124                     XACMLErrorConstants.ERROR_DATA_ISSUE
1125                     + "Improper JSON format... may or may not cause issues in validating the policy: " + value,
1126                     e);
1127             return null;
1128         }
1129     }
1130
1131     private void findRequiredFields(JsonObject json) {
1132         if (json == null) {
1133             return;
1134         }
1135         for (Entry<String, JsonValue> keyMap : json.entrySet()) {
1136             Object obj = keyMap.getValue();
1137             String key = keyMap.getKey();
1138             if (obj instanceof JsonObject) {
1139                 if (allReqTrueKeys.contains(key)) {
1140                     JsonObject jsonObj = (JsonObject) obj;
1141                     // only check fields in obj if obj itself is required.
1142                     for (Entry<String, JsonValue> jsonMap : jsonObj.entrySet()) {
1143                         if (jsonMap.getValue().toString().contains(REQUIRED_ATTRIBUTE)) {
1144                             modelRequiredFieldsList.add(jsonMap.getKey().trim());
1145                         }
1146                     }
1147                 }
1148             } else if (keyMap.getValue().toString().contains(REQUIRED_ATTRIBUTE)) {
1149                 modelRequiredFieldsList.add(key.trim());
1150
1151             }
1152         }
1153
1154     }
1155
1156     // call this method to start the recursive
1157     private Set<String> getAllKeys(JSONObject json) {
1158         return getAllKeys(json, new HashSet<>());
1159     }
1160
1161     private Set<String> getAllKeys(JSONArray arr) {
1162         return getAllKeys(arr, new HashSet<>());
1163     }
1164
1165     private Set<String> getAllKeys(JSONArray arr, Set<String> keys) {
1166         for (int i = 0; i < arr.length(); i++) {
1167             Object obj = arr.get(i);
1168             if (obj instanceof JSONObject) {
1169                 keys.addAll(getAllKeys(arr.getJSONObject(i)));
1170             }
1171             if (obj instanceof JSONArray) {
1172                 keys.addAll(getAllKeys(arr.getJSONArray(i)));
1173             }
1174         }
1175
1176         return keys;
1177     }
1178
1179     // this method returns a set of keys with "required-true" defined in their value.
1180     private Set<String> getAllKeys(JSONObject json, Set<String> keys) {
1181         for (String key : json.keySet()) {
1182             Object obj = json.get(key);
1183             if (obj instanceof String && ((String) obj).contains(REQUIRED_ATTRIBUTE)) {
1184                 LOGGER.debug("key : " + key);
1185                 LOGGER.debug("obj : " + obj);
1186                 allReqTrueKeys.add(key);
1187                 // get the type from value and add that one also
1188                 String type = StringUtils.substringBefore((String) obj, ":");
1189                 if (!StringUtils.isBlank(type) && !StringUtils.containsAny(type.toLowerCase(), MSModelUtils.STRING,
1190                         MSModelUtils.INTEGER, MSModelUtils.LIST, MSModelUtils.MAP, "java", "boolean")) {
1191                     allReqTrueKeys.add(type);
1192                 }
1193             }
1194             if (obj instanceof JSONObject) {
1195                 keys.addAll(getAllKeys(json.getJSONObject(key)));
1196             }
1197             if (obj instanceof JSONArray) {
1198                 keys.addAll(getAllKeys(json.getJSONArray(key)));
1199             }
1200         }
1201
1202         return keys;
1203     }
1204
1205     private boolean validateMsModel(PolicyRestAdapter policyData, StringBuilder responseString)
1206             throws JsonProcessingException {
1207         boolean valid = true;
1208         if (!Strings.isNullOrEmpty(policyData.getServiceType())) {
1209
1210             modelRequiredFieldsList.clear();
1211             pullJsonKeyPairs((JsonNode) policyData.getPolicyJSON());
1212
1213             String service;
1214             String version;
1215             if (policyData.getServiceType().contains("-v")) {
1216                 service = policyData.getServiceType().split("-v")[0];
1217                 version = policyData.getServiceType().split("-v")[1];
1218             } else {
1219                 service = policyData.getServiceType();
1220                 version = policyData.getVersion();
1221             }
1222
1223             if (!Strings.isNullOrEmpty(version)) {
1224                 MicroServiceModels returnModel = getAttributeObject(service, version);
1225
1226                 if (returnModel != null) {
1227
1228                     String annotation = returnModel.getAnnotation();
1229                     String refAttributes = returnModel.getRef_attributes();
1230                     String subAttributes = returnModel.getSub_attributes();
1231                     String modelAttributes = returnModel.getAttributes();
1232
1233                     if (!Strings.isNullOrEmpty(annotation)) {
1234                         Map<String, String> rangeMap = Splitter.on(",").withKeyValueSeparator("=").split(annotation);
1235                         for (Entry<String, String> raMap : rangeMap.entrySet()) {
1236                             if (raMap.getValue().contains("range::")) {
1237                                 String value = mapAttribute.get(raMap.getKey().trim());
1238                                 String[] tempString = raMap.getValue().split("::")[1].split("-");
1239                                 int startNum = Integer.parseInt(tempString[0]);
1240                                 int endNum = Integer.parseInt(tempString[1]);
1241                                 String returnString = "InvalidreturnModel Range:" + raMap.getKey() + " must be between "
1242                                         + startNum + " - " + endNum + ",";
1243
1244                                 if (value != null) {
1245                                     if (PolicyUtils.isInteger(value.replace("\"", ""))) {
1246                                         int result = Integer.parseInt(value.replace("\"", ""));
1247                                         if (result < startNum || result > endNum) {
1248                                             responseString.append(returnString);
1249                                             valid = false;
1250                                         }
1251                                     } else {
1252                                         responseString.append(returnString);
1253                                         valid = false;
1254                                     }
1255                                 } else {
1256                                     responseString.append("<b>" + raMap.getKey() + "</b>:<i>" + raMap.getKey()
1257                                     + " is required for the MicroService model " + service
1258                                     + HTML_ITALICS_LNBREAK);
1259                                     valid = false;
1260                                 }
1261
1262                             }
1263                         }
1264                     } else if (!DECISION_MS_MODEL.equals(policyData.getRuleProvider())) {
1265                         // Validate for configName, location, uuid, and policyScope if no annotations exist for this
1266                         // model
1267                         if (Strings.isNullOrEmpty(policyData.getLocation())) {
1268                             responseString.append("<b>Micro Service Model</b>:<i> location is required for this model"
1269                                     + HTML_ITALICS_LNBREAK);
1270                             valid = false;
1271                         }
1272
1273                         if (Strings.isNullOrEmpty(policyData.getConfigName())) {
1274                             responseString.append("<b>Micro Service Model</b>:<i> configName is required for this model"
1275                                     + HTML_ITALICS_LNBREAK);
1276                             valid = false;
1277                         }
1278
1279                         if (Strings.isNullOrEmpty(policyData.getUuid())) {
1280                             responseString.append("<b>Micro Service Model</b>:<i> uuid is required for this model"
1281                                     + HTML_ITALICS_LNBREAK);
1282                             valid = false;
1283                         }
1284
1285                         if (Strings.isNullOrEmpty(policyData.getPolicyScope())) {
1286                             responseString
1287                             .append("<b>Micro Service Model</b>:<i> policyScope is required for this model"
1288                                     + HTML_ITALICS_LNBREAK);
1289                             valid = false;
1290                         }
1291                     }
1292
1293                     // If request comes from the API we need to validate required fields in the Micro Service Model
1294                     // GUI request are already validated from the SDK-APP
1295                     if ("API".equals(policyData.getApiflag())) {
1296                         // first , get the complete set of required fields
1297                         populateReqFieldSet(new String[] {refAttributes, modelAttributes}, subAttributes);
1298
1299                         // ignore req fields in which parent is not reqd
1300                         populateRequiredFields(new String[] {refAttributes, modelAttributes}, subAttributes,
1301                                 modelAttributes);
1302
1303                         if (modelRequiredFieldsList != null && !modelRequiredFieldsList.isEmpty()) {
1304                             // create jsonRequestMap with all json keys and values from request
1305                             JsonNode rootNode = (JsonNode) policyData.getPolicyJSON();
1306                             jsonRequestMap.clear();
1307                             pullModelJsonKeyPairs(rootNode);
1308
1309                             // validate if the requiredFields are in the request
1310                             for (String requiredField : modelRequiredFieldsList) {
1311                                 if (jsonRequestMap.containsKey(requiredField)) {
1312                                     String value = jsonRequestMap.get(requiredField);
1313                                     if (StringUtils.isBlank(value) || "\"\"".equals(value)) {
1314                                         responseString.append("<b>Micro Service Model</b>:<i> " + requiredField
1315                                                 + ISREQUIRED + HTML_ITALICS_LNBREAK);
1316                                         valid = false;
1317                                     }
1318                                 } else {
1319                                     responseString.append("<b>Micro Service Model</b>:<i> " + requiredField
1320                                             + ISREQUIRED + HTML_ITALICS_LNBREAK);
1321                                     valid = false;
1322                                 }
1323                             }
1324                         }
1325                     }
1326                 } else {
1327                     responseString.append("<b>Micro Service Model</b>:<i> Invalid Model. The model name, " + service
1328                             + " of version, " + version + " was not found in the dictionary" + HTML_ITALICS_LNBREAK);
1329                     valid = false;
1330                 }
1331             } else {
1332                 responseString.append(
1333                         "<b>Micro Service Version</b>:<i> Micro Service Version is required" + HTML_ITALICS_LNBREAK);
1334                 valid = false;
1335             }
1336         } else {
1337             responseString.append("<b>Micro Service</b>:<i> Micro Service Model is required" + HTML_ITALICS_LNBREAK);
1338             valid = false;
1339         }
1340
1341         if (Strings.isNullOrEmpty(policyData.getPriority())
1342                 && !DECISION_MS_MODEL.equals(policyData.getRuleProvider())) {
1343             responseString.append("<b>Priority</b>:<i> Priority is required" + HTML_ITALICS_LNBREAK);
1344         }
1345
1346
1347         return valid;
1348     }
1349
1350     private void populateRequiredFields(String[] attrArr, String subAttributes, String modelAttributes)
1351             throws JsonProcessingException {
1352         // get list of required fields from the ref_Attributes of the Model
1353         for (String attributes : attrArr) {
1354             if (!StringUtils.isBlank(attributes)) {
1355                 Map<String, String> attributesMap = null;
1356                 if (",".equals(attributes.substring(attributes.length() - 1))) {
1357                     String attributesString = attributes.substring(0, attributes.length() - 1);
1358                     attributesMap = Splitter.on(",").withKeyValueSeparator("=").split(attributesString);
1359                 } else if (!StringUtils.isBlank(modelAttributes)) {
1360                     attributesMap = Splitter.on(",").withKeyValueSeparator("=").split(modelAttributes);
1361                 } else {
1362                     continue;
1363                 }
1364                 String json = new ObjectMapper().writeValueAsString(attributesMap);
1365                 findRequiredFields(stringToJsonObject(json));
1366             }
1367
1368         }
1369
1370
1371         // get list of required fields from the sub_Attributes of the Model
1372         if (!StringUtils.isBlank(subAttributes)) {
1373             JsonObject subAttributesJson = stringToJsonObject(subAttributes);
1374             findRequiredFields(subAttributesJson);
1375         }
1376
1377     }
1378
1379     private void populateReqFieldSet(String[] attrArr, String subAttributes) {
1380         allReqTrueKeys.clear();
1381         JSONObject jsonSub = new JSONObject(subAttributes);
1382         // Get all keys with "required-true" defined in their value from subAttribute
1383         getAllKeys(jsonSub);
1384
1385
1386         // parse refAttrbutes
1387         for (String attr : attrArr) {
1388             if (attr != null) {
1389                 String[] referAarray = attr.split(",");
1390                 String[] element = null;
1391                 for (int i = 0; i < referAarray.length; i++) {
1392                     element = referAarray[i].split("=");
1393                     if (element.length > 1 && element[1].contains(REQUIRED_ATTRIBUTE)) {
1394                         allReqTrueKeys.add(element[0]);
1395                     }
1396                 }
1397             }
1398         }
1399     }
1400
1401
1402 }