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 SERVICETYPE_POLICY_NAME = "serviceTypePolicyName";
59 public PolicyRestAdapter populateRequestParameters(HttpServletRequest request) {
61 PolicyRestAdapter policyData = null;
62 ClosedLoopFaultTrapDatas trapDatas = null;
63 ClosedLoopFaultTrapDatas faultDatas = null;
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);
73 if(root.get("faultData") != null){
74 faultDatas = mapper.readValue(root.get("faultData").toString(), ClosedLoopFaultTrapDatas.class);
75 policyData.setFaultDatas(faultDatas);
79 json = stringToJsonObject(root.toString());
82 if(json.containsKey("policyJSON")){
83 policyData.setPolicyJSON(root.get("policyJSON"));
85 String jsonBodyData = json.getJsonObject("policyData").get("jsonBodyData").toString();
86 policyData.setJsonBody(jsonBodyData);
90 } catch (Exception e) {
91 LOGGER.error("Exception Occured while populating request parameters: " +e);
97 public PolicyRestAdapter populateRequestParameters(PolicyParameters parameters) {
99 PolicyRestAdapter policyData = new PolicyRestAdapter();
102 * set policy adapter values for Building JSON object containing policy data
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");
115 //Some policies require jsonObject conversion from String for configBody (i.e. MicroService and Firewall)
116 JsonObject json = null;
118 if(parameters.getConfigBody()!= null){
119 json = stringToJsonObject(parameters.getConfigBody());
121 } catch(JsonException| IllegalStateException e){
122 String message = XACMLErrorConstants.ERROR_DATA_ISSUE+ INVALIDJSON + parameters.getConfigBody();
123 LOGGER.error(message, e);
127 if(parameters.getPolicyClass()!=null && !"Config".equals(parameters.getPolicyClass().toString())){
129 policyData.setPolicyType(parameters.getPolicyClass().toString());
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);
138 if("Decision".equals(parameters.getPolicyClass().toString())){
140 String ruleProvider = parameters.getRuleProvider().toString();
141 policyData.setRuleProvider(ruleProvider);
143 if("Rainy_Day".equals(ruleProvider)){
145 // Set Matching attributes in RainyDayParams in adapter
146 RainyDayParams rainyday = new RainyDayParams();
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"));
155 Map<String, String> treatments = parameters.getTreatments();
156 ArrayList<Object> treatmentsTableChoices = new ArrayList<>();
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);
166 rainyday.setTreatmentTableChoices(treatmentsTableChoices);
167 policyData.setRainyday(rainyday);
169 }else if("GUARD_YAML".equals(ruleProvider) || "GUARD_BL_YAML".equals(ruleProvider)) {
171 // Set Matching attributes in YAMLParams in adapter
172 YAMLParams yamlparams = new YAMLParams();
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"));
180 if("GUARD_YAML".equals(ruleProvider)){
181 yamlparams.setLimit(matching.get("limit"));
182 yamlparams.setTimeWindow(matching.get("timeWindow"));
183 yamlparams.setTimeUnits(matching.get("timeUnits"));
186 List<String> blackList = new ArrayList<>();
188 if(!Strings.isNullOrEmpty(matching.get("blackList"))){
189 String[] blackListArray = matching.get("blackList").split(",");
190 for(String element : blackListArray){
191 blackList.add(element);
195 yamlparams.setBlackList(blackList);
199 policyData.setYamlparams(yamlparams);
202 } else if("Action".equals(parameters.getPolicyClass().toString())){
204 ArrayList<Object> ruleAlgorithmChoices = new ArrayList<>();
206 List<String> dynamicLabelRuleAlgorithms = parameters.getDynamicRuleAlgorithmLabels();
207 List<String> dynamicFieldFunctionRuleAlgorithms = parameters.getDynamicRuleAlgorithmFunctions();
208 List<String> dynamicFieldOneRuleAlgorithms = parameters.getDynamicRuleAlgorithmField1();
209 List<String> dyrnamicFieldTwoRuleAlgorithms = parameters.getDynamicRuleAlgorithmField2();
211 if (dynamicLabelRuleAlgorithms != null && !dynamicLabelRuleAlgorithms.isEmpty()) {
212 int i = dynamicLabelRuleAlgorithms.size() - 1;
214 for (String labelAttr : dynamicLabelRuleAlgorithms) {
215 LinkedHashMap<String, String> ruleAlgorithm = new LinkedHashMap<>();
217 String id = dynamicLabelRuleAlgorithms.get(i);
218 String dynamicRuleAlgorithmField1 = dynamicFieldOneRuleAlgorithms.get(i);
219 String dynamicRuleAlgorithmCombo = dynamicFieldFunctionRuleAlgorithms.get(i);
220 String dynamicRuleAlgorithmField2 = dyrnamicFieldTwoRuleAlgorithms.get(i);
222 ruleAlgorithm.put("id", id);
223 ruleAlgorithm.put("dynamicRuleAlgorithmField1", dynamicRuleAlgorithmField1);
224 ruleAlgorithm.put("dynamicRuleAlgorithmCombo", dynamicRuleAlgorithmCombo);
225 ruleAlgorithm.put("dynamicRuleAlgorithmField2", dynamicRuleAlgorithmField2);
227 ruleAlgorithmChoices.add(ruleAlgorithm);
234 policyData.setRuleAlgorithmschoices(ruleAlgorithmChoices);
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);
248 policyData.setAttributes(attributeList);
249 policyData.setActionAttributeValue(parameters.getActionAttribute());
250 policyData.setActionPerformer(parameters.getActionPerformer());
255 policyData.setPolicyType("Config");
256 policyData.setConfigPolicyType(parameters.getPolicyConfigType().toString());
259 policyData.setConfigBodyData(parameters.getConfigBody()); //Base
260 policyData.setConfigType((parameters.getConfigBodyType()!=null) ? parameters.getConfigBodyType().toString().toUpperCase(): null); //Base
262 if("FW".equalsIgnoreCase(parameters.getPolicyConfigType().toString())){
264 policyData.setConfigPolicyType("Firewall Config");
266 // get values and attributes from the JsonObject
268 if (json.get("securityZoneId")!=null){
269 String securityZone = json.get("securityZoneId").toString().replace("\"", "");
270 policyData.setSecurityZone(securityZone);
272 if (json.get(CONFIG_NAME)!=null){
273 String configName = json.get(CONFIG_NAME).toString().replace("\"", "");
274 policyData.setConfigName(configName);
278 }else if("MS".equals(parameters.getPolicyConfigType().toString())){
280 policyData.setConfigPolicyType("Micro Service");
282 // get values and attributes from the JsonObject
284 if (json.containsKey("content")){
285 String content = json.get("content").toString();
286 ObjectMapper mapper = new ObjectMapper();
287 JsonNode policyJSON = null;
289 policyJSON = mapper.readTree(content);
290 } catch (IOException e) {
291 String message = XACMLErrorConstants.ERROR_DATA_ISSUE+ INVALIDJSON + parameters.getConfigBody();
292 LOGGER.error(message, e);
295 policyData.setPolicyJSON(policyJSON);
297 if (json.containsKey("service")){
298 String serviceType = json.get("service").toString().replace("\"", "");
299 policyData.setServiceType(serviceType);
301 if (json.containsKey("uuid")){
302 String uuid = json.get("uuid").toString().replace("\"", "");
303 policyData.setUuid(uuid);
305 if (json.containsKey("location")){
306 String msLocation = json.get("location").toString().replace("\"", "");
307 policyData.setLocation(msLocation);
309 if (json.containsKey(CONFIG_NAME)){
310 String configName = json.get(CONFIG_NAME).toString().replace("\"", "");
311 policyData.setConfigName(configName);
313 if(json.containsKey("priority")){
314 String priority = json.get("priority").toString().replace("\"", "");
315 policyData.setPriority(priority);
317 if(json.containsKey("version")){
318 String version = json.get("version").toString().replace("\"", "");
319 policyData.setVersion(version);
321 if(json.containsKey("policyScope")){
322 String policyScope = json.get("policyScope").toString().replace("\"", "");
323 policyData.setPolicyScope(policyScope);
325 if(json.containsKey("riskType")){
326 String riskType = json.get("riskType").toString().replace("\"", "");
327 policyData.setRiskType(riskType);
329 if(json.containsKey("riskLevel")){
330 String riskLevel = json.get("riskLevel").toString().replace("\"", "");
331 policyData.setRiskLevel(riskLevel);
333 if(json.containsKey("guard")){
334 String guard = json.get("guard").toString().replace("\"", "");
335 policyData.setGuard(guard);
338 String message = XACMLErrorConstants.ERROR_DATA_ISSUE+ INVALIDJSON + parameters.getConfigBody();
339 LOGGER.error(message);
343 } else if("Fault".equals(parameters.getPolicyConfigType().toString())){
345 policyData.setConfigPolicyType("ClosedLoop_Fault");
348 policyData.setJsonBody(json.toString());
349 if (json.get(ONAPNAME)!=null){
350 String onapName = json.get(ONAPNAME).toString().replace("\"", "");
351 policyData.setOnapName(onapName);
355 } else if("PM".equals(parameters.getPolicyConfigType().toString())){
357 policyData.setConfigPolicyType("ClosedLoop_PM");
360 policyData.setJsonBody(json.toString());
361 if (json.get(ONAPNAME)!=null){
362 String onapName = json.get(ONAPNAME).toString().replace("\"", "");
363 policyData.setOnapName(onapName);
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);
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"));
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);
393 private String convertDate(Date date) {
394 String strDate = null;
396 SimpleDateFormat dateformatJava = new SimpleDateFormat("dd-MM-yyyy");
397 strDate = dateformatJava.format(date);
399 return (strDate==null) ? "NA": strDate;