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