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