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