Modified the code to fix various pushPolicy issues
[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                                 // if policy does not exist and the request is updatePolicy return error
197                                 if(policyData.isEditPolicy()){
198                                         body = "policyNotAvailableForEdit";
199                                         status = HttpStatus.NOT_FOUND;
200                                         response.setStatus(HttpServletResponse.SC_NOT_FOUND);
201                                         response.addHeader("error", body);
202                                         response.addHeader("message", policyData.getPolicyName() + " does not exist on the PAP and cannot be updated.");
203                                         return new ResponseEntity<String>(body, status);
204                                 }
205                                 version = 1;
206                                 if(userId == null){
207                                         createdBy = "API";
208                                         modifiedBy = "API";
209                                         policyData.setUserId("API");
210                                 }else{
211                                         createdBy = userId;
212                                         modifiedBy = userId;
213                                         policyData.setUserId("API");
214                                 }
215                                 policyVersionDao = new PolicyVersion();
216                                 policyVersionDao.setPolicyName(dbCheckPolicyName);
217                                 policyVersionDao.setActiveVersion(version);
218                                 policyVersionDao.setHigherVersion(version);
219                                 policyVersionDao.setCreatedBy(createdBy);
220                                 policyVersionDao.setModifiedBy(modifiedBy);
221                         }
222                         
223                         policyData.setPolicyID(newPolicyID());
224                         policyData.setRuleID(ruleID);
225         
226                         String policyFileName = dbCheckPolicyName.replace(File.separator, ".")+ "." + version + ".xml";
227                         policyData.setNewFileName(policyFileName);
228                         policyData.setPolicyDescription(policyData.getPolicyDescription()+ "@CreatedBy:" +createdBy + "@CreatedBy:" + "@ModifiedBy:" +modifiedBy + "@ModifiedBy:");
229                         policyData.setRuleCombiningAlgId("urn:oasis:names:tc:xacml:3.0:rule-combining-algorithm:permit-overrides");
230                         if(policyData.getApiflag() == null){
231                                 //set the Rule Combining Algorithm Id to be sent to PAP-REST via JSON   
232                                 if(policyData.getAttributes() != null){
233                                         if(policyData.getAttributes().size() > 0){
234                                                 for(Object attribute : policyData.getAttributes()){
235                                                         if(attribute instanceof LinkedHashMap<?, ?>){
236                                                                 String key = ((LinkedHashMap<?, ?>) attribute).get("key").toString();
237                                                                 String value = ((LinkedHashMap<?, ?>) attribute).get("value").toString();
238                                                                 attributeMap.put(key, value);   
239                                                         }
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 (policyType.equalsIgnoreCase("Config")) {
251                                 if (policyConfigType.equalsIgnoreCase("Firewall Config")) {
252                                         newPolicy = new FirewallConfigPolicy(policyData);
253                                 }else if (policyConfigType.equalsIgnoreCase("BRMS_Raw")) { 
254                                         policyData.setOnapName("DROOLS");
255                                         policyData.setConfigName("BRMS_RAW_RULE");
256                                         newPolicy = new CreateBrmsRawPolicy(policyData);
257                                 }else if (policyConfigType.equalsIgnoreCase("BRMS_Param")) {
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=(String) 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 (policyConfigType.equalsIgnoreCase("Base")) {
291                                         newPolicy =  new ConfigPolicy(policyData);
292                                 }else if (policyConfigType.equalsIgnoreCase("ClosedLoop_Fault")) {
293                                         newPolicy = new ClosedLoopPolicy(policyData);
294                                 }else if (policyConfigType.equalsIgnoreCase("ClosedLoop_PM")) {
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 (policyConfigType.equalsIgnoreCase("Micro Service")) {
305                                         newPolicy = new MicroServiceConfigPolicy(policyData);
306                                 }
307                         }else if(policyType.equalsIgnoreCase("Action")) {
308                                 if(policyData.getApiflag() == null){
309                                         List<String> dynamicRuleAlgorithmLabels = new LinkedList<>();
310                                         List<String> dynamicRuleAlgorithmCombo = new LinkedList<>();
311                                         List<String> dynamicRuleAlgorithmField1 = new LinkedList<>();
312                                         List<String> dynamicRuleAlgorithmField2 = new LinkedList<>();
313
314
315                                         if(policyData.getRuleAlgorithmschoices().size() > 0){
316                                                 for(Object attribute : policyData.getRuleAlgorithmschoices()){
317                                                         if(attribute instanceof LinkedHashMap<?, ?>){
318                                                                 String label = ((LinkedHashMap<?, ?>) attribute).get("id").toString();
319                                                                 String key = ((LinkedHashMap<?, ?>) attribute).get("dynamicRuleAlgorithmField1").toString();
320                                                                 String rule = ((LinkedHashMap<?, ?>) attribute).get("dynamicRuleAlgorithmCombo").toString();
321                                                                 String value = ((LinkedHashMap<?, ?>) attribute).get("dynamicRuleAlgorithmField2").toString();
322                                                                 dynamicRuleAlgorithmLabels.add(label);
323                                                                 dynamicRuleAlgorithmField1.add(key);
324                                                                 dynamicRuleAlgorithmCombo.add(rule);
325                                                                 dynamicRuleAlgorithmField2.add(value);
326                                                         }
327                                                 }
328                                         }
329
330                                         String actionDictValue = policyData.getActionAttributeValue();
331                                         ActionPolicyDict jsonData = ((ActionPolicyDict) commonClassDao.getEntityItem(ActionPolicyDict.class, "attributeName", actionDictValue));
332                                         String actionBodyString = jsonData.getBody();
333                                         String actionDictHeader = jsonData.getHeader();
334                                         String actionDictType = jsonData.getType();
335                                         String actionDictUrl = jsonData.getUrl();
336                                         String actionDictMethod = jsonData.getMethod();
337                                         policyData.setActionDictHeader(actionDictHeader);
338                                         policyData.setActionDictType(actionDictType);
339                                         policyData.setActionDictUrl(actionDictUrl);
340                                         policyData.setActionDictMethod(actionDictMethod);
341                                         policyData.setActionAttribute(actionDictValue);
342                                         policyData.setDynamicRuleAlgorithmLabels(dynamicRuleAlgorithmLabels);
343                                         policyData.setDynamicRuleAlgorithmCombo(dynamicRuleAlgorithmCombo);
344                                         policyData.setDynamicRuleAlgorithmField1(dynamicRuleAlgorithmField1);
345                                         policyData.setDynamicRuleAlgorithmField2(dynamicRuleAlgorithmField2);
346                                         if (actionBodyString != null) {
347                                                 policyData.setActionBody(actionBodyString);
348                                         }
349                                 }
350                                 newPolicy = new ActionPolicy(policyData);
351                         } else if (policyType.equalsIgnoreCase("Decision")) {
352                                 if(policyData.getApiflag() == null){
353                                         Map<String, String> settingsMap = new HashMap<>();
354                                         Map<String, String> treatmentMap = new HashMap<>();
355                                         List<String> dynamicRuleAlgorithmLabels = new LinkedList<>();
356                                         List<String> dynamicRuleAlgorithmCombo = new LinkedList<>();
357                                         List<String> dynamicRuleAlgorithmField1 = new LinkedList<>();
358                                         List<String> dynamicRuleAlgorithmField2 = new LinkedList<>();
359                                         List<Object> dynamicVariableList = new LinkedList<>();
360                                         List<String> dataTypeList = new LinkedList<>();
361                                         List<String> errorCodeList = new LinkedList<>();
362                                         List<String> treatmentList = new LinkedList<>();
363
364                                         if(policyData.getSettings().size() > 0){
365                                                 for(Object settingsData : policyData.getSettings()){
366                                                         if(settingsData instanceof LinkedHashMap<?, ?>){
367                                                                 String key = ((LinkedHashMap<?, ?>) settingsData).get("key").toString();
368                                                                 String value = ((LinkedHashMap<?, ?>) settingsData).get("value").toString();
369                                                                 settingsMap.put(key, value);    
370                                                         }
371                                                 }
372                                         }
373                                         if(policyData.getRuleAlgorithmschoices()!=null && policyData.getRuleAlgorithmschoices().size() > 0){
374                                                 for(Object attribute : policyData.getRuleAlgorithmschoices()){
375                                                         if(attribute instanceof LinkedHashMap<?, ?>){
376                                                                 String label = ((LinkedHashMap<?, ?>) attribute).get("id").toString();
377                                                                 String key = ((LinkedHashMap<?, ?>) attribute).get("dynamicRuleAlgorithmField1").toString();
378                                                                 String rule = ((LinkedHashMap<?, ?>) attribute).get("dynamicRuleAlgorithmCombo").toString();
379                                                                 String value = ((LinkedHashMap<?, ?>) attribute).get("dynamicRuleAlgorithmField2").toString();
380                                                                 dynamicRuleAlgorithmLabels.add(label);
381                                                                 dynamicRuleAlgorithmField1.add(key);
382                                                                 dynamicRuleAlgorithmCombo.add(rule);
383                                                                 dynamicRuleAlgorithmField2.add(value);
384                                                         }
385                                                 }
386                                         }
387                                         if(policyData.getRuleProvider()!=null && (policyData.getRuleProvider().equals(DecisionPolicy.GUARD_YAML)|| policyData.getRuleProvider().equals(DecisionPolicy.GUARD_BL_YAML)) 
388                                                         && policyData.getYamlparams()!=null){
389                                                 attributeMap.put("actor", policyData.getYamlparams().getActor());
390                                                 attributeMap.put("recipe", policyData.getYamlparams().getRecipe());
391                                                 attributeMap.put("clname", policyData.getYamlparams().getClname());
392                                                 attributeMap.put("limit", policyData.getYamlparams().getLimit());
393                                                 attributeMap.put("timeWindow", policyData.getYamlparams().getTimeWindow());
394                                                 attributeMap.put("timeUnits", policyData.getYamlparams().getTimeUnits());
395                                                 attributeMap.put("guardActiveStart", policyData.getYamlparams().getGuardActiveStart());
396                                                 attributeMap.put("guardActiveEnd", policyData.getYamlparams().getGuardActiveEnd());
397                                                 if(policyData.getYamlparams().getBlackList()!=null){
398                                                         String blackList = StringUtils.join(policyData.getYamlparams().getBlackList(), ",");
399                                                         attributeMap.put("blackList", blackList);
400                                                 }
401                                                 if(policyData.getYamlparams().getTargets()!=null){
402                                                         String targets = StringUtils.join(policyData.getYamlparams().getTargets(),",");
403                                                         attributeMap.put("targets", targets);
404                                                 }
405                                         }
406                                         if(policyData.getRuleProvider()!=null && policyData.getRuleProvider().equals(DecisionPolicy.RAINY_DAY)){
407                                                 attributeMap.put("ServiceType", policyData.getRainyday().getServiceType());
408                                                 attributeMap.put("VNFType", policyData.getRainyday().getVnfType());
409                                                 attributeMap.put("BB_ID", policyData.getRainyday().getBbid());
410                                                 attributeMap.put("WorkStep", policyData.getRainyday().getWorkstep());
411                                                 
412                                                 if(policyData.getRainyday().getTreatmentTableChoices()!=null && policyData.getRainyday().getTreatmentTableChoices().size() > 0){
413                                                         for (Object table : policyData.getRainyday().getTreatmentTableChoices()){
414                                                                 if(table instanceof LinkedHashMap<?,?>){
415                                                                         String errorcode = ((LinkedHashMap<?,?>) table).get("errorcode").toString();
416                                                                         String treatment = ((LinkedHashMap<?,?>) table).get("treatment").toString();
417                                                                         treatmentMap.put(errorcode, treatment);
418                                                                 }
419                                                         }
420                                                 }
421                                         }
422                                         
423                                         policyData.setDynamicRuleAlgorithmLabels(dynamicRuleAlgorithmLabels);
424                                         policyData.setDynamicRuleAlgorithmCombo(dynamicRuleAlgorithmCombo);
425                                         policyData.setDynamicRuleAlgorithmField1(dynamicRuleAlgorithmField1);
426                                         policyData.setDynamicRuleAlgorithmField2(dynamicRuleAlgorithmField2);
427                                         policyData.setDynamicVariableList(dynamicVariableList);
428                                         policyData.setDynamicSettingsMap(settingsMap);
429                                         policyData.setDynamicFieldConfigAttributes(attributeMap);
430                                         policyData.setDataTypeList(dataTypeList);
431                                         policyData.setRainydayMap(treatmentMap);
432                                         policyData.setErrorCodeList(errorCodeList);
433                                         policyData.setTreatmentList(treatmentList);
434                                 }
435                                 newPolicy = new DecisionPolicy(policyData);
436                         }
437
438                         if(newPolicy != null){
439                                 newPolicy.prepareToSave();
440                         }else{
441                                 body = "error";
442                                 status = HttpStatus.INTERNAL_SERVER_ERROR;
443                                 response.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);                                                               
444                                 response.addHeader("error", "error");
445                                 return new ResponseEntity<String>(body, status);
446                         }
447                         
448                         PolicyDBDaoTransaction policyDBDaoTransaction = null;
449                         try{
450                                 policyDBDao = PolicyDBDao.getPolicyDBDaoInstance(XACMLPapServlet.getEmf());
451                                 policyDBDaoTransaction = policyDBDao.getNewTransaction();
452                                 policyDBDaoTransaction.createPolicy(newPolicy, policyData.getUserId());
453                                 successMap = newPolicy.savePolicies();
454                                 if(successMap.containsKey("success")){
455                                         policyDBDaoTransaction.commitTransaction();
456                                         if(policyData.isEditPolicy()){
457                                                 commonClassDao.update(policyVersionDao);
458                                         }else{
459                                                 commonClassDao.save(policyVersionDao);
460                                         }
461                                         try{
462                                                 PolicyElasticSearchController search= new PolicyElasticSearchController();
463                                                 search.updateElk(policyData);
464                                         }catch(Exception e){
465                                                 LOGGER.error("Error Occured while saving policy to Elastic Database"+e);
466                                         }
467                                         body = "success";
468                                         status = HttpStatus.OK;
469                                         response.setStatus(HttpServletResponse.SC_OK);                                                          
470                                         response.addHeader("successMapKey", "success");                                                         
471                                         response.addHeader("policyName", policyData.getNewFileName());
472                                         
473                     //get message from the SafetyCheckerResults if present
474                     String safetyCheckerResponse = policyData.getClWarning();
475                     String existingCLName = policyData.getExistingCLName();
476
477                     //if safetyCheckerResponse is not null add a header to send back with response
478                     if(safetyCheckerResponse!=null) {
479                         PolicyLogger.info("SafetyCheckerResponse message: " + safetyCheckerResponse);
480                         response.addHeader("safetyChecker", safetyCheckerResponse);
481                         response.addHeader("newCLName", CLName);
482                         response.addHeader("conflictCLName", existingCLName);
483                     } else {
484                         PolicyLogger.info("SafetyCheckerResponse was empty or null.");
485                     }
486                     
487                                 }else if (successMap.containsKey("invalidAttribute")) {
488                                         String message = XACMLErrorConstants.ERROR_DATA_ISSUE + "Invalid Action Attribute";
489                                         LOGGER.error(XACMLErrorConstants.ERROR_DATA_ISSUE + "Could not fine " + policyData.getActionAttribute() + " in the ActionPolicyDict table.");
490                                         body = "invalidAttribute";
491                                         status = HttpStatus.BAD_REQUEST;
492                                         response.setStatus(HttpServletResponse.SC_BAD_REQUEST);                                                         
493                                         response.addHeader("invalidAttribute", policyData.getActionAttribute());
494                                         response.addHeader("error", message);
495                                         response.addHeader("policyName", policyData.getPolicyName());
496                                 }else if (successMap.containsKey("fwdberror")) {
497                                         policyDBDaoTransaction.rollbackTransaction();
498                                         body = "fwdberror";
499                                         status = HttpStatus.BAD_REQUEST;
500                                         String message = XACMLErrorConstants.ERROR_DATA_ISSUE
501                             + "Error when inserting Firewall ConfigBody data into the database.";
502                                 PolicyLogger.error(message);
503                                         response.setStatus(HttpServletResponse.SC_BAD_REQUEST);
504                                         response.addHeader("error", message);
505                                         response.addHeader("policyName", policyData.getPolicyName());
506                                 } else if (successMap.get("error").equals("Validation Failed")) {
507                     policyDBDaoTransaction.rollbackTransaction();
508                     String message = XACMLErrorConstants.ERROR_DATA_ISSUE
509                                         + "Error Validating the Policy on the PAP.";
510                     PolicyLogger.error(message);
511                     body = "Validation";
512                                         status = HttpStatus.BAD_REQUEST;
513                     response.setStatus(HttpServletResponse.SC_BAD_REQUEST);
514                     response.addHeader("error", message);
515                     response.addHeader("policyName", policyData.getPolicyName());
516                 }else {                                         
517                                         policyDBDaoTransaction.rollbackTransaction();
518                                         body = "error";
519                                         status = HttpStatus.INTERNAL_SERVER_ERROR;
520                                         response.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);                                                               
521                                         response.addHeader("error", "error");                                                   
522                                 }
523                         }catch(Exception e){
524                                 LOGGER.error("Exception Occured : ",e);
525                                 if(policyDBDaoTransaction != null){
526                                         policyDBDaoTransaction.rollbackTransaction();
527                                 }
528                         }
529                 }
530                 catch (Exception e){
531                         LOGGER.error("Exception Occured : "+e.getMessage(),e);
532                         body = "error";
533                         response.addHeader("error", e.getMessage());    
534                         response.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
535                 }
536                 return new ResponseEntity<>(body, status);
537         }
538
539         @ExceptionHandler({ HttpMessageNotReadableException.class })
540         public ResponseEntity<String> messageNotReadableExceptionHandler(HttpServletRequest req, HttpMessageNotReadableException exception) {
541                 LOGGER.error("Request not readable: {}", exception);
542                 StringBuilder message = new StringBuilder();
543                 message.append(exception.getMessage());
544                 if (exception.getCause() != null) {
545                         message.append(" Reason Caused: "
546                                         + exception.getCause().getMessage());
547                 }
548                 return new ResponseEntity<>(message.toString(), HttpStatus.BAD_REQUEST);
549         }
550
551         public PolicyVersion getPolicyVersionData(String dbCheckPolicyName){
552                 PolicyVersion entityItem = (PolicyVersion) commonClassDao.getEntityItem(PolicyVersion.class, "policyName", dbCheckPolicyName);
553                 if (entityItem != null) {               
554                         if(entityItem.getPolicyName().equals(dbCheckPolicyName)){
555                                 return entityItem;
556                         }
557                 }       
558                 return entityItem;
559         }
560 }