779c5227aeea1915a49b25560d662012c5c62a78
[policy/engine.git] / ONAP-REST / src / main / java / org / onap / policy / rest / util / PolicyValidationRequestWrapper.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  */package org.onap.policy.rest.util;
20
21 import java.io.IOException;
22 import java.io.StringReader;
23 import java.text.SimpleDateFormat;
24 import java.util.ArrayList;
25 import java.util.Date;
26 import java.util.LinkedHashMap;
27 import java.util.List;
28 import java.util.Map;
29
30 import javax.json.Json;
31 import javax.json.JsonException;
32 import javax.json.JsonObject;
33 import javax.json.JsonReader;
34 import javax.servlet.http.HttpServletRequest;
35
36 import org.onap.policy.api.AttributeType;
37 import org.onap.policy.api.PolicyParameters;
38 import org.onap.policy.common.logging.flexlogger.FlexLogger;
39 import org.onap.policy.common.logging.flexlogger.Logger;
40 import org.onap.policy.rest.adapter.ClosedLoopFaultTrapDatas;
41 import org.onap.policy.rest.adapter.PolicyRestAdapter;
42 import org.onap.policy.rest.adapter.RainyDayParams;
43 import org.onap.policy.rest.adapter.YAMLParams;
44 import org.onap.policy.xacml.api.XACMLErrorConstants;
45
46 import com.fasterxml.jackson.databind.DeserializationFeature;
47 import com.fasterxml.jackson.databind.JsonNode;
48 import com.fasterxml.jackson.databind.ObjectMapper;
49 import com.google.common.base.Strings;
50
51 public class PolicyValidationRequestWrapper {
52
53     private static final Logger LOGGER  = FlexLogger.getLogger(PolicyValidationRequestWrapper.class);
54     public static final String CONFIG_NAME="configName";
55     public static final String INVALIDJSON = " improper JSON format: ";
56     public static final String ONAPNAME = "onapname";
57     public static final String CONTENT = "content";
58     public static final String GUARD = "guard";
59     public static final String LOCATION = "location";
60     public static final String POLICYSCOPE = "policyScope";
61     public static final String PRIORITY = "priority";
62     public static final String RISKLEVEL = "riskLevel";
63     public static final String RISKTYPE = "riskType";
64     public static final String SERVICE = "service";
65     public static final String VERSION = "version";
66
67     public static final String SERVICETYPE_POLICY_NAME = "serviceTypePolicyName";
68
69     public PolicyRestAdapter populateRequestParameters(HttpServletRequest request) {
70
71         PolicyRestAdapter policyData = null;
72         ClosedLoopFaultTrapDatas trapDatas = null;
73         ClosedLoopFaultTrapDatas faultDatas = null;
74         try {
75             ObjectMapper mapper = new ObjectMapper();
76             mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
77             JsonNode root = mapper.readTree(request.getReader());
78             policyData = mapper.readValue(root.get("policyData").toString(), PolicyRestAdapter.class);
79             if(root.get("trapData") != null){
80                 trapDatas = mapper.readValue(root.get("trapData").toString(), ClosedLoopFaultTrapDatas.class);
81                 policyData.setTrapDatas(trapDatas);
82             }
83             if(root.get("faultData") != null){
84                 faultDatas = mapper.readValue(root.get("faultData").toString(), ClosedLoopFaultTrapDatas.class);
85                 policyData.setFaultDatas(faultDatas);
86             }
87
88             JsonObject json;
89             json = stringToJsonObject(root.toString());
90
91             if(json != null){
92                 if(json.containsKey("policyJSON")){
93                     policyData.setPolicyJSON(root.get("policyJSON"));
94                 }else{
95                     String jsonBodyData = json.getJsonObject("policyData").get("jsonBodyData").toString();
96                     policyData.setJsonBody(jsonBodyData);
97                 }
98             }
99
100         } catch (Exception e) {
101             LOGGER.error("Exception Occured while populating request parameters: " +e);
102         }
103
104         return policyData;
105     }
106
107     public PolicyRestAdapter populateRequestParameters(PolicyParameters parameters) {
108
109         PolicyRestAdapter policyData = new PolicyRestAdapter();
110         
111         /*
112          * set policy adapter values for Building JSON object containing policy data
113          */
114         //Common Policy Fields
115         policyData.setPolicyName(parameters.getPolicyName());
116         policyData.setOnapName(parameters.getOnapName());
117         policyData.setPriority(parameters.getPriority()); //Micro Service
118         policyData.setConfigName(parameters.getConfigName());  //Base and Firewall
119         policyData.setRiskType(parameters.getRiskType()); //Safe parameters Attributes
120         policyData.setRiskLevel(parameters.getRiskLevel());//Safe parameters Attributes
121         policyData.setGuard(String.valueOf(parameters.getGuard()));//Safe parameters Attributes
122         policyData.setTtlDate(convertDate(parameters.getTtlDate()));//Safe parameters Attributes
123         policyData.setApiflag("API");
124
125         //Some policies require jsonObject conversion from String for configBody (i.e. MicroService and Firewall)
126         JsonObject json = null;
127         try{
128             if(parameters.getConfigBody()!= null){
129                 json = stringToJsonObject(parameters.getConfigBody());
130             }
131         } catch(JsonException| IllegalStateException e){
132             String message = XACMLErrorConstants.ERROR_DATA_ISSUE+ INVALIDJSON + parameters.getConfigBody();
133             LOGGER.error(message, e);
134             return null;
135         }
136         
137         if(parameters.getPolicyClass()!=null && !"Config".equals(parameters.getPolicyClass().toString())){
138
139             policyData.setPolicyType(parameters.getPolicyClass().toString());
140
141             //Get Matching attribute values
142             Map<AttributeType, Map<String, String>> attributes = parameters.getAttributes();
143             Map<String, String> matching = null;
144             if(attributes != null){
145                 matching = attributes.get(AttributeType.MATCHING);
146             }
147
148             if("Decision".equals(parameters.getPolicyClass().toString())){
149
150                 String ruleProvider = parameters.getRuleProvider().toString();
151                 policyData.setRuleProvider(ruleProvider);
152
153                 if("Rainy_Day".equals(ruleProvider)){
154
155                     // Set Matching attributes in RainyDayParams in adapter
156                     RainyDayParams rainyday = new RainyDayParams();
157
158                     if(matching != null) {
159                         rainyday.setServiceType(matching.get("ServiceType"));
160                         rainyday.setVnfType(matching.get("VNFType"));
161                         rainyday.setBbid(matching.get("BB_ID"));
162                         rainyday.setWorkstep(matching.get("WorkStep"));
163                     }
164
165                     Map<String, String> treatments = parameters.getTreatments();
166                     ArrayList<Object> treatmentsTableChoices = new ArrayList<>();
167
168                     for (String keyField : treatments.keySet()) {
169                         LinkedHashMap<String, String> treatmentMap = new LinkedHashMap<>();
170                         String errorcode = keyField;
171                         String treatment = treatments.get(errorcode);
172                         treatmentMap.put("errorcode", errorcode);
173                         treatmentMap.put("treatment", treatment);
174                         treatmentsTableChoices.add(treatmentMap);
175                     }
176                     rainyday.setTreatmentTableChoices(treatmentsTableChoices);
177                     policyData.setRainyday(rainyday);
178
179                 } else if ("GUARD_YAML".equals(ruleProvider) || "GUARD_BL_YAML".equals(ruleProvider)
180                         || "GUARD_MIN_MAX".equals(ruleProvider)) {
181
182                     // Set Matching attributes in YAMLParams in adapter
183                     YAMLParams yamlparams = new YAMLParams();
184
185                     if (matching != null) {
186                         yamlparams.setActor(matching.get("actor"));
187                         yamlparams.setRecipe(matching.get("recipe"));
188                         yamlparams.setGuardActiveStart(matching.get("guardActiveStart"));
189                         yamlparams.setGuardActiveEnd(matching.get("guardActiveEnd"));
190
191                         if("GUARD_YAML".equals(ruleProvider)){
192                             yamlparams.setLimit(matching.get("limit"));
193                             yamlparams.setTimeWindow(matching.get("timeWindow"));
194                             yamlparams.setTimeUnits(matching.get("timeUnits"));
195                         } else if ("GUARD_MIN_MAX".equals(ruleProvider)) {
196                             yamlparams.setMin(matching.get("min"));
197                             yamlparams.setMax(matching.get("max"));
198                         }else{
199
200                             List<String> blackList = new ArrayList<>();
201
202                             if(!Strings.isNullOrEmpty(matching.get("blackList"))){
203                                 String[] blackListArray = matching.get("blackList").split(",");
204                                 for(String element : blackListArray){
205                                     blackList.add(element);
206                                 }
207                             }
208
209                             yamlparams.setBlackList(blackList);
210
211                         }
212                     }
213                     policyData.setYamlparams(yamlparams);
214                 }
215
216             } else if("Action".equals(parameters.getPolicyClass().toString())){
217
218                 ArrayList<Object> ruleAlgorithmChoices = new ArrayList<>();
219
220                 List<String> dynamicLabelRuleAlgorithms = parameters.getDynamicRuleAlgorithmLabels();
221                 List<String> dynamicFieldFunctionRuleAlgorithms = parameters.getDynamicRuleAlgorithmFunctions();
222                 List<String> dynamicFieldOneRuleAlgorithms = parameters.getDynamicRuleAlgorithmField1();
223                 List<String> dyrnamicFieldTwoRuleAlgorithms = parameters.getDynamicRuleAlgorithmField2();
224
225                 if (dynamicLabelRuleAlgorithms != null && !dynamicLabelRuleAlgorithms.isEmpty()) {
226                     int i = dynamicLabelRuleAlgorithms.size() - 1;
227
228                     for (String labelAttr : dynamicLabelRuleAlgorithms) {
229                         LinkedHashMap<String, String> ruleAlgorithm = new LinkedHashMap<>();
230
231                         String id = dynamicLabelRuleAlgorithms.get(i);
232                         String dynamicRuleAlgorithmField1 = dynamicFieldOneRuleAlgorithms.get(i);
233                         String dynamicRuleAlgorithmCombo = dynamicFieldFunctionRuleAlgorithms.get(i);
234                         String dynamicRuleAlgorithmField2 = dyrnamicFieldTwoRuleAlgorithms.get(i);
235
236                         ruleAlgorithm.put("id", id);
237                         ruleAlgorithm.put("dynamicRuleAlgorithmField1", dynamicRuleAlgorithmField1);
238                         ruleAlgorithm.put("dynamicRuleAlgorithmCombo", dynamicRuleAlgorithmCombo);
239                         ruleAlgorithm.put("dynamicRuleAlgorithmField2", dynamicRuleAlgorithmField2);
240
241                         ruleAlgorithmChoices.add(ruleAlgorithm);
242
243                         i--;
244
245                     }
246                 }
247
248                 policyData.setRuleAlgorithmschoices(ruleAlgorithmChoices);
249
250                 ArrayList<Object> attributeList = new ArrayList<>();
251                 if (matching != null) {
252                     for (Map.Entry<String, String> entry : matching.entrySet()) {
253                         LinkedHashMap<String, String> attributeMap = new LinkedHashMap<>();
254                         String key = entry.getKey();
255                         String value = entry.getValue();
256                         attributeMap.put("key", key);
257                         attributeMap.put("value", value);
258                         attributeList.add(attributeMap);
259                     }
260                 }
261
262                 policyData.setAttributes(attributeList);
263                 policyData.setActionAttributeValue(parameters.getActionAttribute());
264                 policyData.setActionPerformer(parameters.getActionPerformer());
265
266             }
267         }else {
268
269             policyData.setPolicyType("Config");
270             policyData.setConfigPolicyType(parameters.getPolicyConfigType().toString());
271
272             //Config Specific
273             policyData.setConfigBodyData(parameters.getConfigBody()); //Base
274             policyData.setConfigType((parameters.getConfigBodyType()!=null) ? parameters.getConfigBodyType().toString().toUpperCase(): null);  //Base
275
276             if("FW".equalsIgnoreCase(parameters.getPolicyConfigType().toString())){
277
278                 policyData.setConfigPolicyType("Firewall Config");
279
280                 // get values and attributes from the JsonObject
281                 if(json != null){
282                     if (json.get("securityZoneId")!=null){
283                         String securityZone = json.get("securityZoneId").toString().replace("\"", "");
284                         policyData.setSecurityZone(securityZone);
285                     }
286                     if (json.get(CONFIG_NAME)!=null){
287                         String configName = json.get(CONFIG_NAME).toString().replace("\"", "");
288                         policyData.setConfigName(configName);
289                     }
290                 }
291
292             }else if("MS".equals(parameters.getPolicyConfigType().toString())){
293
294                 policyData.setConfigPolicyType("Micro Service");
295
296                 // get values and attributes from the JsonObject
297                 if(json != null){
298                     if (json.containsKey(CONTENT)){
299                         String content = json.get(CONTENT).toString();
300                         ObjectMapper mapper = new ObjectMapper();
301                         JsonNode policyJSON = null;
302                         try {
303                             policyJSON = mapper.readTree(content);
304                         } catch (IOException e) {
305                             String message = XACMLErrorConstants.ERROR_DATA_ISSUE+ INVALIDJSON + parameters.getConfigBody();
306                             LOGGER.error(message, e);
307                             return null;
308                         }
309                         policyData.setPolicyJSON(policyJSON);
310                     }
311                     if (json.containsKey(SERVICE)){
312                         String serviceType = json.get(SERVICE).toString().replace("\"", "");
313                         policyData.setServiceType(serviceType);
314                     }
315                     if (json.containsKey("uuid")){
316                         String uuid = json.get("uuid").toString().replace("\"", "");
317                         policyData.setUuid(uuid);
318                     }
319                     if (json.containsKey(LOCATION)){
320                         String msLocation = json.get(LOCATION).toString().replace("\"", "");
321                         policyData.setLocation(msLocation);
322                     }
323                     if (json.containsKey(CONFIG_NAME)){
324                         String configName = json.get(CONFIG_NAME).toString().replace("\"", "");
325                         policyData.setConfigName(configName);
326                     }
327                     if(json.containsKey(PRIORITY)){
328                         String priority = json.get(PRIORITY).toString().replace("\"", "");
329                         policyData.setPriority(priority);
330                     }
331                     if(json.containsKey(VERSION)){
332                         String version = json.get(VERSION).toString().replace("\"", "");
333                         policyData.setVersion(version);
334                     }
335                     if(json.containsKey(POLICYSCOPE)){
336                         String policyScope = json.get(POLICYSCOPE).toString().replace("\"", "");
337                         policyData.setPolicyScope(policyScope);
338                     }
339                     if(json.containsKey(RISKTYPE)){
340                         String riskType = json.get(RISKTYPE).toString().replace("\"", "");
341                         policyData.setRiskType(riskType);
342                     }
343                     if(json.containsKey(RISKLEVEL)){
344                         String riskLevel = json.get(RISKLEVEL).toString().replace("\"", "");
345                         policyData.setRiskLevel(riskLevel);
346                     }
347                     if(json.containsKey(GUARD)){
348                         String guard = json.get(GUARD).toString().replace("\"", "");
349                         policyData.setGuard(guard);
350                     }
351                 } else {
352                     String message = XACMLErrorConstants.ERROR_DATA_ISSUE+ INVALIDJSON + parameters.getConfigBody();
353                     LOGGER.error(message);
354                     return null;
355                 }
356
357             }else if("Optimization".equals(parameters.getPolicyConfigType().toString())){
358
359                 policyData.setConfigPolicyType("Optimization");
360
361                 // get values and attributes from the JsonObject
362                 if(json != null){
363                     if (json.containsKey(CONTENT)){
364                         String content = json.get(CONTENT).toString();
365                         ObjectMapper mapper = new ObjectMapper();
366                         JsonNode policyJSON = null;
367                         try {
368                             policyJSON = mapper.readTree(content);
369                         } catch (IOException e) {
370                             String message = XACMLErrorConstants.ERROR_DATA_ISSUE+ INVALIDJSON + parameters.getConfigBody();
371                             LOGGER.error(message, e);
372                             return null;
373                         }
374                         policyData.setPolicyJSON(policyJSON);
375                     }
376                     if (json.containsKey(SERVICE)){
377                         String serviceType = json.get(SERVICE).toString().replace("\"", "");
378                         policyData.setServiceType(serviceType);
379                     }
380                     if (json.containsKey("uuid")){
381                         String uuid = json.get("uuid").toString().replace("\"", "");
382                         policyData.setUuid(uuid);
383                     }
384                     if (json.containsKey(LOCATION)){
385                         String msLocation = json.get(LOCATION).toString().replace("\"", "");
386                         policyData.setLocation(msLocation);
387                     }
388                     if (json.containsKey(CONFIG_NAME)){
389                         String configName = json.get(CONFIG_NAME).toString().replace("\"", "");
390                         policyData.setConfigName(configName);
391                     }
392                     if(json.containsKey(PRIORITY)){
393                         String priority = json.get(PRIORITY).toString().replace("\"", "");
394                         policyData.setPriority(priority);
395                     }
396                     if(json.containsKey(VERSION)){
397                         String version = json.get(VERSION).toString().replace("\"", "");
398                         policyData.setVersion(version);
399                     }
400                     if(json.containsKey(POLICYSCOPE)){
401                         String policyScope = json.get(POLICYSCOPE).toString().replace("\"", "");
402                         policyData.setPolicyScope(policyScope);
403                     }
404                     if(json.containsKey(RISKTYPE)){
405                         String riskType = json.get(RISKTYPE).toString().replace("\"", "");
406                         policyData.setRiskType(riskType);
407                     }
408                     if(json.containsKey(RISKLEVEL)){
409                         String riskLevel = json.get(RISKLEVEL).toString().replace("\"", "");
410                         policyData.setRiskLevel(riskLevel);
411                     }
412                     if(json.containsKey(GUARD)){
413                         String guard = json.get(GUARD).toString().replace("\"", "");
414                         policyData.setGuard(guard);
415                     }
416                 }
417
418             } else if("Fault".equals(parameters.getPolicyConfigType().toString())){
419
420                 policyData.setConfigPolicyType("ClosedLoop_Fault");
421
422                 if(json != null){
423                     policyData.setJsonBody(json.toString());
424                     if (json.get(ONAPNAME)!=null){
425                         String onapName = json.get(ONAPNAME).toString().replace("\"", "");
426                         policyData.setOnapName(onapName);
427                     }
428                 }
429
430             } else if("PM".equals(parameters.getPolicyConfigType().toString())){
431
432                 policyData.setConfigPolicyType("ClosedLoop_PM");
433
434                 if(json != null){
435                     policyData.setJsonBody(json.toString());
436                     if (json.get(ONAPNAME)!=null){
437                         String onapName = json.get(ONAPNAME).toString().replace("\"", "");
438                         policyData.setOnapName(onapName);
439                     }
440                     if (json.get(SERVICETYPE_POLICY_NAME)!=null){
441                         String serviceType = json.get(SERVICETYPE_POLICY_NAME).toString().replace("\"", "");
442                         LinkedHashMap<String, String> serviceTypePolicyName = new LinkedHashMap<>();
443                         serviceTypePolicyName.put(SERVICETYPE_POLICY_NAME, serviceType);
444                         policyData.setServiceTypePolicyName(serviceTypePolicyName);
445                     }
446                 }
447             } else if("BRMS_Param".equals(parameters.getPolicyConfigType().toString())){
448                 Map<AttributeType, Map<String, String>> drlRuleAndUIParams = parameters.getAttributes();
449                 Map<String, String> rule = drlRuleAndUIParams.get(AttributeType.RULE);
450                 policyData.setRuleName(rule.get("templateName"));
451
452             }
453         }
454
455         return policyData;
456
457     }
458     
459     private JsonObject stringToJsonObject(String value) {
460         try(JsonReader jsonReader = Json.createReader(new StringReader(value))){
461             return jsonReader.readObject();
462         } catch(JsonException| IllegalStateException e){
463             LOGGER.info(XACMLErrorConstants.ERROR_DATA_ISSUE+ "Improper JSON format... may or may not cause issues in validating the policy: " + value, e);
464             return null;
465         }
466     }
467     
468     private String convertDate(Date date) {
469         String strDate = null;
470         if (date!=null) {
471             SimpleDateFormat dateformatJava = new SimpleDateFormat("dd-MM-yyyy");
472             strDate = dateformatJava.format(date);
473         }
474         return (strDate==null) ? "NA": strDate;
475     }
476
477 }