Fix Policy import/export on gui
[policy/engine.git] / POLICY-SDK-APP / src / main / java / org / onap / policy / controller / PolicyExportAndImportController.java
1 /*-
2  * ============LICENSE_START=======================================================
3  * ONAP Policy Engine
4  * ================================================================================
5  * Copyright (C) 2017-2020 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
21 package org.onap.policy.controller;
22
23 import com.fasterxml.jackson.databind.DeserializationFeature;
24 import com.fasterxml.jackson.databind.JsonNode;
25 import com.fasterxml.jackson.databind.ObjectMapper;
26 import java.io.BufferedWriter;
27 import java.io.File;
28 import java.io.FileInputStream;
29 import java.io.FileOutputStream;
30 import java.io.FileWriter;
31 import java.io.IOException;
32 import java.io.PrintWriter;
33 import java.util.ArrayList;
34 import java.util.Iterator;
35 import java.util.LinkedHashMap;
36 import java.util.List;
37 import java.util.Set;
38 import javax.script.SimpleBindings;
39 import javax.servlet.http.HttpServletRequest;
40 import javax.servlet.http.HttpServletResponse;
41 import org.apache.commons.lang3.StringUtils;
42 import org.apache.poi.hssf.usermodel.HSSFRow;
43 import org.apache.poi.hssf.usermodel.HSSFSheet;
44 import org.apache.poi.hssf.usermodel.HSSFWorkbook;
45 import org.apache.poi.ss.usermodel.Cell;
46 import org.apache.poi.ss.usermodel.Row;
47 import org.apache.poi.ss.usermodel.Sheet;
48 import org.json.JSONObject;
49 import org.onap.policy.admin.PolicyRestController;
50 import org.onap.policy.common.logging.flexlogger.FlexLogger;
51 import org.onap.policy.common.logging.flexlogger.Logger;
52 import org.onap.policy.rest.adapter.PolicyExportAdapter;
53 import org.onap.policy.rest.dao.CommonClassDao;
54 import org.onap.policy.rest.jpa.ActionBodyEntity;
55 import org.onap.policy.rest.jpa.ConfigurationDataEntity;
56 import org.onap.policy.rest.jpa.DcaeUuid;
57 import org.onap.policy.rest.jpa.GroupPolicyScopeList;
58 import org.onap.policy.rest.jpa.MicroServiceConfigName;
59 import org.onap.policy.rest.jpa.MicroServiceLocation;
60 import org.onap.policy.rest.jpa.MicroServiceModels;
61 import org.onap.policy.rest.jpa.PolicyEditorScopes;
62 import org.onap.policy.rest.jpa.PolicyEntity;
63 import org.onap.policy.rest.jpa.PolicyVersion;
64 import org.onap.policy.rest.jpa.UserInfo;
65 import org.onap.policy.utils.PolicyUtils;
66 import org.onap.policy.utils.UserUtils.Pair;
67 import org.onap.policy.xacml.api.XACMLErrorConstants;
68 import org.onap.portalsdk.core.controller.RestrictedBaseController;
69 import org.onap.portalsdk.core.web.support.UserUtils;
70 import org.springframework.beans.factory.annotation.Autowired;
71 import org.springframework.stereotype.Controller;
72 import org.springframework.web.bind.annotation.RequestMapping;
73
74 @Controller
75 @RequestMapping("/")
76 public class PolicyExportAndImportController extends RestrictedBaseController {
77
78     private static Logger logger = FlexLogger.getLogger(PolicyExportAndImportController.class);
79
80     private static String superAdmin = "super-admin";
81     private static String superEditor = "super-editor";
82     private static String admin = "admin";
83     private static String editor = "editor";
84     private static String policyName = "policyName";
85     private static String configurationName = "configurationName";
86     private static String configurationbody = "configurationbody";
87     private static String config = "Config_";
88     private static final String CONFIG_MS = "Config_MS_";
89     private static final String NOTVALID = " is not valid.";
90     private static final String POLICY = "Policy:";
91     private static final String BODYSIZE = "bodySize";
92     private static final String DECISION_MS = "Decision_MS_";
93     private static final String ACTION = "Action_";
94     private static CommonClassDao commonClassDao;
95
96     private PolicyController policyController;
97
98     public PolicyController getPolicyController() {
99         return policyController;
100     }
101
102     public void setPolicyController(PolicyController policyController) {
103         this.policyController = policyController;
104     }
105
106     public static CommonClassDao getCommonClassDao() {
107         return commonClassDao;
108     }
109
110     public static void setCommonClassDao(CommonClassDao commonClassDao) {
111         PolicyExportAndImportController.commonClassDao = commonClassDao;
112     }
113
114     public PolicyExportAndImportController() {
115         // Empty constructor
116     }
117
118     @Autowired
119     private PolicyExportAndImportController(CommonClassDao commonClassDao) {
120         PolicyExportAndImportController.commonClassDao = commonClassDao;
121     }
122
123     /**
124      * This is for downloading existing policy.
125      *
126      * @param request HttpServletRequest
127      * @param response HttpServletResponse
128      * @throws IOException error out
129      */
130     @RequestMapping(
131             value = {"/policy_download/exportPolicy.htm"},
132             method = {org.springframework.web.bind.annotation.RequestMethod.POST})
133     public void exportPolicy(HttpServletRequest request, HttpServletResponse response) throws IOException {
134         try (HSSFWorkbook workBook2 = new HSSFWorkbook()) {
135             ArrayList<String> selectedPolicy = new ArrayList<>();
136             ObjectMapper mapper = new ObjectMapper();
137             mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
138             JsonNode root = mapper.readTree(request.getReader());
139             PolicyExportAdapter adapter =
140                     mapper.readValue(root.get("exportData").toString(), PolicyExportAdapter.class);
141             for (Object policyId : adapter.getPolicyDatas()) {
142                 LinkedHashMap<?, ?> selected = (LinkedHashMap<?, ?>) policyId;
143                 String policyWithScope =
144                         selected.get(policyName).toString() + "." + selected.get("activeVersion").toString() + ".xml";
145                 String scope = policyWithScope.substring(0, policyWithScope.lastIndexOf(File.separator))
146                         .replace(File.separator, ".");
147                 String policyNamel = policyWithScope.substring(policyWithScope.lastIndexOf(File.separator) + 1);
148                 selectedPolicy.add(policyNamel + ":" + scope);
149             }
150
151             HSSFSheet sheet = workBook2.createSheet("PolicyEntity");
152             HSSFRow headingRow = sheet.createRow(0);
153             headingRow.createCell(0).setCellValue(policyName);
154             headingRow.createCell(1).setCellValue("scope");
155             headingRow.createCell(2).setCellValue("version");
156             headingRow.createCell(3).setCellValue("policyData");
157             headingRow.createCell(4).setCellValue("description");
158             headingRow.createCell(5).setCellValue(configurationName);
159             headingRow.createCell(6).setCellValue(BODYSIZE);
160             headingRow.createCell(7).setCellValue(configurationbody);
161
162             List<Object> entityData = commonClassDao.getMultipleDataOnAddingConjunction(PolicyEntity.class,
163                     "policyName:scope", selectedPolicy);
164             processEntityData(entityData, sheet, headingRow); //
165             String tmp = System.getProperty("catalina.base") + File.separator + "webapps" + File.separator + "temp";
166             String deleteCheckPath = tmp + File.separator + "PolicyExport.xls";
167             File deleteCheck = new File(deleteCheckPath);
168             if (deleteCheck.exists() && deleteCheck.delete()) {
169                 logger.info("Deleted the file from system before exporting a new file.");
170             }
171             File temPath = new File(tmp);
172             if (!temPath.exists()) {
173                 temPath.mkdir();
174             }
175
176             String file = temPath + File.separator + "PolicyExport.xls";
177             File filepath = new File(file);
178             FileOutputStream fos = new FileOutputStream(filepath);
179             workBook2.write(fos);
180             fos.flush();
181
182             response.setContentType(PolicyUtils.APPLICATION_JSON);
183             request.setCharacterEncoding(PolicyUtils.CHARACTER_ENCODING);
184
185             PrintWriter out = response.getWriter();
186             String successMap = file.substring(file.lastIndexOf("webapps") + 8);
187             String responseString = mapper.writeValueAsString(successMap);
188             JSONObject json = new JSONObject("{data: " + responseString + "}");
189             out.write(json.toString());
190         } catch (Exception e) {
191             logger.error(XACMLErrorConstants.ERROR_SYSTEM_ERROR + "Exception Occured while Exporting Policies" + e);
192         }
193     }
194
195     private void processEntityData(List<Object> entityData, HSSFSheet sheet, HSSFRow headingRow) {
196
197         short rowNo = 1;
198         for (Object object : entityData) {
199             PolicyEntity policyEntity = (PolicyEntity) object;
200             HSSFRow row = sheet.createRow(rowNo);
201             row.createCell(0).setCellValue(policyEntity.getPolicyName());
202             row.createCell(1).setCellValue(policyEntity.getScope());
203             row.createCell(2).setCellValue(policyEntity.getVersion());
204             row.createCell(3).setCellValue(policyEntity.getPolicyData());
205             row.createCell(4).setCellValue(policyEntity.getDescription());
206             if (policyEntity.getPolicyName().contains(DECISION_MS)
207                     || !policyEntity.getPolicyName().contains("Decision_")) {
208                 if (policyEntity.getConfigurationData() != null) {
209                     row.createCell(5).setCellValue(policyEntity.getConfigurationData().getConfigurationName());
210                     String body = policyEntity.getConfigurationData().getConfigBody();
211                     row = populateConfigParam(policyEntity, row, headingRow, body);
212                 }
213                 populateActionBodyEntity(policyEntity, row);
214             } else {
215                 row.createCell(5).setCellValue("");
216                 row.createCell(6).setCellValue(0);
217                 row.createCell(7).setCellValue("");
218             }
219             rowNo++;
220         }
221     }
222
223     private HSSFRow populateActionBodyEntity(PolicyEntity policyEntity, HSSFRow row) {
224         if (policyEntity.getActionBodyEntity() != null) {
225             row.createCell(5).setCellValue(policyEntity.getActionBodyEntity().getActionBodyName());
226             row.createCell(6).setCellValue(0);
227             row.createCell(7).setCellValue(policyEntity.getActionBodyEntity().getActionBody());
228         }
229         return row;
230     }
231
232     private HSSFRow populateConfigParam(PolicyEntity policyEntity, HSSFRow row, HSSFRow headingRow, String body) {
233
234         if (policyEntity.getPolicyName().contains("Config_BRMS_Param_")) {
235             int index = 0;
236             int arraySize = 0;
237             while (index < body.length()) {
238                 if (arraySize == 0) {
239                     row.createCell(7).setCellValue(body.substring(index, Math.min(index + 30000, body.length())));
240                 } else {
241                     headingRow.createCell(7 + arraySize).setCellValue(configurationbody + arraySize);
242                     row.createCell(7 + arraySize)
243                             .setCellValue(body.substring(index, Math.min(index + 30000, body.length())));
244                 }
245                 index += 30000;
246                 arraySize += 1;
247             }
248             row.createCell(6).setCellValue(arraySize);
249         } else {
250             row.createCell(6).setCellValue(0);
251             row.createCell(7).setCellValue(body);
252         }
253         return row;
254     }
255
256     /**
257      * This is to upload a policy and save it to database.
258      *
259      * @param file String
260      * @param request HttpServletRequest
261      * @return JSONObject
262      * @throws IOException error out
263      */
264     public String importRepositoryFile(String file, HttpServletRequest request) throws IOException {
265         boolean configExists = false;
266         boolean actionExists = false;
267         String configName = null;
268         boolean finalColumn;
269         PolicyController controller = policyController != null ? getPolicyController() : new PolicyController();
270         String userId = UserUtils.getUserSession(request).getOrgUserId();
271         UserInfo userInfo = (UserInfo) commonClassDao.getEntityItem(UserInfo.class, "userLoginId", userId);
272
273         // Check if the Role and Scope Size are Null get the values from db.
274         List<Object> userRoles = controller.getRoles(userId);
275         Pair<Set<String>, List<String>> pair = org.onap.policy.utils.UserUtils.checkRoleAndScope(userRoles);
276         List<String> roles = pair.second;
277         Set<String> scopes = pair.first;
278
279         try (FileInputStream excelFile = new FileInputStream(new File(file));
280                 HSSFWorkbook workbook = new HSSFWorkbook(excelFile)) {
281             Sheet datatypeSheet = workbook.getSheetAt(0);
282             Iterator<Row> rowIterator = datatypeSheet.iterator();
283             String sendResult = null;
284             while (rowIterator.hasNext()) {
285                 finalColumn = false;
286                 PolicyEntity policyEntity = new PolicyEntity();
287                 ConfigurationDataEntity configurationDataEntity = new ConfigurationDataEntity();
288                 ActionBodyEntity actionBodyEntity = new ActionBodyEntity();
289                 Row currentRow = rowIterator.next();
290                 if (currentRow.getRowNum() == 0) {
291                     continue;
292                 }
293                 Iterator<Cell> cellIterator = currentRow.cellIterator();
294                 StringBuilder body = new StringBuilder();
295                 int bodySize = 0;
296                 int setBodySize = 0;
297                 boolean configurationBodySet = false;
298                 boolean errorFlag = false;
299                 while (cellIterator.hasNext()) {
300                     Cell cell = cellIterator.next();
301                     if (policyName.equalsIgnoreCase(getCellHeaderName(cell))) {
302                         policyEntity.setPolicyName(cell.getStringCellValue());
303                         finalColumn = false;
304                         configurationBodySet = false;
305                         configExists = false;
306                         actionExists = false;
307                     }
308                     policyEntity = populatePolicyEntity(cell, policyEntity);
309                     setBodySize = getSetBodySize(policyEntity, cell, setBodySize);
310                     finalColumn = isFinalColumn(policyEntity, cell, setBodySize, setBodySize, finalColumn);
311                     configurationBodySet =
312                             isConfigurationBodySet(policyEntity, cell, setBodySize, setBodySize, configurationBodySet);
313                     configExists = isConfigExists(policyEntity, cell, configExists);
314                     body = addCellValue(policyEntity, cell, body);
315                     actionExists = isActionExists(policyEntity, cell, actionExists);
316                     actionBodyEntity = setActionBodyObject(policyEntity, actionBodyEntity, cell);
317                     bodySize = getBobySize(bodySize, cell); //
318                     configName = getConfigName(cell, configName);
319                     configurationDataEntity =
320                             populateConfigurationDataEntity(policyEntity, configurationDataEntity, cell);
321                     actionBodyEntity = populateActionBodyObject(policyEntity, actionBodyEntity, cell);
322                     String response = null;
323                     response = validatRequiredValue(policyEntity, body, finalColumn, configurationBodySet);
324                     if (!StringUtils.isBlank(response)) {
325                         sendResult = sendResult + "\n" + response;
326                         errorFlag = true;
327                     }
328                     if (!StringUtils.isBlank(response) && !rowIterator.hasNext()) {
329                         return sendResult;
330                     }
331                     savePolicyEntiies(finalColumn, configurationBodySet, configurationDataEntity, policyEntity,
332                             controller, roles, userInfo, scopes, configName, userId, configExists, actionExists,
333                             actionBodyEntity, body, errorFlag);
334
335                 }
336             }
337         } catch (IOException e) {
338             logger.error("Exception Occured While importing the Policy" + e);
339         }
340         return null;
341     }
342
343     private void writeConfigurationFile(ConfigurationDataEntity configurationDataEntity) {
344         try (FileWriter fw = new FileWriter(
345                 PolicyController.getConfigHome() + File.separator + configurationDataEntity.getConfigurationName())) {
346             BufferedWriter bw = new BufferedWriter(fw);
347             bw.write(configurationDataEntity.getConfigBody());
348             bw.close();
349         } catch (IOException e) {
350             logger.error("Exception Occured While cloning the configuration file", e);
351         }
352     }
353
354     private void writeActionBodyFile(ActionBodyEntity actionBodyEntity) {
355         try (FileWriter fw = new FileWriter(
356                 PolicyController.getActionHome() + File.separator + actionBodyEntity.getActionBodyName())) {
357             BufferedWriter bw = new BufferedWriter(fw);
358             bw.write(actionBodyEntity.getActionBody());
359             bw.close();
360         } catch (IOException e) {
361             logger.error("Exception Occured While cloning the configuration file", e);
362         }
363     }
364
365     // return the column header name value
366     private String getCellHeaderName(Cell cell) {
367         return cell.getSheet().getRow(0).getCell(cell.getColumnIndex()).getRichStringCellValue().toString();
368     }
369
370     /**
371      * This is to validate all matching required fields.
372      *
373      * @param policyName String
374      * @param jsonString String
375      * @return String
376      */
377     public String validatMatchRequiredFields(String policyName, String jsonString) {
378         String errorMsg = "";
379         try {
380             JSONObject jsonObject = new JSONObject(jsonString);
381             String confErorMsg = validConfigName(jsonObject.getString("configName"));
382             if (!confErorMsg.isEmpty()) {
383                 errorMsg = errorMsg + "\n POLICY :" + policyName + " at " + confErorMsg;
384             }
385             String uuidErorMsg = validUuid(jsonObject.getString("uuid"));
386             if (!uuidErorMsg.isEmpty()) {
387                 errorMsg = errorMsg + "\n POLICY :" + policyName + " at " + uuidErorMsg;
388             }
389             String locErorMsg = validLocation(jsonObject.getString("location"));
390             if (!locErorMsg.isEmpty()) {
391                 errorMsg = errorMsg + "\n POLICY :" + policyName + " at " + locErorMsg;
392             }
393             String pScopeErorMsg = validPolicyScope(jsonObject.getString("policyScope"));
394             if (!pScopeErorMsg.isEmpty()) {
395                 errorMsg = errorMsg + "\n POLICY :" + policyName + " at " + pScopeErorMsg;
396             }
397             String msVersion = jsonObject.getString("version");
398             String msService = jsonObject.getString("service");
399             if (!isAttributeObjectFound(msService, msVersion)) {
400                 errorMsg = errorMsg + "\n POLICY :" + policyName + " at MS Service: " + msService + " and MS Version: "
401                         + msVersion + NOTVALID;
402             }
403
404         } catch (Exception e) {
405             logger.error("Exception Occured While validating required fields", e);
406         }
407
408         return errorMsg;
409     }
410
411     private String validatRequiredValue(PolicyEntity policyEntity, StringBuilder body, boolean finalColumn,
412             boolean configurationBodySet) {
413         if (finalColumn && configurationBodySet && (policyEntity.getPolicyName().contains(CONFIG_MS))) {
414             String errorMsg = validatMatchRequiredFields(policyEntity.getPolicyName(), body.toString());
415             if (errorMsg != null) {
416                 logger.error("errorMsg => " + errorMsg);
417                 JSONObject response = new JSONObject();
418                 response.append("error", errorMsg);
419                 return errorMsg;
420             }
421         }
422         return null;
423     }
424
425     private String validConfigName(String configName) {
426         String message = null;
427         if (configName != null) {
428             List<String> configNames = commonClassDao.getDataByColumn(MicroServiceConfigName.class, "name");
429             if (configNames != null
430                     && (!(configNames.stream().filter(o -> o.equals(configName)).findFirst().isPresent()))) {
431                 message = POLICY + policyName + " configName: " + configName + NOTVALID;
432             }
433         } else {
434             message = POLICY + policyName + "configName is null";
435         }
436         return message;
437     }
438
439     private String validUuid(String uuid) {
440         String message = null;
441         if (uuid != null) {
442             List<String> uuids = commonClassDao.getDataByColumn(DcaeUuid.class, "name");
443             if (uuids != null && !(uuids.stream().filter(o -> o.equals(uuid)).findFirst().isPresent())) {
444                 message = POLICY + policyName + " uuid: " + uuid + NOTVALID;
445             }
446         } else {
447             message = POLICY + policyName + "uuid is null";
448         }
449         return message;
450     }
451
452     private String validLocation(String location) {
453         String message = null;
454         if (location != null) {
455             List<String> locations = commonClassDao.getDataByColumn(MicroServiceLocation.class, "name");
456             if ((locations != null && !(locations.stream().filter(o -> o.equals(location)).findFirst().isPresent()))) {
457                 message = POLICY + policyName + " location: " + location + NOTVALID;
458             }
459         } else {
460             message = POLICY + policyName + "location is null";
461         }
462         return message;
463     }
464
465     private String validPolicyScope(String policyScope) {
466         String message = null;
467         if (policyScope != null) {
468             List<Object> foundData =
469                     commonClassDao.checkDuplicateEntry(policyScope, "groupList", GroupPolicyScopeList.class);
470             if (foundData == null || foundData.isEmpty()) {
471                 message = POLICY + policyName + " policyScope: " + policyScope + NOTVALID;
472             }
473         } else {
474             message = POLICY + policyName + "policyScope is null";
475         }
476         return message;
477     }
478
479     private boolean isAttributeObjectFound(String msService, String msVersion) {
480         if (msService == null) {
481             return false;
482         }
483
484         if (msVersion == null) {
485             return false;
486         }
487         MicroServiceModels workingModel = null;
488         List<Object> microServiceModelsData =
489                 commonClassDao.getDataById(MicroServiceModels.class, "modelName", msService);
490         if (microServiceModelsData != null) {
491             for (int i = 0; i < microServiceModelsData.size(); i++) {
492                 workingModel = (MicroServiceModels) microServiceModelsData.get(i);
493                 if (workingModel != null && workingModel.getVersion() != null
494                         && workingModel.getVersion().equals(msVersion)) {
495                     return true;
496                 }
497             }
498         }
499         return false;
500     }
501
502     private PolicyEntity populatePolicyEntity(Cell cell, PolicyEntity policyEntityObject) {
503
504         if (policyEntityObject == null) {
505             return null;
506         }
507
508         PolicyEntity policyEntity = policyEntityObject;
509         if ("scope".equalsIgnoreCase(getCellHeaderName(cell))) {
510             policyEntity.setScope(cell.getStringCellValue());
511         }
512         if ("policyData".equalsIgnoreCase(getCellHeaderName(cell))) {
513             policyEntity.setPolicyData(cell.getStringCellValue());
514         }
515         if ("description".equalsIgnoreCase(getCellHeaderName(cell))) {
516             policyEntity.setDescription(cell.getStringCellValue());
517         }
518
519         return policyEntity;
520     }
521
522     private void saveConfigurePolicy(String configName, ConfigurationDataEntity configurationDataEntity, String userId,
523             boolean configExists) {
524         if (configExists) {
525             if (configName.endsWith("json")) {
526                 configurationDataEntity.setConfigType("JSON");
527             } else if (configName.endsWith("txt")) {
528                 configurationDataEntity.setConfigType("OTHER");
529             } else if (configName.endsWith("xml")) {
530                 configurationDataEntity.setConfigType("XML");
531             } else if (configName.endsWith("properties")) {
532                 configurationDataEntity.setConfigType("PROPERTIES");
533             }
534             configurationDataEntity.setDeleted(false);
535             configurationDataEntity.setCreatedBy(userId);
536             configurationDataEntity.setModifiedBy(userId);
537             commonClassDao.save(configurationDataEntity);
538             writeConfigurationFile(configurationDataEntity);
539         }
540     }
541
542     private void saveActionPolicy(ActionBodyEntity actionBodyEntity, String userId, boolean actionExists) {
543         if (actionExists) {
544             actionBodyEntity.setDeleted(false);
545             actionBodyEntity.setCreatedBy(userId);
546             actionBodyEntity.setModifiedBy(userId);
547             commonClassDao.save(actionBodyEntity);
548             writeActionBodyFile(actionBodyEntity);
549         }
550     }
551
552     private boolean isContinue(List<String> roles, String scope, UserInfo userInfo) {
553         if (roles.contains(superAdmin) || roles.contains(superEditor)) {
554             // 1. if Role contains super admin create scope.
555             // 2. if Role contains super editor don't create new scope and add to list to show to user.
556             PolicyEditorScopes policyEditorScope =
557                     (PolicyEditorScopes) commonClassDao.getEntityItem(PolicyEditorScopes.class, "scopeName", scope);
558             if (policyEditorScope == null) {
559                 if (roles.contains(superAdmin)) {
560                     PolicyEditorScopes policyEditorScopeEntity = new PolicyEditorScopes();
561                     policyEditorScopeEntity.setScopeName(scope);
562                     policyEditorScopeEntity.setUserCreatedBy(userInfo);
563                     policyEditorScopeEntity.setUserModifiedBy(userInfo);
564                     commonClassDao.save(policyEditorScopeEntity);
565                 } else {
566                     // Add Error Message a new Scope Exists, contact super-admin to create a new scope
567                     return true;
568                 }
569             }
570         }
571         return false;
572     }
573
574     @SuppressWarnings("rawtypes")
575     private boolean isContinue(List<String> roles, String scope, UserInfo userInfo, Set scopes) {
576         if (roles.contains(admin) || roles.contains(editor)) {
577             if (scopes.isEmpty()) {
578                 logger.error("No Scopes has been Assigned to the User. Please, Contact Super-Admin");
579             } else {
580                 // 1. if Role contains admin, then check if parent scope has role admin, if not don't
581                 // create a scope and add to list.
582                 if (roles.contains(admin)) {
583                     String scopeCheck = scope.substring(0, scope.lastIndexOf('.'));
584                     if (scopes.contains(scopeCheck)) {
585                         PolicyEditorScopes policyEditorScopeEntity = new PolicyEditorScopes();
586                         policyEditorScopeEntity.setScopeName(scope);
587                         policyEditorScopeEntity.setUserCreatedBy(userInfo);
588                         policyEditorScopeEntity.setUserModifiedBy(userInfo);
589                         commonClassDao.save(policyEditorScopeEntity);
590                     } else {
591                         return true;
592                     }
593                 } else {
594                     return true;
595                 }
596             }
597         }
598         return false;
599     }
600
601     private boolean isContinue(List<Object> queryData, List<String> roles, String scope, UserInfo userInfo,
602             Set<String> scopes) {
603         if (!queryData.isEmpty()) {
604             return true;
605         }
606         if (isContinue(roles, scope, userInfo)) {
607             return true;
608         }
609         return isContinue(roles, scope, userInfo, scopes);
610     }
611
612     private void savePolicyEntity(PolicyEntity policyEntity, String configName, String userId) {
613         if (configName != null) {
614             if (configName.contains(config) || configName.contains(DECISION_MS)) {
615                 ConfigurationDataEntity configuration = (ConfigurationDataEntity) commonClassDao
616                         .getEntityItem(ConfigurationDataEntity.class, configurationName, configName);
617                 policyEntity.setConfigurationData(configuration);
618             } else {
619                 ActionBodyEntity actionBody = (ActionBodyEntity) commonClassDao.getEntityItem(ActionBodyEntity.class,
620                         "actionBodyName", configName);
621                 policyEntity.setActionBodyEntity(actionBody);
622             }
623         }
624         policyEntity.setCreatedBy(userId);
625         policyEntity.setModifiedBy(userId);
626         policyEntity.setDeleted(false);
627         commonClassDao.save(policyEntity);
628     }
629
630     private void saveVersion(PolicyEntity policyEntity, String scope, String userId) {
631         PolicyVersion policyVersion = new PolicyVersion();
632         String policyNamel = policyEntity.getPolicyName().replace(".xml", "");
633         int version = Integer.parseInt(policyNamel.substring(policyNamel.lastIndexOf('.') + 1));
634         policyNamel = policyNamel.substring(0, policyNamel.lastIndexOf('.'));
635
636         policyVersion.setPolicyName(scope.replace(".", File.separator) + File.separator + policyNamel);
637         policyVersion.setActiveVersion(version);
638         policyVersion.setHigherVersion(version);
639         policyVersion.setCreatedBy(userId);
640         policyVersion.setModifiedBy(userId);
641         commonClassDao.save(policyVersion);
642     }
643
644     private int getSetBodySize(PolicyEntity policyEntity, Cell cell, int setBodySize) {
645         int setBodySizel = setBodySize;
646         if (configurationbody.equalsIgnoreCase(getCellHeaderName(cell))
647                 && ((policyEntity.getPolicyName().contains(config)
648                         || policyEntity.getPolicyName().contains(DECISION_MS))
649                         && (policyEntity.getPolicyName().contains("Config_BRMS_Param_")))) {
650             setBodySizel += 1;
651         }
652         return setBodySizel;
653     }
654
655     private boolean isFinalColumn(PolicyEntity policyEntity, Cell cell, int setBodySize, int bodySize,
656             boolean finalColumn) {
657         boolean finalColumnl = finalColumn;
658         if (configurationbody.equalsIgnoreCase(getCellHeaderName(cell))
659                 && (policyEntity.getPolicyName().contains(config) || policyEntity.getPolicyName().contains(DECISION_MS))
660                 && setBodySize == bodySize) {
661             finalColumnl = true;
662         }
663         if (BODYSIZE.equalsIgnoreCase(getCellHeaderName(cell)) && cell.getNumericCellValue() < 1) {
664             finalColumnl = true;
665         }
666         return finalColumnl;
667     }
668
669     private boolean isConfigurationBodySet(PolicyEntity policyEntity, Cell cell, int setBodySize, int bodySize,
670             boolean configurationBodySet) {
671         boolean configurationBodySetl = configurationBodySet;
672         if (configurationbody.equalsIgnoreCase(getCellHeaderName(cell))
673                 && (policyEntity.getPolicyName().contains(config) || policyEntity.getPolicyName().contains(DECISION_MS))
674                 && (setBodySize == bodySize)) {
675             configurationBodySetl = true;
676         }
677         if (configurationbody.equalsIgnoreCase(getCellHeaderName(cell))
678                 && (policyEntity.getPolicyName().contains(config) || policyEntity.getPolicyName().contains(DECISION_MS))
679                 && (setBodySize == 0)) {
680             configurationBodySetl = true;
681         }
682         return configurationBodySetl;
683     }
684
685     private boolean isConfigExists(PolicyEntity policyEntity, Cell cell, boolean configExists) {
686         boolean configExistsl = configExists;
687         if (configurationbody.equalsIgnoreCase(getCellHeaderName(cell))
688                 && (policyEntity.getPolicyName().contains(config)
689                         || policyEntity.getPolicyName().contains(DECISION_MS))) {
690             configExistsl = true;
691         }
692         return configExistsl;
693     }
694
695     private boolean isActionExists(PolicyEntity policyEntity, Cell cell, boolean actionExists) {
696         boolean actionExistsl = actionExists;
697         if (configurationbody.equalsIgnoreCase(getCellHeaderName(cell))
698                 && policyEntity.getPolicyName().contains(ACTION)) {
699             actionExistsl = true;
700         }
701         return actionExistsl;
702     }
703
704     private int getBobySize(int bodySize, Cell cell) {
705         int bodySizel = bodySize;
706         if (BODYSIZE.equalsIgnoreCase(getCellHeaderName(cell)) && cell.getNumericCellValue() >= 1) {
707             bodySizel = (int) cell.getNumericCellValue();
708         }
709         return bodySizel;
710     }
711
712     private StringBuilder addCellValue(PolicyEntity policyEntity, Cell cell, StringBuilder body) {
713         if (configurationbody.equalsIgnoreCase(getCellHeaderName(cell))
714                 && (policyEntity.getPolicyName().contains(config)
715                         || policyEntity.getPolicyName().contains(DECISION_MS))) {
716             body.append(cell.getStringCellValue());
717         }
718
719         return body;
720     }
721
722     private ActionBodyEntity setActionBodyObject(PolicyEntity policyEntity, ActionBodyEntity actionBodyEntity,
723             Cell cell) {
724         if (configurationbody.equalsIgnoreCase(getCellHeaderName(cell))
725                 && (policyEntity.getPolicyName().contains(ACTION))) {
726             actionBodyEntity.setActionBody(cell.getStringCellValue());
727         }
728         return actionBodyEntity;
729     }
730
731     private ActionBodyEntity populateActionBodyObject(PolicyEntity policyEntity, ActionBodyEntity actionBodyEntity,
732             Cell cell) {
733         if (configurationName.equalsIgnoreCase(getCellHeaderName(cell))
734                 && policyEntity.getPolicyName().contains(ACTION)) {
735             actionBodyEntity.setActionBodyName(cell.getStringCellValue());
736         }
737         return actionBodyEntity;
738     }
739
740     private ConfigurationDataEntity populateConfigurationDataEntity(PolicyEntity policyEntity,
741             ConfigurationDataEntity configurationDataEntity, Cell cell) {
742         if (configurationName.equalsIgnoreCase(getCellHeaderName(cell))
743                 && (policyEntity.getPolicyName().contains(config)
744                         || policyEntity.getPolicyName().contains(DECISION_MS))) {
745             configurationDataEntity.setConfigurationName(cell.getStringCellValue());
746         }
747         return configurationDataEntity;
748     }
749
750     private String getConfigName(Cell cell, String configName) {
751         String configNameL = configName;
752         if (configurationName.equalsIgnoreCase(getCellHeaderName(cell))) {
753             configNameL = cell.getStringCellValue();
754         }
755         return configNameL;
756     }
757
758     private void savePolicyEntiies(boolean finalColumn, boolean configurationBodySet,
759             ConfigurationDataEntity configurationDataEntity, PolicyEntity policyEntity, PolicyController controller,
760             List<String> roles, UserInfo userInfo, Set<String> scopes, String configName, String userId,
761             boolean configExists, boolean actionExists, ActionBodyEntity actionBodyEntity, StringBuilder body, boolean errorFlagSent) {
762
763         if (finalColumn && configurationBodySet && !errorFlagSent) {
764             configurationDataEntity.setConfigBody(body.toString());
765             String scope = policyEntity.getScope().replace(".", File.separator);
766             String query = "FROM PolicyEntity where policyName = :policyName and scope = :policyScope";
767             SimpleBindings params = new SimpleBindings();
768             params.put(policyName, policyEntity.getPolicyName());
769             params.put("policyScope", policyEntity.getScope());
770             List<Object> queryData = controller.getDataByQuery(query, params);
771
772             if (isContinue(queryData, roles, scope, userInfo, scopes)) {
773                 return;
774             }
775             saveConfigurePolicy(configName, configurationDataEntity, userId, configExists); //
776             saveActionPolicy(actionBodyEntity, userId, actionExists); //
777             savePolicyEntity(policyEntity, configName, userId);//
778             saveVersion(policyEntity, scope, userId); //
779             // Notify Other paps regarding Export Policy.
780             PolicyRestController restController = new PolicyRestController();
781             restController.notifyOtherPapsToUpdateConfigurations("exportPolicy", configName, null);
782         }
783     }
784 }