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";
56 public PolicyRestAdapter populateRequestParameters(HttpServletRequest request) {
58 PolicyRestAdapter policyData = null;
59 ClosedLoopFaultTrapDatas trapDatas = null;
60 ClosedLoopFaultTrapDatas faultDatas = null;
62 ObjectMapper mapper = new ObjectMapper();
63 mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
64 JsonNode root = mapper.readTree(request.getReader());
65 policyData = mapper.readValue(root.get("policyData").toString(), PolicyRestAdapter.class);
66 if(root.get("trapData") != null){
67 trapDatas = mapper.readValue(root.get("trapData").toString(), ClosedLoopFaultTrapDatas.class);
68 policyData.setTrapDatas(trapDatas);
70 if(root.get("faultData") != null){
71 faultDatas = mapper.readValue(root.get("faultData").toString(), ClosedLoopFaultTrapDatas.class);
72 policyData.setFaultDatas(faultDatas);
76 json = stringToJsonObject(root.toString());
79 if(json.containsKey("policyJSON")){
80 policyData.setPolicyJSON(root.get("policyJSON"));
82 String jsonBodyData = json.getJsonObject("policyData").get("jsonBodyData").toString();
83 policyData.setJsonBody(jsonBodyData);
87 } catch (Exception e) {
88 LOGGER.error("Exception Occured while populating request parameters: " +e);
94 public PolicyRestAdapter populateRequestParameters(PolicyParameters parameters) {
96 PolicyRestAdapter policyData = new PolicyRestAdapter();
99 * set policy adapter values for Building JSON object containing policy data
101 //Common Policy Fields
102 policyData.setPolicyName(parameters.getPolicyName());
103 policyData.setOnapName(parameters.getOnapName());
104 policyData.setPriority(parameters.getPriority()); //Micro Service
105 policyData.setConfigName(parameters.getConfigName()); //Base and Firewall
106 policyData.setRiskType(parameters.getRiskType()); //Safe parameters Attributes
107 policyData.setRiskLevel(parameters.getRiskLevel());//Safe parameters Attributes
108 policyData.setGuard(String.valueOf(parameters.getGuard()));//Safe parameters Attributes
109 policyData.setTtlDate(convertDate(parameters.getTtlDate()));//Safe parameters Attributes
111 //Some policies require jsonObject conversion from String for configBody (i.e. MicroService and Firewall)
112 JsonObject json = null;
114 if(parameters.getConfigBody()!= null){
115 json = stringToJsonObject(parameters.getConfigBody());
117 } catch(JsonException| IllegalStateException e){
118 String message = XACMLErrorConstants.ERROR_DATA_ISSUE+ " improper JSON object : " + parameters.getConfigBody();
119 LOGGER.error(message, e);
123 if(parameters.getPolicyClass()!=null && !"Config".equals(parameters.getPolicyClass().toString())){
125 policyData.setPolicyType(parameters.getPolicyClass().toString());
127 //Get Matching attribute values
128 Map<AttributeType, Map<String, String>> attributes = parameters.getAttributes();
129 Map<String, String> matching = null;
130 if(attributes != null){
131 matching = attributes.get(AttributeType.MATCHING);
134 if("Decision".equals(parameters.getPolicyClass().toString())){
136 String ruleProvider = parameters.getRuleProvider().toString();
137 policyData.setRuleProvider(ruleProvider);
139 if("Rainy_Day".equals(ruleProvider)){
141 // Set Matching attributes in RainyDayParams in adapter
142 RainyDayParams rainyday = new RainyDayParams();
144 if(matching != null) {
145 rainyday.setServiceType(matching.get("ServiceType"));
146 rainyday.setVnfType(matching.get("VNFType"));
147 rainyday.setBbid(matching.get("BB_ID"));
148 rainyday.setWorkstep(matching.get("WorkStep"));
151 Map<String, String> treatments = parameters.getTreatments();
152 ArrayList<Object> treatmentsTableChoices = new ArrayList<>();
154 for (String keyField : treatments.keySet()) {
155 LinkedHashMap<String, String> treatmentMap = new LinkedHashMap<>();
156 String errorcode = keyField;
157 String treatment = treatments.get(errorcode);
158 treatmentMap.put("errorcode", errorcode);
159 treatmentMap.put("treatment", treatment);
160 treatmentsTableChoices.add(treatmentMap);
162 rainyday.setTreatmentTableChoices(treatmentsTableChoices);
163 policyData.setRainyday(rainyday);
165 }else if("GUARD_YAML".equals(ruleProvider) || "GUARD_BL_YAML".equals(ruleProvider)) {
167 // Set Matching attributes in YAMLParams in adapter
168 YAMLParams yamlparams = new YAMLParams();
170 if (matching != null) {
171 yamlparams.setActor(matching.get("actor"));
172 yamlparams.setRecipe(matching.get("recipe"));
173 yamlparams.setGuardActiveStart(matching.get("guardActiveStart"));
174 yamlparams.setGuardActiveEnd(matching.get("guardActiveEnd"));
176 if("GUARD_YAML".equals(ruleProvider)){
177 yamlparams.setLimit(matching.get("limit"));
178 yamlparams.setTimeWindow(matching.get("timeWindow"));
179 yamlparams.setTimeUnits(matching.get("timeUnits"));
182 List<String> blackList = new ArrayList<>();
184 if(!Strings.isNullOrEmpty(matching.get("blackList"))){
185 String[] blackListArray = matching.get("blackList").split(",");
186 for(String element : blackListArray){
187 blackList.add(element);
191 yamlparams.setBlackList(blackList);
195 policyData.setYamlparams(yamlparams);
198 } else if("Action".equals(parameters.getPolicyClass().toString())){
200 ArrayList<Object> ruleAlgorithmChoices = new ArrayList<>();
202 List<String> dynamicLabelRuleAlgorithms = parameters.getDynamicRuleAlgorithmLabels();
203 List<String> dynamicFieldFunctionRuleAlgorithms = parameters.getDynamicRuleAlgorithmFunctions();
204 List<String> dynamicFieldOneRuleAlgorithms = parameters.getDynamicRuleAlgorithmField1();
205 List<String> dyrnamicFieldTwoRuleAlgorithms = parameters.getDynamicRuleAlgorithmField2();
207 if (dynamicLabelRuleAlgorithms != null && !dynamicLabelRuleAlgorithms.isEmpty()) {
208 int i = dynamicLabelRuleAlgorithms.size() - 1;
210 for (String labelAttr : dynamicLabelRuleAlgorithms) {
211 LinkedHashMap<String, String> ruleAlgorithm = new LinkedHashMap<>();
213 String id = dynamicLabelRuleAlgorithms.get(i);
214 String dynamicRuleAlgorithmField1 = dynamicFieldOneRuleAlgorithms.get(i);
215 String dynamicRuleAlgorithmCombo = dynamicFieldFunctionRuleAlgorithms.get(i);
216 String dynamicRuleAlgorithmField2 = dyrnamicFieldTwoRuleAlgorithms.get(i);
218 ruleAlgorithm.put("id", id);
219 ruleAlgorithm.put("dynamicRuleAlgorithmField1", dynamicRuleAlgorithmField1);
220 ruleAlgorithm.put("dynamicRuleAlgorithmCombo", dynamicRuleAlgorithmCombo);
221 ruleAlgorithm.put("dynamicRuleAlgorithmField2", dynamicRuleAlgorithmField2);
223 ruleAlgorithmChoices.add(ruleAlgorithm);
230 policyData.setRuleAlgorithmschoices(ruleAlgorithmChoices);
232 ArrayList<Object> attributeList = new ArrayList<>();
233 if (matching != null) {
234 for (Map.Entry<String, String> entry : matching.entrySet()) {
235 LinkedHashMap<String, String> attributeMap = new LinkedHashMap<>();
236 String key = entry.getKey();
237 String value = entry.getValue();
238 attributeMap.put("key", key);
239 attributeMap.put("value", value);
240 attributeList.add(attributeMap);
244 policyData.setAttributes(attributeList);
245 policyData.setActionAttributeValue(parameters.getActionAttribute());
246 policyData.setActionPerformer(parameters.getActionPerformer());
251 policyData.setPolicyType("Config");
252 policyData.setConfigPolicyType(parameters.getPolicyConfigType().toString());
255 policyData.setConfigBodyData(parameters.getConfigBody()); //Base
256 policyData.setConfigType((parameters.getConfigBodyType()!=null) ? parameters.getConfigBodyType().toString().toUpperCase(): null); //Base
258 if("FW".equalsIgnoreCase(parameters.getPolicyConfigType().toString())){
260 policyData.setConfigPolicyType("Firewall Config");
262 // get values and attributes from the JsonObject
264 if (json.get("securityZoneId")!=null){
265 String securityZone = json.get("securityZoneId").toString().replace("\"", "");
266 policyData.setSecurityZone(securityZone);
268 if (json.get(CONFIG_NAME)!=null){
269 String configName = json.get(CONFIG_NAME).toString().replace("\"", "");
270 policyData.setConfigName(configName);
274 }else if("MS".equals(parameters.getPolicyConfigType().toString())){
276 policyData.setConfigPolicyType("Micro Service");
278 // get values and attributes from the JsonObject
280 if (json.containsKey("content")){
281 String content = json.get("content").toString();
282 ObjectMapper mapper = new ObjectMapper();
283 JsonNode policyJSON = null;
285 policyJSON = mapper.readTree(content);
286 } catch (IOException e) {
287 String message = XACMLErrorConstants.ERROR_DATA_ISSUE+ " improper JSON object : " + parameters.getConfigBody();
288 LOGGER.error(message, e);
291 policyData.setPolicyJSON(policyJSON);
293 if (json.containsKey("service")){
294 String serviceType = json.get("service").toString().replace("\"", "");
295 policyData.setServiceType(serviceType);
297 if (json.containsKey("uuid")){
298 String uuid = json.get("uuid").toString().replace("\"", "");
299 policyData.setUuid(uuid);
301 if (json.containsKey("location")){
302 String msLocation = json.get("location").toString().replace("\"", "");
303 policyData.setMsLocation(msLocation);
305 if (json.containsKey(CONFIG_NAME)){
306 String configName = json.get(CONFIG_NAME).toString().replace("\"", "");
307 policyData.setConfigName(configName);
309 if(json.containsKey("priority")){
310 String priority = json.get("priority").toString().replace("\"", "");
311 policyData.setPriority(priority);
313 if(json.containsKey("version")){
314 String version = json.get("version").toString().replace("\"", "");
315 policyData.setVersion(version);
317 if(json.containsKey("policyScope")){
318 String policyScope = json.get("policyScope").toString().replace("\"", "");
319 policyData.setPolicyScope(policyScope);
321 if(json.containsKey("riskType")){
322 String riskType = json.get("riskType").toString().replace("\"", "");
323 policyData.setRiskType(riskType);
325 if(json.containsKey("riskLevel")){
326 String riskLevel = json.get("riskLevel").toString().replace("\"", "");
327 policyData.setRiskLevel(riskLevel);
329 if(json.containsKey("guard")){
330 String guard = json.get("guard").toString().replace("\"", "");
331 policyData.setGuard(guard);
334 String message = XACMLErrorConstants.ERROR_DATA_ISSUE+ " improper JSON object : " + parameters.getConfigBody();
335 LOGGER.error(message);
339 } else if("Fault".equals(parameters.getPolicyConfigType().toString())){
341 policyData.setConfigPolicyType("ClosedLoop_Fault");
342 policyData.setApiflag("API");
345 policyData.setJsonBody(json.toString());
346 if (json.get("onapname")!=null){
347 String onapName = json.get("onapname").toString().replace("\"", "");
348 policyData.setOnapName(onapName);
352 } else if("PM".equals(parameters.getPolicyConfigType().toString())){
354 policyData.setConfigPolicyType("ClosedLoop_PM");
357 policyData.setJsonBody(json.toString());
358 if (json.get("onapname")!=null){
359 String onapName = json.get("onapname").toString().replace("\"", "");
360 policyData.setOnapName(onapName);
362 if (json.get("serviceTypePolicyName")!=null){
363 String serviceType = json.get("serviceTypePolicyName").toString().replace("\"", "");
364 LinkedHashMap<String, String> serviceTypePolicyName = new LinkedHashMap<>();
365 serviceTypePolicyName.put("serviceTypePolicyName", serviceType);
366 policyData.setServiceTypePolicyName(serviceTypePolicyName);
369 } else if("BRMS_Param".equals(parameters.getPolicyConfigType().toString())){
370 Map<AttributeType, Map<String, String>> drlRuleAndUIParams = parameters.getAttributes();
371 Map<String, String> rule = drlRuleAndUIParams.get(AttributeType.RULE);
372 policyData.setRuleName(rule.get("templateName"));
381 private JsonObject stringToJsonObject(String value) {
383 try(JsonReader jsonReader = Json.createReader(new StringReader(value))){
384 return jsonReader.readObject();
385 } catch(JsonException| IllegalStateException e){
386 LOGGER.info(XACMLErrorConstants.ERROR_DATA_ISSUE+ "Improper JSON format... may or may not cause issues in validating the policy: " + value, e);
391 private String convertDate(Date date) {
392 String strDate = null;
394 SimpleDateFormat dateformatJava = new SimpleDateFormat("dd-MM-yyyy");
395 strDate = dateformatJava.format(date);
397 return (strDate==null) ? "NA": strDate;