2 * ============LICENSE_START=======================================================
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
11 * http://www.apache.org/licenses/LICENSE-2.0
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;
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;
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;
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;
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;
51 public class PolicyValidationRequestWrapper {
53 private static final Logger LOGGER = FlexLogger.getLogger(PolicyValidationRequestWrapper.class);
54 public static final String CONFIG_NAME="configName";
55 public static final String INVALIDJSON = " improper JSON format: ";
56 public static final String ONAPNAME = "onapname";
57 public static final String CONTENT = "content";
58 public static final String GUARD = "guard";
59 public static final String LOCATION = "location";
60 public static final String POLICYSCOPE = "policyScope";
61 public static final String PRIORITY = "priority";
62 public static final String RISKLEVEL = "riskLevel";
63 public static final String RISKTYPE = "riskType";
64 public static final String SERVICE = "service";
65 public static final String VERSION = "version";
67 public static final String SERVICETYPE_POLICY_NAME = "serviceTypePolicyName";
69 public PolicyRestAdapter populateRequestParameters(HttpServletRequest request) {
71 PolicyRestAdapter policyData = null;
72 ClosedLoopFaultTrapDatas trapDatas = null;
73 ClosedLoopFaultTrapDatas faultDatas = null;
75 ObjectMapper mapper = new ObjectMapper();
76 mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
77 JsonNode root = mapper.readTree(request.getReader());
78 policyData = mapper.readValue(root.get("policyData").toString(), PolicyRestAdapter.class);
79 if(root.get("trapData") != null){
80 trapDatas = mapper.readValue(root.get("trapData").toString(), ClosedLoopFaultTrapDatas.class);
81 policyData.setTrapDatas(trapDatas);
83 if(root.get("faultData") != null){
84 faultDatas = mapper.readValue(root.get("faultData").toString(), ClosedLoopFaultTrapDatas.class);
85 policyData.setFaultDatas(faultDatas);
89 json = stringToJsonObject(root.toString());
92 if(json.containsKey("policyJSON")){
93 policyData.setPolicyJSON(root.get("policyJSON"));
95 String jsonBodyData = json.getJsonObject("policyData").get("jsonBodyData").toString();
96 policyData.setJsonBody(jsonBodyData);
100 } catch (Exception e) {
101 LOGGER.error("Exception Occured while populating request parameters: " +e);
107 public PolicyRestAdapter populateRequestParameters(PolicyParameters parameters) {
109 PolicyRestAdapter policyData = new PolicyRestAdapter();
112 * set policy adapter values for Building JSON object containing policy data
114 //Common Policy Fields
115 policyData.setPolicyName(parameters.getPolicyName());
116 policyData.setOnapName(parameters.getOnapName());
117 policyData.setPriority(parameters.getPriority()); //Micro Service
118 policyData.setConfigName(parameters.getConfigName()); //Base and Firewall
119 policyData.setRiskType(parameters.getRiskType()); //Safe parameters Attributes
120 policyData.setRiskLevel(parameters.getRiskLevel());//Safe parameters Attributes
121 policyData.setGuard(String.valueOf(parameters.getGuard()));//Safe parameters Attributes
122 policyData.setTtlDate(convertDate(parameters.getTtlDate()));//Safe parameters Attributes
123 policyData.setApiflag("API");
125 //Some policies require jsonObject conversion from String for configBody (i.e. MicroService and Firewall)
126 JsonObject json = null;
128 if(parameters.getConfigBody()!= null){
129 json = stringToJsonObject(parameters.getConfigBody());
131 } catch(JsonException| IllegalStateException e){
132 String message = XACMLErrorConstants.ERROR_DATA_ISSUE+ INVALIDJSON + parameters.getConfigBody();
133 LOGGER.error(message, e);
137 if(parameters.getPolicyClass()!=null && !"Config".equals(parameters.getPolicyClass().toString())){
139 policyData.setPolicyType(parameters.getPolicyClass().toString());
141 //Get Matching attribute values
142 Map<AttributeType, Map<String, String>> attributes = parameters.getAttributes();
143 Map<String, String> matching = null;
144 if(attributes != null){
145 matching = attributes.get(AttributeType.MATCHING);
148 if("Decision".equals(parameters.getPolicyClass().toString())){
150 String ruleProvider = parameters.getRuleProvider().toString();
151 policyData.setRuleProvider(ruleProvider);
153 if("Rainy_Day".equals(ruleProvider)){
155 // Set Matching attributes in RainyDayParams in adapter
156 RainyDayParams rainyday = new RainyDayParams();
158 if(matching != null) {
159 rainyday.setServiceType(matching.get("ServiceType"));
160 rainyday.setVnfType(matching.get("VNFType"));
161 rainyday.setBbid(matching.get("BB_ID"));
162 rainyday.setWorkstep(matching.get("WorkStep"));
165 Map<String, String> treatments = parameters.getTreatments();
166 ArrayList<Object> treatmentsTableChoices = new ArrayList<>();
168 for (String keyField : treatments.keySet()) {
169 LinkedHashMap<String, String> treatmentMap = new LinkedHashMap<>();
170 String errorcode = keyField;
171 String treatment = treatments.get(errorcode);
172 treatmentMap.put("errorcode", errorcode);
173 treatmentMap.put("treatment", treatment);
174 treatmentsTableChoices.add(treatmentMap);
176 rainyday.setTreatmentTableChoices(treatmentsTableChoices);
177 policyData.setRainyday(rainyday);
179 } else if ("GUARD_YAML".equals(ruleProvider) || "GUARD_BL_YAML".equals(ruleProvider)
180 || "GUARD_MIN_MAX".equals(ruleProvider)) {
182 // Set Matching attributes in YAMLParams in adapter
183 YAMLParams yamlparams = new YAMLParams();
185 if (matching != null) {
186 yamlparams.setActor(matching.get("actor"));
187 yamlparams.setRecipe(matching.get("recipe"));
188 yamlparams.setGuardActiveStart(matching.get("guardActiveStart"));
189 yamlparams.setGuardActiveEnd(matching.get("guardActiveEnd"));
191 if("GUARD_YAML".equals(ruleProvider)){
192 yamlparams.setLimit(matching.get("limit"));
193 yamlparams.setTimeWindow(matching.get("timeWindow"));
194 yamlparams.setTimeUnits(matching.get("timeUnits"));
195 } else if ("GUARD_MIN_MAX".equals(ruleProvider)) {
196 yamlparams.setMin(matching.get("min"));
197 yamlparams.setMax(matching.get("max"));
200 List<String> blackList = new ArrayList<>();
202 if(!Strings.isNullOrEmpty(matching.get("blackList"))){
203 String[] blackListArray = matching.get("blackList").split(",");
204 for(String element : blackListArray){
205 blackList.add(element);
209 yamlparams.setBlackList(blackList);
213 policyData.setYamlparams(yamlparams);
216 } else if("Action".equals(parameters.getPolicyClass().toString())){
218 ArrayList<Object> ruleAlgorithmChoices = new ArrayList<>();
220 List<String> dynamicLabelRuleAlgorithms = parameters.getDynamicRuleAlgorithmLabels();
221 List<String> dynamicFieldFunctionRuleAlgorithms = parameters.getDynamicRuleAlgorithmFunctions();
222 List<String> dynamicFieldOneRuleAlgorithms = parameters.getDynamicRuleAlgorithmField1();
223 List<String> dyrnamicFieldTwoRuleAlgorithms = parameters.getDynamicRuleAlgorithmField2();
225 if (dynamicLabelRuleAlgorithms != null && !dynamicLabelRuleAlgorithms.isEmpty()) {
226 int i = dynamicLabelRuleAlgorithms.size() - 1;
228 for (String labelAttr : dynamicLabelRuleAlgorithms) {
229 LinkedHashMap<String, String> ruleAlgorithm = new LinkedHashMap<>();
231 String id = dynamicLabelRuleAlgorithms.get(i);
232 String dynamicRuleAlgorithmField1 = dynamicFieldOneRuleAlgorithms.get(i);
233 String dynamicRuleAlgorithmCombo = dynamicFieldFunctionRuleAlgorithms.get(i);
234 String dynamicRuleAlgorithmField2 = dyrnamicFieldTwoRuleAlgorithms.get(i);
236 ruleAlgorithm.put("id", id);
237 ruleAlgorithm.put("dynamicRuleAlgorithmField1", dynamicRuleAlgorithmField1);
238 ruleAlgorithm.put("dynamicRuleAlgorithmCombo", dynamicRuleAlgorithmCombo);
239 ruleAlgorithm.put("dynamicRuleAlgorithmField2", dynamicRuleAlgorithmField2);
241 ruleAlgorithmChoices.add(ruleAlgorithm);
248 policyData.setRuleAlgorithmschoices(ruleAlgorithmChoices);
250 ArrayList<Object> attributeList = new ArrayList<>();
251 if (matching != null) {
252 for (Map.Entry<String, String> entry : matching.entrySet()) {
253 LinkedHashMap<String, String> attributeMap = new LinkedHashMap<>();
254 String key = entry.getKey();
255 String value = entry.getValue();
256 attributeMap.put("key", key);
257 attributeMap.put("value", value);
258 attributeList.add(attributeMap);
262 policyData.setAttributes(attributeList);
263 policyData.setActionAttributeValue(parameters.getActionAttribute());
264 policyData.setActionPerformer(parameters.getActionPerformer());
269 policyData.setPolicyType("Config");
270 policyData.setConfigPolicyType(parameters.getPolicyConfigType().toString());
273 policyData.setConfigBodyData(parameters.getConfigBody()); //Base
274 policyData.setConfigType((parameters.getConfigBodyType()!=null) ? parameters.getConfigBodyType().toString().toUpperCase(): null); //Base
276 if("FW".equalsIgnoreCase(parameters.getPolicyConfigType().toString())){
278 policyData.setConfigPolicyType("Firewall Config");
280 // get values and attributes from the JsonObject
282 if (json.get("securityZoneId")!=null){
283 String securityZone = json.get("securityZoneId").toString().replace("\"", "");
284 policyData.setSecurityZone(securityZone);
286 if (json.get(CONFIG_NAME)!=null){
287 String configName = json.get(CONFIG_NAME).toString().replace("\"", "");
288 policyData.setConfigName(configName);
292 }else if("MS".equals(parameters.getPolicyConfigType().toString())){
294 policyData.setConfigPolicyType("Micro Service");
296 // get values and attributes from the JsonObject
298 if (json.containsKey(CONTENT)){
299 String content = json.get(CONTENT).toString();
300 ObjectMapper mapper = new ObjectMapper();
301 JsonNode policyJSON = null;
303 policyJSON = mapper.readTree(content);
304 } catch (IOException e) {
305 String message = XACMLErrorConstants.ERROR_DATA_ISSUE+ INVALIDJSON + parameters.getConfigBody();
306 LOGGER.error(message, e);
309 policyData.setPolicyJSON(policyJSON);
311 if (json.containsKey(SERVICE)){
312 String serviceType = json.get(SERVICE).toString().replace("\"", "");
313 policyData.setServiceType(serviceType);
315 if (json.containsKey("uuid")){
316 String uuid = json.get("uuid").toString().replace("\"", "");
317 policyData.setUuid(uuid);
319 if (json.containsKey(LOCATION)){
320 String msLocation = json.get(LOCATION).toString().replace("\"", "");
321 policyData.setLocation(msLocation);
323 if (json.containsKey(CONFIG_NAME)){
324 String configName = json.get(CONFIG_NAME).toString().replace("\"", "");
325 policyData.setConfigName(configName);
327 if(json.containsKey(PRIORITY)){
328 String priority = json.get(PRIORITY).toString().replace("\"", "");
329 policyData.setPriority(priority);
331 if(json.containsKey(VERSION)){
332 String version = json.get(VERSION).toString().replace("\"", "");
333 policyData.setVersion(version);
335 if(json.containsKey(POLICYSCOPE)){
336 String policyScope = json.get(POLICYSCOPE).toString().replace("\"", "");
337 policyData.setPolicyScope(policyScope);
339 if(json.containsKey(RISKTYPE)){
340 String riskType = json.get(RISKTYPE).toString().replace("\"", "");
341 policyData.setRiskType(riskType);
343 if(json.containsKey(RISKLEVEL)){
344 String riskLevel = json.get(RISKLEVEL).toString().replace("\"", "");
345 policyData.setRiskLevel(riskLevel);
347 if(json.containsKey(GUARD)){
348 String guard = json.get(GUARD).toString().replace("\"", "");
349 policyData.setGuard(guard);
352 String message = XACMLErrorConstants.ERROR_DATA_ISSUE+ INVALIDJSON + parameters.getConfigBody();
353 LOGGER.error(message);
357 }else if("Optimization".equals(parameters.getPolicyConfigType().toString())){
359 policyData.setConfigPolicyType("Optimization");
361 // get values and attributes from the JsonObject
363 if (json.containsKey(CONTENT)){
364 String content = json.get(CONTENT).toString();
365 ObjectMapper mapper = new ObjectMapper();
366 JsonNode policyJSON = null;
368 policyJSON = mapper.readTree(content);
369 } catch (IOException e) {
370 String message = XACMLErrorConstants.ERROR_DATA_ISSUE+ INVALIDJSON + parameters.getConfigBody();
371 LOGGER.error(message, e);
374 policyData.setPolicyJSON(policyJSON);
376 if (json.containsKey(SERVICE)){
377 String serviceType = json.get(SERVICE).toString().replace("\"", "");
378 policyData.setServiceType(serviceType);
380 if (json.containsKey("uuid")){
381 String uuid = json.get("uuid").toString().replace("\"", "");
382 policyData.setUuid(uuid);
384 if (json.containsKey(LOCATION)){
385 String msLocation = json.get(LOCATION).toString().replace("\"", "");
386 policyData.setLocation(msLocation);
388 if (json.containsKey(CONFIG_NAME)){
389 String configName = json.get(CONFIG_NAME).toString().replace("\"", "");
390 policyData.setConfigName(configName);
392 if(json.containsKey(PRIORITY)){
393 String priority = json.get(PRIORITY).toString().replace("\"", "");
394 policyData.setPriority(priority);
396 if(json.containsKey(VERSION)){
397 String version = json.get(VERSION).toString().replace("\"", "");
398 policyData.setVersion(version);
400 if(json.containsKey(POLICYSCOPE)){
401 String policyScope = json.get(POLICYSCOPE).toString().replace("\"", "");
402 policyData.setPolicyScope(policyScope);
404 if(json.containsKey(RISKTYPE)){
405 String riskType = json.get(RISKTYPE).toString().replace("\"", "");
406 policyData.setRiskType(riskType);
408 if(json.containsKey(RISKLEVEL)){
409 String riskLevel = json.get(RISKLEVEL).toString().replace("\"", "");
410 policyData.setRiskLevel(riskLevel);
412 if(json.containsKey(GUARD)){
413 String guard = json.get(GUARD).toString().replace("\"", "");
414 policyData.setGuard(guard);
418 } else if("Fault".equals(parameters.getPolicyConfigType().toString())){
420 policyData.setConfigPolicyType("ClosedLoop_Fault");
423 policyData.setJsonBody(json.toString());
424 if (json.get(ONAPNAME)!=null){
425 String onapName = json.get(ONAPNAME).toString().replace("\"", "");
426 policyData.setOnapName(onapName);
430 } else if("PM".equals(parameters.getPolicyConfigType().toString())){
432 policyData.setConfigPolicyType("ClosedLoop_PM");
435 policyData.setJsonBody(json.toString());
436 if (json.get(ONAPNAME)!=null){
437 String onapName = json.get(ONAPNAME).toString().replace("\"", "");
438 policyData.setOnapName(onapName);
440 if (json.get(SERVICETYPE_POLICY_NAME)!=null){
441 String serviceType = json.get(SERVICETYPE_POLICY_NAME).toString().replace("\"", "");
442 LinkedHashMap<String, String> serviceTypePolicyName = new LinkedHashMap<>();
443 serviceTypePolicyName.put(SERVICETYPE_POLICY_NAME, serviceType);
444 policyData.setServiceTypePolicyName(serviceTypePolicyName);
447 } else if("BRMS_Param".equals(parameters.getPolicyConfigType().toString())){
448 Map<AttributeType, Map<String, String>> drlRuleAndUIParams = parameters.getAttributes();
449 Map<String, String> rule = drlRuleAndUIParams.get(AttributeType.RULE);
450 policyData.setRuleName(rule.get("templateName"));
459 private JsonObject stringToJsonObject(String value) {
460 try(JsonReader jsonReader = Json.createReader(new StringReader(value))){
461 return jsonReader.readObject();
462 } catch(JsonException| IllegalStateException e){
463 LOGGER.info(XACMLErrorConstants.ERROR_DATA_ISSUE+ "Improper JSON format... may or may not cause issues in validating the policy: " + value, e);
468 private String convertDate(Date date) {
469 String strDate = null;
471 SimpleDateFormat dateformatJava = new SimpleDateFormat("dd-MM-yyyy");
472 strDate = dateformatJava.format(date);
474 return (strDate==null) ? "NA": strDate;