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