a6cda5e680f66c04fb5fcdf6a77c5fab63255631
[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 && (policyData.getRuleProvider().equals(DecisionPolicy.GUARD_YAML)|| policyData.getRuleProvider().equals(DecisionPolicy.GUARD_BL_YAML)) 
406                                                         && policyData.getYamlparams()!=null){
407                                                 attributeMap.put("actor", policyData.getYamlparams().getActor());
408                                                 attributeMap.put("recipe", policyData.getYamlparams().getRecipe());
409                                                 attributeMap.put("clname", policyData.getYamlparams().getClname());
410                                                 attributeMap.put("limit", policyData.getYamlparams().getLimit());
411                                                 attributeMap.put("timeWindow", policyData.getYamlparams().getTimeWindow());
412                                                 attributeMap.put("timeUnits", policyData.getYamlparams().getTimeUnits());
413                                                 attributeMap.put("guardActiveStart", policyData.getYamlparams().getGuardActiveStart());
414                                                 attributeMap.put("guardActiveEnd", policyData.getYamlparams().getGuardActiveEnd());
415                                                 if(policyData.getYamlparams().getBlackList()!=null){
416                                                         String blackList = StringUtils.join(policyData.getYamlparams().getBlackList(), ",");
417                                                         attributeMap.put("blackList", blackList);
418                                                 }
419                                                 if(DecisionPolicy.GUARD_BL_YAML.equals(policyData.getRuleProvider()) && "Use File Upload".equals(policyData.getBlackListEntryType())){
420                                                         if(policyData.getBlackListEntries() != null && !policyData.getBlackListEntries().isEmpty()){
421                                                                 String blackList = StringUtils.join(policyData.getBlackListEntries(), ",");
422                                                                 attributeMap.put("blackList", blackList);
423                                                         }
424                                                         if(policyData.getAppendBlackListEntries() != null && !policyData.getAppendBlackListEntries().isEmpty()){
425                                                                 String blackList = StringUtils.join(policyData.getAppendBlackListEntries(), ",");
426                                                                 attributeMap.put("appendBlackList", blackList);
427                                                         }
428                                                 }
429                                                 if(policyData.getYamlparams().getTargets()!=null){
430                                                         String targets = StringUtils.join(policyData.getYamlparams().getTargets(),",");
431                                                         attributeMap.put("targets", targets);
432                                                 }
433                                         }
434                                         if(policyData.getRuleProvider()!=null && policyData.getRuleProvider().equals(DecisionPolicy.RAINY_DAY)){
435                                                 attributeMap.put("ServiceType", policyData.getRainyday().getServiceType());
436                                                 attributeMap.put("VNFType", policyData.getRainyday().getVnfType());
437                                                 attributeMap.put("BB_ID", policyData.getRainyday().getBbid());
438                                                 attributeMap.put("WorkStep", policyData.getRainyday().getWorkstep());
439                                                 
440                                                 if(policyData.getRainyday().getTreatmentTableChoices()!=null && policyData.getRainyday().getTreatmentTableChoices().size() > 0){
441                                                         for (Object table : policyData.getRainyday().getTreatmentTableChoices()){
442                                                                 if(table instanceof LinkedHashMap<?,?>){
443                                                                         String errorcode = ((LinkedHashMap<?,?>) table).get("errorcode").toString();
444                                                                         String treatment = ((LinkedHashMap<?,?>) table).get("treatment").toString();
445                                                                         treatmentMap.put(errorcode, treatment);
446                                                                 }
447                                                         }
448                                                 }
449                                         }
450                                         
451                                         policyData.setDynamicRuleAlgorithmLabels(dynamicRuleAlgorithmLabels);
452                                         policyData.setDynamicRuleAlgorithmCombo(dynamicRuleAlgorithmCombo);
453                                         policyData.setDynamicRuleAlgorithmField1(dynamicRuleAlgorithmField1);
454                                         policyData.setDynamicRuleAlgorithmField2(dynamicRuleAlgorithmField2);
455                                         policyData.setDynamicVariableList(dynamicVariableList);
456                                         policyData.setDynamicSettingsMap(settingsMap);
457                                         policyData.setDynamicFieldConfigAttributes(attributeMap);
458                                         policyData.setDataTypeList(dataTypeList);
459                                         policyData.setRainydayMap(treatmentMap);
460                                         policyData.setErrorCodeList(errorCodeList);
461                                         policyData.setTreatmentList(treatmentList);
462                                 }
463                                 newPolicy = new DecisionPolicy(policyData, commonClassDao);
464                         }
465
466                         if(newPolicy != null){
467                                 newPolicy.prepareToSave();
468                         }else{
469                                 body = "error";
470                                 status = HttpStatus.INTERNAL_SERVER_ERROR;
471                                 response.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);                                                               
472                                 response.addHeader("error", "error");
473                                 return new ResponseEntity<>(body, status);
474                         }
475                         
476                         PolicyDBDaoTransaction policyDBDaoTransaction = null;
477                         try{
478                                 policyDBDao = PolicyDBDao.getPolicyDBDaoInstance(XACMLPapServlet.getEmf());
479                                 policyDBDaoTransaction = policyDBDao.getNewTransaction();
480                                 policyDBDaoTransaction.createPolicy(newPolicy, policyData.getUserId());
481                                 successMap = newPolicy.savePolicies();
482                                 if(successMap.containsKey("success")){
483                                         policyDBDaoTransaction.commitTransaction();
484                                         if(policyData.isEditPolicy()){
485                                                 commonClassDao.update(policyVersionDao);
486                                         }else{
487                                                 commonClassDao.save(policyVersionDao);
488                                         }
489                                         try{
490                                                 PolicyElasticSearchController search= new PolicyElasticSearchController();
491                                                 search.updateElk(policyData);
492                                         }catch(Exception e){
493                                                 LOGGER.error("Error Occured while saving policy to Elastic Database"+e);
494                                         }
495                                         body = "success";
496                                         status = HttpStatus.OK;
497                                         response.setStatus(HttpServletResponse.SC_OK);                                                          
498                                         response.addHeader("successMapKey", "success");                                                         
499                                         response.addHeader("policyName", policyData.getNewFileName());
500                                         
501                     //get message from the SafetyCheckerResults if present
502                     String safetyCheckerResponse = policyData.getClWarning();
503                     String existingCLName = policyData.getExistingCLName();
504
505                     //if safetyCheckerResponse is not null add a header to send back with response
506                     if(safetyCheckerResponse!=null) {
507                         PolicyLogger.info("SafetyCheckerResponse message: " + safetyCheckerResponse);
508                         response.addHeader("safetyChecker", safetyCheckerResponse);
509                         response.addHeader("newCLName", CLName);
510                         response.addHeader("conflictCLName", existingCLName);
511                     } else {
512                         PolicyLogger.info("SafetyCheckerResponse was empty or null.");
513                     }
514                     
515                                 }else if (successMap.containsKey("invalidAttribute")) {
516                                         String message = XACMLErrorConstants.ERROR_DATA_ISSUE + "Invalid Action Attribute";
517                                         LOGGER.error(XACMLErrorConstants.ERROR_DATA_ISSUE + "Could not fine " + policyData.getActionAttribute() + " in the ActionPolicyDict table.");
518                                         body = "invalidAttribute";
519                                         status = HttpStatus.BAD_REQUEST;
520                                         response.setStatus(HttpServletResponse.SC_BAD_REQUEST);                                                         
521                                         response.addHeader("invalidAttribute", policyData.getActionAttribute());
522                                         response.addHeader("error", message);
523                                         response.addHeader("policyName", policyData.getPolicyName());
524                                 }else if (successMap.containsKey("fwdberror")) {
525                                         policyDBDaoTransaction.rollbackTransaction();
526                                         body = "fwdberror";
527                                         status = HttpStatus.BAD_REQUEST;
528                                         String message = XACMLErrorConstants.ERROR_DATA_ISSUE
529                             + "Error when inserting Firewall ConfigBody data into the database.";
530                                 PolicyLogger.error(message);
531                                         response.setStatus(HttpServletResponse.SC_BAD_REQUEST);
532                                         response.addHeader("error", message);
533                                         response.addHeader("policyName", policyData.getPolicyName());
534                                 } else if (successMap.get("error").equals("Validation Failed")) {
535                     policyDBDaoTransaction.rollbackTransaction();
536                     String message = XACMLErrorConstants.ERROR_DATA_ISSUE
537                                         + "Error Validating the Policy on the PAP.";
538                     PolicyLogger.error(message);
539                     body = "Validation";
540                                         status = HttpStatus.BAD_REQUEST;
541                     response.setStatus(HttpServletResponse.SC_BAD_REQUEST);
542                     response.addHeader("error", message);
543                     response.addHeader("policyName", policyData.getPolicyName());
544                 }else {                                         
545                                         policyDBDaoTransaction.rollbackTransaction();
546                                         body = "error";
547                                         status = HttpStatus.INTERNAL_SERVER_ERROR;
548                                         response.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);                                                               
549                                         response.addHeader("error", "error");                                                   
550                                 }
551                         }catch(Exception e){
552                                 LOGGER.error("Exception Occured : ",e);
553                                 if(policyDBDaoTransaction != null){
554                                         policyDBDaoTransaction.rollbackTransaction();
555                                 }
556                         }
557                 }
558                 catch (Exception e){
559                         LOGGER.error("Exception Occured : "+e.getMessage(),e);
560                         body = "error";
561                         response.addHeader("error", e.getMessage());    
562                         response.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
563                 }
564                 return new ResponseEntity<>(body, status);
565         }
566
567         @ExceptionHandler({ HttpMessageNotReadableException.class })
568         public ResponseEntity<String> messageNotReadableExceptionHandler(HttpServletRequest req, HttpMessageNotReadableException exception) {
569                 LOGGER.error("Request not readable: {}", exception);
570                 StringBuilder message = new StringBuilder();
571                 message.append(exception.getMessage());
572                 if (exception.getCause() != null) {
573                         message.append(" Reason Caused: "
574                                         + exception.getCause().getMessage());
575                 }
576                 return new ResponseEntity<>(message.toString(), HttpStatus.BAD_REQUEST);
577         }
578
579         public PolicyVersion getPolicyVersionData(String dbCheckPolicyName){
580                 PolicyVersion entityItem = (PolicyVersion) commonClassDao.getEntityItem(PolicyVersion.class, "policyName", dbCheckPolicyName);
581                 if (entityItem != null) {               
582                         if(entityItem.getPolicyName().equals(dbCheckPolicyName)){
583                                 return entityItem;
584                         }
585                 }       
586                 return entityItem;
587         }
588 }