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