f19773964b2e3d3b87c4b6c1e4b393cf05de7f69
[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
56         public PolicyRestAdapter populateRequestParameters(HttpServletRequest request) {
57                 
58                 PolicyRestAdapter policyData = null;
59                 ClosedLoopFaultTrapDatas trapDatas = null;
60                 ClosedLoopFaultTrapDatas faultDatas = null;
61                 try {
62                         ObjectMapper mapper = new ObjectMapper();
63                         mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
64                         JsonNode root = mapper.readTree(request.getReader());
65                         policyData = mapper.readValue(root.get("policyData").toString(), PolicyRestAdapter.class);
66                         if(root.get("trapData") != null){
67                                 trapDatas = mapper.readValue(root.get("trapData").toString(), ClosedLoopFaultTrapDatas.class);
68                                 policyData.setTrapDatas(trapDatas);
69                         }
70                         if(root.get("faultData") != null){
71                                 faultDatas = mapper.readValue(root.get("faultData").toString(), ClosedLoopFaultTrapDatas.class);
72                                 policyData.setFaultDatas(faultDatas);
73                         }
74                         
75                         JsonObject json;
76                         json = stringToJsonObject(root.toString());
77                         
78                         if(json != null){
79                                 if(json.containsKey("policyJSON")){
80                                         policyData.setPolicyJSON(root.get("policyJSON"));
81                                 }else{
82                                         String jsonBodyData = json.getJsonObject("policyData").get("jsonBodyData").toString();
83                                         policyData.setJsonBody(jsonBodyData);
84                                 }
85                         }                       
86                                                 
87                 } catch (Exception e) {
88                         LOGGER.error("Exception Occured while populating request parameters: " +e);
89                 }
90                 
91                 return policyData;
92         }
93         
94         public PolicyRestAdapter populateRequestParameters(PolicyParameters parameters) {
95                 
96                 PolicyRestAdapter policyData = new PolicyRestAdapter();
97         
98                 /*
99                  * set policy adapter values for Building JSON object containing policy data
100                  */
101                 //Common Policy Fields
102                 policyData.setPolicyName(parameters.getPolicyName());
103                 policyData.setOnapName(parameters.getOnapName()); 
104                 policyData.setPriority(parameters.getPriority()); //Micro Service
105                 policyData.setConfigName(parameters.getConfigName());  //Base and Firewall
106                 policyData.setRiskType(parameters.getRiskType()); //Safe parameters Attributes
107                 policyData.setRiskLevel(parameters.getRiskLevel());//Safe parameters Attributes
108                 policyData.setGuard(String.valueOf(parameters.getGuard()));//Safe parameters Attributes
109                 policyData.setTtlDate(convertDate(parameters.getTtlDate()));//Safe parameters Attributes
110                 
111                 //Some policies require jsonObject conversion from String for configBody (i.e. MicroService and Firewall)
112                 JsonObject json = null;
113         try{
114                 if(parameters.getConfigBody()!= null){
115                         json = stringToJsonObject(parameters.getConfigBody());
116                 }
117         } catch(JsonException| IllegalStateException e){
118             String message = XACMLErrorConstants.ERROR_DATA_ISSUE+ " improper JSON object : " + parameters.getConfigBody();
119             LOGGER.error(message, e);
120             return null;
121         }
122         
123                 if(parameters.getPolicyClass()!=null && !"Config".equals(parameters.getPolicyClass().toString())){
124                         
125                         policyData.setPolicyType(parameters.getPolicyClass().toString());
126                         
127                         //Get Matching attribute values
128                         Map<AttributeType, Map<String, String>> attributes = parameters.getAttributes();
129                         Map<String, String> matching = null;
130                         if(attributes != null){
131                                 matching = attributes.get(AttributeType.MATCHING);
132                         }
133                         
134                         if("Decision".equals(parameters.getPolicyClass().toString())){
135                                 
136                                 String ruleProvider = parameters.getRuleProvider().toString();
137                                 policyData.setRuleProvider(ruleProvider);
138                                 
139                                 if("Rainy_Day".equals(ruleProvider)){
140                                         
141                                         // Set Matching attributes in RainyDayParams in adapter
142                                         RainyDayParams rainyday = new RainyDayParams();
143                                         
144                                         if(matching != null) {
145                                                 rainyday.setServiceType(matching.get("ServiceType"));
146                                                 rainyday.setVnfType(matching.get("VNFType"));
147                                                 rainyday.setBbid(matching.get("BB_ID"));
148                                                 rainyday.setWorkstep(matching.get("WorkStep"));
149                                         }
150
151                                         Map<String, String> treatments = parameters.getTreatments();
152                                         ArrayList<Object> treatmentsTableChoices = new ArrayList<>();
153                                         
154                                         for (String keyField : treatments.keySet()) {
155                                                 LinkedHashMap<String, String> treatmentMap = new LinkedHashMap<>();
156                                                 String errorcode = keyField;
157                                                 String treatment = treatments.get(errorcode);
158                                                 treatmentMap.put("errorcode", errorcode);
159                                                 treatmentMap.put("treatment", treatment);
160                                                 treatmentsTableChoices.add(treatmentMap);
161                                         }
162                                         rainyday.setTreatmentTableChoices(treatmentsTableChoices);
163                                         policyData.setRainyday(rainyday);
164                                         
165                                 }else if("GUARD_YAML".equals(ruleProvider) || "GUARD_BL_YAML".equals(ruleProvider)) {
166                                         
167                                         // Set Matching attributes in YAMLParams in adapter
168                                         YAMLParams yamlparams = new YAMLParams();
169                                         
170                                         if (matching != null) {
171                                                 yamlparams.setActor(matching.get("actor"));
172                                                 yamlparams.setRecipe(matching.get("recipe"));
173                                                 yamlparams.setGuardActiveStart(matching.get("guardActiveStart"));
174                                                 yamlparams.setGuardActiveEnd(matching.get("guardActiveEnd"));
175                                                 
176                                                 if("GUARD_YAML".equals(ruleProvider)){
177                                                         yamlparams.setLimit(matching.get("limit"));
178                                                         yamlparams.setTimeWindow(matching.get("timeWindow"));
179                                                         yamlparams.setTimeUnits(matching.get("timeUnits"));     
180                                                 }else{
181                                                         
182                                                         List<String> blackList = new ArrayList<>();
183
184                                                         if(!Strings.isNullOrEmpty(matching.get("blackList"))){
185                                                                 String[] blackListArray = matching.get("blackList").split(",");
186                                                                 for(String element : blackListArray){
187                                                                         blackList.add(element);
188                                                                 }                                       
189                                                         }       
190                                                         
191                                                         yamlparams.setBlackList(blackList);
192
193                                                 }                                       
194                                         }
195                                         policyData.setYamlparams(yamlparams);
196                                 }
197                                 
198                         } else if("Action".equals(parameters.getPolicyClass().toString())){
199                                 
200                                 ArrayList<Object> ruleAlgorithmChoices = new ArrayList<>();
201                                                                 
202                                 List<String> dynamicLabelRuleAlgorithms = parameters.getDynamicRuleAlgorithmLabels();
203                                 List<String> dynamicFieldFunctionRuleAlgorithms = parameters.getDynamicRuleAlgorithmFunctions();
204                                 List<String> dynamicFieldOneRuleAlgorithms = parameters.getDynamicRuleAlgorithmField1();
205                                 List<String> dyrnamicFieldTwoRuleAlgorithms = parameters.getDynamicRuleAlgorithmField2();
206                     
207                                 if (dynamicLabelRuleAlgorithms != null && !dynamicLabelRuleAlgorithms.isEmpty()) {
208                         int i = dynamicLabelRuleAlgorithms.size() - 1;
209
210                         for (String labelAttr : dynamicLabelRuleAlgorithms) {
211                                         LinkedHashMap<String, String> ruleAlgorithm = new LinkedHashMap<>();
212
213                                 String id = dynamicLabelRuleAlgorithms.get(i);
214                                 String dynamicRuleAlgorithmField1 = dynamicFieldOneRuleAlgorithms.get(i);
215                                 String dynamicRuleAlgorithmCombo = dynamicFieldFunctionRuleAlgorithms.get(i);
216                                 String dynamicRuleAlgorithmField2 = dyrnamicFieldTwoRuleAlgorithms.get(i);
217                                 
218                                 ruleAlgorithm.put("id", id);
219                                 ruleAlgorithm.put("dynamicRuleAlgorithmField1", dynamicRuleAlgorithmField1);
220                                 ruleAlgorithm.put("dynamicRuleAlgorithmCombo", dynamicRuleAlgorithmCombo);
221                                 ruleAlgorithm.put("dynamicRuleAlgorithmField2", dynamicRuleAlgorithmField2);
222                                 
223                                 ruleAlgorithmChoices.add(ruleAlgorithm);
224                                 
225                                 i--;
226                                 
227                         }
228                     }
229                     
230                     policyData.setRuleAlgorithmschoices(ruleAlgorithmChoices);
231                     
232                     ArrayList<Object> attributeList = new ArrayList<>();
233                     if (matching != null) {
234                             for (Map.Entry<String, String> entry : matching.entrySet()) {
235                                                 LinkedHashMap<String, String> attributeMap = new LinkedHashMap<>();
236                                                 String key = entry.getKey();
237                                                 String value = entry.getValue();
238                                                 attributeMap.put("key", key);
239                                                 attributeMap.put("value", value);
240                                                 attributeList.add(attributeMap);
241                                         }       
242                     }
243                     
244                     policyData.setAttributes(attributeList);        
245                     policyData.setActionAttributeValue(parameters.getActionAttribute());
246                     policyData.setActionPerformer(parameters.getActionPerformer());
247                                 
248                         }
249                 }else {
250                         
251                         policyData.setPolicyType("Config");
252                         policyData.setConfigPolicyType(parameters.getPolicyConfigType().toString());
253                         
254                         //Config Specific
255                         policyData.setConfigBodyData(parameters.getConfigBody()); //Base
256                         policyData.setConfigType((parameters.getConfigBodyType()!=null) ? parameters.getConfigBodyType().toString().toUpperCase(): null);  //Base
257                         
258                         if("FW".equalsIgnoreCase(parameters.getPolicyConfigType().toString())){
259                                 
260                                 policyData.setConfigPolicyType("Firewall Config"); 
261
262                         // get values and attributes from the JsonObject
263                                 if(json != null){
264                                 if (json.get("securityZoneId")!=null){
265                                         String securityZone = json.get("securityZoneId").toString().replace("\"", "");
266                                         policyData.setSecurityZone(securityZone);
267                                 }
268                                 if (json.get(CONFIG_NAME)!=null){
269                                     String configName = json.get(CONFIG_NAME).toString().replace("\"", "");
270                                     policyData.setConfigName(configName);
271                                 }
272                                 }
273                                                                 
274                         }else if("MS".equals(parameters.getPolicyConfigType().toString())){
275                                 
276                                 policyData.setConfigPolicyType("Micro Service");
277                                 
278                         // get values and attributes from the JsonObject
279                                 if(json != null){
280                                         if (json.containsKey("content")){
281                                                 String content = json.get("content").toString();
282                                                 ObjectMapper mapper = new ObjectMapper();
283                                                 JsonNode policyJSON = null;
284                                                 try {
285                                                         policyJSON = mapper.readTree(content);
286                                                 } catch (IOException e) {
287                                             String message = XACMLErrorConstants.ERROR_DATA_ISSUE+ " improper JSON object : " + parameters.getConfigBody();
288                                             LOGGER.error(message, e);
289                                             return null;                                        
290                                         }
291                                                 policyData.setPolicyJSON(policyJSON);
292                                         }
293                                 if (json.containsKey("service")){
294                                         String serviceType = json.get("service").toString().replace("\"", "");
295                                         policyData.setServiceType(serviceType);
296                                 }
297                                 if (json.containsKey("uuid")){
298                                     String uuid = json.get("uuid").toString().replace("\"", "");
299                                     policyData.setUuid(uuid);
300                                 }
301                                 if (json.containsKey("location")){
302                                     String msLocation = json.get("location").toString().replace("\"", "");
303                                     policyData.setMsLocation(msLocation);
304                                 }
305                                 if (json.containsKey(CONFIG_NAME)){
306                                     String configName = json.get(CONFIG_NAME).toString().replace("\"", "");
307                                     policyData.setConfigName(configName);
308                                 }
309                                 if(json.containsKey("priority")){
310                                         String priority = json.get("priority").toString().replace("\"", "");
311                                         policyData.setPriority(priority);
312                                 }
313                                 if(json.containsKey("version")){
314                                         String version = json.get("version").toString().replace("\"", "");
315                                         policyData.setVersion(version);
316                                 }
317                                 if(json.containsKey("policyScope")){
318                                         String policyScope = json.get("policyScope").toString().replace("\"", "");
319                                         policyData.setPolicyScope(policyScope);
320                                 }
321                                 if(json.containsKey("riskType")){
322                                         String riskType = json.get("riskType").toString().replace("\"", "");
323                                         policyData.setRiskType(riskType);
324                                 }
325                                 if(json.containsKey("riskLevel")){
326                                         String riskLevel = json.get("riskLevel").toString().replace("\"", "");
327                                         policyData.setRiskLevel(riskLevel);
328                                 }
329                                 if(json.containsKey("guard")){
330                                         String guard = json.get("guard").toString().replace("\"", "");
331                                         policyData.setGuard(guard);
332                                 }
333                                 } else {
334                             String message = XACMLErrorConstants.ERROR_DATA_ISSUE+ " improper JSON object : " + parameters.getConfigBody();
335                             LOGGER.error(message);
336                             return null;                                
337                                 }
338                                 
339                         } else if("Fault".equals(parameters.getPolicyConfigType().toString())){
340                                 
341                                 policyData.setConfigPolicyType("ClosedLoop_Fault");
342                                 policyData.setApiflag("API");
343                                 
344                                 if(json != null){
345                                         policyData.setJsonBody(json.toString());
346                                 if (json.get("onapname")!=null){
347                                         String onapName = json.get("onapname").toString().replace("\"", "");
348                                         policyData.setOnapName(onapName);
349                                 }
350                                 }
351                                 
352                         } else if("PM".equals(parameters.getPolicyConfigType().toString())){
353                                 
354                                 policyData.setConfigPolicyType("ClosedLoop_PM");
355                                 
356                                 if(json != null){
357                                         policyData.setJsonBody(json.toString());
358                                 if (json.get("onapname")!=null){
359                                         String onapName = json.get("onapname").toString().replace("\"", "");
360                                         policyData.setOnapName(onapName);
361                                 }
362                                 if (json.get("serviceTypePolicyName")!=null){
363                                         String serviceType = json.get("serviceTypePolicyName").toString().replace("\"", "");
364                                                 LinkedHashMap<String, String> serviceTypePolicyName = new LinkedHashMap<>();
365                                                 serviceTypePolicyName.put("serviceTypePolicyName", serviceType);
366                                         policyData.setServiceTypePolicyName(serviceTypePolicyName);
367                                 }
368                                 }
369                         } else if("BRMS_Param".equals(parameters.getPolicyConfigType().toString())){
370                                 Map<AttributeType, Map<String, String>> drlRuleAndUIParams = parameters.getAttributes();
371                                 Map<String, String> rule = drlRuleAndUIParams.get(AttributeType.RULE);
372                                 policyData.setRuleName(rule.get("templateName"));
373                                 
374                         }
375                 }
376
377                 return policyData;
378                                 
379         }
380         
381     private JsonObject stringToJsonObject(String value) {
382
383         try(JsonReader jsonReader = Json.createReader(new StringReader(value))){
384                         return jsonReader.readObject();
385         } catch(JsonException| IllegalStateException e){
386             LOGGER.info(XACMLErrorConstants.ERROR_DATA_ISSUE+ "Improper JSON format... may or may not cause issues in validating the policy: " + value, e);
387             return null;
388         }
389     }
390     
391     private String convertDate(Date date) {
392         String strDate = null;
393         if (date!=null) {
394             SimpleDateFormat dateformatJava = new SimpleDateFormat("dd-MM-yyyy");
395             strDate = dateformatJava.format(date);
396         }
397         return (strDate==null) ? "NA": strDate;
398     }
399
400 }