Merge "Continue addressing technical debt for ONAP-XACML"
[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 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 package org.onap.policy.rest.util;
21
22 import java.io.IOException;
23 import java.util.HashMap;
24 import java.util.Iterator;
25 import java.util.LinkedHashMap;
26 import java.util.List;
27 import java.util.Map;
28 import java.util.Map.Entry;
29
30 import org.apache.commons.lang.StringUtils;
31 import org.json.JSONObject;
32 import org.onap.policy.common.logging.flexlogger.FlexLogger;
33 import org.onap.policy.common.logging.flexlogger.Logger;
34 import org.onap.policy.rest.adapter.ClosedLoopFaultBody;
35 import org.onap.policy.rest.adapter.ClosedLoopPMBody;
36 import org.onap.policy.rest.adapter.PolicyRestAdapter;
37 import org.onap.policy.rest.dao.CommonClassDao;
38 import org.onap.policy.rest.jpa.MicroServiceModels;
39 import org.onap.policy.rest.jpa.SafePolicyWarning;
40 import org.onap.policy.utils.PolicyUtils;
41 import org.onap.policy.xacml.api.XACMLErrorConstants;
42 import org.springframework.beans.factory.annotation.Autowired;
43 import org.springframework.stereotype.Service;
44
45 import com.fasterxml.jackson.databind.JsonNode;
46 import com.fasterxml.jackson.databind.ObjectMapper;
47 import com.google.common.base.Splitter;
48 import com.google.common.base.Strings;
49
50 @Service
51 public class PolicyValidation {
52         
53         private static final Logger LOGGER      = FlexLogger.getLogger(PolicyValidation.class);
54         
55         public static final String CONFIG_POLICY = "Config";
56         public static final String ACTION_POLICY = "Action";
57         public static final String DECISION_POLICY = "Decision";
58         public static final String CLOSEDLOOP_POLICY = "ClosedLoop_Fault";
59         public static final String CLOSEDLOOP_PM = "ClosedLoop_PM";
60         public static final String ENFORCER_CONFIG_POLICY= "Enforcer Config";
61         public static final String MICROSERVICES="Micro Service";
62         public static final String FIREWALL="Firewall Config";
63         public static final String HTML_ITALICS_LNBREAK = "</i><br>";
64         public static final String SUCCESS = "success";
65         public static final String EMPTY_COMPONENT_ATTR = "Component Attributes: One or more Fields in Component Attributes is Empty.";
66         
67         private static Map<String, String> mapAttribute = new HashMap<>();
68         
69         private static CommonClassDao commonClassDao;
70         
71         @Autowired
72         public PolicyValidation(CommonClassDao commonClassDao){
73                 PolicyValidation.commonClassDao = commonClassDao;
74         }
75         
76         /*
77          * This is an empty constructor
78          */
79         public PolicyValidation(){
80                 // Empty constructor
81         }
82         
83         
84         public StringBuilder validatePolicy(PolicyRestAdapter policyData) throws IOException{
85                 try{
86                         boolean valid = true;
87                         StringBuilder responseString = new StringBuilder();
88                         ObjectMapper mapper = new ObjectMapper();
89                         
90                         if(policyData.getPolicyName() != null){
91                                 String policyNameValidate = PolicyUtils.policySpecialCharValidator(policyData.getPolicyName());
92                                 if(!policyNameValidate.contains(SUCCESS)){
93                                         responseString.append("PolicyName:" +  policyNameValidate + "<br>");
94                                         valid = false;
95                                 };
96                         }else{
97                                 responseString.append( "PolicyName: PolicyName Should not be empty" + "<br>");
98                                 valid = false;
99                         }
100                         if(policyData.getPolicyDescription() != null){
101                                 String descriptionValidate = PolicyUtils.descriptionValidator(policyData.getPolicyDescription());
102                                 if(!descriptionValidate.contains(SUCCESS)){
103                                         responseString.append("Description:" +  descriptionValidate + "<br>");
104                                         valid = false;
105                                 }       
106                         }
107
108                         if(CONFIG_POLICY.equalsIgnoreCase(policyData.getPolicyType())){
109                                 if ("Base".equals(policyData.getConfigPolicyType()) || CLOSEDLOOP_POLICY.equals(policyData.getConfigPolicyType())
110                                                 ||  CLOSEDLOOP_PM.equals(policyData.getConfigPolicyType()) || ENFORCER_CONFIG_POLICY.equals(policyData.getConfigPolicyType()) 
111                                                 || MICROSERVICES.equals(policyData.getConfigPolicyType())) {
112                                         
113                                         if(!Strings.isNullOrEmpty(policyData.getOnapName())) {
114                                                 String onapNameValidate = PolicyUtils.policySpecialCharValidator(policyData.getOnapName());
115                                                 if(!onapNameValidate.contains(SUCCESS)){
116                                                         responseString.append("OnapName:" +  onapNameValidate + "<br>");
117                                                         valid = false;
118                                                 }
119                                         }else{
120                                                 responseString.append("Onap Name: Onap Name Should not be empty" + "<br>");
121                                                 valid = false;
122                                         }
123                                 }
124
125                                 if(!Strings.isNullOrEmpty(policyData.getRiskType())) {
126                                         String riskTypeValidate = PolicyUtils.policySpecialCharValidator(policyData.getRiskType());
127                                         if(!riskTypeValidate.contains(SUCCESS)){
128                                                 responseString.append("RiskType:" +  riskTypeValidate + "<br>");
129                                                 valid = false;
130                                         }
131                                 }else {
132                                         responseString.append("Risk Type: Risk Type Should not be Empty" + "<br>");
133                                         valid = false;
134                                 }
135
136                                 if(!Strings.isNullOrEmpty(policyData.getRiskLevel())) {
137                                         String validateRiskLevel = PolicyUtils.policySpecialCharValidator(policyData.getRiskLevel());
138                                         if(!validateRiskLevel.contains(SUCCESS)){
139                                                 responseString.append("RiskLevel:" +  validateRiskLevel + "<br>");
140                                                 valid = false;
141                                         }
142                                 }else {
143                                         responseString.append("Risk Level: Risk Level Should not be Empty" + "<br>");
144                                         valid = false;
145                                 }
146
147                                 if(!Strings.isNullOrEmpty(policyData.getGuard())) {
148                                         String validateGuard = PolicyUtils.policySpecialCharValidator(policyData.getGuard());
149                                         if(!validateGuard.contains(SUCCESS)){
150                                                 responseString.append("Guard:" +  validateGuard + "<br>");
151                                                 valid = false;
152                                         }
153                                 }else {
154                                         responseString.append("Guard: Guard Value Should not be Empty" + "<br>");
155                                         valid = false;
156                                 }
157
158                                 if("Base".equalsIgnoreCase(policyData.getConfigPolicyType())){
159                                         if(!Strings.isNullOrEmpty(policyData.getConfigName())) {
160                                                 String configNameValidate = PolicyUtils.policySpecialCharValidator(policyData.getConfigName());
161                                                 if(!configNameValidate.contains(SUCCESS)){
162                                                         responseString.append("ConfigName:" +  configNameValidate + "<br>");
163                                                         valid = false;
164                                                 }
165                                         }else{
166                                                 responseString.append("Config Name: Config Name Should not be Empty" + "<br>");
167                                                 valid = false;
168                                         }
169                                         if(!Strings.isNullOrEmpty(policyData.getConfigType())) {
170                                                 String configTypeValidate = PolicyUtils.policySpecialCharValidator(policyData.getConfigType());
171                                                 if(!configTypeValidate.contains(SUCCESS)){
172                                                         responseString.append("ConfigType:" +  configTypeValidate + "<br>");
173                                                         valid = false;
174                                                 }
175                                         }else{
176                                                 responseString.append("Config Type: Config Type Should not be Empty" + "<br>");
177                                                 valid = false;
178                                         }
179                                         if(!Strings.isNullOrEmpty(policyData.getConfigBodyData())) {
180                                                 String configBodyData = policyData.getConfigBodyData();
181                                                 String configType = policyData.getConfigType();
182                                                 if (configType != null) {
183                                                         if ("JSON".equals(configType)) {
184                                                                 if (!PolicyUtils.isJSONValid(configBodyData)) {
185                                                                         responseString.append("Config Body: JSON Content is not valid" + "<br>");
186                                                                         valid = false;
187                                                                 }
188                                                         } else if ("XML".equals(configType)) {
189                                                                 if (!PolicyUtils.isXMLValid(configBodyData)) {
190                                                                         responseString.append("Config Body: XML Content data is not valid" + "<br>");
191                                                                         valid = false;
192                                                                 }
193                                                         } else if ("PROPERTIES".equals(configType)) {
194                                                                 if (!PolicyUtils.isPropValid(configBodyData)||configBodyData.equals("")) {
195                                                                         responseString.append("Config Body: Property data is not valid" + "<br>");
196                                                                         valid = false;
197                                                                 } 
198                                                         } else if ("OTHER".equals(configType) && ("".equals(configBodyData))) {
199                                                                 responseString.append("Config Body: Config Body Should not be Empty" + "<br>");
200                                                                 valid = false;
201                                                         }
202                                                 }
203                                         }else{
204                                                 responseString.append("Config Body: Config Body Should not be Empty" + "<br>");
205                                                 valid = false;
206                                         }
207                                 }
208
209                                 if(FIREWALL.equalsIgnoreCase(policyData.getConfigPolicyType())){
210                                         if(policyData.getConfigName() != null && !policyData.getConfigName().isEmpty()){
211                                                 String configNameValidate = PolicyUtils.policySpecialCharValidator(policyData.getConfigName());
212                                                 if(!configNameValidate.contains(SUCCESS)){
213                                                         responseString.append("<b>ConfigName</b>:<i>" +  configNameValidate + HTML_ITALICS_LNBREAK);
214                                                         valid = false;
215                                                 }
216                                         }else{
217                                                 responseString.append("<b>Config Name</b>:<i> Config Name is required" + HTML_ITALICS_LNBREAK);
218                                                 valid = false;
219                                         }
220                                         if(policyData.getSecurityZone() == null || policyData.getSecurityZone().isEmpty()){
221                                                 responseString.append("<b>Security Zone</b>:<i> Security Zone is required" + HTML_ITALICS_LNBREAK);
222                                                 valid = false;
223                                         }
224                                 }
225                                 if("BRMS_Param".equalsIgnoreCase(policyData.getConfigPolicyType()) && Strings.isNullOrEmpty(policyData.getRuleName())){
226                                         responseString.append("<b>BRMS Template</b>:<i>BRMS Template is required" + HTML_ITALICS_LNBREAK);
227                                         valid = false;
228                                 }
229                                 if("BRMS_Raw".equalsIgnoreCase(policyData.getConfigPolicyType())){
230                                         if(policyData.getConfigBodyData() != null && !policyData.getConfigBodyData().isEmpty()){
231                                                 String message = PolicyUtils.brmsRawValidate(policyData.getConfigBodyData());
232                                                 
233                                                 // If there are any error other than Annotations then this is not Valid
234                                                 if(message.contains("[ERR")){
235                                                         responseString.append("<b>Raw Rule Validate</b>:<i>Raw Rule has error"+ message + HTML_ITALICS_LNBREAK);
236                                                         valid = false;
237                                                 }
238                                         }else{
239                                                 responseString.append("<b>Raw Rule</b>:<i>Raw Rule is required" + HTML_ITALICS_LNBREAK);
240                                                 valid = false;
241                                         }
242                                 }
243                                 if(CLOSEDLOOP_PM.equalsIgnoreCase(policyData.getConfigPolicyType())){
244                                         try{
245                                                 if(Strings.isNullOrEmpty(policyData.getServiceTypePolicyName().get("serviceTypePolicyName").toString())){
246                                                         responseString.append("<b>ServiceType PolicyName</b>:<i>ServiceType PolicyName is required" + HTML_ITALICS_LNBREAK);
247                                                         valid = false; 
248                                                 }
249                                                 
250                                         }catch(Exception e){
251                                             LOGGER.error("ERROR in ClosedLoop_PM PolicyName" , e);
252                                                 responseString.append("<b>ServiceType PolicyName</b>:<i>ServiceType PolicyName is required" + HTML_ITALICS_LNBREAK);
253                                                 valid = false;
254                                         }
255
256                                         if(policyData.getJsonBody() != null){
257                                                 
258                                                 ClosedLoopPMBody pmBody = mapper.readValue(policyData.getJsonBody(), ClosedLoopPMBody.class);
259                                                 if(pmBody.getEmailAddress() != null){
260                                                         String result = emailValidation(pmBody.getEmailAddress(), responseString.toString());
261                                                         if(result != SUCCESS){
262                                                                 responseString.append(result + "<br>");
263                                                                 valid = false;
264                                                         }
265                                                 }
266                                                 if((pmBody.isGamma() || pmBody.isMcr() || pmBody.isTrinity() || pmBody.isvDNS() || pmBody.isvUSP()) != true){
267                                                         responseString.append("<b>D2/Virtualized Services</b>: <i>Select at least one D2/Virtualized Services" + HTML_ITALICS_LNBREAK);
268                                                         valid = false; 
269                                                 }
270                                                 if(pmBody.getGeoLink() != null && !pmBody.getGeoLink().isEmpty()){
271                                                         String result = PolicyUtils.policySpecialCharValidator(pmBody.getGeoLink());
272                                                         if(!result.contains(SUCCESS)){
273                                                                 responseString.append("<b>GeoLink</b>:<i>" +  result + HTML_ITALICS_LNBREAK);
274                                                                 valid = false;
275                                                         };
276                                                 }
277                                                 if(pmBody.getAttributes() != null && !pmBody.getAttributes().isEmpty()){
278                                                         for(Entry<String, String> entry : pmBody.getAttributes().entrySet()){
279                                                                 String key = entry.getKey();
280                                                                 String value = entry.getValue();
281                                                                 if(!key.contains("Message")){
282                                                                         String attributeValidate = PolicyUtils.policySpecialCharValidator(value);
283                                                                         if(!attributeValidate.contains(SUCCESS)){
284                                                                                 responseString.append("<b>Attributes</b>:<i>" +  key + " : value has spaces or invalid characters" + HTML_ITALICS_LNBREAK);
285                                                                                 valid = false;
286                                                                         };
287                                                                 }
288                                                         }       
289                                                 }
290                                         }else{
291                                                 responseString.append("<b>D2/Virtualized Services</b>:<i>Select atleast one D2/Virtualized Services" + HTML_ITALICS_LNBREAK);
292                                                 valid = false;
293                                         }
294                                 }
295                                 if(CLOSEDLOOP_POLICY.equalsIgnoreCase(policyData.getConfigPolicyType())){
296                                         if(policyData.getJsonBody() != null){
297
298                                                 // For API we need to get the conditions key from the Json request and check it before deserializing to POJO due to the enum
299                                                 if("API".equals(policyData.getApiflag())){
300                                                         JSONObject json = new JSONObject(policyData.getJsonBody());
301                                                         if(!json.isNull("conditions")){
302                                                                 String apiCondition = (String) json.get("conditions");
303                                                                 if(Strings.isNullOrEmpty(apiCondition)){
304                                                                         responseString.append("<b>Conditions</b>: <i>Select At least one Condition" + HTML_ITALICS_LNBREAK);
305                                                                         return responseString;
306                                                                 }
307                                                         } else {
308                                                                 responseString.append("<b>Conditions</b>: <i>There were no conditions provided in configBody json" + HTML_ITALICS_LNBREAK);
309                                                                 return responseString;
310                                                         }
311                                                 }
312
313                                                 ClosedLoopFaultBody faultBody = mapper.readValue(policyData.getJsonBody(), ClosedLoopFaultBody.class);
314                                                 if(faultBody.getEmailAddress() != null && !faultBody.getEmailAddress().isEmpty()){
315                                                         String result = emailValidation(faultBody.getEmailAddress(), responseString.toString());
316                                                         if(result != SUCCESS){
317                                                                 responseString.append(result+ "<br>");
318                                                                 valid = false;
319                                                         }
320                                                 }
321                                                 if((faultBody.isGamma() || faultBody.isMcr() || faultBody.isTrinity() || faultBody.isvDNS() || faultBody.isvUSP()) != true){
322                                                         responseString.append("<b>D2/Virtualized Services</b>: <i>Select at least one D2/Virtualized Services" + HTML_ITALICS_LNBREAK);
323                                                         valid = false; 
324                                                 }
325                                                 if(faultBody.getActions() == null || faultBody.getActions().isEmpty()){
326                                                         responseString.append("<b>vPRO Actions</b>: <i>vPRO Actions is required" + HTML_ITALICS_LNBREAK);
327                                                         valid = false;
328                                                 }
329                                                 if(faultBody.getClosedLoopPolicyStatus() == null || faultBody.getClosedLoopPolicyStatus().isEmpty()){
330                                                         responseString.append("<b>Policy Status</b>: <i>Policy Status is required" + HTML_ITALICS_LNBREAK);
331                                                         valid = false;
332                                                 }
333                                                 if(faultBody.getConditions() == null){
334                                                         responseString.append("<b>Conditions</b>: <i>Select At least one Condition" + HTML_ITALICS_LNBREAK);
335                                                         valid = false;
336                                                 }
337                                                 if(faultBody.getGeoLink() != null && !faultBody.getGeoLink().isEmpty()){
338                                                         String result = PolicyUtils.policySpecialCharWithSpaceValidator(faultBody.getGeoLink());
339                                                         if(!result.contains(SUCCESS)){
340                                                                 responseString.append("<b>GeoLink</b>:<i>" +  result + HTML_ITALICS_LNBREAK);
341                                                                 valid = false;
342                                                         }
343                                                 }
344                                                 if(faultBody.getAgingWindow() == 0){
345                                                         responseString.append("<b>Aging Window</b>: <i>Aging Window is required" + HTML_ITALICS_LNBREAK);
346                                                         valid = false;
347                                                 }
348                                                 if(faultBody.getTimeInterval() == 0){
349                                                         responseString.append("<b>Time Interval</b>: <i>Time Interval is required" + HTML_ITALICS_LNBREAK);
350                                                         valid = false;
351                                                 }
352                                                 if(faultBody.getRetrys() == 0){
353                                                         responseString.append("<b>Number of Retries</b>: <i>Number of Retries is required" + HTML_ITALICS_LNBREAK);
354                                                         valid = false;
355                                                 }
356                                                 if(faultBody.getTimeOutvPRO() == 0){
357                                                         responseString.append("<b>APP-C Timeout</b>: <i>APP-C Timeout is required" + HTML_ITALICS_LNBREAK);
358                                                         valid = false;
359                                                 }
360                                                 if(faultBody.getTimeOutRuby() == 0){
361                                                         responseString.append("<b>TimeOutRuby</b>: <i>TimeOutRuby is required" + HTML_ITALICS_LNBREAK);
362                                                         valid = false;
363                                                 }
364                                                 if(faultBody.getVnfType() == null || faultBody.getVnfType().isEmpty()){
365                                                         responseString.append("<b>Vnf Type</b>: <i>Vnf Type is required" + HTML_ITALICS_LNBREAK);
366                                                         valid = false;
367                                                 }
368                                         }else{
369                                                 responseString.append("<b>D2/Virtualized Services</b>: <i>Select atleast one D2/Virtualized Services" + HTML_ITALICS_LNBREAK);
370                                                 responseString.append("<b>vPRO Actions</b>: <i>vPRO Actions is required" + HTML_ITALICS_LNBREAK);
371                                                 responseString.append("<b>Aging Window</b>: <i>Aging Window is required" + HTML_ITALICS_LNBREAK);
372                                                 responseString.append("<b>Policy Status</b>: <i>Policy Status is required" + HTML_ITALICS_LNBREAK);
373                                                 responseString.append("<b>Conditions</b>: <i>Select Atleast one Condition" + HTML_ITALICS_LNBREAK);
374                                                 responseString.append("<b>PEP Name</b>: <i>PEP Name is required" + HTML_ITALICS_LNBREAK);
375                                                 responseString.append("<b>PEP Action</b>: <i>PEP Action is required" + HTML_ITALICS_LNBREAK);
376                                                 responseString.append("<b>Time Interval</b>: <i>Time Interval is required" + HTML_ITALICS_LNBREAK);
377                                                 responseString.append("<b>Number of Retries</b>: <i>Number of Retries is required" + HTML_ITALICS_LNBREAK);
378                                                 responseString.append("<b>APP-C Timeout</b>: <i>APP-C Timeout is required" + HTML_ITALICS_LNBREAK);
379                                                 responseString.append("<b>TimeOutRuby</b>: <i>TimeOutRuby is required" + HTML_ITALICS_LNBREAK);
380                                                 responseString.append("<b>Vnf Type</b>: <i>Vnf Type is required" + HTML_ITALICS_LNBREAK);
381                                                 valid = false; 
382                                         }
383                                 }
384
385                                 if (MICROSERVICES.equals(policyData.getConfigPolicyType())){
386                                         if(!Strings.isNullOrEmpty(policyData.getServiceType())){
387                                                 pullJsonKeyPairs((JsonNode) policyData.getPolicyJSON());
388
389                                                 String service;
390                                                 String version;
391                                                 if (policyData.getServiceType().contains("-v")){
392                                                         service = policyData.getServiceType().split("-v")[0];
393                                                         version = policyData.getServiceType().split("-v")[1];
394                                                 }else {
395                                                         service = policyData.getServiceType();
396                                                         version = policyData.getVersion();
397                                                 }
398                                                 
399                                                 if(!Strings.isNullOrEmpty(version)) {
400                                                         MicroServiceModels returnModel = getAttributeObject(service, version);
401                                                         
402                                                         if(returnModel != null) {
403                                                                 String annotation = returnModel.getAnnotation();
404                                                                 if (!Strings.isNullOrEmpty(annotation)){ 
405                                                                         Map<String, String> rangeMap = Splitter.on(",").withKeyValueSeparator("=").split(annotation);
406                                                                         for (Entry<String, String> rMap : rangeMap.entrySet()){
407                                                                                 if (rMap.getValue().contains("range::")){
408                                                                                         String value = mapAttribute.get(rMap.getKey().trim());
409                                                                                         String[] tempString = rMap.getValue().split("::")[1].split("-");
410                                                                                         int startNum = Integer.parseInt(tempString[0]);
411                                                                                         int endNum = Integer.parseInt(tempString[1]);
412                                                                                         String returnString = "InvalidreturnModel Range:" + rMap.getKey() + " must be between " 
413                                                                                                         + startNum + " - "  + endNum + ",";
414                                                                                         
415                                                                                         if(value != null) {
416                                                                                                 if (PolicyUtils.isInteger(value.replace("\"", ""))){
417                                                                                                         int result = Integer.parseInt(value.replace("\"", ""));
418                                                                                                         if (result < startNum || result > endNum){
419                                                                                                                 responseString.append(returnString);                                                                    
420                                                                                                                 valid = false;
421                                                                                                         }
422                                                                                                 }else {
423                                                                                                         responseString.append(returnString);
424                                                                                                         valid = false;
425                                                                                                 }
426                                                                                         } else {
427                                                                                                 responseString.append("<b>"+rMap.getKey()+"</b>:<i>" + rMap.getKey() 
428                                                                                                 + " is required for the MicroService model " + service + HTML_ITALICS_LNBREAK);
429                                                                                                 valid = false;
430                                                                                         }
431
432                                                                                 }
433                                                                         }
434                                                                 }
435                                                         } else {
436                                                                 responseString.append("<b>Micro Service Model</b>:<i> Invalid Model. The model name, " + service + 
437                                                                                 " of version, " + version + " was not found in the dictionary" + HTML_ITALICS_LNBREAK);
438                                                                 valid = false;
439                                                         }
440                                                 } else {
441                                                         responseString.append("<b>Micro Version</b>:<i> Micro Service Version is required" + HTML_ITALICS_LNBREAK);
442                                                         valid = false;
443                                                 }
444                                         } else {
445                                                 responseString.append("<b>Micro Service</b>:<i> Micro Service is required" + HTML_ITALICS_LNBREAK);
446                                                 valid = false;
447                                         }
448
449                                         if(Strings.isNullOrEmpty(policyData.getPriority())){
450                                                 responseString.append("<b>Priority</b>:<i> Priority is required" + HTML_ITALICS_LNBREAK);
451                                                 valid = false;
452                                         }
453                                 }       
454                         }
455                         if (DECISION_POLICY.equalsIgnoreCase(policyData.getPolicyType())){
456                                 if(!Strings.isNullOrEmpty(policyData.getOnapName())){
457                                         String onapNameValidate = PolicyUtils.policySpecialCharValidator(policyData.getOnapName());
458                                         if(!onapNameValidate.contains(SUCCESS)){
459                                                 responseString.append("OnapName:" +  onapNameValidate + "<br>");
460                                                 valid = false;
461                                         }
462                                 }else{
463                                         responseString.append("Onap Name: Onap Name Should not be empty" + "<br>");
464                                         valid = false;
465                                 }
466
467                                 if("Rainy_Day".equals(policyData.getRuleProvider())){
468                                         if(policyData.getRainyday()==null){
469                                                 responseString.append("<b> Rainy Day Parameters are Required </b><br>");
470                                                 valid = false;
471                                         }else{
472                                                 if(Strings.isNullOrEmpty(policyData.getRainyday().getServiceType())){
473                                                         responseString.append("Rainy Day <b>Service Type</b> is Required<br>");
474                                                         valid = false;
475                                                 }
476                                                 if(Strings.isNullOrEmpty(policyData.getRainyday().getVnfType())){
477                                                         responseString.append("Rainy Day <b>VNF Type</b> is Required<br>");
478                                                         valid = false;
479                                                 }                                               
480                                                 if(Strings.isNullOrEmpty(policyData.getRainyday().getBbid())){
481                                                         responseString.append("Rainy Day <b>Building Block ID</b> is Required<br>");
482                                                         valid = false;
483                                                 }
484                                                 if(Strings.isNullOrEmpty(policyData.getRainyday().getWorkstep())){
485                                                         responseString.append("Rainy Day <b>Work Step</b> is Required<br>");
486                                                         valid = false;
487                                                 }
488                                                 if(!policyData.getRainyday().getTreatmentTableChoices().isEmpty() &&
489                                                                 policyData.getRainyday().getTreatmentTableChoices() != null){
490                                                         
491                                                         for(Object treatmentMap: policyData.getRainyday().getTreatmentTableChoices()){
492                                                                 String errorCode = null;
493                                                                 String treatment = null;
494                                                                 if(treatmentMap instanceof LinkedHashMap<?, ?>){
495                                                                         
496                                                                         if(((LinkedHashMap<?, ?>) treatmentMap).containsKey("errorcode")){
497                                                                                 errorCode = ((LinkedHashMap<?, ?>) treatmentMap).get("errorcode").toString();
498                                                                         }
499                                                                         if(((LinkedHashMap<?, ?>) treatmentMap).containsKey("treatment")){
500                                                                                 treatment = ((LinkedHashMap<?, ?>) treatmentMap).get("treatment").toString();
501                                                                         }
502                                                                         
503                                                                 }
504                                                                 if(Strings.isNullOrEmpty(errorCode) && Strings.isNullOrEmpty(treatment)){
505                                                                         responseString.append("Rainy Day <b>Error Code</b> and <b>Desired Treatment</b> cannot be empty<br>");
506                                                                         valid = false;
507                                                                         break;
508                                                                 }
509                                                                 if(Strings.isNullOrEmpty(errorCode)){
510                                                                         responseString.append("Rainy Day <b>Error Code</b> is Required for each Desired Treatment<br>");
511                                                                         valid = false;
512                                                                         break;
513                                                                 }
514                                                                 if(Strings.isNullOrEmpty(treatment)){
515                                                                         responseString.append("Rainy Day <b>Desired Treatment</b> is Required for each Error Code<br>");
516                                                                         valid = false;
517                                                                         break;
518                                                                 }
519                                                         }
520                                                         
521                                                 } else {
522                                                         responseString.append("Rainy Day <b>Desired Automated Treatments</b> are Required<br>");
523                                                         valid = false;
524                                                 }
525                                         }
526                                 }
527                                 
528                                 if("GUARD_YAML".equals(policyData.getRuleProvider()) || "GUARD_BL_YAML".equals(policyData.getRuleProvider())){
529                                         if(policyData.getYamlparams()==null){
530                                                 responseString.append("<b> Guard Params are Required </b>" + "<br>");
531                                                 valid = false;
532                                         }else{
533                                                 if(Strings.isNullOrEmpty(policyData.getYamlparams().getActor())){
534                                                         responseString.append("Guard Params <b>Actor</b> is Required " + "<br>");
535                                                         valid = false;
536                                                 }
537                                                 if(Strings.isNullOrEmpty(policyData.getYamlparams().getRecipe())){
538                                                         responseString.append("Guard Params <b>Recipe</b> is Required " + "<br>");
539                                                         valid = false;
540                                                 }
541                                                 if(Strings.isNullOrEmpty(policyData.getYamlparams().getGuardActiveStart())){
542                                                         responseString.append("Guard Params <b>Guard Active Start</b> is Required " + "<br>");
543                                                         valid = false;
544                                                 }
545                                                 if(Strings.isNullOrEmpty(policyData.getYamlparams().getGuardActiveEnd())){
546                                                         responseString.append("Guard Params <b>Guard Active End</b> is Required " + "<br>");
547                                                         valid = false;
548                                                 }
549                                                 if("GUARD_YAML".equals(policyData.getRuleProvider())){
550                                                         if(Strings.isNullOrEmpty(policyData.getYamlparams().getLimit())){
551                                                                 responseString.append(" Guard Params <b>Limit</b> is Required " + "<br>");
552                                                                 valid = false;
553                                                         }else if(!PolicyUtils.isInteger(policyData.getYamlparams().getLimit())){
554                                                                 responseString.append(" Guard Params <b>Limit</b> Should be Integer " + "<br>");
555                                                                 valid = false;
556                                                         }
557                                                         if(Strings.isNullOrEmpty(policyData.getYamlparams().getTimeWindow())){
558                                                                 responseString.append("Guard Params <b>Time Window</b> is Required" + "<br>");
559                                                                 valid = false;
560                                                         }else if(!PolicyUtils.isInteger(policyData.getYamlparams().getTimeWindow())){
561                                                                 responseString.append(" Guard Params <b>Time Window</b> Should be Integer " + "<br>");
562                                                                 valid = false;
563                                                         }
564                                                         if(Strings.isNullOrEmpty(policyData.getYamlparams().getTimeUnits())){
565                                                                 responseString.append("Guard Params <b>Time Units</b> is Required" + "<br>");
566                                                                 valid = false;
567                                                         }
568                                                 }else if("GUARD_BL_YAML".equals(policyData.getRuleProvider())){
569                                                         if(policyData.getYamlparams().getBlackList()==null || policyData.getYamlparams().getBlackList().isEmpty()){
570                                                                 responseString.append(" Guard Params <b>BlackList</b> is Required " + "<br>");
571                                                                 valid = false;
572                                                         }else{
573                                                                 for(String blackList: policyData.getYamlparams().getBlackList()){
574                                                                         if(blackList==null || !(SUCCESS.equals(PolicyUtils.policySpecialCharValidator(blackList)))){
575                                                                                 responseString.append(" Guard Params <b>BlackList</b> Should be valid String" + "<br>");
576                                                                                 valid = false;
577                                                                                 break;
578                                                                         }
579                                                                 }
580                                                         }
581                                                 }
582                                         }
583                                 }
584                         }
585
586                         if(ACTION_POLICY.equalsIgnoreCase(policyData.getPolicyType())){
587                                 if(!Strings.isNullOrEmpty(policyData.getActionPerformer())){
588                                         String actionPerformer = PolicyUtils.policySpecialCharValidator(policyData.getActionPerformer());
589                                         if(!actionPerformer.contains(SUCCESS)){
590                                                 responseString.append("ActionPerformer:" +  actionPerformer + "<br>");
591                                                 valid = false;
592                                         }
593                                 }else{
594                                         responseString.append("ActionPerformer: ActionPerformer Should not be empty" + "<br>");
595                                         valid = false;
596                                 }
597                                 if(policyData.getAttributes() != null){
598                                         for(Object attribute : policyData.getAttributes()){
599                                                 if(attribute instanceof LinkedHashMap<?, ?>){
600                                                         try{
601                                                                 //This is for validation check if the value exists or not
602                                                                 String key = ((LinkedHashMap<?, ?>) attribute).get("key").toString();
603                                                                 String value =  ((LinkedHashMap<?, ?>) attribute).get("value").toString();
604                                                                 if("".equals(key) || "".equals(value)){
605                                                                         responseString.append(EMPTY_COMPONENT_ATTR + "<br>");
606                                                                         valid = false;
607                                                                         break;  
608                                                                 }
609                                                         }catch(Exception e){
610                                                                 LOGGER.error("This is a Policy Validation check" +e);
611                                                                 responseString.append(EMPTY_COMPONENT_ATTR + "<br>");
612                                                                 valid = false;
613                                                                 break;
614                                                         }
615                                                 }
616                                         }
617                                 }else{
618                                         responseString.append(EMPTY_COMPONENT_ATTR + "<br>");
619                                         valid = false;
620                                 }
621                                 if(!Strings.isNullOrEmpty(policyData.getActionAttributeValue())){
622                                         String actionAttribute = PolicyUtils.policySpecialCharValidator(policyData.getActionAttributeValue());
623                                         if(!actionAttribute.contains(SUCCESS)){
624                                                 responseString.append("ActionAttribute:" +  actionAttribute + "<br>");
625                                                 valid = false;
626                                         };
627                                 }else{
628                                         responseString.append("ActionAttribute: ActionAttribute Should not be empty" + "<br>");
629                                         valid = false;
630                                 }
631                                 
632                                 if(!policyData.getRuleAlgorithmschoices().isEmpty()){
633                                         for(Object attribute : policyData.getRuleAlgorithmschoices()){
634                                                 if(attribute instanceof LinkedHashMap<?, ?>){
635                                                         try{
636                                                                 String label = ((LinkedHashMap<?, ?>) attribute).get("id").toString();
637                                                                 String key = ((LinkedHashMap<?, ?>) attribute).get("dynamicRuleAlgorithmField1").toString();
638                                                                 String rule = ((LinkedHashMap<?, ?>) attribute).get("dynamicRuleAlgorithmCombo").toString();
639                                                                 String value = ((LinkedHashMap<?, ?>) attribute).get("dynamicRuleAlgorithmField2").toString();
640
641                                                                 if(Strings.isNullOrEmpty(label) || Strings.isNullOrEmpty(key) || Strings.isNullOrEmpty(rule) || Strings.isNullOrEmpty(value)){
642                                                                         responseString.append("Rule Algorithms: One or more Fields in Rule Algorithms is Empty." + "<br>");
643                                                                         valid = false;
644                                                                 }
645                                                         }catch(Exception e){
646                                                                 LOGGER.error("This is a Policy Validation check" +e);
647                                                                 responseString.append("Rule Algorithms: One or more Fields in Rule Algorithms is Empty." + "<br>");
648                                                                 valid = false;
649                                                                 break;
650                                                         }
651                                                 }
652                                         }
653                                 }
654                         }
655
656                         if(CONFIG_POLICY.equals(policyData.getPolicyType())){
657                                 String value = "";
658                                 if(valid){
659                                         if(commonClassDao!=null){
660                                                 List<Object> spData = commonClassDao.getDataById(SafePolicyWarning.class, "riskType", policyData.getRiskType());
661                                                 if (!spData.isEmpty()){
662                                                         SafePolicyWarning safePolicyWarningData  = (SafePolicyWarning) spData.get(0);
663                                                         value = "Message:" +  safePolicyWarningData.getMessage();
664                                                 }
665                                         }
666                                         responseString.append(SUCCESS + "@#"+ value);
667                                 }
668                         }else{
669                                 if(valid){
670                                         responseString.append(SUCCESS);
671                                 }
672                         }
673
674                         return responseString;
675                 }
676                 catch (Exception e){
677                         LOGGER.error("Exception Occured during Policy Validation" +e);
678                         return null;
679                 }
680         }
681
682         protected String emailValidation(String email, String response){
683                 String res = response;
684                 if(email != null){
685                         String validateEmail = PolicyUtils.validateEmailAddress(email.replace("\"", ""));
686                         if(!validateEmail.contains(SUCCESS)){
687                                 res  += "<b>Email</b>:<i>" +  validateEmail + HTML_ITALICS_LNBREAK;
688                         }
689                         else {
690                                 return SUCCESS;
691                         }
692                 }
693                 return res;
694         }
695
696         private MicroServiceModels getAttributeObject(String name, String version) {    
697                 MicroServiceModels workingModel = null;
698                 try{
699                         List<Object> microServiceModelsData = commonClassDao.getDataById(MicroServiceModels.class, "modelName:version", name+":"+version);
700                         if(microServiceModelsData != null){
701                                 workingModel = (MicroServiceModels) microServiceModelsData.get(0);
702                         }
703                 }catch(Exception e){
704                         String message = XACMLErrorConstants.ERROR_DATA_ISSUE + "Invalid Template.  The template name, " 
705                     + name + " was not found in the dictionary: ";
706                         LOGGER.error(XACMLErrorConstants.ERROR_DATA_ISSUE + message + e);
707                         return null;
708                 }
709
710                 return workingModel;
711         }
712
713         private void pullJsonKeyPairs(JsonNode rootNode) {
714                 Iterator<Map.Entry<String, JsonNode>> fieldsIterator = rootNode.fields();
715
716                 while (fieldsIterator.hasNext()) {
717                         Map.Entry<String, JsonNode> field = fieldsIterator.next();
718                         final String key = field.getKey();
719                         final JsonNode value = field.getValue();
720                         if (value.isContainerNode() && !value.isArray()) {
721                                 pullJsonKeyPairs(value); // RECURSIVE CALL
722                         } else {
723                                 if (value.isArray()){
724                                         String newValue = StringUtils.replaceEach(value.toString(), new String[]{"[", "]", "\""}, new String[]{"", "", ""});
725                                         mapAttribute.put(key, newValue);
726                                 }else {
727                                         mapAttribute.put(key, value.toString().trim());
728                                 }
729                         }
730                 }
731         }
732
733 }