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