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)) {
181 // Set Matching attributes in YAMLParams in adapter
182 YAMLParams yamlparams = new YAMLParams();
184 if (matching != null) {
185 yamlparams.setActor(matching.get("actor"));
186 yamlparams.setRecipe(matching.get("recipe"));
187 yamlparams.setGuardActiveStart(matching.get("guardActiveStart"));
188 yamlparams.setGuardActiveEnd(matching.get("guardActiveEnd"));
190 if("GUARD_YAML".equals(ruleProvider)){
191 yamlparams.setLimit(matching.get("limit"));
192 yamlparams.setTimeWindow(matching.get("timeWindow"));
193 yamlparams.setTimeUnits(matching.get("timeUnits"));
196 List<String> blackList = new ArrayList<>();
198 if(!Strings.isNullOrEmpty(matching.get("blackList"))){
199 String[] blackListArray = matching.get("blackList").split(",");
200 for(String element : blackListArray){
201 blackList.add(element);
205 yamlparams.setBlackList(blackList);
209 policyData.setYamlparams(yamlparams);
212 } else if("Action".equals(parameters.getPolicyClass().toString())){
214 ArrayList<Object> ruleAlgorithmChoices = new ArrayList<>();
216 List<String> dynamicLabelRuleAlgorithms = parameters.getDynamicRuleAlgorithmLabels();
217 List<String> dynamicFieldFunctionRuleAlgorithms = parameters.getDynamicRuleAlgorithmFunctions();
218 List<String> dynamicFieldOneRuleAlgorithms = parameters.getDynamicRuleAlgorithmField1();
219 List<String> dyrnamicFieldTwoRuleAlgorithms = parameters.getDynamicRuleAlgorithmField2();
221 if (dynamicLabelRuleAlgorithms != null && !dynamicLabelRuleAlgorithms.isEmpty()) {
222 int i = dynamicLabelRuleAlgorithms.size() - 1;
224 for (String labelAttr : dynamicLabelRuleAlgorithms) {
225 LinkedHashMap<String, String> ruleAlgorithm = new LinkedHashMap<>();
227 String id = dynamicLabelRuleAlgorithms.get(i);
228 String dynamicRuleAlgorithmField1 = dynamicFieldOneRuleAlgorithms.get(i);
229 String dynamicRuleAlgorithmCombo = dynamicFieldFunctionRuleAlgorithms.get(i);
230 String dynamicRuleAlgorithmField2 = dyrnamicFieldTwoRuleAlgorithms.get(i);
232 ruleAlgorithm.put("id", id);
233 ruleAlgorithm.put("dynamicRuleAlgorithmField1", dynamicRuleAlgorithmField1);
234 ruleAlgorithm.put("dynamicRuleAlgorithmCombo", dynamicRuleAlgorithmCombo);
235 ruleAlgorithm.put("dynamicRuleAlgorithmField2", dynamicRuleAlgorithmField2);
237 ruleAlgorithmChoices.add(ruleAlgorithm);
244 policyData.setRuleAlgorithmschoices(ruleAlgorithmChoices);
246 ArrayList<Object> attributeList = new ArrayList<>();
247 if (matching != null) {
248 for (Map.Entry<String, String> entry : matching.entrySet()) {
249 LinkedHashMap<String, String> attributeMap = new LinkedHashMap<>();
250 String key = entry.getKey();
251 String value = entry.getValue();
252 attributeMap.put("key", key);
253 attributeMap.put("value", value);
254 attributeList.add(attributeMap);
258 policyData.setAttributes(attributeList);
259 policyData.setActionAttributeValue(parameters.getActionAttribute());
260 policyData.setActionPerformer(parameters.getActionPerformer());
265 policyData.setPolicyType("Config");
266 policyData.setConfigPolicyType(parameters.getPolicyConfigType().toString());
269 policyData.setConfigBodyData(parameters.getConfigBody()); //Base
270 policyData.setConfigType((parameters.getConfigBodyType()!=null) ? parameters.getConfigBodyType().toString().toUpperCase(): null); //Base
272 if("FW".equalsIgnoreCase(parameters.getPolicyConfigType().toString())){
274 policyData.setConfigPolicyType("Firewall Config");
276 // get values and attributes from the JsonObject
278 if (json.get("securityZoneId")!=null){
279 String securityZone = json.get("securityZoneId").toString().replace("\"", "");
280 policyData.setSecurityZone(securityZone);
282 if (json.get(CONFIG_NAME)!=null){
283 String configName = json.get(CONFIG_NAME).toString().replace("\"", "");
284 policyData.setConfigName(configName);
288 }else if("MS".equals(parameters.getPolicyConfigType().toString())){
290 policyData.setConfigPolicyType("Micro Service");
292 // get values and attributes from the JsonObject
294 if (json.containsKey(CONTENT)){
295 String content = json.get(CONTENT).toString();
296 ObjectMapper mapper = new ObjectMapper();
297 JsonNode policyJSON = null;
299 policyJSON = mapper.readTree(content);
300 } catch (IOException e) {
301 String message = XACMLErrorConstants.ERROR_DATA_ISSUE+ INVALIDJSON + parameters.getConfigBody();
302 LOGGER.error(message, e);
305 policyData.setPolicyJSON(policyJSON);
307 if (json.containsKey(SERVICE)){
308 String serviceType = json.get(SERVICE).toString().replace("\"", "");
309 policyData.setServiceType(serviceType);
311 if (json.containsKey("uuid")){
312 String uuid = json.get("uuid").toString().replace("\"", "");
313 policyData.setUuid(uuid);
315 if (json.containsKey(LOCATION)){
316 String msLocation = json.get(LOCATION).toString().replace("\"", "");
317 policyData.setLocation(msLocation);
319 if (json.containsKey(CONFIG_NAME)){
320 String configName = json.get(CONFIG_NAME).toString().replace("\"", "");
321 policyData.setConfigName(configName);
323 if(json.containsKey(PRIORITY)){
324 String priority = json.get(PRIORITY).toString().replace("\"", "");
325 policyData.setPriority(priority);
327 if(json.containsKey(VERSION)){
328 String version = json.get(VERSION).toString().replace("\"", "");
329 policyData.setVersion(version);
331 if(json.containsKey(POLICYSCOPE)){
332 String policyScope = json.get(POLICYSCOPE).toString().replace("\"", "");
333 policyData.setPolicyScope(policyScope);
335 if(json.containsKey(RISKTYPE)){
336 String riskType = json.get(RISKTYPE).toString().replace("\"", "");
337 policyData.setRiskType(riskType);
339 if(json.containsKey(RISKLEVEL)){
340 String riskLevel = json.get(RISKLEVEL).toString().replace("\"", "");
341 policyData.setRiskLevel(riskLevel);
343 if(json.containsKey(GUARD)){
344 String guard = json.get(GUARD).toString().replace("\"", "");
345 policyData.setGuard(guard);
348 String message = XACMLErrorConstants.ERROR_DATA_ISSUE+ INVALIDJSON + parameters.getConfigBody();
349 LOGGER.error(message);
353 }else if("Optimization".equals(parameters.getPolicyConfigType().toString())){
355 policyData.setConfigPolicyType("Optimization");
357 // get values and attributes from the JsonObject
359 if (json.containsKey(CONTENT)){
360 String content = json.get(CONTENT).toString();
361 ObjectMapper mapper = new ObjectMapper();
362 JsonNode policyJSON = null;
364 policyJSON = mapper.readTree(content);
365 } catch (IOException e) {
366 String message = XACMLErrorConstants.ERROR_DATA_ISSUE+ INVALIDJSON + parameters.getConfigBody();
367 LOGGER.error(message, e);
370 policyData.setPolicyJSON(policyJSON);
372 if (json.containsKey(SERVICE)){
373 String serviceType = json.get(SERVICE).toString().replace("\"", "");
374 policyData.setServiceType(serviceType);
376 if (json.containsKey("uuid")){
377 String uuid = json.get("uuid").toString().replace("\"", "");
378 policyData.setUuid(uuid);
380 if (json.containsKey(LOCATION)){
381 String msLocation = json.get(LOCATION).toString().replace("\"", "");
382 policyData.setLocation(msLocation);
384 if (json.containsKey(CONFIG_NAME)){
385 String configName = json.get(CONFIG_NAME).toString().replace("\"", "");
386 policyData.setConfigName(configName);
388 if(json.containsKey(PRIORITY)){
389 String priority = json.get(PRIORITY).toString().replace("\"", "");
390 policyData.setPriority(priority);
392 if(json.containsKey(VERSION)){
393 String version = json.get(VERSION).toString().replace("\"", "");
394 policyData.setVersion(version);
396 if(json.containsKey(POLICYSCOPE)){
397 String policyScope = json.get(POLICYSCOPE).toString().replace("\"", "");
398 policyData.setPolicyScope(policyScope);
400 if(json.containsKey(RISKTYPE)){
401 String riskType = json.get(RISKTYPE).toString().replace("\"", "");
402 policyData.setRiskType(riskType);
404 if(json.containsKey(RISKLEVEL)){
405 String riskLevel = json.get(RISKLEVEL).toString().replace("\"", "");
406 policyData.setRiskLevel(riskLevel);
408 if(json.containsKey(GUARD)){
409 String guard = json.get(GUARD).toString().replace("\"", "");
410 policyData.setGuard(guard);
414 } else if("Fault".equals(parameters.getPolicyConfigType().toString())){
416 policyData.setConfigPolicyType("ClosedLoop_Fault");
419 policyData.setJsonBody(json.toString());
420 if (json.get(ONAPNAME)!=null){
421 String onapName = json.get(ONAPNAME).toString().replace("\"", "");
422 policyData.setOnapName(onapName);
426 } else if("PM".equals(parameters.getPolicyConfigType().toString())){
428 policyData.setConfigPolicyType("ClosedLoop_PM");
431 policyData.setJsonBody(json.toString());
432 if (json.get(ONAPNAME)!=null){
433 String onapName = json.get(ONAPNAME).toString().replace("\"", "");
434 policyData.setOnapName(onapName);
436 if (json.get(SERVICETYPE_POLICY_NAME)!=null){
437 String serviceType = json.get(SERVICETYPE_POLICY_NAME).toString().replace("\"", "");
438 LinkedHashMap<String, String> serviceTypePolicyName = new LinkedHashMap<>();
439 serviceTypePolicyName.put(SERVICETYPE_POLICY_NAME, serviceType);
440 policyData.setServiceTypePolicyName(serviceTypePolicyName);
443 } else if("BRMS_Param".equals(parameters.getPolicyConfigType().toString())){
444 Map<AttributeType, Map<String, String>> drlRuleAndUIParams = parameters.getAttributes();
445 Map<String, String> rule = drlRuleAndUIParams.get(AttributeType.RULE);
446 policyData.setRuleName(rule.get("templateName"));
455 private JsonObject stringToJsonObject(String value) {
456 try(JsonReader jsonReader = Json.createReader(new StringReader(value))){
457 return jsonReader.readObject();
458 } catch(JsonException| IllegalStateException e){
459 LOGGER.info(XACMLErrorConstants.ERROR_DATA_ISSUE+ "Improper JSON format... may or may not cause issues in validating the policy: " + value, e);
464 private String convertDate(Date date) {
465 String strDate = null;
467 SimpleDateFormat dateformatJava = new SimpleDateFormat("dd-MM-yyyy");
468 strDate = dateformatJava.format(date);
470 return (strDate==null) ? "NA": strDate;