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