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