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