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