Convert tabs to spaces basic refactoring
[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
181                     // Set Matching attributes in YAMLParams in adapter
182                     YAMLParams yamlparams = new YAMLParams();
183
184                     if (matching != null) {
185                         yamlparams.setActor(matching.get("actor"));
186                         yamlparams.setRecipe(matching.get("recipe"));
187                         yamlparams.setGuardActiveStart(matching.get("guardActiveStart"));
188                         yamlparams.setGuardActiveEnd(matching.get("guardActiveEnd"));
189
190                         if("GUARD_YAML".equals(ruleProvider)){
191                             yamlparams.setLimit(matching.get("limit"));
192                             yamlparams.setTimeWindow(matching.get("timeWindow"));
193                             yamlparams.setTimeUnits(matching.get("timeUnits"));
194                         }else{
195
196                             List<String> blackList = new ArrayList<>();
197
198                             if(!Strings.isNullOrEmpty(matching.get("blackList"))){
199                                 String[] blackListArray = matching.get("blackList").split(",");
200                                 for(String element : blackListArray){
201                                     blackList.add(element);
202                                 }
203                             }
204
205                             yamlparams.setBlackList(blackList);
206
207                         }
208                     }
209                     policyData.setYamlparams(yamlparams);
210                 }
211
212             } else if("Action".equals(parameters.getPolicyClass().toString())){
213
214                 ArrayList<Object> ruleAlgorithmChoices = new ArrayList<>();
215
216                 List<String> dynamicLabelRuleAlgorithms = parameters.getDynamicRuleAlgorithmLabels();
217                 List<String> dynamicFieldFunctionRuleAlgorithms = parameters.getDynamicRuleAlgorithmFunctions();
218                 List<String> dynamicFieldOneRuleAlgorithms = parameters.getDynamicRuleAlgorithmField1();
219                 List<String> dyrnamicFieldTwoRuleAlgorithms = parameters.getDynamicRuleAlgorithmField2();
220
221                 if (dynamicLabelRuleAlgorithms != null && !dynamicLabelRuleAlgorithms.isEmpty()) {
222                     int i = dynamicLabelRuleAlgorithms.size() - 1;
223
224                     for (String labelAttr : dynamicLabelRuleAlgorithms) {
225                         LinkedHashMap<String, String> ruleAlgorithm = new LinkedHashMap<>();
226
227                         String id = dynamicLabelRuleAlgorithms.get(i);
228                         String dynamicRuleAlgorithmField1 = dynamicFieldOneRuleAlgorithms.get(i);
229                         String dynamicRuleAlgorithmCombo = dynamicFieldFunctionRuleAlgorithms.get(i);
230                         String dynamicRuleAlgorithmField2 = dyrnamicFieldTwoRuleAlgorithms.get(i);
231
232                         ruleAlgorithm.put("id", id);
233                         ruleAlgorithm.put("dynamicRuleAlgorithmField1", dynamicRuleAlgorithmField1);
234                         ruleAlgorithm.put("dynamicRuleAlgorithmCombo", dynamicRuleAlgorithmCombo);
235                         ruleAlgorithm.put("dynamicRuleAlgorithmField2", dynamicRuleAlgorithmField2);
236
237                         ruleAlgorithmChoices.add(ruleAlgorithm);
238
239                         i--;
240
241                     }
242                 }
243
244                 policyData.setRuleAlgorithmschoices(ruleAlgorithmChoices);
245
246                 ArrayList<Object> attributeList = new ArrayList<>();
247                 if (matching != null) {
248                     for (Map.Entry<String, String> entry : matching.entrySet()) {
249                         LinkedHashMap<String, String> attributeMap = new LinkedHashMap<>();
250                         String key = entry.getKey();
251                         String value = entry.getValue();
252                         attributeMap.put("key", key);
253                         attributeMap.put("value", value);
254                         attributeList.add(attributeMap);
255                     }
256                 }
257
258                 policyData.setAttributes(attributeList);
259                 policyData.setActionAttributeValue(parameters.getActionAttribute());
260                 policyData.setActionPerformer(parameters.getActionPerformer());
261
262             }
263         }else {
264
265             policyData.setPolicyType("Config");
266             policyData.setConfigPolicyType(parameters.getPolicyConfigType().toString());
267
268             //Config Specific
269             policyData.setConfigBodyData(parameters.getConfigBody()); //Base
270             policyData.setConfigType((parameters.getConfigBodyType()!=null) ? parameters.getConfigBodyType().toString().toUpperCase(): null);  //Base
271
272             if("FW".equalsIgnoreCase(parameters.getPolicyConfigType().toString())){
273
274                 policyData.setConfigPolicyType("Firewall Config");
275
276                 // get values and attributes from the JsonObject
277                 if(json != null){
278                     if (json.get("securityZoneId")!=null){
279                         String securityZone = json.get("securityZoneId").toString().replace("\"", "");
280                         policyData.setSecurityZone(securityZone);
281                     }
282                     if (json.get(CONFIG_NAME)!=null){
283                         String configName = json.get(CONFIG_NAME).toString().replace("\"", "");
284                         policyData.setConfigName(configName);
285                     }
286                 }
287
288             }else if("MS".equals(parameters.getPolicyConfigType().toString())){
289
290                 policyData.setConfigPolicyType("Micro Service");
291
292                 // get values and attributes from the JsonObject
293                 if(json != null){
294                     if (json.containsKey(CONTENT)){
295                         String content = json.get(CONTENT).toString();
296                         ObjectMapper mapper = new ObjectMapper();
297                         JsonNode policyJSON = null;
298                         try {
299                             policyJSON = mapper.readTree(content);
300                         } catch (IOException e) {
301                             String message = XACMLErrorConstants.ERROR_DATA_ISSUE+ INVALIDJSON + parameters.getConfigBody();
302                             LOGGER.error(message, e);
303                             return null;
304                         }
305                         policyData.setPolicyJSON(policyJSON);
306                     }
307                     if (json.containsKey(SERVICE)){
308                         String serviceType = json.get(SERVICE).toString().replace("\"", "");
309                         policyData.setServiceType(serviceType);
310                     }
311                     if (json.containsKey("uuid")){
312                         String uuid = json.get("uuid").toString().replace("\"", "");
313                         policyData.setUuid(uuid);
314                     }
315                     if (json.containsKey(LOCATION)){
316                         String msLocation = json.get(LOCATION).toString().replace("\"", "");
317                         policyData.setLocation(msLocation);
318                     }
319                     if (json.containsKey(CONFIG_NAME)){
320                         String configName = json.get(CONFIG_NAME).toString().replace("\"", "");
321                         policyData.setConfigName(configName);
322                     }
323                     if(json.containsKey(PRIORITY)){
324                         String priority = json.get(PRIORITY).toString().replace("\"", "");
325                         policyData.setPriority(priority);
326                     }
327                     if(json.containsKey(VERSION)){
328                         String version = json.get(VERSION).toString().replace("\"", "");
329                         policyData.setVersion(version);
330                     }
331                     if(json.containsKey(POLICYSCOPE)){
332                         String policyScope = json.get(POLICYSCOPE).toString().replace("\"", "");
333                         policyData.setPolicyScope(policyScope);
334                     }
335                     if(json.containsKey(RISKTYPE)){
336                         String riskType = json.get(RISKTYPE).toString().replace("\"", "");
337                         policyData.setRiskType(riskType);
338                     }
339                     if(json.containsKey(RISKLEVEL)){
340                         String riskLevel = json.get(RISKLEVEL).toString().replace("\"", "");
341                         policyData.setRiskLevel(riskLevel);
342                     }
343                     if(json.containsKey(GUARD)){
344                         String guard = json.get(GUARD).toString().replace("\"", "");
345                         policyData.setGuard(guard);
346                     }
347                 } else {
348                     String message = XACMLErrorConstants.ERROR_DATA_ISSUE+ INVALIDJSON + parameters.getConfigBody();
349                     LOGGER.error(message);
350                     return null;
351                 }
352
353             }else if("Optimization".equals(parameters.getPolicyConfigType().toString())){
354
355                 policyData.setConfigPolicyType("Optimization");
356
357                 // get values and attributes from the JsonObject
358                 if(json != null){
359                     if (json.containsKey(CONTENT)){
360                         String content = json.get(CONTENT).toString();
361                         ObjectMapper mapper = new ObjectMapper();
362                         JsonNode policyJSON = null;
363                         try {
364                             policyJSON = mapper.readTree(content);
365                         } catch (IOException e) {
366                             String message = XACMLErrorConstants.ERROR_DATA_ISSUE+ INVALIDJSON + parameters.getConfigBody();
367                             LOGGER.error(message, e);
368                             return null;
369                         }
370                         policyData.setPolicyJSON(policyJSON);
371                     }
372                     if (json.containsKey(SERVICE)){
373                         String serviceType = json.get(SERVICE).toString().replace("\"", "");
374                         policyData.setServiceType(serviceType);
375                     }
376                     if (json.containsKey("uuid")){
377                         String uuid = json.get("uuid").toString().replace("\"", "");
378                         policyData.setUuid(uuid);
379                     }
380                     if (json.containsKey(LOCATION)){
381                         String msLocation = json.get(LOCATION).toString().replace("\"", "");
382                         policyData.setLocation(msLocation);
383                     }
384                     if (json.containsKey(CONFIG_NAME)){
385                         String configName = json.get(CONFIG_NAME).toString().replace("\"", "");
386                         policyData.setConfigName(configName);
387                     }
388                     if(json.containsKey(PRIORITY)){
389                         String priority = json.get(PRIORITY).toString().replace("\"", "");
390                         policyData.setPriority(priority);
391                     }
392                     if(json.containsKey(VERSION)){
393                         String version = json.get(VERSION).toString().replace("\"", "");
394                         policyData.setVersion(version);
395                     }
396                     if(json.containsKey(POLICYSCOPE)){
397                         String policyScope = json.get(POLICYSCOPE).toString().replace("\"", "");
398                         policyData.setPolicyScope(policyScope);
399                     }
400                     if(json.containsKey(RISKTYPE)){
401                         String riskType = json.get(RISKTYPE).toString().replace("\"", "");
402                         policyData.setRiskType(riskType);
403                     }
404                     if(json.containsKey(RISKLEVEL)){
405                         String riskLevel = json.get(RISKLEVEL).toString().replace("\"", "");
406                         policyData.setRiskLevel(riskLevel);
407                     }
408                     if(json.containsKey(GUARD)){
409                         String guard = json.get(GUARD).toString().replace("\"", "");
410                         policyData.setGuard(guard);
411                     }
412                 }
413
414             } else if("Fault".equals(parameters.getPolicyConfigType().toString())){
415
416                 policyData.setConfigPolicyType("ClosedLoop_Fault");
417
418                 if(json != null){
419                     policyData.setJsonBody(json.toString());
420                     if (json.get(ONAPNAME)!=null){
421                         String onapName = json.get(ONAPNAME).toString().replace("\"", "");
422                         policyData.setOnapName(onapName);
423                     }
424                 }
425
426             } else if("PM".equals(parameters.getPolicyConfigType().toString())){
427
428                 policyData.setConfigPolicyType("ClosedLoop_PM");
429
430                 if(json != null){
431                     policyData.setJsonBody(json.toString());
432                     if (json.get(ONAPNAME)!=null){
433                         String onapName = json.get(ONAPNAME).toString().replace("\"", "");
434                         policyData.setOnapName(onapName);
435                     }
436                     if (json.get(SERVICETYPE_POLICY_NAME)!=null){
437                         String serviceType = json.get(SERVICETYPE_POLICY_NAME).toString().replace("\"", "");
438                         LinkedHashMap<String, String> serviceTypePolicyName = new LinkedHashMap<>();
439                         serviceTypePolicyName.put(SERVICETYPE_POLICY_NAME, serviceType);
440                         policyData.setServiceTypePolicyName(serviceTypePolicyName);
441                     }
442                 }
443             } else if("BRMS_Param".equals(parameters.getPolicyConfigType().toString())){
444                 Map<AttributeType, Map<String, String>> drlRuleAndUIParams = parameters.getAttributes();
445                 Map<String, String> rule = drlRuleAndUIParams.get(AttributeType.RULE);
446                 policyData.setRuleName(rule.get("templateName"));
447
448             }
449         }
450
451         return policyData;
452
453     }
454     
455     private JsonObject stringToJsonObject(String value) {
456         try(JsonReader jsonReader = Json.createReader(new StringReader(value))){
457             return jsonReader.readObject();
458         } catch(JsonException| IllegalStateException e){
459             LOGGER.info(XACMLErrorConstants.ERROR_DATA_ISSUE+ "Improper JSON format... may or may not cause issues in validating the policy: " + value, e);
460             return null;
461         }
462     }
463     
464     private String convertDate(Date date) {
465         String strDate = null;
466         if (date!=null) {
467             SimpleDateFormat dateformatJava = new SimpleDateFormat("dd-MM-yyyy");
468             strDate = dateformatJava.format(date);
469         }
470         return (strDate==null) ? "NA": strDate;
471     }
472
473 }