2 * ============LICENSE_START=======================================================
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
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=========================================================
20 package org.openecomp.policy.pap.xacml.rest.policycontroller;
23 import java.util.HashMap;
24 import java.util.LinkedHashMap;
25 import java.util.LinkedList;
26 import java.util.List;
29 import javax.servlet.http.HttpServletRequest;
30 import javax.servlet.http.HttpServletResponse;
32 import org.openecomp.policy.common.logging.eelf.PolicyLogger;
33 import org.openecomp.policy.common.logging.flexlogger.FlexLogger;
34 import org.openecomp.policy.common.logging.flexlogger.Logger;
35 import org.openecomp.policy.pap.xacml.rest.XACMLPapServlet;
36 import org.openecomp.policy.pap.xacml.rest.components.ActionPolicy;
37 import org.openecomp.policy.pap.xacml.rest.components.ClosedLoopPolicy;
38 import org.openecomp.policy.pap.xacml.rest.components.ConfigPolicy;
39 import org.openecomp.policy.pap.xacml.rest.components.CreateBrmsParamPolicy;
40 import org.openecomp.policy.pap.xacml.rest.components.CreateBrmsRawPolicy;
41 import org.openecomp.policy.pap.xacml.rest.components.CreateClosedLoopPerformanceMetrics;
42 import org.openecomp.policy.pap.xacml.rest.components.DecisionPolicy;
43 import org.openecomp.policy.pap.xacml.rest.components.FirewallConfigPolicy;
44 import org.openecomp.policy.pap.xacml.rest.components.MicroServiceConfigPolicy;
45 import org.openecomp.policy.pap.xacml.rest.components.Policy;
46 import org.openecomp.policy.pap.xacml.rest.components.PolicyDBDao;
47 import org.openecomp.policy.pap.xacml.rest.components.PolicyDBDaoTransaction;
48 import org.openecomp.policy.pap.xacml.rest.elk.client.PolicyElasticSearchController;
49 import org.openecomp.policy.pap.xacml.rest.util.AbstractPolicyCreation;
50 import org.openecomp.policy.rest.adapter.PolicyRestAdapter;
51 import org.openecomp.policy.rest.dao.CommonClassDao;
52 import org.openecomp.policy.rest.jpa.ActionPolicyDict;
53 import org.openecomp.policy.rest.jpa.BRMSParamTemplate;
54 import org.openecomp.policy.rest.jpa.PolicyEditorScopes;
55 import org.openecomp.policy.rest.jpa.PolicyVersion;
56 import org.openecomp.policy.rest.jpa.UserInfo;
57 import org.openecomp.policy.xacml.api.XACMLErrorConstants;
58 import org.springframework.beans.factory.annotation.Autowired;
59 import org.springframework.http.HttpStatus;
60 import org.springframework.http.ResponseEntity;
61 import org.springframework.http.converter.HttpMessageNotReadableException;
62 import org.springframework.web.bind.annotation.ExceptionHandler;
63 import org.springframework.web.bind.annotation.RequestBody;
64 import org.springframework.web.bind.annotation.RequestMapping;
65 import org.springframework.web.bind.annotation.RequestMethod;
66 import org.springframework.web.bind.annotation.ResponseBody;
67 import org.springframework.web.bind.annotation.RestController;
69 import com.fasterxml.jackson.databind.ObjectMapper;
74 public class PolicyCreation extends AbstractPolicyCreation{
76 private static final Logger LOGGER = FlexLogger.getLogger(PolicyCreation.class);
78 private String ruleID = "";
79 private PolicyDBDao policyDBDao;
82 private static CommonClassDao commonClassDao;
85 public PolicyCreation(CommonClassDao commonClassDao){
86 PolicyCreation.commonClassDao = commonClassDao;
89 public PolicyCreation(){}
91 @RequestMapping(value="/policycreation/save_policy", method = RequestMethod.POST)
93 public ResponseEntity<String> savePolicy(@RequestBody PolicyRestAdapter policyData, HttpServletResponse response) throws Exception{
95 HttpStatus status = HttpStatus.BAD_REQUEST;
96 Map<String, String> successMap = new HashMap<String, String>();
97 Map<String, String> attributeMap = new HashMap<String, String>();
98 PolicyVersion policyVersionDao;
101 Policy newPolicy = null;
102 String policyConfigType = null;
103 String userId = policyData.getUserId();
105 if (policyData.getTtlDate()==null){
106 policyData.setTtlDate("NA");
108 String dateTTL = policyData.getTtlDate();
109 String newDate = convertDate(dateTTL, false);
110 policyData.setTtlDate(newDate);
113 String policyType = policyData.getPolicyType();
115 String filePrefix = null;
116 if (policyType.equalsIgnoreCase("Config")) {
117 policyConfigType = policyData.getConfigPolicyType();
118 if (policyConfigType.equalsIgnoreCase("Firewall Config")) {
119 filePrefix = "Config_FW_";
120 }else if (policyConfigType.equalsIgnoreCase("ClosedLoop_Fault")) {
121 filePrefix = "Config_Fault_";
122 }else if (policyConfigType.equalsIgnoreCase("ClosedLoop_PM")) {
123 filePrefix = "Config_PM_";
124 }else if (policyConfigType.equalsIgnoreCase("Micro Service")) {
125 filePrefix = "Config_MS_";
126 }else if (policyConfigType.equalsIgnoreCase("BRMS_Raw")) {
127 filePrefix = "Config_BRMS_Raw_";
128 }else if (policyConfigType.equalsIgnoreCase("BRMS_Param")) {
129 filePrefix = "Config_BRMS_Param_";
131 filePrefix = "Config_";
133 } else if (policyType.equalsIgnoreCase("Action")) {
134 filePrefix = "Action_";
135 } else if (policyType.equalsIgnoreCase("Decision")) {
136 filePrefix = "Decision_";
140 int highestVersion = 0;
141 String createdBy = "";
142 String modifiedBy = userId;
143 String scopeCheck = policyData.getDomainDir().replace(".", File.separator);
144 PolicyEditorScopes policyEditorScope = (PolicyEditorScopes) commonClassDao.getEntityItem(PolicyEditorScopes.class, "scopeName", scopeCheck);
145 if(policyEditorScope == null){
146 UserInfo userInfo = new UserInfo();
147 userInfo.setUserName("API");
148 userInfo.setUserLoginId("API");
149 PolicyEditorScopes editorScope = new PolicyEditorScopes();
150 editorScope.setScopeName(scopeCheck);
151 editorScope.setUserCreatedBy(userInfo);
152 editorScope.setUserModifiedBy(userInfo);
153 commonClassDao.save(editorScope);
155 //get the highest version of policy from policy version table.
156 String dbCheckPolicyName = policyData.getDomainDir() + File.separator + filePrefix + policyData.getPolicyName();
157 PolicyVersion policyVersion = getPolicyVersionData(dbCheckPolicyName);
158 if(policyVersion == null){
161 highestVersion = policyVersion.getHigherVersion();
164 if(highestVersion != 0){
165 if(policyData.isEditPolicy){
166 version = highestVersion +1;
172 policyData.setUserId("API");
173 createdBy = policyVersion.getCreatedBy();
174 policyVersionDao = policyVersion;
175 policyVersionDao.setActiveVersion(version);
176 policyVersionDao.setHigherVersion(version);
177 policyVersionDao.setModifiedBy(modifiedBy);
179 body = "policyExists";
180 status = HttpStatus.CONFLICT;
181 response.setStatus(HttpServletResponse.SC_CONFLICT);
182 response.addHeader("error", "policyExists");
183 response.addHeader("policyName", policyData.getPolicyName());
184 return new ResponseEntity<String>(body, status);
191 policyData.setUserId("API");
195 policyData.setUserId("API");
197 policyVersionDao = new PolicyVersion();
198 policyVersionDao.setPolicyName(dbCheckPolicyName);
199 policyVersionDao.setActiveVersion(version);
200 policyVersionDao.setHigherVersion(version);
201 policyVersionDao.setCreatedBy(createdBy);
202 policyVersionDao.setModifiedBy(modifiedBy);
205 policyData.setPolicyID(newPolicyID());
206 policyData.setRuleID(ruleID);
208 String policyFileName = dbCheckPolicyName.replace(File.separator, ".")+ "." + version + ".xml";
209 policyData.setNewFileName(policyFileName);
210 policyData.setPolicyDescription(policyData.getPolicyDescription()+ "@CreatedBy:" +createdBy + "@CreatedBy:" + "@ModifiedBy:" +modifiedBy + "@ModifiedBy:");
211 policyData.setRuleCombiningAlgId("urn:oasis:names:tc:xacml:3.0:rule-combining-algorithm:permit-overrides");
212 if(policyData.getApiflag() == null){
213 //set the Rule Combining Algorithm Id to be sent to PAP-REST via JSON
214 if(policyData.getAttributes() != null){
215 if(policyData.getAttributes().size() > 0){
216 for(Object attribute : policyData.getAttributes()){
217 if(attribute instanceof LinkedHashMap<?, ?>){
218 String key = ((LinkedHashMap<?, ?>) attribute).get("key").toString();
219 String value = ((LinkedHashMap<?, ?>) attribute).get("value").toString();
220 attributeMap.put(key, value);
225 policyData.setDynamicFieldConfigAttributes(attributeMap);
228 policyData.setVersion(String.valueOf(version));
229 policyData.setHighestVersion(version);
231 // Calling Component class per policy type
232 if (policyType.equalsIgnoreCase("Config")) {
233 if (policyConfigType.equalsIgnoreCase("Firewall Config")) {
234 newPolicy = new FirewallConfigPolicy(policyData);
235 }else if (policyConfigType.equalsIgnoreCase("BRMS_Raw")) {
236 policyData.setEcompName("DROOLS");
237 policyData.setConfigName("BRMS_RAW_RULE");
238 newPolicy = new CreateBrmsRawPolicy(policyData);
239 }else if (policyConfigType.equalsIgnoreCase("BRMS_Param")) {
240 policyData.setEcompName("DROOLS");
241 policyData.setConfigName("BRMS_PARAM_RULE");
242 Map<String, String> drlRuleAndUIParams = new HashMap<String, String>();
243 if(policyData.getApiflag() == null){
244 // If there is any dynamic field create the matches here
245 String key="templateName";
246 String value=(String) policyData.getRuleName();
247 drlRuleAndUIParams.put(key, value);
248 if(policyData.getRuleData().size() > 0){
249 for(Object keyValue: policyData.getRuleData().keySet()){
250 drlRuleAndUIParams.put(keyValue.toString(), policyData.getRuleData().get(keyValue).toString());
253 policyData.setBrmsParamBody(drlRuleAndUIParams);
255 drlRuleAndUIParams=policyData.getBrmsParamBody();
256 String modelName= drlRuleAndUIParams.get("templateName");
257 PolicyLogger.info("Template name from API is: "+modelName);
259 BRMSParamTemplate template = (BRMSParamTemplate) commonClassDao.getEntityItem(BRMSParamTemplate.class, "ruleName", modelName);
260 if(template == null){
261 String message = XACMLErrorConstants.ERROR_DATA_ISSUE + "Invalid Template. The template name, "
262 + modelName + " was not found in the dictionary.";
264 status = HttpStatus.BAD_REQUEST;
265 response.setStatus(HttpServletResponse.SC_BAD_REQUEST);
266 response.addHeader("error", message);
267 response.addHeader("modelName", modelName);
268 return new ResponseEntity<String>(body, status);
271 newPolicy = new CreateBrmsParamPolicy(policyData);
272 }else if (policyConfigType.equalsIgnoreCase("Base")) {
273 newPolicy = new ConfigPolicy(policyData);
274 }else if (policyConfigType.equalsIgnoreCase("ClosedLoop_Fault")) {
275 newPolicy = new ClosedLoopPolicy(policyData);
276 }else if (policyConfigType.equalsIgnoreCase("ClosedLoop_PM")) {
277 if(policyData.getApiflag() == null){
278 policyData.setServiceType(policyData.getServiceTypePolicyName().get("serviceTypePolicyName").toString());
279 ObjectMapper jsonMapper = new ObjectMapper();
280 String jsonBody = jsonMapper.writeValueAsString(policyData.getJsonBodyData());
281 jsonBody = jsonBody.replaceFirst("\\{", "\\{\"serviceTypePolicyName\": \"serviceTypeFieldValue\",");
282 jsonBody = jsonBody.replace("serviceTypeFieldValue", policyData.getServiceType());
283 policyData.setJsonBody(jsonBody);
285 newPolicy = new CreateClosedLoopPerformanceMetrics(policyData);
286 }else if (policyConfigType.equalsIgnoreCase("Micro Service")) {
287 newPolicy = new MicroServiceConfigPolicy(policyData);
289 }else if(policyType.equalsIgnoreCase("Action")) {
290 if(policyData.getApiflag() == null){
291 List<String> dynamicRuleAlgorithmLabels = new LinkedList<String>();
292 List<String> dynamicRuleAlgorithmCombo = new LinkedList<String>();
293 List<String> dynamicRuleAlgorithmField1 = new LinkedList<String>();
294 List<String> dynamicRuleAlgorithmField2 = new LinkedList<String>();
297 if(policyData.getRuleAlgorithmschoices().size() > 0){
298 for(Object attribute : policyData.getRuleAlgorithmschoices()){
299 if(attribute instanceof LinkedHashMap<?, ?>){
300 String label = ((LinkedHashMap<?, ?>) attribute).get("id").toString();
301 String key = ((LinkedHashMap<?, ?>) attribute).get("dynamicRuleAlgorithmField1").toString();
302 String rule = ((LinkedHashMap<?, ?>) attribute).get("dynamicRuleAlgorithmCombo").toString();
303 String value = ((LinkedHashMap<?, ?>) attribute).get("dynamicRuleAlgorithmField2").toString();
304 dynamicRuleAlgorithmLabels.add(label);
305 dynamicRuleAlgorithmField1.add(key);
306 dynamicRuleAlgorithmCombo.add(rule);
307 dynamicRuleAlgorithmField2.add(value);
312 String actionDictValue = policyData.getActionAttributeValue();
313 ActionPolicyDict jsonData = ((ActionPolicyDict) commonClassDao.getEntityItem(ActionPolicyDict.class, "attributeName", actionDictValue));
314 String actionBodyString = jsonData.getBody();
315 String actionDictHeader = jsonData.getHeader();
316 String actionDictType = jsonData.getType();
317 String actionDictUrl = jsonData.getUrl();
318 String actionDictMethod = jsonData.getMethod();
319 policyData.setActionDictHeader(actionDictHeader);
320 policyData.setActionDictType(actionDictType);
321 policyData.setActionDictUrl(actionDictUrl);
322 policyData.setActionDictMethod(actionDictMethod);
323 policyData.setActionAttribute(actionDictValue);
324 policyData.setDynamicRuleAlgorithmLabels(dynamicRuleAlgorithmLabels);
325 policyData.setDynamicRuleAlgorithmCombo(dynamicRuleAlgorithmCombo);
326 policyData.setDynamicRuleAlgorithmField1(dynamicRuleAlgorithmField1);
327 policyData.setDynamicRuleAlgorithmField2(dynamicRuleAlgorithmField2);
328 if (actionBodyString != null) {
329 policyData.setActionBody(actionBodyString);
332 newPolicy = new ActionPolicy(policyData);
333 } else if (policyType.equalsIgnoreCase("Decision")) {
334 if(policyData.getApiflag() == null){
335 Map<String, String> settingsMap = new HashMap<String, String>();
336 List<String> dynamicRuleAlgorithmLabels = new LinkedList<String>();
337 List<String> dynamicRuleAlgorithmCombo = new LinkedList<String>();
338 List<String> dynamicRuleAlgorithmField1 = new LinkedList<String>();
339 List<String> dynamicRuleAlgorithmField2 = new LinkedList<String>();
340 List<Object> dynamicVariableList = new LinkedList<Object>();
341 List<String> dataTypeList = new LinkedList<String>();
343 if(policyData.getSettings().size() > 0){
344 for(Object settingsData : policyData.getSettings()){
345 if(settingsData instanceof LinkedHashMap<?, ?>){
346 String key = ((LinkedHashMap<?, ?>) settingsData).get("key").toString();
347 String value = ((LinkedHashMap<?, ?>) settingsData).get("value").toString();
348 settingsMap.put(key, value);
352 if(policyData.getRuleAlgorithmschoices()!=null && policyData.getRuleAlgorithmschoices().size() > 0){
353 for(Object attribute : policyData.getRuleAlgorithmschoices()){
354 if(attribute instanceof LinkedHashMap<?, ?>){
355 String label = ((LinkedHashMap<?, ?>) attribute).get("id").toString();
356 String key = ((LinkedHashMap<?, ?>) attribute).get("dynamicRuleAlgorithmField1").toString();
357 String rule = ((LinkedHashMap<?, ?>) attribute).get("dynamicRuleAlgorithmCombo").toString();
358 String value = ((LinkedHashMap<?, ?>) attribute).get("dynamicRuleAlgorithmField2").toString();
359 dynamicRuleAlgorithmLabels.add(label);
360 dynamicRuleAlgorithmField1.add(key);
361 dynamicRuleAlgorithmCombo.add(rule);
362 dynamicRuleAlgorithmField2.add(value);
366 if(policyData.getRuleProvider()!=null && policyData.getRuleProvider().equals(DecisionPolicy.GUARD_YAML) && policyData.getYamlparams()!=null){
367 attributeMap.put("actor", policyData.getYamlparams().getActor());
368 attributeMap.put("recipe", policyData.getYamlparams().getRecipe());
369 attributeMap.put("limit", policyData.getYamlparams().getLimit());
370 attributeMap.put("timeWindow", policyData.getYamlparams().getTimeWindow());
371 attributeMap.put("guardActiveStart", policyData.getYamlparams().getGuardActiveStart());
372 attributeMap.put("guardActiveEnd", policyData.getYamlparams().getGuardActiveEnd());
374 policyData.setDynamicRuleAlgorithmLabels(dynamicRuleAlgorithmLabels);
375 policyData.setDynamicRuleAlgorithmCombo(dynamicRuleAlgorithmCombo);
376 policyData.setDynamicRuleAlgorithmField1(dynamicRuleAlgorithmField1);
377 policyData.setDynamicRuleAlgorithmField2(dynamicRuleAlgorithmField2);
378 policyData.setDynamicVariableList(dynamicVariableList);
379 policyData.setDynamicSettingsMap(settingsMap);
380 policyData.setDynamicFieldConfigAttributes(attributeMap);
381 policyData.setDataTypeList(dataTypeList);
383 newPolicy = new DecisionPolicy(policyData);
386 newPolicy.prepareToSave();
388 PolicyDBDaoTransaction policyDBDaoTransaction = null;
390 policyDBDao = PolicyDBDao.getPolicyDBDaoInstance(XACMLPapServlet.getEmf());
391 policyDBDaoTransaction = policyDBDao.getNewTransaction();
392 policyDBDaoTransaction.createPolicy(newPolicy, policyData.getUserId());
393 successMap = newPolicy.savePolicies();
394 if(successMap.containsKey("success")){
395 policyDBDaoTransaction.commitTransaction();
396 if(policyData.isEditPolicy){
397 commonClassDao.update(policyVersionDao);
399 commonClassDao.save(policyVersionDao);
402 PolicyElasticSearchController search= new PolicyElasticSearchController();
403 search.updateElk(policyData);
405 LOGGER.error("Error Occured while saving policy to Elastic Database"+e);
408 status = HttpStatus.OK;
409 response.setStatus(HttpServletResponse.SC_OK);
410 response.addHeader("successMapKey", "success");
411 response.addHeader("policyName", policyData.getNewFileName());
413 //get message from the SafetyCheckerResults if present
414 String safetyCheckerResponse = policyData.getClWarning();
415 String existingCLName = policyData.getExistingCLName();
417 //if safetyCheckerResponse is not null add a header to send back with response
418 if(safetyCheckerResponse!=null) {
419 PolicyLogger.info("SafetyCheckerResponse message: " + safetyCheckerResponse);
420 response.addHeader("safetyChecker", safetyCheckerResponse);
421 response.addHeader("newCLName", CLName);
422 response.addHeader("conflictCLName", existingCLName);
424 PolicyLogger.info("SafetyCheckerResponse was empty or null.");
427 }else if (successMap.containsKey("invalidAttribute")) {
428 String message = XACMLErrorConstants.ERROR_DATA_ISSUE + "Invalid Action Attribute";
429 LOGGER.error(XACMLErrorConstants.ERROR_DATA_ISSUE + "Could not fine " + policyData.getActionAttribute() + " in the ActionPolicyDict table.");
430 body = "invalidAttribute";
431 status = HttpStatus.BAD_REQUEST;
432 response.setStatus(HttpServletResponse.SC_BAD_REQUEST);
433 response.addHeader("invalidAttribute", policyData.getActionAttribute());
434 response.addHeader("error", message);
435 response.addHeader("policyName", policyData.getPolicyName());
436 }else if (successMap.containsKey("fwdberror")) {
437 policyDBDaoTransaction.rollbackTransaction();
439 status = HttpStatus.BAD_REQUEST;
440 String message = XACMLErrorConstants.ERROR_DATA_ISSUE
441 + "Error when inserting Firewall ConfigBody data into the database.";
442 PolicyLogger.error(message);
443 response.setStatus(HttpServletResponse.SC_BAD_REQUEST);
444 response.addHeader("error", message);
445 response.addHeader("policyName", policyData.getPolicyName());
446 } else if (successMap.get("error").equals("Validation Failed")) {
447 policyDBDaoTransaction.rollbackTransaction();
448 String message = XACMLErrorConstants.ERROR_DATA_ISSUE
449 + "Error Validating the Policy on the PAP.";
450 PolicyLogger.error(message);
452 status = HttpStatus.BAD_REQUEST;
453 response.setStatus(HttpServletResponse.SC_BAD_REQUEST);
454 response.addHeader("error", message);
455 response.addHeader("policyName", policyData.getPolicyName());
457 policyDBDaoTransaction.rollbackTransaction();
459 status = HttpStatus.INTERNAL_SERVER_ERROR;
460 response.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
461 response.addHeader("error", "error");
464 policyDBDaoTransaction.rollbackTransaction();
469 LOGGER.error("Exception Occured"+e);
471 return new ResponseEntity<String>(body, status);
474 @ExceptionHandler({ HttpMessageNotReadableException.class })
475 public ResponseEntity<String> messageNotReadableExceptionHandler(HttpServletRequest req, HttpMessageNotReadableException exception) {
476 LOGGER.error("Request not readable: {}", exception);
477 StringBuilder message = new StringBuilder();
478 message.append(exception.getMessage());
479 if (exception.getCause() != null) {
480 message.append(" Reason Caused: "
481 + exception.getCause().getMessage());
483 return new ResponseEntity<>(message.toString(), HttpStatus.BAD_REQUEST);
486 public PolicyVersion getPolicyVersionData(String dbCheckPolicyName){
487 PolicyVersion entityItem = (PolicyVersion) commonClassDao.getEntityItem(PolicyVersion.class, "policyName", dbCheckPolicyName);
488 if (entityItem != null) {
489 if(entityItem.getPolicyName().equals(dbCheckPolicyName)){