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