2 * ============LICENSE_START=======================================================
4 * ================================================================================
5 * Copyright (C) 2017-2019 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=========================================================
21 package org.onap.policy.pap.xacml.rest.policycontroller;
23 import com.fasterxml.jackson.databind.ObjectMapper;
26 import java.util.Date;
27 import java.util.HashMap;
28 import java.util.LinkedHashMap;
29 import java.util.LinkedList;
30 import java.util.List;
33 import javax.servlet.http.HttpServletRequest;
34 import javax.servlet.http.HttpServletResponse;
36 import org.apache.commons.lang.StringUtils;
37 import org.onap.policy.common.logging.eelf.PolicyLogger;
38 import org.onap.policy.common.logging.flexlogger.FlexLogger;
39 import org.onap.policy.common.logging.flexlogger.Logger;
40 import org.onap.policy.pap.xacml.rest.components.ActionPolicy;
41 import org.onap.policy.pap.xacml.rest.components.ClosedLoopPolicy;
42 import org.onap.policy.pap.xacml.rest.components.ConfigPolicy;
43 import org.onap.policy.pap.xacml.rest.components.CreateBrmsParamPolicy;
44 import org.onap.policy.pap.xacml.rest.components.CreateBrmsRawPolicy;
45 import org.onap.policy.pap.xacml.rest.components.CreateClosedLoopPerformanceMetrics;
46 import org.onap.policy.pap.xacml.rest.components.DecisionPolicy;
47 import org.onap.policy.pap.xacml.rest.components.FirewallConfigPolicy;
48 import org.onap.policy.pap.xacml.rest.components.MicroServiceConfigPolicy;
49 import org.onap.policy.pap.xacml.rest.components.OptimizationConfigPolicy;
50 import org.onap.policy.pap.xacml.rest.components.Policy;
51 import org.onap.policy.pap.xacml.rest.components.PolicyDBDao;
52 import org.onap.policy.pap.xacml.rest.components.PolicyDBDaoTransaction;
53 import org.onap.policy.pap.xacml.rest.elk.client.PolicyElasticSearchController;
54 import org.onap.policy.pap.xacml.rest.util.AbstractPolicyCreation;
55 import org.onap.policy.rest.adapter.PolicyRestAdapter;
56 import org.onap.policy.rest.dao.CommonClassDao;
57 import org.onap.policy.rest.jpa.ActionPolicyDict;
58 import org.onap.policy.rest.jpa.BRMSParamTemplate;
59 import org.onap.policy.rest.jpa.PolicyEditorScopes;
60 import org.onap.policy.rest.jpa.PolicyVersion;
61 import org.onap.policy.rest.jpa.UserInfo;
62 import org.onap.policy.xacml.api.XACMLErrorConstants;
63 import org.springframework.beans.factory.annotation.Autowired;
64 import org.springframework.http.HttpStatus;
65 import org.springframework.http.ResponseEntity;
66 import org.springframework.http.converter.HttpMessageNotReadableException;
67 import org.springframework.web.bind.annotation.ExceptionHandler;
68 import org.springframework.web.bind.annotation.RequestBody;
69 import org.springframework.web.bind.annotation.RequestMapping;
70 import org.springframework.web.bind.annotation.RequestMethod;
71 import org.springframework.web.bind.annotation.ResponseBody;
72 import org.springframework.web.bind.annotation.RestController;
76 public class PolicyCreation extends AbstractPolicyCreation {
78 private static final Logger LOGGER = FlexLogger.getLogger(PolicyCreation.class);
80 private String ruleID = "";
81 private PolicyDBDao policyDBDao;
84 private static CommonClassDao commonClassDao;
86 public static CommonClassDao getCommonClassDao() {
87 return commonClassDao;
90 public static void setCommonClassDao(CommonClassDao commonClassDao) {
91 PolicyCreation.commonClassDao = commonClassDao;
95 public PolicyCreation(CommonClassDao commonClassDao) {
96 PolicyCreation.commonClassDao = commonClassDao;
99 public PolicyCreation() {
102 @RequestMapping(value = "/policycreation/save_policy", method = RequestMethod.POST)
104 public ResponseEntity<String> savePolicy(@RequestBody PolicyRestAdapter policyData, HttpServletResponse response) {
106 HttpStatus status = HttpStatus.BAD_REQUEST;
107 Map<String, String> successMap = new HashMap<>();
108 Map<String, String> attributeMap = new HashMap<>();
109 PolicyVersion policyVersionDao;
112 Policy newPolicy = null;
113 String policyConfigType = null;
114 String userId = policyData.getUserId();
116 if (policyData.getTtlDate() == null) {
117 policyData.setTtlDate("NA");
119 String dateTTL = policyData.getTtlDate();
120 String newDate = convertDate(dateTTL);
121 policyData.setTtlDate(newDate);
124 String policyType = policyData.getPolicyType();
126 String filePrefix = null;
127 if ("Config".equalsIgnoreCase(policyType)) {
128 policyConfigType = policyData.getConfigPolicyType();
129 if ("Firewall Config".equalsIgnoreCase(policyConfigType)) {
130 filePrefix = "Config_FW_";
131 } else if ("ClosedLoop_Fault".equalsIgnoreCase(policyConfigType)) {
132 filePrefix = "Config_Fault_";
133 } else if ("ClosedLoop_PM".equalsIgnoreCase(policyConfigType)) {
134 filePrefix = "Config_PM_";
135 } else if ("Micro Service".equalsIgnoreCase(policyConfigType)) {
136 filePrefix = "Config_MS_";
137 } else if ("Optimization".equalsIgnoreCase(policyConfigType)) {
138 filePrefix = "Config_OOF_";
139 } else if ("BRMS_Raw".equalsIgnoreCase(policyConfigType)) {
140 filePrefix = "Config_BRMS_Raw_";
141 } else if ("BRMS_Param".equalsIgnoreCase(policyConfigType)) {
142 filePrefix = "Config_BRMS_Param_";
144 filePrefix = "Config_";
146 } else if ("Action".equalsIgnoreCase(policyType)) {
147 filePrefix = "Action_";
148 } else if ("Decision".equalsIgnoreCase(policyType)) {
149 filePrefix = "Decision_";
153 int highestVersion = 0;
156 String scopeCheck = policyData.getDomainDir().replace(".", File.separator);
157 PolicyEditorScopes policyEditorScope = (PolicyEditorScopes) commonClassDao
158 .getEntityItem(PolicyEditorScopes.class, "scopeName", scopeCheck);
159 if (policyEditorScope == null) {
160 UserInfo userInfo = new UserInfo();
161 userInfo.setUserName("API");
162 userInfo.setUserLoginId("API");
163 PolicyEditorScopes editorScope = new PolicyEditorScopes();
164 editorScope.setScopeName(scopeCheck);
165 editorScope.setUserCreatedBy(userInfo);
166 editorScope.setUserModifiedBy(userInfo);
167 commonClassDao.save(editorScope);
169 // get the highest version of policy from policy version table.
170 String dbCheckPolicyName =
171 policyData.getDomainDir() + File.separator + filePrefix + policyData.getPolicyName();
172 PolicyVersion policyVersion = getPolicyVersionData(dbCheckPolicyName);
173 if (policyVersion == null) {
176 highestVersion = policyVersion.getHigherVersion();
179 if (highestVersion != 0 && policyVersion != null) {
180 if (policyData.isEditPolicy()) {
181 version = highestVersion + 1;
182 if (userId == null) {
187 policyData.setUserId("API");
188 createdBy = policyVersion.getCreatedBy();
189 policyVersionDao = policyVersion;
190 policyVersionDao.setActiveVersion(version);
191 policyVersionDao.setHigherVersion(version);
192 policyVersionDao.setModifiedBy(modifiedBy);
193 policyVersionDao.setModifiedDate(new Date());
195 body = "policyExists";
196 status = HttpStatus.CONFLICT;
197 response.setStatus(HttpServletResponse.SC_CONFLICT);
198 response.addHeader("error", "policyExists");
199 response.addHeader("policyName", policyData.getPolicyName());
200 return new ResponseEntity<>(body, status);
203 // if policy does not exist and the request is updatePolicy return error
204 if (policyData.isEditPolicy()) {
205 body = "policyNotAvailableForEdit";
206 status = HttpStatus.NOT_FOUND;
207 response.setStatus(HttpServletResponse.SC_NOT_FOUND);
208 response.addHeader("error", body);
209 response.addHeader("message",
210 policyData.getPolicyName() + " does not exist on the PAP and cannot be updated.");
211 return new ResponseEntity<>(body, status);
214 if (userId == null) {
217 policyData.setUserId("API");
221 policyData.setUserId("API");
223 policyVersionDao = new PolicyVersion();
224 policyVersionDao.setPolicyName(dbCheckPolicyName);
225 policyVersionDao.setActiveVersion(version);
226 policyVersionDao.setHigherVersion(version);
227 policyVersionDao.setCreatedBy(createdBy);
228 policyVersionDao.setModifiedBy(modifiedBy);
231 policyData.setPolicyID(newPolicyID());
232 policyData.setRuleID(ruleID);
234 String policyFileName = dbCheckPolicyName.replace(File.separator, ".") + "." + version + ".xml";
235 policyData.setNewFileName(policyFileName);
236 policyData.setPolicyDescription(policyData.getPolicyDescription() + "@CreatedBy:" + createdBy
237 + "@CreatedBy:" + "@ModifiedBy:" + modifiedBy + "@ModifiedBy:");
238 policyData.setRuleCombiningAlgId("urn:oasis:names:tc:xacml:3.0:rule-combining-algorithm:permit-overrides");
239 if (policyData.getApiflag() == null) {
240 // set the Rule Combining Algorithm Id to be sent to PAP-REST via JSON
241 if (policyData.getAttributes() != null && !policyData.getAttributes().isEmpty()) {
242 for (Object attribute : policyData.getAttributes()) {
243 if (attribute instanceof LinkedHashMap<?, ?>) {
244 String key = ((LinkedHashMap<?, ?>) attribute).get("key").toString();
245 String value = ((LinkedHashMap<?, ?>) attribute).get("value").toString();
246 attributeMap.put(key, value);
250 policyData.setDynamicFieldConfigAttributes(attributeMap);
253 policyData.setVersion(String.valueOf(version));
254 policyData.setHighestVersion(version);
256 // Calling Component class per policy type
257 if ("Config".equalsIgnoreCase(policyType)) {
258 if ("Firewall Config".equalsIgnoreCase(policyConfigType)) {
259 newPolicy = new FirewallConfigPolicy(policyData);
260 } else if ("BRMS_Raw".equalsIgnoreCase(policyConfigType)) {
261 policyData.setOnapName("DROOLS");
262 policyData.setConfigName("BRMS_RAW_RULE");
263 newPolicy = new CreateBrmsRawPolicy(policyData);
264 } else if ("BRMS_Param".equalsIgnoreCase(policyConfigType)) {
265 policyData.setOnapName("DROOLS");
266 policyData.setConfigName("BRMS_PARAM_RULE");
267 Map<String, String> drlRuleAndUIParams = new HashMap<>();
268 if (policyData.getApiflag() == null) {
269 // If there is any dynamic field create the matches here
270 String key = "templateName";
271 String value = policyData.getRuleName();
272 drlRuleAndUIParams.put(key, value);
273 if (policyData.getRuleData().size() > 0) {
274 for (Object keyValue : policyData.getRuleData().keySet()) {
275 drlRuleAndUIParams.put(keyValue.toString(),
276 policyData.getRuleData().get(keyValue).toString());
279 policyData.setBrmsParamBody(drlRuleAndUIParams);
281 drlRuleAndUIParams = policyData.getBrmsParamBody();
282 String modelName = drlRuleAndUIParams.get("templateName");
283 PolicyLogger.info("Template name from API is: " + modelName);
285 BRMSParamTemplate template = (BRMSParamTemplate) commonClassDao
286 .getEntityItem(BRMSParamTemplate.class, "ruleName", modelName);
287 if (template == null) {
289 XACMLErrorConstants.ERROR_DATA_ISSUE + "Invalid Template. The template name, "
290 + modelName + " was not found in the dictionary.";
292 status = HttpStatus.BAD_REQUEST;
293 response.setStatus(HttpServletResponse.SC_BAD_REQUEST);
294 response.addHeader("error", message);
295 response.addHeader("modelName", modelName);
296 return new ResponseEntity<String>(body, status);
299 newPolicy = new CreateBrmsParamPolicy(policyData);
300 } else if ("Base".equalsIgnoreCase(policyConfigType)) {
301 newPolicy = new ConfigPolicy(policyData);
302 } else if ("ClosedLoop_Fault".equalsIgnoreCase(policyConfigType)) {
303 newPolicy = new ClosedLoopPolicy(policyData);
304 } else if ("ClosedLoop_PM".equalsIgnoreCase(policyConfigType)) {
305 if (policyData.getApiflag() == null) {
306 policyData.setServiceType(
307 policyData.getServiceTypePolicyName().get("serviceTypePolicyName").toString());
308 ObjectMapper jsonMapper = new ObjectMapper();
309 String jsonBody = jsonMapper.writeValueAsString(policyData.getJsonBodyData());
310 jsonBody = jsonBody.replaceFirst("\\{",
311 "\\{\"serviceTypePolicyName\": \"serviceTypeFieldValue\",");
312 jsonBody = jsonBody.replace("serviceTypeFieldValue", policyData.getServiceType());
313 policyData.setJsonBody(jsonBody);
315 newPolicy = new CreateClosedLoopPerformanceMetrics(policyData);
316 } else if ("Micro Service".equalsIgnoreCase(policyConfigType)) {
317 newPolicy = new MicroServiceConfigPolicy(policyData);
318 } else if ("Optimization".equalsIgnoreCase(policyConfigType)) {
319 newPolicy = new OptimizationConfigPolicy(policyData);
321 } else if ("Action".equalsIgnoreCase(policyType)) {
322 if (policyData.getApiflag() == null) {
323 List<String> dynamicRuleAlgorithmLabels = new LinkedList<>();
324 List<String> dynamicRuleAlgorithmCombo = new LinkedList<>();
325 List<String> dynamicRuleAlgorithmField1 = new LinkedList<>();
326 List<String> dynamicRuleAlgorithmField2 = new LinkedList<>();
328 if (!policyData.getRuleAlgorithmschoices().isEmpty()) {
329 for (Object attribute : policyData.getRuleAlgorithmschoices()) {
330 if (attribute instanceof LinkedHashMap<?, ?>) {
331 String label = ((LinkedHashMap<?, ?>) attribute).get("id").toString();
333 ((LinkedHashMap<?, ?>) attribute).get("dynamicRuleAlgorithmField1").toString();
335 ((LinkedHashMap<?, ?>) attribute).get("dynamicRuleAlgorithmCombo").toString();
337 ((LinkedHashMap<?, ?>) attribute).get("dynamicRuleAlgorithmField2").toString();
338 dynamicRuleAlgorithmLabels.add(label);
339 dynamicRuleAlgorithmField1.add(key);
340 dynamicRuleAlgorithmCombo.add(rule);
341 dynamicRuleAlgorithmField2.add(value);
346 String actionDictValue = policyData.getActionAttributeValue();
347 ActionPolicyDict jsonData = ((ActionPolicyDict) commonClassDao.getEntityItem(ActionPolicyDict.class,
348 "attributeName", actionDictValue));
349 if (jsonData != null) {
350 String actionBodyString = jsonData.getBody();
351 String actionDictHeader = jsonData.getHeader();
352 String actionDictType = jsonData.getType();
353 String actionDictUrl = jsonData.getUrl();
354 String actionDictMethod = jsonData.getMethod();
355 policyData.setActionDictHeader(actionDictHeader);
356 policyData.setActionDictType(actionDictType);
357 policyData.setActionDictUrl(actionDictUrl);
358 policyData.setActionDictMethod(actionDictMethod);
359 if (actionBodyString != null) {
360 policyData.setActionBody(actionBodyString);
363 policyData.setActionAttribute(actionDictValue);
364 policyData.setDynamicRuleAlgorithmLabels(dynamicRuleAlgorithmLabels);
365 policyData.setDynamicRuleAlgorithmCombo(dynamicRuleAlgorithmCombo);
366 policyData.setDynamicRuleAlgorithmField1(dynamicRuleAlgorithmField1);
367 policyData.setDynamicRuleAlgorithmField2(dynamicRuleAlgorithmField2);
370 String comboDictValue = policyData.getActionAttribute();
371 ActionPolicyDict jsonData = ((ActionPolicyDict) commonClassDao.getEntityItem(ActionPolicyDict.class,
372 "attributeName", comboDictValue));
373 if (jsonData != null) {
374 policyData.setActionBody(jsonData.getBody());
375 policyData.setActionDictHeader(jsonData.getHeader());
376 policyData.setActionDictType(jsonData.getType());
377 policyData.setActionDictUrl(jsonData.getUrl());
378 policyData.setActionDictMethod(jsonData.getMethod());
381 newPolicy = new ActionPolicy(policyData, commonClassDao);
382 } else if ("Decision".equalsIgnoreCase(policyType)) {
383 if (policyData.getApiflag() == null) {
384 Map<String, String> settingsMap = new HashMap<>();
385 Map<String, String> treatmentMap = new HashMap<>();
386 List<String> dynamicRuleAlgorithmLabels = new LinkedList<>();
387 List<String> dynamicRuleAlgorithmCombo = new LinkedList<>();
388 List<String> dynamicRuleAlgorithmField1 = new LinkedList<>();
389 List<String> dynamicRuleAlgorithmField2 = new LinkedList<>();
390 List<Object> dynamicVariableList = new LinkedList<>();
391 List<String> dataTypeList = new LinkedList<>();
392 List<String> errorCodeList = new LinkedList<>();
393 List<String> treatmentList = new LinkedList<>();
395 if (!policyData.getSettings().isEmpty()) {
396 for (Object settingsData : policyData.getSettings()) {
397 if (settingsData instanceof LinkedHashMap<?, ?>) {
398 String key = ((LinkedHashMap<?, ?>) settingsData).get("key").toString();
399 String value = ((LinkedHashMap<?, ?>) settingsData).get("value").toString();
400 settingsMap.put(key, value);
404 if (policyData.getRuleAlgorithmschoices() != null
405 && policyData.getRuleAlgorithmschoices().size() > 0) {
406 for (Object attribute : policyData.getRuleAlgorithmschoices()) {
407 if (attribute instanceof LinkedHashMap<?, ?>) {
408 String label = ((LinkedHashMap<?, ?>) attribute).get("id").toString();
410 ((LinkedHashMap<?, ?>) attribute).get("dynamicRuleAlgorithmField1").toString();
412 ((LinkedHashMap<?, ?>) attribute).get("dynamicRuleAlgorithmCombo").toString();
414 ((LinkedHashMap<?, ?>) attribute).get("dynamicRuleAlgorithmField2").toString();
415 dynamicRuleAlgorithmLabels.add(label);
416 dynamicRuleAlgorithmField1.add(key);
417 dynamicRuleAlgorithmCombo.add(rule);
418 dynamicRuleAlgorithmField2.add(value);
422 if (policyData.getRuleProvider() != null
423 && (policyData.getRuleProvider().equals(DecisionPolicy.GUARD_YAML)
424 || policyData.getRuleProvider().equals(DecisionPolicy.GUARD_BL_YAML)
425 || policyData.getRuleProvider().equals(DecisionPolicy.GUARD_MIN_MAX))
426 && policyData.getYamlparams() != null) {
427 attributeMap.put("actor", policyData.getYamlparams().getActor());
428 attributeMap.put("recipe", policyData.getYamlparams().getRecipe());
429 attributeMap.put("clname", policyData.getYamlparams().getClname());
430 attributeMap.put("limit", policyData.getYamlparams().getLimit());
431 attributeMap.put("min", policyData.getYamlparams().getMin());
432 attributeMap.put("max", policyData.getYamlparams().getMax());
433 attributeMap.put("timeWindow", policyData.getYamlparams().getTimeWindow());
434 attributeMap.put("timeUnits", policyData.getYamlparams().getTimeUnits());
435 attributeMap.put("guardActiveStart", policyData.getYamlparams().getGuardActiveStart());
436 attributeMap.put("guardActiveEnd", policyData.getYamlparams().getGuardActiveEnd());
437 if (policyData.getYamlparams().getBlackList() != null) {
438 String blackList = StringUtils.join(policyData.getYamlparams().getBlackList(), ",");
439 attributeMap.put("blackList", blackList);
441 if (DecisionPolicy.GUARD_BL_YAML.equals(policyData.getRuleProvider())
442 && "Use File Upload".equals(policyData.getBlackListEntryType())) {
443 if (policyData.getBlackListEntries() != null
444 && !policyData.getBlackListEntries().isEmpty()) {
445 String blackList = StringUtils.join(policyData.getBlackListEntries(), ",");
446 attributeMap.put("blackList", blackList);
448 if (policyData.getAppendBlackListEntries() != null
449 && !policyData.getAppendBlackListEntries().isEmpty()) {
450 String blackList = StringUtils.join(policyData.getAppendBlackListEntries(), ",");
451 attributeMap.put("appendBlackList", blackList);
454 if (policyData.getYamlparams().getTargets() != null) {
455 String targets = StringUtils.join(policyData.getYamlparams().getTargets(), ",");
456 attributeMap.put("targets", targets);
459 if (policyData.getRuleProvider() != null
460 && policyData.getRuleProvider().equals(DecisionPolicy.RAINY_DAY)) {
461 attributeMap.put("ServiceType", policyData.getRainyday().getServiceType());
462 attributeMap.put("VNFType", policyData.getRainyday().getVnfType());
463 attributeMap.put("BB_ID", policyData.getRainyday().getBbid());
464 attributeMap.put("WorkStep", policyData.getRainyday().getWorkstep());
466 if (policyData.getRainyday().getTreatmentTableChoices() != null
467 && policyData.getRainyday().getTreatmentTableChoices().isEmpty()) {
468 for (Object table : policyData.getRainyday().getTreatmentTableChoices()) {
469 if (table instanceof LinkedHashMap<?, ?>) {
470 String errorcode = ((LinkedHashMap<?, ?>) table).get("errorcode").toString();
471 String treatment = ((LinkedHashMap<?, ?>) table).get("treatment").toString();
472 treatmentMap.put(errorcode, treatment);
478 policyData.setDynamicRuleAlgorithmLabels(dynamicRuleAlgorithmLabels);
479 policyData.setDynamicRuleAlgorithmCombo(dynamicRuleAlgorithmCombo);
480 policyData.setDynamicRuleAlgorithmField1(dynamicRuleAlgorithmField1);
481 policyData.setDynamicRuleAlgorithmField2(dynamicRuleAlgorithmField2);
482 policyData.setDynamicVariableList(dynamicVariableList);
483 policyData.setDynamicSettingsMap(settingsMap);
484 policyData.setDynamicFieldConfigAttributes(attributeMap);
485 policyData.setDataTypeList(dataTypeList);
486 policyData.setRainydayMap(treatmentMap);
487 policyData.setErrorCodeList(errorCodeList);
488 policyData.setTreatmentList(treatmentList);
490 newPolicy = new DecisionPolicy(policyData);
493 if (newPolicy != null) {
494 newPolicy.prepareToSave();
497 status = HttpStatus.INTERNAL_SERVER_ERROR;
498 response.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
499 response.addHeader("error", "error");
500 return new ResponseEntity<>(body, status);
503 PolicyDBDaoTransaction policyDBDaoTransaction = null;
505 policyDBDao = PolicyDBDao.getPolicyDBDaoInstance();
506 policyDBDaoTransaction = policyDBDao.getNewTransaction();
507 policyDBDaoTransaction.createPolicy(newPolicy, policyData.getUserId());
508 successMap = newPolicy.savePolicies();
509 if (successMap.containsKey("success")) {
510 policyDBDaoTransaction.commitTransaction();
511 if (policyData.isEditPolicy()) {
512 commonClassDao.update(policyVersionDao);
514 commonClassDao.save(policyVersionDao);
517 PolicyElasticSearchController search = new PolicyElasticSearchController();
518 search.updateElk(policyData);
519 } catch (Exception e) {
520 LOGGER.error("Error Occured while saving policy to Elastic Database" + e);
523 status = HttpStatus.OK;
524 response.setStatus(HttpServletResponse.SC_OK);
525 response.addHeader("successMapKey", "success");
526 response.addHeader("policyName", policyData.getNewFileName());
528 // get message from the SafetyCheckerResults if present
529 String safetyCheckerResponse = policyData.getClWarning();
530 String existingCLName = policyData.getExistingCLName();
532 // if safetyCheckerResponse is not null add a header to send back with response
533 if (safetyCheckerResponse != null) {
534 PolicyLogger.info("SafetyCheckerResponse message: " + safetyCheckerResponse);
535 response.addHeader("safetyChecker", safetyCheckerResponse);
536 response.addHeader("newCLName", CLName);
537 response.addHeader("conflictCLName", existingCLName);
539 PolicyLogger.info("SafetyCheckerResponse was empty or null.");
542 } else if (successMap.containsKey("invalidAttribute")) {
543 String message = XACMLErrorConstants.ERROR_DATA_ISSUE + "Invalid Action Attribute";
544 LOGGER.error(XACMLErrorConstants.ERROR_DATA_ISSUE + "Could not fine "
545 + policyData.getActionAttribute() + " in the ActionPolicyDict table.");
546 body = "invalidAttribute";
547 status = HttpStatus.BAD_REQUEST;
548 response.setStatus(HttpServletResponse.SC_BAD_REQUEST);
549 response.addHeader("invalidAttribute", policyData.getActionAttribute());
550 response.addHeader("error", message);
551 response.addHeader("policyName", policyData.getPolicyName());
552 } else if (successMap.containsKey("fwdberror")) {
553 policyDBDaoTransaction.rollbackTransaction();
555 status = HttpStatus.BAD_REQUEST;
556 String message = XACMLErrorConstants.ERROR_DATA_ISSUE
557 + "Error when inserting Firewall ConfigBody data into the database.";
558 PolicyLogger.error(message);
559 response.setStatus(HttpServletResponse.SC_BAD_REQUEST);
560 response.addHeader("error", message);
561 response.addHeader("policyName", policyData.getPolicyName());
562 } else if (successMap.get("error").equals("Validation Failed")) {
563 policyDBDaoTransaction.rollbackTransaction();
564 String message = XACMLErrorConstants.ERROR_DATA_ISSUE + "Error Validating the Policy on the PAP.";
565 PolicyLogger.error(message);
567 status = HttpStatus.BAD_REQUEST;
568 response.setStatus(HttpServletResponse.SC_BAD_REQUEST);
569 response.addHeader("error", message);
570 response.addHeader("policyName", policyData.getPolicyName());
572 policyDBDaoTransaction.rollbackTransaction();
574 status = HttpStatus.INTERNAL_SERVER_ERROR;
575 response.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
576 response.addHeader("error", "error");
578 } catch (Exception e) {
579 LOGGER.error("Exception Occured : ", e);
580 if (policyDBDaoTransaction != null) {
581 policyDBDaoTransaction.rollbackTransaction();
584 } catch (Exception e) {
585 LOGGER.error("Exception Occured : " + e.getMessage(), e);
587 response.addHeader("error", e.getMessage());
588 response.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
590 return new ResponseEntity<>(body, status);
593 @ExceptionHandler({HttpMessageNotReadableException.class})
594 public ResponseEntity<String> messageNotReadableExceptionHandler(HttpServletRequest req,
595 HttpMessageNotReadableException exception) {
596 LOGGER.error("Request not readable: {}", exception);
597 StringBuilder message = new StringBuilder();
598 message.append(exception.getMessage());
599 if (exception.getCause() != null) {
600 message.append(" Reason Caused: " + exception.getCause().getMessage());
602 return new ResponseEntity<>(message.toString(), HttpStatus.BAD_REQUEST);
605 public PolicyVersion getPolicyVersionData(String dbCheckPolicyName) {
606 PolicyVersion entityItem =
607 (PolicyVersion) commonClassDao.getEntityItem(PolicyVersion.class, "policyName", dbCheckPolicyName);
608 if (entityItem != null) {
609 if (entityItem.getPolicyName().equals(dbCheckPolicyName)) {